uloop-cli 0.44.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.prettierrc.json +28 -0
- package/CLAUDE.md +61 -0
- package/dist/cli.bundle.cjs +4761 -0
- package/dist/cli.bundle.cjs.map +7 -0
- package/eslint.config.mjs +72 -0
- package/jest.config.cjs +19 -0
- package/package.json +61 -0
- package/src/__tests__/cli-e2e.test.ts +349 -0
- package/src/__tests__/setup.ts +24 -0
- package/src/arg-parser.ts +128 -0
- package/src/cli.ts +489 -0
- package/src/default-tools.json +355 -0
- package/src/direct-unity-client.ts +125 -0
- package/src/execute-tool.ts +155 -0
- package/src/port-resolver.ts +60 -0
- package/src/project-root.ts +31 -0
- package/src/simple-framer.ts +97 -0
- package/src/skills/bundled-skills.ts +64 -0
- package/src/skills/markdown.d.ts +4 -0
- package/src/skills/skill-definitions/uloop-capture-gameview/SKILL.md +39 -0
- package/src/skills/skill-definitions/uloop-clear-console/SKILL.md +34 -0
- package/src/skills/skill-definitions/uloop-compile/SKILL.md +37 -0
- package/src/skills/skill-definitions/uloop-execute-dynamic-code/SKILL.md +79 -0
- package/src/skills/skill-definitions/uloop-execute-menu-item/SKILL.md +43 -0
- package/src/skills/skill-definitions/uloop-find-game-objects/SKILL.md +46 -0
- package/src/skills/skill-definitions/uloop-focus-window/SKILL.md +34 -0
- package/src/skills/skill-definitions/uloop-get-hierarchy/SKILL.md +44 -0
- package/src/skills/skill-definitions/uloop-get-logs/SKILL.md +45 -0
- package/src/skills/skill-definitions/uloop-get-menu-items/SKILL.md +44 -0
- package/src/skills/skill-definitions/uloop-get-project-info/SKILL.md +34 -0
- package/src/skills/skill-definitions/uloop-get-provider-details/SKILL.md +45 -0
- package/src/skills/skill-definitions/uloop-get-version/SKILL.md +31 -0
- package/src/skills/skill-definitions/uloop-run-tests/SKILL.md +43 -0
- package/src/skills/skill-definitions/uloop-unity-search/SKILL.md +44 -0
- package/src/skills/skills-command.ts +118 -0
- package/src/skills/skills-manager.ts +135 -0
- package/src/tool-cache.ts +104 -0
- package/src/version.ts +7 -0
- package/tsconfig.json +26 -0
|
@@ -0,0 +1,4761 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
"use strict";
|
|
3
|
+
var __create = Object.create;
|
|
4
|
+
var __defProp = Object.defineProperty;
|
|
5
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
6
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
7
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
8
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
9
|
+
var __commonJS = (cb, mod) => function __require() {
|
|
10
|
+
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
11
|
+
};
|
|
12
|
+
var __copyProps = (to, from, except, desc) => {
|
|
13
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
14
|
+
for (let key of __getOwnPropNames(from))
|
|
15
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
16
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
17
|
+
}
|
|
18
|
+
return to;
|
|
19
|
+
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
28
|
+
|
|
29
|
+
// node_modules/commander/lib/error.js
|
|
30
|
+
var require_error = __commonJS({
|
|
31
|
+
"node_modules/commander/lib/error.js"(exports2) {
|
|
32
|
+
var CommanderError2 = class extends Error {
|
|
33
|
+
/**
|
|
34
|
+
* Constructs the CommanderError class
|
|
35
|
+
* @param {number} exitCode suggested exit code which could be used with process.exit
|
|
36
|
+
* @param {string} code an id string representing the error
|
|
37
|
+
* @param {string} message human-readable description of the error
|
|
38
|
+
*/
|
|
39
|
+
constructor(exitCode, code, message) {
|
|
40
|
+
super(message);
|
|
41
|
+
Error.captureStackTrace(this, this.constructor);
|
|
42
|
+
this.name = this.constructor.name;
|
|
43
|
+
this.code = code;
|
|
44
|
+
this.exitCode = exitCode;
|
|
45
|
+
this.nestedError = void 0;
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
var InvalidArgumentError2 = class extends CommanderError2 {
|
|
49
|
+
/**
|
|
50
|
+
* Constructs the InvalidArgumentError class
|
|
51
|
+
* @param {string} [message] explanation of why argument is invalid
|
|
52
|
+
*/
|
|
53
|
+
constructor(message) {
|
|
54
|
+
super(1, "commander.invalidArgument", message);
|
|
55
|
+
Error.captureStackTrace(this, this.constructor);
|
|
56
|
+
this.name = this.constructor.name;
|
|
57
|
+
}
|
|
58
|
+
};
|
|
59
|
+
exports2.CommanderError = CommanderError2;
|
|
60
|
+
exports2.InvalidArgumentError = InvalidArgumentError2;
|
|
61
|
+
}
|
|
62
|
+
});
|
|
63
|
+
|
|
64
|
+
// node_modules/commander/lib/argument.js
|
|
65
|
+
var require_argument = __commonJS({
|
|
66
|
+
"node_modules/commander/lib/argument.js"(exports2) {
|
|
67
|
+
var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
|
|
68
|
+
var Argument2 = class {
|
|
69
|
+
/**
|
|
70
|
+
* Initialize a new command argument with the given name and description.
|
|
71
|
+
* The default is that the argument is required, and you can explicitly
|
|
72
|
+
* indicate this with <> around the name. Put [] around the name for an optional argument.
|
|
73
|
+
*
|
|
74
|
+
* @param {string} name
|
|
75
|
+
* @param {string} [description]
|
|
76
|
+
*/
|
|
77
|
+
constructor(name, description) {
|
|
78
|
+
this.description = description || "";
|
|
79
|
+
this.variadic = false;
|
|
80
|
+
this.parseArg = void 0;
|
|
81
|
+
this.defaultValue = void 0;
|
|
82
|
+
this.defaultValueDescription = void 0;
|
|
83
|
+
this.argChoices = void 0;
|
|
84
|
+
switch (name[0]) {
|
|
85
|
+
case "<":
|
|
86
|
+
this.required = true;
|
|
87
|
+
this._name = name.slice(1, -1);
|
|
88
|
+
break;
|
|
89
|
+
case "[":
|
|
90
|
+
this.required = false;
|
|
91
|
+
this._name = name.slice(1, -1);
|
|
92
|
+
break;
|
|
93
|
+
default:
|
|
94
|
+
this.required = true;
|
|
95
|
+
this._name = name;
|
|
96
|
+
break;
|
|
97
|
+
}
|
|
98
|
+
if (this._name.endsWith("...")) {
|
|
99
|
+
this.variadic = true;
|
|
100
|
+
this._name = this._name.slice(0, -3);
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* Return argument name.
|
|
105
|
+
*
|
|
106
|
+
* @return {string}
|
|
107
|
+
*/
|
|
108
|
+
name() {
|
|
109
|
+
return this._name;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* @package
|
|
113
|
+
*/
|
|
114
|
+
_collectValue(value, previous) {
|
|
115
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) {
|
|
116
|
+
return [value];
|
|
117
|
+
}
|
|
118
|
+
previous.push(value);
|
|
119
|
+
return previous;
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Set the default value, and optionally supply the description to be displayed in the help.
|
|
123
|
+
*
|
|
124
|
+
* @param {*} value
|
|
125
|
+
* @param {string} [description]
|
|
126
|
+
* @return {Argument}
|
|
127
|
+
*/
|
|
128
|
+
default(value, description) {
|
|
129
|
+
this.defaultValue = value;
|
|
130
|
+
this.defaultValueDescription = description;
|
|
131
|
+
return this;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Set the custom handler for processing CLI command arguments into argument values.
|
|
135
|
+
*
|
|
136
|
+
* @param {Function} [fn]
|
|
137
|
+
* @return {Argument}
|
|
138
|
+
*/
|
|
139
|
+
argParser(fn) {
|
|
140
|
+
this.parseArg = fn;
|
|
141
|
+
return this;
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Only allow argument value to be one of choices.
|
|
145
|
+
*
|
|
146
|
+
* @param {string[]} values
|
|
147
|
+
* @return {Argument}
|
|
148
|
+
*/
|
|
149
|
+
choices(values) {
|
|
150
|
+
this.argChoices = values.slice();
|
|
151
|
+
this.parseArg = (arg, previous) => {
|
|
152
|
+
if (!this.argChoices.includes(arg)) {
|
|
153
|
+
throw new InvalidArgumentError2(
|
|
154
|
+
`Allowed choices are ${this.argChoices.join(", ")}.`
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
if (this.variadic) {
|
|
158
|
+
return this._collectValue(arg, previous);
|
|
159
|
+
}
|
|
160
|
+
return arg;
|
|
161
|
+
};
|
|
162
|
+
return this;
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Make argument required.
|
|
166
|
+
*
|
|
167
|
+
* @returns {Argument}
|
|
168
|
+
*/
|
|
169
|
+
argRequired() {
|
|
170
|
+
this.required = true;
|
|
171
|
+
return this;
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Make argument optional.
|
|
175
|
+
*
|
|
176
|
+
* @returns {Argument}
|
|
177
|
+
*/
|
|
178
|
+
argOptional() {
|
|
179
|
+
this.required = false;
|
|
180
|
+
return this;
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
function humanReadableArgName(arg) {
|
|
184
|
+
const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
|
|
185
|
+
return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
|
|
186
|
+
}
|
|
187
|
+
exports2.Argument = Argument2;
|
|
188
|
+
exports2.humanReadableArgName = humanReadableArgName;
|
|
189
|
+
}
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
// node_modules/commander/lib/help.js
|
|
193
|
+
var require_help = __commonJS({
|
|
194
|
+
"node_modules/commander/lib/help.js"(exports2) {
|
|
195
|
+
var { humanReadableArgName } = require_argument();
|
|
196
|
+
var Help2 = class {
|
|
197
|
+
constructor() {
|
|
198
|
+
this.helpWidth = void 0;
|
|
199
|
+
this.minWidthToWrap = 40;
|
|
200
|
+
this.sortSubcommands = false;
|
|
201
|
+
this.sortOptions = false;
|
|
202
|
+
this.showGlobalOptions = false;
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
|
|
206
|
+
* and just before calling `formatHelp()`.
|
|
207
|
+
*
|
|
208
|
+
* Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
|
|
209
|
+
*
|
|
210
|
+
* @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
|
|
211
|
+
*/
|
|
212
|
+
prepareContext(contextOptions) {
|
|
213
|
+
this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
|
|
214
|
+
}
|
|
215
|
+
/**
|
|
216
|
+
* Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
|
|
217
|
+
*
|
|
218
|
+
* @param {Command} cmd
|
|
219
|
+
* @returns {Command[]}
|
|
220
|
+
*/
|
|
221
|
+
visibleCommands(cmd) {
|
|
222
|
+
const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
|
|
223
|
+
const helpCommand = cmd._getHelpCommand();
|
|
224
|
+
if (helpCommand && !helpCommand._hidden) {
|
|
225
|
+
visibleCommands.push(helpCommand);
|
|
226
|
+
}
|
|
227
|
+
if (this.sortSubcommands) {
|
|
228
|
+
visibleCommands.sort((a, b) => {
|
|
229
|
+
return a.name().localeCompare(b.name());
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
return visibleCommands;
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Compare options for sort.
|
|
236
|
+
*
|
|
237
|
+
* @param {Option} a
|
|
238
|
+
* @param {Option} b
|
|
239
|
+
* @returns {number}
|
|
240
|
+
*/
|
|
241
|
+
compareOptions(a, b) {
|
|
242
|
+
const getSortKey = (option) => {
|
|
243
|
+
return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
|
|
244
|
+
};
|
|
245
|
+
return getSortKey(a).localeCompare(getSortKey(b));
|
|
246
|
+
}
|
|
247
|
+
/**
|
|
248
|
+
* Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
|
|
249
|
+
*
|
|
250
|
+
* @param {Command} cmd
|
|
251
|
+
* @returns {Option[]}
|
|
252
|
+
*/
|
|
253
|
+
visibleOptions(cmd) {
|
|
254
|
+
const visibleOptions = cmd.options.filter((option) => !option.hidden);
|
|
255
|
+
const helpOption = cmd._getHelpOption();
|
|
256
|
+
if (helpOption && !helpOption.hidden) {
|
|
257
|
+
const removeShort = helpOption.short && cmd._findOption(helpOption.short);
|
|
258
|
+
const removeLong = helpOption.long && cmd._findOption(helpOption.long);
|
|
259
|
+
if (!removeShort && !removeLong) {
|
|
260
|
+
visibleOptions.push(helpOption);
|
|
261
|
+
} else if (helpOption.long && !removeLong) {
|
|
262
|
+
visibleOptions.push(
|
|
263
|
+
cmd.createOption(helpOption.long, helpOption.description)
|
|
264
|
+
);
|
|
265
|
+
} else if (helpOption.short && !removeShort) {
|
|
266
|
+
visibleOptions.push(
|
|
267
|
+
cmd.createOption(helpOption.short, helpOption.description)
|
|
268
|
+
);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
if (this.sortOptions) {
|
|
272
|
+
visibleOptions.sort(this.compareOptions);
|
|
273
|
+
}
|
|
274
|
+
return visibleOptions;
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Get an array of the visible global options. (Not including help.)
|
|
278
|
+
*
|
|
279
|
+
* @param {Command} cmd
|
|
280
|
+
* @returns {Option[]}
|
|
281
|
+
*/
|
|
282
|
+
visibleGlobalOptions(cmd) {
|
|
283
|
+
if (!this.showGlobalOptions) return [];
|
|
284
|
+
const globalOptions = [];
|
|
285
|
+
for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
|
|
286
|
+
const visibleOptions = ancestorCmd.options.filter(
|
|
287
|
+
(option) => !option.hidden
|
|
288
|
+
);
|
|
289
|
+
globalOptions.push(...visibleOptions);
|
|
290
|
+
}
|
|
291
|
+
if (this.sortOptions) {
|
|
292
|
+
globalOptions.sort(this.compareOptions);
|
|
293
|
+
}
|
|
294
|
+
return globalOptions;
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* Get an array of the arguments if any have a description.
|
|
298
|
+
*
|
|
299
|
+
* @param {Command} cmd
|
|
300
|
+
* @returns {Argument[]}
|
|
301
|
+
*/
|
|
302
|
+
visibleArguments(cmd) {
|
|
303
|
+
if (cmd._argsDescription) {
|
|
304
|
+
cmd.registeredArguments.forEach((argument) => {
|
|
305
|
+
argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
if (cmd.registeredArguments.find((argument) => argument.description)) {
|
|
309
|
+
return cmd.registeredArguments;
|
|
310
|
+
}
|
|
311
|
+
return [];
|
|
312
|
+
}
|
|
313
|
+
/**
|
|
314
|
+
* Get the command term to show in the list of subcommands.
|
|
315
|
+
*
|
|
316
|
+
* @param {Command} cmd
|
|
317
|
+
* @returns {string}
|
|
318
|
+
*/
|
|
319
|
+
subcommandTerm(cmd) {
|
|
320
|
+
const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
|
|
321
|
+
return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
|
|
322
|
+
(args ? " " + args : "");
|
|
323
|
+
}
|
|
324
|
+
/**
|
|
325
|
+
* Get the option term to show in the list of options.
|
|
326
|
+
*
|
|
327
|
+
* @param {Option} option
|
|
328
|
+
* @returns {string}
|
|
329
|
+
*/
|
|
330
|
+
optionTerm(option) {
|
|
331
|
+
return option.flags;
|
|
332
|
+
}
|
|
333
|
+
/**
|
|
334
|
+
* Get the argument term to show in the list of arguments.
|
|
335
|
+
*
|
|
336
|
+
* @param {Argument} argument
|
|
337
|
+
* @returns {string}
|
|
338
|
+
*/
|
|
339
|
+
argumentTerm(argument) {
|
|
340
|
+
return argument.name();
|
|
341
|
+
}
|
|
342
|
+
/**
|
|
343
|
+
* Get the longest command term length.
|
|
344
|
+
*
|
|
345
|
+
* @param {Command} cmd
|
|
346
|
+
* @param {Help} helper
|
|
347
|
+
* @returns {number}
|
|
348
|
+
*/
|
|
349
|
+
longestSubcommandTermLength(cmd, helper) {
|
|
350
|
+
return helper.visibleCommands(cmd).reduce((max, command) => {
|
|
351
|
+
return Math.max(
|
|
352
|
+
max,
|
|
353
|
+
this.displayWidth(
|
|
354
|
+
helper.styleSubcommandTerm(helper.subcommandTerm(command))
|
|
355
|
+
)
|
|
356
|
+
);
|
|
357
|
+
}, 0);
|
|
358
|
+
}
|
|
359
|
+
/**
|
|
360
|
+
* Get the longest option term length.
|
|
361
|
+
*
|
|
362
|
+
* @param {Command} cmd
|
|
363
|
+
* @param {Help} helper
|
|
364
|
+
* @returns {number}
|
|
365
|
+
*/
|
|
366
|
+
longestOptionTermLength(cmd, helper) {
|
|
367
|
+
return helper.visibleOptions(cmd).reduce((max, option) => {
|
|
368
|
+
return Math.max(
|
|
369
|
+
max,
|
|
370
|
+
this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
|
|
371
|
+
);
|
|
372
|
+
}, 0);
|
|
373
|
+
}
|
|
374
|
+
/**
|
|
375
|
+
* Get the longest global option term length.
|
|
376
|
+
*
|
|
377
|
+
* @param {Command} cmd
|
|
378
|
+
* @param {Help} helper
|
|
379
|
+
* @returns {number}
|
|
380
|
+
*/
|
|
381
|
+
longestGlobalOptionTermLength(cmd, helper) {
|
|
382
|
+
return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
|
|
383
|
+
return Math.max(
|
|
384
|
+
max,
|
|
385
|
+
this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
|
|
386
|
+
);
|
|
387
|
+
}, 0);
|
|
388
|
+
}
|
|
389
|
+
/**
|
|
390
|
+
* Get the longest argument term length.
|
|
391
|
+
*
|
|
392
|
+
* @param {Command} cmd
|
|
393
|
+
* @param {Help} helper
|
|
394
|
+
* @returns {number}
|
|
395
|
+
*/
|
|
396
|
+
longestArgumentTermLength(cmd, helper) {
|
|
397
|
+
return helper.visibleArguments(cmd).reduce((max, argument) => {
|
|
398
|
+
return Math.max(
|
|
399
|
+
max,
|
|
400
|
+
this.displayWidth(
|
|
401
|
+
helper.styleArgumentTerm(helper.argumentTerm(argument))
|
|
402
|
+
)
|
|
403
|
+
);
|
|
404
|
+
}, 0);
|
|
405
|
+
}
|
|
406
|
+
/**
|
|
407
|
+
* Get the command usage to be displayed at the top of the built-in help.
|
|
408
|
+
*
|
|
409
|
+
* @param {Command} cmd
|
|
410
|
+
* @returns {string}
|
|
411
|
+
*/
|
|
412
|
+
commandUsage(cmd) {
|
|
413
|
+
let cmdName = cmd._name;
|
|
414
|
+
if (cmd._aliases[0]) {
|
|
415
|
+
cmdName = cmdName + "|" + cmd._aliases[0];
|
|
416
|
+
}
|
|
417
|
+
let ancestorCmdNames = "";
|
|
418
|
+
for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
|
|
419
|
+
ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
|
|
420
|
+
}
|
|
421
|
+
return ancestorCmdNames + cmdName + " " + cmd.usage();
|
|
422
|
+
}
|
|
423
|
+
/**
|
|
424
|
+
* Get the description for the command.
|
|
425
|
+
*
|
|
426
|
+
* @param {Command} cmd
|
|
427
|
+
* @returns {string}
|
|
428
|
+
*/
|
|
429
|
+
commandDescription(cmd) {
|
|
430
|
+
return cmd.description();
|
|
431
|
+
}
|
|
432
|
+
/**
|
|
433
|
+
* Get the subcommand summary to show in the list of subcommands.
|
|
434
|
+
* (Fallback to description for backwards compatibility.)
|
|
435
|
+
*
|
|
436
|
+
* @param {Command} cmd
|
|
437
|
+
* @returns {string}
|
|
438
|
+
*/
|
|
439
|
+
subcommandDescription(cmd) {
|
|
440
|
+
return cmd.summary() || cmd.description();
|
|
441
|
+
}
|
|
442
|
+
/**
|
|
443
|
+
* Get the option description to show in the list of options.
|
|
444
|
+
*
|
|
445
|
+
* @param {Option} option
|
|
446
|
+
* @return {string}
|
|
447
|
+
*/
|
|
448
|
+
optionDescription(option) {
|
|
449
|
+
const extraInfo = [];
|
|
450
|
+
if (option.argChoices) {
|
|
451
|
+
extraInfo.push(
|
|
452
|
+
// use stringify to match the display of the default value
|
|
453
|
+
`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
|
|
454
|
+
);
|
|
455
|
+
}
|
|
456
|
+
if (option.defaultValue !== void 0) {
|
|
457
|
+
const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
|
|
458
|
+
if (showDefault) {
|
|
459
|
+
extraInfo.push(
|
|
460
|
+
`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
|
|
461
|
+
);
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
if (option.presetArg !== void 0 && option.optional) {
|
|
465
|
+
extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
|
|
466
|
+
}
|
|
467
|
+
if (option.envVar !== void 0) {
|
|
468
|
+
extraInfo.push(`env: ${option.envVar}`);
|
|
469
|
+
}
|
|
470
|
+
if (extraInfo.length > 0) {
|
|
471
|
+
const extraDescription = `(${extraInfo.join(", ")})`;
|
|
472
|
+
if (option.description) {
|
|
473
|
+
return `${option.description} ${extraDescription}`;
|
|
474
|
+
}
|
|
475
|
+
return extraDescription;
|
|
476
|
+
}
|
|
477
|
+
return option.description;
|
|
478
|
+
}
|
|
479
|
+
/**
|
|
480
|
+
* Get the argument description to show in the list of arguments.
|
|
481
|
+
*
|
|
482
|
+
* @param {Argument} argument
|
|
483
|
+
* @return {string}
|
|
484
|
+
*/
|
|
485
|
+
argumentDescription(argument) {
|
|
486
|
+
const extraInfo = [];
|
|
487
|
+
if (argument.argChoices) {
|
|
488
|
+
extraInfo.push(
|
|
489
|
+
// use stringify to match the display of the default value
|
|
490
|
+
`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
|
|
491
|
+
);
|
|
492
|
+
}
|
|
493
|
+
if (argument.defaultValue !== void 0) {
|
|
494
|
+
extraInfo.push(
|
|
495
|
+
`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`
|
|
496
|
+
);
|
|
497
|
+
}
|
|
498
|
+
if (extraInfo.length > 0) {
|
|
499
|
+
const extraDescription = `(${extraInfo.join(", ")})`;
|
|
500
|
+
if (argument.description) {
|
|
501
|
+
return `${argument.description} ${extraDescription}`;
|
|
502
|
+
}
|
|
503
|
+
return extraDescription;
|
|
504
|
+
}
|
|
505
|
+
return argument.description;
|
|
506
|
+
}
|
|
507
|
+
/**
|
|
508
|
+
* Format a list of items, given a heading and an array of formatted items.
|
|
509
|
+
*
|
|
510
|
+
* @param {string} heading
|
|
511
|
+
* @param {string[]} items
|
|
512
|
+
* @param {Help} helper
|
|
513
|
+
* @returns string[]
|
|
514
|
+
*/
|
|
515
|
+
formatItemList(heading, items, helper) {
|
|
516
|
+
if (items.length === 0) return [];
|
|
517
|
+
return [helper.styleTitle(heading), ...items, ""];
|
|
518
|
+
}
|
|
519
|
+
/**
|
|
520
|
+
* Group items by their help group heading.
|
|
521
|
+
*
|
|
522
|
+
* @param {Command[] | Option[]} unsortedItems
|
|
523
|
+
* @param {Command[] | Option[]} visibleItems
|
|
524
|
+
* @param {Function} getGroup
|
|
525
|
+
* @returns {Map<string, Command[] | Option[]>}
|
|
526
|
+
*/
|
|
527
|
+
groupItems(unsortedItems, visibleItems, getGroup) {
|
|
528
|
+
const result = /* @__PURE__ */ new Map();
|
|
529
|
+
unsortedItems.forEach((item) => {
|
|
530
|
+
const group = getGroup(item);
|
|
531
|
+
if (!result.has(group)) result.set(group, []);
|
|
532
|
+
});
|
|
533
|
+
visibleItems.forEach((item) => {
|
|
534
|
+
const group = getGroup(item);
|
|
535
|
+
if (!result.has(group)) {
|
|
536
|
+
result.set(group, []);
|
|
537
|
+
}
|
|
538
|
+
result.get(group).push(item);
|
|
539
|
+
});
|
|
540
|
+
return result;
|
|
541
|
+
}
|
|
542
|
+
/**
|
|
543
|
+
* Generate the built-in help text.
|
|
544
|
+
*
|
|
545
|
+
* @param {Command} cmd
|
|
546
|
+
* @param {Help} helper
|
|
547
|
+
* @returns {string}
|
|
548
|
+
*/
|
|
549
|
+
formatHelp(cmd, helper) {
|
|
550
|
+
const termWidth = helper.padWidth(cmd, helper);
|
|
551
|
+
const helpWidth = helper.helpWidth ?? 80;
|
|
552
|
+
function callFormatItem(term, description) {
|
|
553
|
+
return helper.formatItem(term, termWidth, description, helper);
|
|
554
|
+
}
|
|
555
|
+
let output = [
|
|
556
|
+
`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
|
|
557
|
+
""
|
|
558
|
+
];
|
|
559
|
+
const commandDescription = helper.commandDescription(cmd);
|
|
560
|
+
if (commandDescription.length > 0) {
|
|
561
|
+
output = output.concat([
|
|
562
|
+
helper.boxWrap(
|
|
563
|
+
helper.styleCommandDescription(commandDescription),
|
|
564
|
+
helpWidth
|
|
565
|
+
),
|
|
566
|
+
""
|
|
567
|
+
]);
|
|
568
|
+
}
|
|
569
|
+
const argumentList = helper.visibleArguments(cmd).map((argument) => {
|
|
570
|
+
return callFormatItem(
|
|
571
|
+
helper.styleArgumentTerm(helper.argumentTerm(argument)),
|
|
572
|
+
helper.styleArgumentDescription(helper.argumentDescription(argument))
|
|
573
|
+
);
|
|
574
|
+
});
|
|
575
|
+
output = output.concat(
|
|
576
|
+
this.formatItemList("Arguments:", argumentList, helper)
|
|
577
|
+
);
|
|
578
|
+
const optionGroups = this.groupItems(
|
|
579
|
+
cmd.options,
|
|
580
|
+
helper.visibleOptions(cmd),
|
|
581
|
+
(option) => option.helpGroupHeading ?? "Options:"
|
|
582
|
+
);
|
|
583
|
+
optionGroups.forEach((options, group) => {
|
|
584
|
+
const optionList = options.map((option) => {
|
|
585
|
+
return callFormatItem(
|
|
586
|
+
helper.styleOptionTerm(helper.optionTerm(option)),
|
|
587
|
+
helper.styleOptionDescription(helper.optionDescription(option))
|
|
588
|
+
);
|
|
589
|
+
});
|
|
590
|
+
output = output.concat(this.formatItemList(group, optionList, helper));
|
|
591
|
+
});
|
|
592
|
+
if (helper.showGlobalOptions) {
|
|
593
|
+
const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
|
|
594
|
+
return callFormatItem(
|
|
595
|
+
helper.styleOptionTerm(helper.optionTerm(option)),
|
|
596
|
+
helper.styleOptionDescription(helper.optionDescription(option))
|
|
597
|
+
);
|
|
598
|
+
});
|
|
599
|
+
output = output.concat(
|
|
600
|
+
this.formatItemList("Global Options:", globalOptionList, helper)
|
|
601
|
+
);
|
|
602
|
+
}
|
|
603
|
+
const commandGroups = this.groupItems(
|
|
604
|
+
cmd.commands,
|
|
605
|
+
helper.visibleCommands(cmd),
|
|
606
|
+
(sub) => sub.helpGroup() || "Commands:"
|
|
607
|
+
);
|
|
608
|
+
commandGroups.forEach((commands, group) => {
|
|
609
|
+
const commandList = commands.map((sub) => {
|
|
610
|
+
return callFormatItem(
|
|
611
|
+
helper.styleSubcommandTerm(helper.subcommandTerm(sub)),
|
|
612
|
+
helper.styleSubcommandDescription(helper.subcommandDescription(sub))
|
|
613
|
+
);
|
|
614
|
+
});
|
|
615
|
+
output = output.concat(this.formatItemList(group, commandList, helper));
|
|
616
|
+
});
|
|
617
|
+
return output.join("\n");
|
|
618
|
+
}
|
|
619
|
+
/**
|
|
620
|
+
* Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
|
|
621
|
+
*
|
|
622
|
+
* @param {string} str
|
|
623
|
+
* @returns {number}
|
|
624
|
+
*/
|
|
625
|
+
displayWidth(str) {
|
|
626
|
+
return stripColor(str).length;
|
|
627
|
+
}
|
|
628
|
+
/**
|
|
629
|
+
* Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
|
|
630
|
+
*
|
|
631
|
+
* @param {string} str
|
|
632
|
+
* @returns {string}
|
|
633
|
+
*/
|
|
634
|
+
styleTitle(str) {
|
|
635
|
+
return str;
|
|
636
|
+
}
|
|
637
|
+
styleUsage(str) {
|
|
638
|
+
return str.split(" ").map((word) => {
|
|
639
|
+
if (word === "[options]") return this.styleOptionText(word);
|
|
640
|
+
if (word === "[command]") return this.styleSubcommandText(word);
|
|
641
|
+
if (word[0] === "[" || word[0] === "<")
|
|
642
|
+
return this.styleArgumentText(word);
|
|
643
|
+
return this.styleCommandText(word);
|
|
644
|
+
}).join(" ");
|
|
645
|
+
}
|
|
646
|
+
styleCommandDescription(str) {
|
|
647
|
+
return this.styleDescriptionText(str);
|
|
648
|
+
}
|
|
649
|
+
styleOptionDescription(str) {
|
|
650
|
+
return this.styleDescriptionText(str);
|
|
651
|
+
}
|
|
652
|
+
styleSubcommandDescription(str) {
|
|
653
|
+
return this.styleDescriptionText(str);
|
|
654
|
+
}
|
|
655
|
+
styleArgumentDescription(str) {
|
|
656
|
+
return this.styleDescriptionText(str);
|
|
657
|
+
}
|
|
658
|
+
styleDescriptionText(str) {
|
|
659
|
+
return str;
|
|
660
|
+
}
|
|
661
|
+
styleOptionTerm(str) {
|
|
662
|
+
return this.styleOptionText(str);
|
|
663
|
+
}
|
|
664
|
+
styleSubcommandTerm(str) {
|
|
665
|
+
return str.split(" ").map((word) => {
|
|
666
|
+
if (word === "[options]") return this.styleOptionText(word);
|
|
667
|
+
if (word[0] === "[" || word[0] === "<")
|
|
668
|
+
return this.styleArgumentText(word);
|
|
669
|
+
return this.styleSubcommandText(word);
|
|
670
|
+
}).join(" ");
|
|
671
|
+
}
|
|
672
|
+
styleArgumentTerm(str) {
|
|
673
|
+
return this.styleArgumentText(str);
|
|
674
|
+
}
|
|
675
|
+
styleOptionText(str) {
|
|
676
|
+
return str;
|
|
677
|
+
}
|
|
678
|
+
styleArgumentText(str) {
|
|
679
|
+
return str;
|
|
680
|
+
}
|
|
681
|
+
styleSubcommandText(str) {
|
|
682
|
+
return str;
|
|
683
|
+
}
|
|
684
|
+
styleCommandText(str) {
|
|
685
|
+
return str;
|
|
686
|
+
}
|
|
687
|
+
/**
|
|
688
|
+
* Calculate the pad width from the maximum term length.
|
|
689
|
+
*
|
|
690
|
+
* @param {Command} cmd
|
|
691
|
+
* @param {Help} helper
|
|
692
|
+
* @returns {number}
|
|
693
|
+
*/
|
|
694
|
+
padWidth(cmd, helper) {
|
|
695
|
+
return Math.max(
|
|
696
|
+
helper.longestOptionTermLength(cmd, helper),
|
|
697
|
+
helper.longestGlobalOptionTermLength(cmd, helper),
|
|
698
|
+
helper.longestSubcommandTermLength(cmd, helper),
|
|
699
|
+
helper.longestArgumentTermLength(cmd, helper)
|
|
700
|
+
);
|
|
701
|
+
}
|
|
702
|
+
/**
|
|
703
|
+
* Detect manually wrapped and indented strings by checking for line break followed by whitespace.
|
|
704
|
+
*
|
|
705
|
+
* @param {string} str
|
|
706
|
+
* @returns {boolean}
|
|
707
|
+
*/
|
|
708
|
+
preformatted(str) {
|
|
709
|
+
return /\n[^\S\r\n]/.test(str);
|
|
710
|
+
}
|
|
711
|
+
/**
|
|
712
|
+
* Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
|
|
713
|
+
*
|
|
714
|
+
* So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
|
|
715
|
+
* TTT DDD DDDD
|
|
716
|
+
* DD DDD
|
|
717
|
+
*
|
|
718
|
+
* @param {string} term
|
|
719
|
+
* @param {number} termWidth
|
|
720
|
+
* @param {string} description
|
|
721
|
+
* @param {Help} helper
|
|
722
|
+
* @returns {string}
|
|
723
|
+
*/
|
|
724
|
+
formatItem(term, termWidth, description, helper) {
|
|
725
|
+
const itemIndent = 2;
|
|
726
|
+
const itemIndentStr = " ".repeat(itemIndent);
|
|
727
|
+
if (!description) return itemIndentStr + term;
|
|
728
|
+
const paddedTerm = term.padEnd(
|
|
729
|
+
termWidth + term.length - helper.displayWidth(term)
|
|
730
|
+
);
|
|
731
|
+
const spacerWidth = 2;
|
|
732
|
+
const helpWidth = this.helpWidth ?? 80;
|
|
733
|
+
const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
|
|
734
|
+
let formattedDescription;
|
|
735
|
+
if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
|
|
736
|
+
formattedDescription = description;
|
|
737
|
+
} else {
|
|
738
|
+
const wrappedDescription = helper.boxWrap(description, remainingWidth);
|
|
739
|
+
formattedDescription = wrappedDescription.replace(
|
|
740
|
+
/\n/g,
|
|
741
|
+
"\n" + " ".repeat(termWidth + spacerWidth)
|
|
742
|
+
);
|
|
743
|
+
}
|
|
744
|
+
return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
|
|
745
|
+
${itemIndentStr}`);
|
|
746
|
+
}
|
|
747
|
+
/**
|
|
748
|
+
* Wrap a string at whitespace, preserving existing line breaks.
|
|
749
|
+
* Wrapping is skipped if the width is less than `minWidthToWrap`.
|
|
750
|
+
*
|
|
751
|
+
* @param {string} str
|
|
752
|
+
* @param {number} width
|
|
753
|
+
* @returns {string}
|
|
754
|
+
*/
|
|
755
|
+
boxWrap(str, width) {
|
|
756
|
+
if (width < this.minWidthToWrap) return str;
|
|
757
|
+
const rawLines = str.split(/\r\n|\n/);
|
|
758
|
+
const chunkPattern = /[\s]*[^\s]+/g;
|
|
759
|
+
const wrappedLines = [];
|
|
760
|
+
rawLines.forEach((line) => {
|
|
761
|
+
const chunks = line.match(chunkPattern);
|
|
762
|
+
if (chunks === null) {
|
|
763
|
+
wrappedLines.push("");
|
|
764
|
+
return;
|
|
765
|
+
}
|
|
766
|
+
let sumChunks = [chunks.shift()];
|
|
767
|
+
let sumWidth = this.displayWidth(sumChunks[0]);
|
|
768
|
+
chunks.forEach((chunk) => {
|
|
769
|
+
const visibleWidth = this.displayWidth(chunk);
|
|
770
|
+
if (sumWidth + visibleWidth <= width) {
|
|
771
|
+
sumChunks.push(chunk);
|
|
772
|
+
sumWidth += visibleWidth;
|
|
773
|
+
return;
|
|
774
|
+
}
|
|
775
|
+
wrappedLines.push(sumChunks.join(""));
|
|
776
|
+
const nextChunk = chunk.trimStart();
|
|
777
|
+
sumChunks = [nextChunk];
|
|
778
|
+
sumWidth = this.displayWidth(nextChunk);
|
|
779
|
+
});
|
|
780
|
+
wrappedLines.push(sumChunks.join(""));
|
|
781
|
+
});
|
|
782
|
+
return wrappedLines.join("\n");
|
|
783
|
+
}
|
|
784
|
+
};
|
|
785
|
+
function stripColor(str) {
|
|
786
|
+
const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
|
|
787
|
+
return str.replace(sgrPattern, "");
|
|
788
|
+
}
|
|
789
|
+
exports2.Help = Help2;
|
|
790
|
+
exports2.stripColor = stripColor;
|
|
791
|
+
}
|
|
792
|
+
});
|
|
793
|
+
|
|
794
|
+
// node_modules/commander/lib/option.js
|
|
795
|
+
var require_option = __commonJS({
|
|
796
|
+
"node_modules/commander/lib/option.js"(exports2) {
|
|
797
|
+
var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
|
|
798
|
+
var Option2 = class {
|
|
799
|
+
/**
|
|
800
|
+
* Initialize a new `Option` with the given `flags` and `description`.
|
|
801
|
+
*
|
|
802
|
+
* @param {string} flags
|
|
803
|
+
* @param {string} [description]
|
|
804
|
+
*/
|
|
805
|
+
constructor(flags, description) {
|
|
806
|
+
this.flags = flags;
|
|
807
|
+
this.description = description || "";
|
|
808
|
+
this.required = flags.includes("<");
|
|
809
|
+
this.optional = flags.includes("[");
|
|
810
|
+
this.variadic = /\w\.\.\.[>\]]$/.test(flags);
|
|
811
|
+
this.mandatory = false;
|
|
812
|
+
const optionFlags = splitOptionFlags(flags);
|
|
813
|
+
this.short = optionFlags.shortFlag;
|
|
814
|
+
this.long = optionFlags.longFlag;
|
|
815
|
+
this.negate = false;
|
|
816
|
+
if (this.long) {
|
|
817
|
+
this.negate = this.long.startsWith("--no-");
|
|
818
|
+
}
|
|
819
|
+
this.defaultValue = void 0;
|
|
820
|
+
this.defaultValueDescription = void 0;
|
|
821
|
+
this.presetArg = void 0;
|
|
822
|
+
this.envVar = void 0;
|
|
823
|
+
this.parseArg = void 0;
|
|
824
|
+
this.hidden = false;
|
|
825
|
+
this.argChoices = void 0;
|
|
826
|
+
this.conflictsWith = [];
|
|
827
|
+
this.implied = void 0;
|
|
828
|
+
this.helpGroupHeading = void 0;
|
|
829
|
+
}
|
|
830
|
+
/**
|
|
831
|
+
* Set the default value, and optionally supply the description to be displayed in the help.
|
|
832
|
+
*
|
|
833
|
+
* @param {*} value
|
|
834
|
+
* @param {string} [description]
|
|
835
|
+
* @return {Option}
|
|
836
|
+
*/
|
|
837
|
+
default(value, description) {
|
|
838
|
+
this.defaultValue = value;
|
|
839
|
+
this.defaultValueDescription = description;
|
|
840
|
+
return this;
|
|
841
|
+
}
|
|
842
|
+
/**
|
|
843
|
+
* Preset to use when option used without option-argument, especially optional but also boolean and negated.
|
|
844
|
+
* The custom processing (parseArg) is called.
|
|
845
|
+
*
|
|
846
|
+
* @example
|
|
847
|
+
* new Option('--color').default('GREYSCALE').preset('RGB');
|
|
848
|
+
* new Option('--donate [amount]').preset('20').argParser(parseFloat);
|
|
849
|
+
*
|
|
850
|
+
* @param {*} arg
|
|
851
|
+
* @return {Option}
|
|
852
|
+
*/
|
|
853
|
+
preset(arg) {
|
|
854
|
+
this.presetArg = arg;
|
|
855
|
+
return this;
|
|
856
|
+
}
|
|
857
|
+
/**
|
|
858
|
+
* Add option name(s) that conflict with this option.
|
|
859
|
+
* An error will be displayed if conflicting options are found during parsing.
|
|
860
|
+
*
|
|
861
|
+
* @example
|
|
862
|
+
* new Option('--rgb').conflicts('cmyk');
|
|
863
|
+
* new Option('--js').conflicts(['ts', 'jsx']);
|
|
864
|
+
*
|
|
865
|
+
* @param {(string | string[])} names
|
|
866
|
+
* @return {Option}
|
|
867
|
+
*/
|
|
868
|
+
conflicts(names) {
|
|
869
|
+
this.conflictsWith = this.conflictsWith.concat(names);
|
|
870
|
+
return this;
|
|
871
|
+
}
|
|
872
|
+
/**
|
|
873
|
+
* Specify implied option values for when this option is set and the implied options are not.
|
|
874
|
+
*
|
|
875
|
+
* The custom processing (parseArg) is not called on the implied values.
|
|
876
|
+
*
|
|
877
|
+
* @example
|
|
878
|
+
* program
|
|
879
|
+
* .addOption(new Option('--log', 'write logging information to file'))
|
|
880
|
+
* .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
|
|
881
|
+
*
|
|
882
|
+
* @param {object} impliedOptionValues
|
|
883
|
+
* @return {Option}
|
|
884
|
+
*/
|
|
885
|
+
implies(impliedOptionValues) {
|
|
886
|
+
let newImplied = impliedOptionValues;
|
|
887
|
+
if (typeof impliedOptionValues === "string") {
|
|
888
|
+
newImplied = { [impliedOptionValues]: true };
|
|
889
|
+
}
|
|
890
|
+
this.implied = Object.assign(this.implied || {}, newImplied);
|
|
891
|
+
return this;
|
|
892
|
+
}
|
|
893
|
+
/**
|
|
894
|
+
* Set environment variable to check for option value.
|
|
895
|
+
*
|
|
896
|
+
* An environment variable is only used if when processed the current option value is
|
|
897
|
+
* undefined, or the source of the current value is 'default' or 'config' or 'env'.
|
|
898
|
+
*
|
|
899
|
+
* @param {string} name
|
|
900
|
+
* @return {Option}
|
|
901
|
+
*/
|
|
902
|
+
env(name) {
|
|
903
|
+
this.envVar = name;
|
|
904
|
+
return this;
|
|
905
|
+
}
|
|
906
|
+
/**
|
|
907
|
+
* Set the custom handler for processing CLI option arguments into option values.
|
|
908
|
+
*
|
|
909
|
+
* @param {Function} [fn]
|
|
910
|
+
* @return {Option}
|
|
911
|
+
*/
|
|
912
|
+
argParser(fn) {
|
|
913
|
+
this.parseArg = fn;
|
|
914
|
+
return this;
|
|
915
|
+
}
|
|
916
|
+
/**
|
|
917
|
+
* Whether the option is mandatory and must have a value after parsing.
|
|
918
|
+
*
|
|
919
|
+
* @param {boolean} [mandatory=true]
|
|
920
|
+
* @return {Option}
|
|
921
|
+
*/
|
|
922
|
+
makeOptionMandatory(mandatory = true) {
|
|
923
|
+
this.mandatory = !!mandatory;
|
|
924
|
+
return this;
|
|
925
|
+
}
|
|
926
|
+
/**
|
|
927
|
+
* Hide option in help.
|
|
928
|
+
*
|
|
929
|
+
* @param {boolean} [hide=true]
|
|
930
|
+
* @return {Option}
|
|
931
|
+
*/
|
|
932
|
+
hideHelp(hide = true) {
|
|
933
|
+
this.hidden = !!hide;
|
|
934
|
+
return this;
|
|
935
|
+
}
|
|
936
|
+
/**
|
|
937
|
+
* @package
|
|
938
|
+
*/
|
|
939
|
+
_collectValue(value, previous) {
|
|
940
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) {
|
|
941
|
+
return [value];
|
|
942
|
+
}
|
|
943
|
+
previous.push(value);
|
|
944
|
+
return previous;
|
|
945
|
+
}
|
|
946
|
+
/**
|
|
947
|
+
* Only allow option value to be one of choices.
|
|
948
|
+
*
|
|
949
|
+
* @param {string[]} values
|
|
950
|
+
* @return {Option}
|
|
951
|
+
*/
|
|
952
|
+
choices(values) {
|
|
953
|
+
this.argChoices = values.slice();
|
|
954
|
+
this.parseArg = (arg, previous) => {
|
|
955
|
+
if (!this.argChoices.includes(arg)) {
|
|
956
|
+
throw new InvalidArgumentError2(
|
|
957
|
+
`Allowed choices are ${this.argChoices.join(", ")}.`
|
|
958
|
+
);
|
|
959
|
+
}
|
|
960
|
+
if (this.variadic) {
|
|
961
|
+
return this._collectValue(arg, previous);
|
|
962
|
+
}
|
|
963
|
+
return arg;
|
|
964
|
+
};
|
|
965
|
+
return this;
|
|
966
|
+
}
|
|
967
|
+
/**
|
|
968
|
+
* Return option name.
|
|
969
|
+
*
|
|
970
|
+
* @return {string}
|
|
971
|
+
*/
|
|
972
|
+
name() {
|
|
973
|
+
if (this.long) {
|
|
974
|
+
return this.long.replace(/^--/, "");
|
|
975
|
+
}
|
|
976
|
+
return this.short.replace(/^-/, "");
|
|
977
|
+
}
|
|
978
|
+
/**
|
|
979
|
+
* Return option name, in a camelcase format that can be used
|
|
980
|
+
* as an object attribute key.
|
|
981
|
+
*
|
|
982
|
+
* @return {string}
|
|
983
|
+
*/
|
|
984
|
+
attributeName() {
|
|
985
|
+
if (this.negate) {
|
|
986
|
+
return camelcase(this.name().replace(/^no-/, ""));
|
|
987
|
+
}
|
|
988
|
+
return camelcase(this.name());
|
|
989
|
+
}
|
|
990
|
+
/**
|
|
991
|
+
* Set the help group heading.
|
|
992
|
+
*
|
|
993
|
+
* @param {string} heading
|
|
994
|
+
* @return {Option}
|
|
995
|
+
*/
|
|
996
|
+
helpGroup(heading) {
|
|
997
|
+
this.helpGroupHeading = heading;
|
|
998
|
+
return this;
|
|
999
|
+
}
|
|
1000
|
+
/**
|
|
1001
|
+
* Check if `arg` matches the short or long flag.
|
|
1002
|
+
*
|
|
1003
|
+
* @param {string} arg
|
|
1004
|
+
* @return {boolean}
|
|
1005
|
+
* @package
|
|
1006
|
+
*/
|
|
1007
|
+
is(arg) {
|
|
1008
|
+
return this.short === arg || this.long === arg;
|
|
1009
|
+
}
|
|
1010
|
+
/**
|
|
1011
|
+
* Return whether a boolean option.
|
|
1012
|
+
*
|
|
1013
|
+
* Options are one of boolean, negated, required argument, or optional argument.
|
|
1014
|
+
*
|
|
1015
|
+
* @return {boolean}
|
|
1016
|
+
* @package
|
|
1017
|
+
*/
|
|
1018
|
+
isBoolean() {
|
|
1019
|
+
return !this.required && !this.optional && !this.negate;
|
|
1020
|
+
}
|
|
1021
|
+
};
|
|
1022
|
+
var DualOptions = class {
|
|
1023
|
+
/**
|
|
1024
|
+
* @param {Option[]} options
|
|
1025
|
+
*/
|
|
1026
|
+
constructor(options) {
|
|
1027
|
+
this.positiveOptions = /* @__PURE__ */ new Map();
|
|
1028
|
+
this.negativeOptions = /* @__PURE__ */ new Map();
|
|
1029
|
+
this.dualOptions = /* @__PURE__ */ new Set();
|
|
1030
|
+
options.forEach((option) => {
|
|
1031
|
+
if (option.negate) {
|
|
1032
|
+
this.negativeOptions.set(option.attributeName(), option);
|
|
1033
|
+
} else {
|
|
1034
|
+
this.positiveOptions.set(option.attributeName(), option);
|
|
1035
|
+
}
|
|
1036
|
+
});
|
|
1037
|
+
this.negativeOptions.forEach((value, key) => {
|
|
1038
|
+
if (this.positiveOptions.has(key)) {
|
|
1039
|
+
this.dualOptions.add(key);
|
|
1040
|
+
}
|
|
1041
|
+
});
|
|
1042
|
+
}
|
|
1043
|
+
/**
|
|
1044
|
+
* Did the value come from the option, and not from possible matching dual option?
|
|
1045
|
+
*
|
|
1046
|
+
* @param {*} value
|
|
1047
|
+
* @param {Option} option
|
|
1048
|
+
* @returns {boolean}
|
|
1049
|
+
*/
|
|
1050
|
+
valueFromOption(value, option) {
|
|
1051
|
+
const optionKey = option.attributeName();
|
|
1052
|
+
if (!this.dualOptions.has(optionKey)) return true;
|
|
1053
|
+
const preset = this.negativeOptions.get(optionKey).presetArg;
|
|
1054
|
+
const negativeValue = preset !== void 0 ? preset : false;
|
|
1055
|
+
return option.negate === (negativeValue === value);
|
|
1056
|
+
}
|
|
1057
|
+
};
|
|
1058
|
+
function camelcase(str) {
|
|
1059
|
+
return str.split("-").reduce((str2, word) => {
|
|
1060
|
+
return str2 + word[0].toUpperCase() + word.slice(1);
|
|
1061
|
+
});
|
|
1062
|
+
}
|
|
1063
|
+
function splitOptionFlags(flags) {
|
|
1064
|
+
let shortFlag;
|
|
1065
|
+
let longFlag;
|
|
1066
|
+
const shortFlagExp = /^-[^-]$/;
|
|
1067
|
+
const longFlagExp = /^--[^-]/;
|
|
1068
|
+
const flagParts = flags.split(/[ |,]+/).concat("guard");
|
|
1069
|
+
if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
|
|
1070
|
+
if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
|
|
1071
|
+
if (!shortFlag && shortFlagExp.test(flagParts[0]))
|
|
1072
|
+
shortFlag = flagParts.shift();
|
|
1073
|
+
if (!shortFlag && longFlagExp.test(flagParts[0])) {
|
|
1074
|
+
shortFlag = longFlag;
|
|
1075
|
+
longFlag = flagParts.shift();
|
|
1076
|
+
}
|
|
1077
|
+
if (flagParts[0].startsWith("-")) {
|
|
1078
|
+
const unsupportedFlag = flagParts[0];
|
|
1079
|
+
const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
|
|
1080
|
+
if (/^-[^-][^-]/.test(unsupportedFlag))
|
|
1081
|
+
throw new Error(
|
|
1082
|
+
`${baseError}
|
|
1083
|
+
- a short flag is a single dash and a single character
|
|
1084
|
+
- either use a single dash and a single character (for a short flag)
|
|
1085
|
+
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`
|
|
1086
|
+
);
|
|
1087
|
+
if (shortFlagExp.test(unsupportedFlag))
|
|
1088
|
+
throw new Error(`${baseError}
|
|
1089
|
+
- too many short flags`);
|
|
1090
|
+
if (longFlagExp.test(unsupportedFlag))
|
|
1091
|
+
throw new Error(`${baseError}
|
|
1092
|
+
- too many long flags`);
|
|
1093
|
+
throw new Error(`${baseError}
|
|
1094
|
+
- unrecognised flag format`);
|
|
1095
|
+
}
|
|
1096
|
+
if (shortFlag === void 0 && longFlag === void 0)
|
|
1097
|
+
throw new Error(
|
|
1098
|
+
`option creation failed due to no flags found in '${flags}'.`
|
|
1099
|
+
);
|
|
1100
|
+
return { shortFlag, longFlag };
|
|
1101
|
+
}
|
|
1102
|
+
exports2.Option = Option2;
|
|
1103
|
+
exports2.DualOptions = DualOptions;
|
|
1104
|
+
}
|
|
1105
|
+
});
|
|
1106
|
+
|
|
1107
|
+
// node_modules/commander/lib/suggestSimilar.js
|
|
1108
|
+
var require_suggestSimilar = __commonJS({
|
|
1109
|
+
"node_modules/commander/lib/suggestSimilar.js"(exports2) {
|
|
1110
|
+
var maxDistance = 3;
|
|
1111
|
+
function editDistance(a, b) {
|
|
1112
|
+
if (Math.abs(a.length - b.length) > maxDistance)
|
|
1113
|
+
return Math.max(a.length, b.length);
|
|
1114
|
+
const d = [];
|
|
1115
|
+
for (let i = 0; i <= a.length; i++) {
|
|
1116
|
+
d[i] = [i];
|
|
1117
|
+
}
|
|
1118
|
+
for (let j = 0; j <= b.length; j++) {
|
|
1119
|
+
d[0][j] = j;
|
|
1120
|
+
}
|
|
1121
|
+
for (let j = 1; j <= b.length; j++) {
|
|
1122
|
+
for (let i = 1; i <= a.length; i++) {
|
|
1123
|
+
let cost = 1;
|
|
1124
|
+
if (a[i - 1] === b[j - 1]) {
|
|
1125
|
+
cost = 0;
|
|
1126
|
+
} else {
|
|
1127
|
+
cost = 1;
|
|
1128
|
+
}
|
|
1129
|
+
d[i][j] = Math.min(
|
|
1130
|
+
d[i - 1][j] + 1,
|
|
1131
|
+
// deletion
|
|
1132
|
+
d[i][j - 1] + 1,
|
|
1133
|
+
// insertion
|
|
1134
|
+
d[i - 1][j - 1] + cost
|
|
1135
|
+
// substitution
|
|
1136
|
+
);
|
|
1137
|
+
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
|
|
1138
|
+
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
}
|
|
1142
|
+
return d[a.length][b.length];
|
|
1143
|
+
}
|
|
1144
|
+
function suggestSimilar(word, candidates) {
|
|
1145
|
+
if (!candidates || candidates.length === 0) return "";
|
|
1146
|
+
candidates = Array.from(new Set(candidates));
|
|
1147
|
+
const searchingOptions = word.startsWith("--");
|
|
1148
|
+
if (searchingOptions) {
|
|
1149
|
+
word = word.slice(2);
|
|
1150
|
+
candidates = candidates.map((candidate) => candidate.slice(2));
|
|
1151
|
+
}
|
|
1152
|
+
let similar = [];
|
|
1153
|
+
let bestDistance = maxDistance;
|
|
1154
|
+
const minSimilarity = 0.4;
|
|
1155
|
+
candidates.forEach((candidate) => {
|
|
1156
|
+
if (candidate.length <= 1) return;
|
|
1157
|
+
const distance = editDistance(word, candidate);
|
|
1158
|
+
const length = Math.max(word.length, candidate.length);
|
|
1159
|
+
const similarity = (length - distance) / length;
|
|
1160
|
+
if (similarity > minSimilarity) {
|
|
1161
|
+
if (distance < bestDistance) {
|
|
1162
|
+
bestDistance = distance;
|
|
1163
|
+
similar = [candidate];
|
|
1164
|
+
} else if (distance === bestDistance) {
|
|
1165
|
+
similar.push(candidate);
|
|
1166
|
+
}
|
|
1167
|
+
}
|
|
1168
|
+
});
|
|
1169
|
+
similar.sort((a, b) => a.localeCompare(b));
|
|
1170
|
+
if (searchingOptions) {
|
|
1171
|
+
similar = similar.map((candidate) => `--${candidate}`);
|
|
1172
|
+
}
|
|
1173
|
+
if (similar.length > 1) {
|
|
1174
|
+
return `
|
|
1175
|
+
(Did you mean one of ${similar.join(", ")}?)`;
|
|
1176
|
+
}
|
|
1177
|
+
if (similar.length === 1) {
|
|
1178
|
+
return `
|
|
1179
|
+
(Did you mean ${similar[0]}?)`;
|
|
1180
|
+
}
|
|
1181
|
+
return "";
|
|
1182
|
+
}
|
|
1183
|
+
exports2.suggestSimilar = suggestSimilar;
|
|
1184
|
+
}
|
|
1185
|
+
});
|
|
1186
|
+
|
|
1187
|
+
// node_modules/commander/lib/command.js
|
|
1188
|
+
var require_command = __commonJS({
|
|
1189
|
+
"node_modules/commander/lib/command.js"(exports2) {
|
|
1190
|
+
var EventEmitter = require("node:events").EventEmitter;
|
|
1191
|
+
var childProcess = require("node:child_process");
|
|
1192
|
+
var path = require("node:path");
|
|
1193
|
+
var fs = require("node:fs");
|
|
1194
|
+
var process2 = require("node:process");
|
|
1195
|
+
var { Argument: Argument2, humanReadableArgName } = require_argument();
|
|
1196
|
+
var { CommanderError: CommanderError2 } = require_error();
|
|
1197
|
+
var { Help: Help2, stripColor } = require_help();
|
|
1198
|
+
var { Option: Option2, DualOptions } = require_option();
|
|
1199
|
+
var { suggestSimilar } = require_suggestSimilar();
|
|
1200
|
+
var Command2 = class _Command extends EventEmitter {
|
|
1201
|
+
/**
|
|
1202
|
+
* Initialize a new `Command`.
|
|
1203
|
+
*
|
|
1204
|
+
* @param {string} [name]
|
|
1205
|
+
*/
|
|
1206
|
+
constructor(name) {
|
|
1207
|
+
super();
|
|
1208
|
+
this.commands = [];
|
|
1209
|
+
this.options = [];
|
|
1210
|
+
this.parent = null;
|
|
1211
|
+
this._allowUnknownOption = false;
|
|
1212
|
+
this._allowExcessArguments = false;
|
|
1213
|
+
this.registeredArguments = [];
|
|
1214
|
+
this._args = this.registeredArguments;
|
|
1215
|
+
this.args = [];
|
|
1216
|
+
this.rawArgs = [];
|
|
1217
|
+
this.processedArgs = [];
|
|
1218
|
+
this._scriptPath = null;
|
|
1219
|
+
this._name = name || "";
|
|
1220
|
+
this._optionValues = {};
|
|
1221
|
+
this._optionValueSources = {};
|
|
1222
|
+
this._storeOptionsAsProperties = false;
|
|
1223
|
+
this._actionHandler = null;
|
|
1224
|
+
this._executableHandler = false;
|
|
1225
|
+
this._executableFile = null;
|
|
1226
|
+
this._executableDir = null;
|
|
1227
|
+
this._defaultCommandName = null;
|
|
1228
|
+
this._exitCallback = null;
|
|
1229
|
+
this._aliases = [];
|
|
1230
|
+
this._combineFlagAndOptionalValue = true;
|
|
1231
|
+
this._description = "";
|
|
1232
|
+
this._summary = "";
|
|
1233
|
+
this._argsDescription = void 0;
|
|
1234
|
+
this._enablePositionalOptions = false;
|
|
1235
|
+
this._passThroughOptions = false;
|
|
1236
|
+
this._lifeCycleHooks = {};
|
|
1237
|
+
this._showHelpAfterError = false;
|
|
1238
|
+
this._showSuggestionAfterError = true;
|
|
1239
|
+
this._savedState = null;
|
|
1240
|
+
this._outputConfiguration = {
|
|
1241
|
+
writeOut: (str) => process2.stdout.write(str),
|
|
1242
|
+
writeErr: (str) => process2.stderr.write(str),
|
|
1243
|
+
outputError: (str, write) => write(str),
|
|
1244
|
+
getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
|
|
1245
|
+
getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
|
|
1246
|
+
getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
|
|
1247
|
+
getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
|
|
1248
|
+
stripColor: (str) => stripColor(str)
|
|
1249
|
+
};
|
|
1250
|
+
this._hidden = false;
|
|
1251
|
+
this._helpOption = void 0;
|
|
1252
|
+
this._addImplicitHelpCommand = void 0;
|
|
1253
|
+
this._helpCommand = void 0;
|
|
1254
|
+
this._helpConfiguration = {};
|
|
1255
|
+
this._helpGroupHeading = void 0;
|
|
1256
|
+
this._defaultCommandGroup = void 0;
|
|
1257
|
+
this._defaultOptionGroup = void 0;
|
|
1258
|
+
}
|
|
1259
|
+
/**
|
|
1260
|
+
* Copy settings that are useful to have in common across root command and subcommands.
|
|
1261
|
+
*
|
|
1262
|
+
* (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
|
|
1263
|
+
*
|
|
1264
|
+
* @param {Command} sourceCommand
|
|
1265
|
+
* @return {Command} `this` command for chaining
|
|
1266
|
+
*/
|
|
1267
|
+
copyInheritedSettings(sourceCommand) {
|
|
1268
|
+
this._outputConfiguration = sourceCommand._outputConfiguration;
|
|
1269
|
+
this._helpOption = sourceCommand._helpOption;
|
|
1270
|
+
this._helpCommand = sourceCommand._helpCommand;
|
|
1271
|
+
this._helpConfiguration = sourceCommand._helpConfiguration;
|
|
1272
|
+
this._exitCallback = sourceCommand._exitCallback;
|
|
1273
|
+
this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
|
|
1274
|
+
this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
|
|
1275
|
+
this._allowExcessArguments = sourceCommand._allowExcessArguments;
|
|
1276
|
+
this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
|
|
1277
|
+
this._showHelpAfterError = sourceCommand._showHelpAfterError;
|
|
1278
|
+
this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
|
|
1279
|
+
return this;
|
|
1280
|
+
}
|
|
1281
|
+
/**
|
|
1282
|
+
* @returns {Command[]}
|
|
1283
|
+
* @private
|
|
1284
|
+
*/
|
|
1285
|
+
_getCommandAndAncestors() {
|
|
1286
|
+
const result = [];
|
|
1287
|
+
for (let command = this; command; command = command.parent) {
|
|
1288
|
+
result.push(command);
|
|
1289
|
+
}
|
|
1290
|
+
return result;
|
|
1291
|
+
}
|
|
1292
|
+
/**
|
|
1293
|
+
* Define a command.
|
|
1294
|
+
*
|
|
1295
|
+
* There are two styles of command: pay attention to where to put the description.
|
|
1296
|
+
*
|
|
1297
|
+
* @example
|
|
1298
|
+
* // Command implemented using action handler (description is supplied separately to `.command`)
|
|
1299
|
+
* program
|
|
1300
|
+
* .command('clone <source> [destination]')
|
|
1301
|
+
* .description('clone a repository into a newly created directory')
|
|
1302
|
+
* .action((source, destination) => {
|
|
1303
|
+
* console.log('clone command called');
|
|
1304
|
+
* });
|
|
1305
|
+
*
|
|
1306
|
+
* // Command implemented using separate executable file (description is second parameter to `.command`)
|
|
1307
|
+
* program
|
|
1308
|
+
* .command('start <service>', 'start named service')
|
|
1309
|
+
* .command('stop [service]', 'stop named service, or all if no name supplied');
|
|
1310
|
+
*
|
|
1311
|
+
* @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
|
|
1312
|
+
* @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
|
|
1313
|
+
* @param {object} [execOpts] - configuration options (for executable)
|
|
1314
|
+
* @return {Command} returns new command for action handler, or `this` for executable command
|
|
1315
|
+
*/
|
|
1316
|
+
command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
|
|
1317
|
+
let desc = actionOptsOrExecDesc;
|
|
1318
|
+
let opts = execOpts;
|
|
1319
|
+
if (typeof desc === "object" && desc !== null) {
|
|
1320
|
+
opts = desc;
|
|
1321
|
+
desc = null;
|
|
1322
|
+
}
|
|
1323
|
+
opts = opts || {};
|
|
1324
|
+
const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
|
|
1325
|
+
const cmd = this.createCommand(name);
|
|
1326
|
+
if (desc) {
|
|
1327
|
+
cmd.description(desc);
|
|
1328
|
+
cmd._executableHandler = true;
|
|
1329
|
+
}
|
|
1330
|
+
if (opts.isDefault) this._defaultCommandName = cmd._name;
|
|
1331
|
+
cmd._hidden = !!(opts.noHelp || opts.hidden);
|
|
1332
|
+
cmd._executableFile = opts.executableFile || null;
|
|
1333
|
+
if (args) cmd.arguments(args);
|
|
1334
|
+
this._registerCommand(cmd);
|
|
1335
|
+
cmd.parent = this;
|
|
1336
|
+
cmd.copyInheritedSettings(this);
|
|
1337
|
+
if (desc) return this;
|
|
1338
|
+
return cmd;
|
|
1339
|
+
}
|
|
1340
|
+
/**
|
|
1341
|
+
* Factory routine to create a new unattached command.
|
|
1342
|
+
*
|
|
1343
|
+
* See .command() for creating an attached subcommand, which uses this routine to
|
|
1344
|
+
* create the command. You can override createCommand to customise subcommands.
|
|
1345
|
+
*
|
|
1346
|
+
* @param {string} [name]
|
|
1347
|
+
* @return {Command} new command
|
|
1348
|
+
*/
|
|
1349
|
+
createCommand(name) {
|
|
1350
|
+
return new _Command(name);
|
|
1351
|
+
}
|
|
1352
|
+
/**
|
|
1353
|
+
* You can customise the help with a subclass of Help by overriding createHelp,
|
|
1354
|
+
* or by overriding Help properties using configureHelp().
|
|
1355
|
+
*
|
|
1356
|
+
* @return {Help}
|
|
1357
|
+
*/
|
|
1358
|
+
createHelp() {
|
|
1359
|
+
return Object.assign(new Help2(), this.configureHelp());
|
|
1360
|
+
}
|
|
1361
|
+
/**
|
|
1362
|
+
* You can customise the help by overriding Help properties using configureHelp(),
|
|
1363
|
+
* or with a subclass of Help by overriding createHelp().
|
|
1364
|
+
*
|
|
1365
|
+
* @param {object} [configuration] - configuration options
|
|
1366
|
+
* @return {(Command | object)} `this` command for chaining, or stored configuration
|
|
1367
|
+
*/
|
|
1368
|
+
configureHelp(configuration) {
|
|
1369
|
+
if (configuration === void 0) return this._helpConfiguration;
|
|
1370
|
+
this._helpConfiguration = configuration;
|
|
1371
|
+
return this;
|
|
1372
|
+
}
|
|
1373
|
+
/**
|
|
1374
|
+
* The default output goes to stdout and stderr. You can customise this for special
|
|
1375
|
+
* applications. You can also customise the display of errors by overriding outputError.
|
|
1376
|
+
*
|
|
1377
|
+
* The configuration properties are all functions:
|
|
1378
|
+
*
|
|
1379
|
+
* // change how output being written, defaults to stdout and stderr
|
|
1380
|
+
* writeOut(str)
|
|
1381
|
+
* writeErr(str)
|
|
1382
|
+
* // change how output being written for errors, defaults to writeErr
|
|
1383
|
+
* outputError(str, write) // used for displaying errors and not used for displaying help
|
|
1384
|
+
* // specify width for wrapping help
|
|
1385
|
+
* getOutHelpWidth()
|
|
1386
|
+
* getErrHelpWidth()
|
|
1387
|
+
* // color support, currently only used with Help
|
|
1388
|
+
* getOutHasColors()
|
|
1389
|
+
* getErrHasColors()
|
|
1390
|
+
* stripColor() // used to remove ANSI escape codes if output does not have colors
|
|
1391
|
+
*
|
|
1392
|
+
* @param {object} [configuration] - configuration options
|
|
1393
|
+
* @return {(Command | object)} `this` command for chaining, or stored configuration
|
|
1394
|
+
*/
|
|
1395
|
+
configureOutput(configuration) {
|
|
1396
|
+
if (configuration === void 0) return this._outputConfiguration;
|
|
1397
|
+
this._outputConfiguration = {
|
|
1398
|
+
...this._outputConfiguration,
|
|
1399
|
+
...configuration
|
|
1400
|
+
};
|
|
1401
|
+
return this;
|
|
1402
|
+
}
|
|
1403
|
+
/**
|
|
1404
|
+
* Display the help or a custom message after an error occurs.
|
|
1405
|
+
*
|
|
1406
|
+
* @param {(boolean|string)} [displayHelp]
|
|
1407
|
+
* @return {Command} `this` command for chaining
|
|
1408
|
+
*/
|
|
1409
|
+
showHelpAfterError(displayHelp = true) {
|
|
1410
|
+
if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
|
|
1411
|
+
this._showHelpAfterError = displayHelp;
|
|
1412
|
+
return this;
|
|
1413
|
+
}
|
|
1414
|
+
/**
|
|
1415
|
+
* Display suggestion of similar commands for unknown commands, or options for unknown options.
|
|
1416
|
+
*
|
|
1417
|
+
* @param {boolean} [displaySuggestion]
|
|
1418
|
+
* @return {Command} `this` command for chaining
|
|
1419
|
+
*/
|
|
1420
|
+
showSuggestionAfterError(displaySuggestion = true) {
|
|
1421
|
+
this._showSuggestionAfterError = !!displaySuggestion;
|
|
1422
|
+
return this;
|
|
1423
|
+
}
|
|
1424
|
+
/**
|
|
1425
|
+
* Add a prepared subcommand.
|
|
1426
|
+
*
|
|
1427
|
+
* See .command() for creating an attached subcommand which inherits settings from its parent.
|
|
1428
|
+
*
|
|
1429
|
+
* @param {Command} cmd - new subcommand
|
|
1430
|
+
* @param {object} [opts] - configuration options
|
|
1431
|
+
* @return {Command} `this` command for chaining
|
|
1432
|
+
*/
|
|
1433
|
+
addCommand(cmd, opts) {
|
|
1434
|
+
if (!cmd._name) {
|
|
1435
|
+
throw new Error(`Command passed to .addCommand() must have a name
|
|
1436
|
+
- specify the name in Command constructor or using .name()`);
|
|
1437
|
+
}
|
|
1438
|
+
opts = opts || {};
|
|
1439
|
+
if (opts.isDefault) this._defaultCommandName = cmd._name;
|
|
1440
|
+
if (opts.noHelp || opts.hidden) cmd._hidden = true;
|
|
1441
|
+
this._registerCommand(cmd);
|
|
1442
|
+
cmd.parent = this;
|
|
1443
|
+
cmd._checkForBrokenPassThrough();
|
|
1444
|
+
return this;
|
|
1445
|
+
}
|
|
1446
|
+
/**
|
|
1447
|
+
* Factory routine to create a new unattached argument.
|
|
1448
|
+
*
|
|
1449
|
+
* See .argument() for creating an attached argument, which uses this routine to
|
|
1450
|
+
* create the argument. You can override createArgument to return a custom argument.
|
|
1451
|
+
*
|
|
1452
|
+
* @param {string} name
|
|
1453
|
+
* @param {string} [description]
|
|
1454
|
+
* @return {Argument} new argument
|
|
1455
|
+
*/
|
|
1456
|
+
createArgument(name, description) {
|
|
1457
|
+
return new Argument2(name, description);
|
|
1458
|
+
}
|
|
1459
|
+
/**
|
|
1460
|
+
* Define argument syntax for command.
|
|
1461
|
+
*
|
|
1462
|
+
* The default is that the argument is required, and you can explicitly
|
|
1463
|
+
* indicate this with <> around the name. Put [] around the name for an optional argument.
|
|
1464
|
+
*
|
|
1465
|
+
* @example
|
|
1466
|
+
* program.argument('<input-file>');
|
|
1467
|
+
* program.argument('[output-file]');
|
|
1468
|
+
*
|
|
1469
|
+
* @param {string} name
|
|
1470
|
+
* @param {string} [description]
|
|
1471
|
+
* @param {(Function|*)} [parseArg] - custom argument processing function or default value
|
|
1472
|
+
* @param {*} [defaultValue]
|
|
1473
|
+
* @return {Command} `this` command for chaining
|
|
1474
|
+
*/
|
|
1475
|
+
argument(name, description, parseArg, defaultValue) {
|
|
1476
|
+
const argument = this.createArgument(name, description);
|
|
1477
|
+
if (typeof parseArg === "function") {
|
|
1478
|
+
argument.default(defaultValue).argParser(parseArg);
|
|
1479
|
+
} else {
|
|
1480
|
+
argument.default(parseArg);
|
|
1481
|
+
}
|
|
1482
|
+
this.addArgument(argument);
|
|
1483
|
+
return this;
|
|
1484
|
+
}
|
|
1485
|
+
/**
|
|
1486
|
+
* Define argument syntax for command, adding multiple at once (without descriptions).
|
|
1487
|
+
*
|
|
1488
|
+
* See also .argument().
|
|
1489
|
+
*
|
|
1490
|
+
* @example
|
|
1491
|
+
* program.arguments('<cmd> [env]');
|
|
1492
|
+
*
|
|
1493
|
+
* @param {string} names
|
|
1494
|
+
* @return {Command} `this` command for chaining
|
|
1495
|
+
*/
|
|
1496
|
+
arguments(names) {
|
|
1497
|
+
names.trim().split(/ +/).forEach((detail) => {
|
|
1498
|
+
this.argument(detail);
|
|
1499
|
+
});
|
|
1500
|
+
return this;
|
|
1501
|
+
}
|
|
1502
|
+
/**
|
|
1503
|
+
* Define argument syntax for command, adding a prepared argument.
|
|
1504
|
+
*
|
|
1505
|
+
* @param {Argument} argument
|
|
1506
|
+
* @return {Command} `this` command for chaining
|
|
1507
|
+
*/
|
|
1508
|
+
addArgument(argument) {
|
|
1509
|
+
const previousArgument = this.registeredArguments.slice(-1)[0];
|
|
1510
|
+
if (previousArgument?.variadic) {
|
|
1511
|
+
throw new Error(
|
|
1512
|
+
`only the last argument can be variadic '${previousArgument.name()}'`
|
|
1513
|
+
);
|
|
1514
|
+
}
|
|
1515
|
+
if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
|
|
1516
|
+
throw new Error(
|
|
1517
|
+
`a default value for a required argument is never used: '${argument.name()}'`
|
|
1518
|
+
);
|
|
1519
|
+
}
|
|
1520
|
+
this.registeredArguments.push(argument);
|
|
1521
|
+
return this;
|
|
1522
|
+
}
|
|
1523
|
+
/**
|
|
1524
|
+
* Customise or override default help command. By default a help command is automatically added if your command has subcommands.
|
|
1525
|
+
*
|
|
1526
|
+
* @example
|
|
1527
|
+
* program.helpCommand('help [cmd]');
|
|
1528
|
+
* program.helpCommand('help [cmd]', 'show help');
|
|
1529
|
+
* program.helpCommand(false); // suppress default help command
|
|
1530
|
+
* program.helpCommand(true); // add help command even if no subcommands
|
|
1531
|
+
*
|
|
1532
|
+
* @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
|
|
1533
|
+
* @param {string} [description] - custom description
|
|
1534
|
+
* @return {Command} `this` command for chaining
|
|
1535
|
+
*/
|
|
1536
|
+
helpCommand(enableOrNameAndArgs, description) {
|
|
1537
|
+
if (typeof enableOrNameAndArgs === "boolean") {
|
|
1538
|
+
this._addImplicitHelpCommand = enableOrNameAndArgs;
|
|
1539
|
+
if (enableOrNameAndArgs && this._defaultCommandGroup) {
|
|
1540
|
+
this._initCommandGroup(this._getHelpCommand());
|
|
1541
|
+
}
|
|
1542
|
+
return this;
|
|
1543
|
+
}
|
|
1544
|
+
const nameAndArgs = enableOrNameAndArgs ?? "help [command]";
|
|
1545
|
+
const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
|
|
1546
|
+
const helpDescription = description ?? "display help for command";
|
|
1547
|
+
const helpCommand = this.createCommand(helpName);
|
|
1548
|
+
helpCommand.helpOption(false);
|
|
1549
|
+
if (helpArgs) helpCommand.arguments(helpArgs);
|
|
1550
|
+
if (helpDescription) helpCommand.description(helpDescription);
|
|
1551
|
+
this._addImplicitHelpCommand = true;
|
|
1552
|
+
this._helpCommand = helpCommand;
|
|
1553
|
+
if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
|
|
1554
|
+
return this;
|
|
1555
|
+
}
|
|
1556
|
+
/**
|
|
1557
|
+
* Add prepared custom help command.
|
|
1558
|
+
*
|
|
1559
|
+
* @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
|
|
1560
|
+
* @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
|
|
1561
|
+
* @return {Command} `this` command for chaining
|
|
1562
|
+
*/
|
|
1563
|
+
addHelpCommand(helpCommand, deprecatedDescription) {
|
|
1564
|
+
if (typeof helpCommand !== "object") {
|
|
1565
|
+
this.helpCommand(helpCommand, deprecatedDescription);
|
|
1566
|
+
return this;
|
|
1567
|
+
}
|
|
1568
|
+
this._addImplicitHelpCommand = true;
|
|
1569
|
+
this._helpCommand = helpCommand;
|
|
1570
|
+
this._initCommandGroup(helpCommand);
|
|
1571
|
+
return this;
|
|
1572
|
+
}
|
|
1573
|
+
/**
|
|
1574
|
+
* Lazy create help command.
|
|
1575
|
+
*
|
|
1576
|
+
* @return {(Command|null)}
|
|
1577
|
+
* @package
|
|
1578
|
+
*/
|
|
1579
|
+
_getHelpCommand() {
|
|
1580
|
+
const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
|
|
1581
|
+
if (hasImplicitHelpCommand) {
|
|
1582
|
+
if (this._helpCommand === void 0) {
|
|
1583
|
+
this.helpCommand(void 0, void 0);
|
|
1584
|
+
}
|
|
1585
|
+
return this._helpCommand;
|
|
1586
|
+
}
|
|
1587
|
+
return null;
|
|
1588
|
+
}
|
|
1589
|
+
/**
|
|
1590
|
+
* Add hook for life cycle event.
|
|
1591
|
+
*
|
|
1592
|
+
* @param {string} event
|
|
1593
|
+
* @param {Function} listener
|
|
1594
|
+
* @return {Command} `this` command for chaining
|
|
1595
|
+
*/
|
|
1596
|
+
hook(event, listener) {
|
|
1597
|
+
const allowedValues = ["preSubcommand", "preAction", "postAction"];
|
|
1598
|
+
if (!allowedValues.includes(event)) {
|
|
1599
|
+
throw new Error(`Unexpected value for event passed to hook : '${event}'.
|
|
1600
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
1601
|
+
}
|
|
1602
|
+
if (this._lifeCycleHooks[event]) {
|
|
1603
|
+
this._lifeCycleHooks[event].push(listener);
|
|
1604
|
+
} else {
|
|
1605
|
+
this._lifeCycleHooks[event] = [listener];
|
|
1606
|
+
}
|
|
1607
|
+
return this;
|
|
1608
|
+
}
|
|
1609
|
+
/**
|
|
1610
|
+
* Register callback to use as replacement for calling process.exit.
|
|
1611
|
+
*
|
|
1612
|
+
* @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
|
|
1613
|
+
* @return {Command} `this` command for chaining
|
|
1614
|
+
*/
|
|
1615
|
+
exitOverride(fn) {
|
|
1616
|
+
if (fn) {
|
|
1617
|
+
this._exitCallback = fn;
|
|
1618
|
+
} else {
|
|
1619
|
+
this._exitCallback = (err) => {
|
|
1620
|
+
if (err.code !== "commander.executeSubCommandAsync") {
|
|
1621
|
+
throw err;
|
|
1622
|
+
} else {
|
|
1623
|
+
}
|
|
1624
|
+
};
|
|
1625
|
+
}
|
|
1626
|
+
return this;
|
|
1627
|
+
}
|
|
1628
|
+
/**
|
|
1629
|
+
* Call process.exit, and _exitCallback if defined.
|
|
1630
|
+
*
|
|
1631
|
+
* @param {number} exitCode exit code for using with process.exit
|
|
1632
|
+
* @param {string} code an id string representing the error
|
|
1633
|
+
* @param {string} message human-readable description of the error
|
|
1634
|
+
* @return never
|
|
1635
|
+
* @private
|
|
1636
|
+
*/
|
|
1637
|
+
_exit(exitCode, code, message) {
|
|
1638
|
+
if (this._exitCallback) {
|
|
1639
|
+
this._exitCallback(new CommanderError2(exitCode, code, message));
|
|
1640
|
+
}
|
|
1641
|
+
process2.exit(exitCode);
|
|
1642
|
+
}
|
|
1643
|
+
/**
|
|
1644
|
+
* Register callback `fn` for the command.
|
|
1645
|
+
*
|
|
1646
|
+
* @example
|
|
1647
|
+
* program
|
|
1648
|
+
* .command('serve')
|
|
1649
|
+
* .description('start service')
|
|
1650
|
+
* .action(function() {
|
|
1651
|
+
* // do work here
|
|
1652
|
+
* });
|
|
1653
|
+
*
|
|
1654
|
+
* @param {Function} fn
|
|
1655
|
+
* @return {Command} `this` command for chaining
|
|
1656
|
+
*/
|
|
1657
|
+
action(fn) {
|
|
1658
|
+
const listener = (args) => {
|
|
1659
|
+
const expectedArgsCount = this.registeredArguments.length;
|
|
1660
|
+
const actionArgs = args.slice(0, expectedArgsCount);
|
|
1661
|
+
if (this._storeOptionsAsProperties) {
|
|
1662
|
+
actionArgs[expectedArgsCount] = this;
|
|
1663
|
+
} else {
|
|
1664
|
+
actionArgs[expectedArgsCount] = this.opts();
|
|
1665
|
+
}
|
|
1666
|
+
actionArgs.push(this);
|
|
1667
|
+
return fn.apply(this, actionArgs);
|
|
1668
|
+
};
|
|
1669
|
+
this._actionHandler = listener;
|
|
1670
|
+
return this;
|
|
1671
|
+
}
|
|
1672
|
+
/**
|
|
1673
|
+
* Factory routine to create a new unattached option.
|
|
1674
|
+
*
|
|
1675
|
+
* See .option() for creating an attached option, which uses this routine to
|
|
1676
|
+
* create the option. You can override createOption to return a custom option.
|
|
1677
|
+
*
|
|
1678
|
+
* @param {string} flags
|
|
1679
|
+
* @param {string} [description]
|
|
1680
|
+
* @return {Option} new option
|
|
1681
|
+
*/
|
|
1682
|
+
createOption(flags, description) {
|
|
1683
|
+
return new Option2(flags, description);
|
|
1684
|
+
}
|
|
1685
|
+
/**
|
|
1686
|
+
* Wrap parseArgs to catch 'commander.invalidArgument'.
|
|
1687
|
+
*
|
|
1688
|
+
* @param {(Option | Argument)} target
|
|
1689
|
+
* @param {string} value
|
|
1690
|
+
* @param {*} previous
|
|
1691
|
+
* @param {string} invalidArgumentMessage
|
|
1692
|
+
* @private
|
|
1693
|
+
*/
|
|
1694
|
+
_callParseArg(target, value, previous, invalidArgumentMessage) {
|
|
1695
|
+
try {
|
|
1696
|
+
return target.parseArg(value, previous);
|
|
1697
|
+
} catch (err) {
|
|
1698
|
+
if (err.code === "commander.invalidArgument") {
|
|
1699
|
+
const message = `${invalidArgumentMessage} ${err.message}`;
|
|
1700
|
+
this.error(message, { exitCode: err.exitCode, code: err.code });
|
|
1701
|
+
}
|
|
1702
|
+
throw err;
|
|
1703
|
+
}
|
|
1704
|
+
}
|
|
1705
|
+
/**
|
|
1706
|
+
* Check for option flag conflicts.
|
|
1707
|
+
* Register option if no conflicts found, or throw on conflict.
|
|
1708
|
+
*
|
|
1709
|
+
* @param {Option} option
|
|
1710
|
+
* @private
|
|
1711
|
+
*/
|
|
1712
|
+
_registerOption(option) {
|
|
1713
|
+
const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
|
|
1714
|
+
if (matchingOption) {
|
|
1715
|
+
const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
|
|
1716
|
+
throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
|
|
1717
|
+
- already used by option '${matchingOption.flags}'`);
|
|
1718
|
+
}
|
|
1719
|
+
this._initOptionGroup(option);
|
|
1720
|
+
this.options.push(option);
|
|
1721
|
+
}
|
|
1722
|
+
/**
|
|
1723
|
+
* Check for command name and alias conflicts with existing commands.
|
|
1724
|
+
* Register command if no conflicts found, or throw on conflict.
|
|
1725
|
+
*
|
|
1726
|
+
* @param {Command} command
|
|
1727
|
+
* @private
|
|
1728
|
+
*/
|
|
1729
|
+
_registerCommand(command) {
|
|
1730
|
+
const knownBy = (cmd) => {
|
|
1731
|
+
return [cmd.name()].concat(cmd.aliases());
|
|
1732
|
+
};
|
|
1733
|
+
const alreadyUsed = knownBy(command).find(
|
|
1734
|
+
(name) => this._findCommand(name)
|
|
1735
|
+
);
|
|
1736
|
+
if (alreadyUsed) {
|
|
1737
|
+
const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
|
|
1738
|
+
const newCmd = knownBy(command).join("|");
|
|
1739
|
+
throw new Error(
|
|
1740
|
+
`cannot add command '${newCmd}' as already have command '${existingCmd}'`
|
|
1741
|
+
);
|
|
1742
|
+
}
|
|
1743
|
+
this._initCommandGroup(command);
|
|
1744
|
+
this.commands.push(command);
|
|
1745
|
+
}
|
|
1746
|
+
/**
|
|
1747
|
+
* Add an option.
|
|
1748
|
+
*
|
|
1749
|
+
* @param {Option} option
|
|
1750
|
+
* @return {Command} `this` command for chaining
|
|
1751
|
+
*/
|
|
1752
|
+
addOption(option) {
|
|
1753
|
+
this._registerOption(option);
|
|
1754
|
+
const oname = option.name();
|
|
1755
|
+
const name = option.attributeName();
|
|
1756
|
+
if (option.negate) {
|
|
1757
|
+
const positiveLongFlag = option.long.replace(/^--no-/, "--");
|
|
1758
|
+
if (!this._findOption(positiveLongFlag)) {
|
|
1759
|
+
this.setOptionValueWithSource(
|
|
1760
|
+
name,
|
|
1761
|
+
option.defaultValue === void 0 ? true : option.defaultValue,
|
|
1762
|
+
"default"
|
|
1763
|
+
);
|
|
1764
|
+
}
|
|
1765
|
+
} else if (option.defaultValue !== void 0) {
|
|
1766
|
+
this.setOptionValueWithSource(name, option.defaultValue, "default");
|
|
1767
|
+
}
|
|
1768
|
+
const handleOptionValue = (val, invalidValueMessage, valueSource) => {
|
|
1769
|
+
if (val == null && option.presetArg !== void 0) {
|
|
1770
|
+
val = option.presetArg;
|
|
1771
|
+
}
|
|
1772
|
+
const oldValue = this.getOptionValue(name);
|
|
1773
|
+
if (val !== null && option.parseArg) {
|
|
1774
|
+
val = this._callParseArg(option, val, oldValue, invalidValueMessage);
|
|
1775
|
+
} else if (val !== null && option.variadic) {
|
|
1776
|
+
val = option._collectValue(val, oldValue);
|
|
1777
|
+
}
|
|
1778
|
+
if (val == null) {
|
|
1779
|
+
if (option.negate) {
|
|
1780
|
+
val = false;
|
|
1781
|
+
} else if (option.isBoolean() || option.optional) {
|
|
1782
|
+
val = true;
|
|
1783
|
+
} else {
|
|
1784
|
+
val = "";
|
|
1785
|
+
}
|
|
1786
|
+
}
|
|
1787
|
+
this.setOptionValueWithSource(name, val, valueSource);
|
|
1788
|
+
};
|
|
1789
|
+
this.on("option:" + oname, (val) => {
|
|
1790
|
+
const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
|
|
1791
|
+
handleOptionValue(val, invalidValueMessage, "cli");
|
|
1792
|
+
});
|
|
1793
|
+
if (option.envVar) {
|
|
1794
|
+
this.on("optionEnv:" + oname, (val) => {
|
|
1795
|
+
const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
|
|
1796
|
+
handleOptionValue(val, invalidValueMessage, "env");
|
|
1797
|
+
});
|
|
1798
|
+
}
|
|
1799
|
+
return this;
|
|
1800
|
+
}
|
|
1801
|
+
/**
|
|
1802
|
+
* Internal implementation shared by .option() and .requiredOption()
|
|
1803
|
+
*
|
|
1804
|
+
* @return {Command} `this` command for chaining
|
|
1805
|
+
* @private
|
|
1806
|
+
*/
|
|
1807
|
+
_optionEx(config, flags, description, fn, defaultValue) {
|
|
1808
|
+
if (typeof flags === "object" && flags instanceof Option2) {
|
|
1809
|
+
throw new Error(
|
|
1810
|
+
"To add an Option object use addOption() instead of option() or requiredOption()"
|
|
1811
|
+
);
|
|
1812
|
+
}
|
|
1813
|
+
const option = this.createOption(flags, description);
|
|
1814
|
+
option.makeOptionMandatory(!!config.mandatory);
|
|
1815
|
+
if (typeof fn === "function") {
|
|
1816
|
+
option.default(defaultValue).argParser(fn);
|
|
1817
|
+
} else if (fn instanceof RegExp) {
|
|
1818
|
+
const regex = fn;
|
|
1819
|
+
fn = (val, def) => {
|
|
1820
|
+
const m = regex.exec(val);
|
|
1821
|
+
return m ? m[0] : def;
|
|
1822
|
+
};
|
|
1823
|
+
option.default(defaultValue).argParser(fn);
|
|
1824
|
+
} else {
|
|
1825
|
+
option.default(fn);
|
|
1826
|
+
}
|
|
1827
|
+
return this.addOption(option);
|
|
1828
|
+
}
|
|
1829
|
+
/**
|
|
1830
|
+
* Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
|
|
1831
|
+
*
|
|
1832
|
+
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
|
|
1833
|
+
* option-argument is indicated by `<>` and an optional option-argument by `[]`.
|
|
1834
|
+
*
|
|
1835
|
+
* See the README for more details, and see also addOption() and requiredOption().
|
|
1836
|
+
*
|
|
1837
|
+
* @example
|
|
1838
|
+
* program
|
|
1839
|
+
* .option('-p, --pepper', 'add pepper')
|
|
1840
|
+
* .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
|
|
1841
|
+
* .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
|
|
1842
|
+
* .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
|
|
1843
|
+
*
|
|
1844
|
+
* @param {string} flags
|
|
1845
|
+
* @param {string} [description]
|
|
1846
|
+
* @param {(Function|*)} [parseArg] - custom option processing function or default value
|
|
1847
|
+
* @param {*} [defaultValue]
|
|
1848
|
+
* @return {Command} `this` command for chaining
|
|
1849
|
+
*/
|
|
1850
|
+
option(flags, description, parseArg, defaultValue) {
|
|
1851
|
+
return this._optionEx({}, flags, description, parseArg, defaultValue);
|
|
1852
|
+
}
|
|
1853
|
+
/**
|
|
1854
|
+
* Add a required option which must have a value after parsing. This usually means
|
|
1855
|
+
* the option must be specified on the command line. (Otherwise the same as .option().)
|
|
1856
|
+
*
|
|
1857
|
+
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
|
|
1858
|
+
*
|
|
1859
|
+
* @param {string} flags
|
|
1860
|
+
* @param {string} [description]
|
|
1861
|
+
* @param {(Function|*)} [parseArg] - custom option processing function or default value
|
|
1862
|
+
* @param {*} [defaultValue]
|
|
1863
|
+
* @return {Command} `this` command for chaining
|
|
1864
|
+
*/
|
|
1865
|
+
requiredOption(flags, description, parseArg, defaultValue) {
|
|
1866
|
+
return this._optionEx(
|
|
1867
|
+
{ mandatory: true },
|
|
1868
|
+
flags,
|
|
1869
|
+
description,
|
|
1870
|
+
parseArg,
|
|
1871
|
+
defaultValue
|
|
1872
|
+
);
|
|
1873
|
+
}
|
|
1874
|
+
/**
|
|
1875
|
+
* Alter parsing of short flags with optional values.
|
|
1876
|
+
*
|
|
1877
|
+
* @example
|
|
1878
|
+
* // for `.option('-f,--flag [value]'):
|
|
1879
|
+
* program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
|
|
1880
|
+
* program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
|
|
1881
|
+
*
|
|
1882
|
+
* @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
|
|
1883
|
+
* @return {Command} `this` command for chaining
|
|
1884
|
+
*/
|
|
1885
|
+
combineFlagAndOptionalValue(combine = true) {
|
|
1886
|
+
this._combineFlagAndOptionalValue = !!combine;
|
|
1887
|
+
return this;
|
|
1888
|
+
}
|
|
1889
|
+
/**
|
|
1890
|
+
* Allow unknown options on the command line.
|
|
1891
|
+
*
|
|
1892
|
+
* @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
|
|
1893
|
+
* @return {Command} `this` command for chaining
|
|
1894
|
+
*/
|
|
1895
|
+
allowUnknownOption(allowUnknown = true) {
|
|
1896
|
+
this._allowUnknownOption = !!allowUnknown;
|
|
1897
|
+
return this;
|
|
1898
|
+
}
|
|
1899
|
+
/**
|
|
1900
|
+
* Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
|
|
1901
|
+
*
|
|
1902
|
+
* @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
|
|
1903
|
+
* @return {Command} `this` command for chaining
|
|
1904
|
+
*/
|
|
1905
|
+
allowExcessArguments(allowExcess = true) {
|
|
1906
|
+
this._allowExcessArguments = !!allowExcess;
|
|
1907
|
+
return this;
|
|
1908
|
+
}
|
|
1909
|
+
/**
|
|
1910
|
+
* Enable positional options. Positional means global options are specified before subcommands which lets
|
|
1911
|
+
* subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
|
|
1912
|
+
* The default behaviour is non-positional and global options may appear anywhere on the command line.
|
|
1913
|
+
*
|
|
1914
|
+
* @param {boolean} [positional]
|
|
1915
|
+
* @return {Command} `this` command for chaining
|
|
1916
|
+
*/
|
|
1917
|
+
enablePositionalOptions(positional = true) {
|
|
1918
|
+
this._enablePositionalOptions = !!positional;
|
|
1919
|
+
return this;
|
|
1920
|
+
}
|
|
1921
|
+
/**
|
|
1922
|
+
* Pass through options that come after command-arguments rather than treat them as command-options,
|
|
1923
|
+
* so actual command-options come before command-arguments. Turning this on for a subcommand requires
|
|
1924
|
+
* positional options to have been enabled on the program (parent commands).
|
|
1925
|
+
* The default behaviour is non-positional and options may appear before or after command-arguments.
|
|
1926
|
+
*
|
|
1927
|
+
* @param {boolean} [passThrough] for unknown options.
|
|
1928
|
+
* @return {Command} `this` command for chaining
|
|
1929
|
+
*/
|
|
1930
|
+
passThroughOptions(passThrough = true) {
|
|
1931
|
+
this._passThroughOptions = !!passThrough;
|
|
1932
|
+
this._checkForBrokenPassThrough();
|
|
1933
|
+
return this;
|
|
1934
|
+
}
|
|
1935
|
+
/**
|
|
1936
|
+
* @private
|
|
1937
|
+
*/
|
|
1938
|
+
_checkForBrokenPassThrough() {
|
|
1939
|
+
if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
|
|
1940
|
+
throw new Error(
|
|
1941
|
+
`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
|
|
1942
|
+
);
|
|
1943
|
+
}
|
|
1944
|
+
}
|
|
1945
|
+
/**
|
|
1946
|
+
* Whether to store option values as properties on command object,
|
|
1947
|
+
* or store separately (specify false). In both cases the option values can be accessed using .opts().
|
|
1948
|
+
*
|
|
1949
|
+
* @param {boolean} [storeAsProperties=true]
|
|
1950
|
+
* @return {Command} `this` command for chaining
|
|
1951
|
+
*/
|
|
1952
|
+
storeOptionsAsProperties(storeAsProperties = true) {
|
|
1953
|
+
if (this.options.length) {
|
|
1954
|
+
throw new Error("call .storeOptionsAsProperties() before adding options");
|
|
1955
|
+
}
|
|
1956
|
+
if (Object.keys(this._optionValues).length) {
|
|
1957
|
+
throw new Error(
|
|
1958
|
+
"call .storeOptionsAsProperties() before setting option values"
|
|
1959
|
+
);
|
|
1960
|
+
}
|
|
1961
|
+
this._storeOptionsAsProperties = !!storeAsProperties;
|
|
1962
|
+
return this;
|
|
1963
|
+
}
|
|
1964
|
+
/**
|
|
1965
|
+
* Retrieve option value.
|
|
1966
|
+
*
|
|
1967
|
+
* @param {string} key
|
|
1968
|
+
* @return {object} value
|
|
1969
|
+
*/
|
|
1970
|
+
getOptionValue(key) {
|
|
1971
|
+
if (this._storeOptionsAsProperties) {
|
|
1972
|
+
return this[key];
|
|
1973
|
+
}
|
|
1974
|
+
return this._optionValues[key];
|
|
1975
|
+
}
|
|
1976
|
+
/**
|
|
1977
|
+
* Store option value.
|
|
1978
|
+
*
|
|
1979
|
+
* @param {string} key
|
|
1980
|
+
* @param {object} value
|
|
1981
|
+
* @return {Command} `this` command for chaining
|
|
1982
|
+
*/
|
|
1983
|
+
setOptionValue(key, value) {
|
|
1984
|
+
return this.setOptionValueWithSource(key, value, void 0);
|
|
1985
|
+
}
|
|
1986
|
+
/**
|
|
1987
|
+
* Store option value and where the value came from.
|
|
1988
|
+
*
|
|
1989
|
+
* @param {string} key
|
|
1990
|
+
* @param {object} value
|
|
1991
|
+
* @param {string} source - expected values are default/config/env/cli/implied
|
|
1992
|
+
* @return {Command} `this` command for chaining
|
|
1993
|
+
*/
|
|
1994
|
+
setOptionValueWithSource(key, value, source) {
|
|
1995
|
+
if (this._storeOptionsAsProperties) {
|
|
1996
|
+
this[key] = value;
|
|
1997
|
+
} else {
|
|
1998
|
+
this._optionValues[key] = value;
|
|
1999
|
+
}
|
|
2000
|
+
this._optionValueSources[key] = source;
|
|
2001
|
+
return this;
|
|
2002
|
+
}
|
|
2003
|
+
/**
|
|
2004
|
+
* Get source of option value.
|
|
2005
|
+
* Expected values are default | config | env | cli | implied
|
|
2006
|
+
*
|
|
2007
|
+
* @param {string} key
|
|
2008
|
+
* @return {string}
|
|
2009
|
+
*/
|
|
2010
|
+
getOptionValueSource(key) {
|
|
2011
|
+
return this._optionValueSources[key];
|
|
2012
|
+
}
|
|
2013
|
+
/**
|
|
2014
|
+
* Get source of option value. See also .optsWithGlobals().
|
|
2015
|
+
* Expected values are default | config | env | cli | implied
|
|
2016
|
+
*
|
|
2017
|
+
* @param {string} key
|
|
2018
|
+
* @return {string}
|
|
2019
|
+
*/
|
|
2020
|
+
getOptionValueSourceWithGlobals(key) {
|
|
2021
|
+
let source;
|
|
2022
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
2023
|
+
if (cmd.getOptionValueSource(key) !== void 0) {
|
|
2024
|
+
source = cmd.getOptionValueSource(key);
|
|
2025
|
+
}
|
|
2026
|
+
});
|
|
2027
|
+
return source;
|
|
2028
|
+
}
|
|
2029
|
+
/**
|
|
2030
|
+
* Get user arguments from implied or explicit arguments.
|
|
2031
|
+
* Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
|
|
2032
|
+
*
|
|
2033
|
+
* @private
|
|
2034
|
+
*/
|
|
2035
|
+
_prepareUserArgs(argv, parseOptions) {
|
|
2036
|
+
if (argv !== void 0 && !Array.isArray(argv)) {
|
|
2037
|
+
throw new Error("first parameter to parse must be array or undefined");
|
|
2038
|
+
}
|
|
2039
|
+
parseOptions = parseOptions || {};
|
|
2040
|
+
if (argv === void 0 && parseOptions.from === void 0) {
|
|
2041
|
+
if (process2.versions?.electron) {
|
|
2042
|
+
parseOptions.from = "electron";
|
|
2043
|
+
}
|
|
2044
|
+
const execArgv = process2.execArgv ?? [];
|
|
2045
|
+
if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
|
|
2046
|
+
parseOptions.from = "eval";
|
|
2047
|
+
}
|
|
2048
|
+
}
|
|
2049
|
+
if (argv === void 0) {
|
|
2050
|
+
argv = process2.argv;
|
|
2051
|
+
}
|
|
2052
|
+
this.rawArgs = argv.slice();
|
|
2053
|
+
let userArgs;
|
|
2054
|
+
switch (parseOptions.from) {
|
|
2055
|
+
case void 0:
|
|
2056
|
+
case "node":
|
|
2057
|
+
this._scriptPath = argv[1];
|
|
2058
|
+
userArgs = argv.slice(2);
|
|
2059
|
+
break;
|
|
2060
|
+
case "electron":
|
|
2061
|
+
if (process2.defaultApp) {
|
|
2062
|
+
this._scriptPath = argv[1];
|
|
2063
|
+
userArgs = argv.slice(2);
|
|
2064
|
+
} else {
|
|
2065
|
+
userArgs = argv.slice(1);
|
|
2066
|
+
}
|
|
2067
|
+
break;
|
|
2068
|
+
case "user":
|
|
2069
|
+
userArgs = argv.slice(0);
|
|
2070
|
+
break;
|
|
2071
|
+
case "eval":
|
|
2072
|
+
userArgs = argv.slice(1);
|
|
2073
|
+
break;
|
|
2074
|
+
default:
|
|
2075
|
+
throw new Error(
|
|
2076
|
+
`unexpected parse option { from: '${parseOptions.from}' }`
|
|
2077
|
+
);
|
|
2078
|
+
}
|
|
2079
|
+
if (!this._name && this._scriptPath)
|
|
2080
|
+
this.nameFromFilename(this._scriptPath);
|
|
2081
|
+
this._name = this._name || "program";
|
|
2082
|
+
return userArgs;
|
|
2083
|
+
}
|
|
2084
|
+
/**
|
|
2085
|
+
* Parse `argv`, setting options and invoking commands when defined.
|
|
2086
|
+
*
|
|
2087
|
+
* Use parseAsync instead of parse if any of your action handlers are async.
|
|
2088
|
+
*
|
|
2089
|
+
* Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
|
|
2090
|
+
*
|
|
2091
|
+
* Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
|
|
2092
|
+
* - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
|
|
2093
|
+
* - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
|
|
2094
|
+
* - `'user'`: just user arguments
|
|
2095
|
+
*
|
|
2096
|
+
* @example
|
|
2097
|
+
* program.parse(); // parse process.argv and auto-detect electron and special node flags
|
|
2098
|
+
* program.parse(process.argv); // assume argv[0] is app and argv[1] is script
|
|
2099
|
+
* program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
|
|
2100
|
+
*
|
|
2101
|
+
* @param {string[]} [argv] - optional, defaults to process.argv
|
|
2102
|
+
* @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
|
|
2103
|
+
* @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
|
|
2104
|
+
* @return {Command} `this` command for chaining
|
|
2105
|
+
*/
|
|
2106
|
+
parse(argv, parseOptions) {
|
|
2107
|
+
this._prepareForParse();
|
|
2108
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
2109
|
+
this._parseCommand([], userArgs);
|
|
2110
|
+
return this;
|
|
2111
|
+
}
|
|
2112
|
+
/**
|
|
2113
|
+
* Parse `argv`, setting options and invoking commands when defined.
|
|
2114
|
+
*
|
|
2115
|
+
* Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
|
|
2116
|
+
*
|
|
2117
|
+
* Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
|
|
2118
|
+
* - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
|
|
2119
|
+
* - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
|
|
2120
|
+
* - `'user'`: just user arguments
|
|
2121
|
+
*
|
|
2122
|
+
* @example
|
|
2123
|
+
* await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
|
|
2124
|
+
* await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
|
|
2125
|
+
* await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
|
|
2126
|
+
*
|
|
2127
|
+
* @param {string[]} [argv]
|
|
2128
|
+
* @param {object} [parseOptions]
|
|
2129
|
+
* @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
|
|
2130
|
+
* @return {Promise}
|
|
2131
|
+
*/
|
|
2132
|
+
async parseAsync(argv, parseOptions) {
|
|
2133
|
+
this._prepareForParse();
|
|
2134
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
2135
|
+
await this._parseCommand([], userArgs);
|
|
2136
|
+
return this;
|
|
2137
|
+
}
|
|
2138
|
+
_prepareForParse() {
|
|
2139
|
+
if (this._savedState === null) {
|
|
2140
|
+
this.saveStateBeforeParse();
|
|
2141
|
+
} else {
|
|
2142
|
+
this.restoreStateBeforeParse();
|
|
2143
|
+
}
|
|
2144
|
+
}
|
|
2145
|
+
/**
|
|
2146
|
+
* Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
|
|
2147
|
+
* Not usually called directly, but available for subclasses to save their custom state.
|
|
2148
|
+
*
|
|
2149
|
+
* This is called in a lazy way. Only commands used in parsing chain will have state saved.
|
|
2150
|
+
*/
|
|
2151
|
+
saveStateBeforeParse() {
|
|
2152
|
+
this._savedState = {
|
|
2153
|
+
// name is stable if supplied by author, but may be unspecified for root command and deduced during parsing
|
|
2154
|
+
_name: this._name,
|
|
2155
|
+
// option values before parse have default values (including false for negated options)
|
|
2156
|
+
// shallow clones
|
|
2157
|
+
_optionValues: { ...this._optionValues },
|
|
2158
|
+
_optionValueSources: { ...this._optionValueSources }
|
|
2159
|
+
};
|
|
2160
|
+
}
|
|
2161
|
+
/**
|
|
2162
|
+
* Restore state before parse for calls after the first.
|
|
2163
|
+
* Not usually called directly, but available for subclasses to save their custom state.
|
|
2164
|
+
*
|
|
2165
|
+
* This is called in a lazy way. Only commands used in parsing chain will have state restored.
|
|
2166
|
+
*/
|
|
2167
|
+
restoreStateBeforeParse() {
|
|
2168
|
+
if (this._storeOptionsAsProperties)
|
|
2169
|
+
throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
2170
|
+
- either make a new Command for each call to parse, or stop storing options as properties`);
|
|
2171
|
+
this._name = this._savedState._name;
|
|
2172
|
+
this._scriptPath = null;
|
|
2173
|
+
this.rawArgs = [];
|
|
2174
|
+
this._optionValues = { ...this._savedState._optionValues };
|
|
2175
|
+
this._optionValueSources = { ...this._savedState._optionValueSources };
|
|
2176
|
+
this.args = [];
|
|
2177
|
+
this.processedArgs = [];
|
|
2178
|
+
}
|
|
2179
|
+
/**
|
|
2180
|
+
* Throw if expected executable is missing. Add lots of help for author.
|
|
2181
|
+
*
|
|
2182
|
+
* @param {string} executableFile
|
|
2183
|
+
* @param {string} executableDir
|
|
2184
|
+
* @param {string} subcommandName
|
|
2185
|
+
*/
|
|
2186
|
+
_checkForMissingExecutable(executableFile, executableDir, subcommandName) {
|
|
2187
|
+
if (fs.existsSync(executableFile)) return;
|
|
2188
|
+
const executableDirMessage = executableDir ? `searched for local subcommand relative to directory '${executableDir}'` : "no directory for search for local subcommand, use .executableDir() to supply a custom directory";
|
|
2189
|
+
const executableMissing = `'${executableFile}' does not exist
|
|
2190
|
+
- if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
2191
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
2192
|
+
- ${executableDirMessage}`;
|
|
2193
|
+
throw new Error(executableMissing);
|
|
2194
|
+
}
|
|
2195
|
+
/**
|
|
2196
|
+
* Execute a sub-command executable.
|
|
2197
|
+
*
|
|
2198
|
+
* @private
|
|
2199
|
+
*/
|
|
2200
|
+
_executeSubCommand(subcommand, args) {
|
|
2201
|
+
args = args.slice();
|
|
2202
|
+
let launchWithNode = false;
|
|
2203
|
+
const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
|
|
2204
|
+
function findFile(baseDir, baseName) {
|
|
2205
|
+
const localBin = path.resolve(baseDir, baseName);
|
|
2206
|
+
if (fs.existsSync(localBin)) return localBin;
|
|
2207
|
+
if (sourceExt.includes(path.extname(baseName))) return void 0;
|
|
2208
|
+
const foundExt = sourceExt.find(
|
|
2209
|
+
(ext) => fs.existsSync(`${localBin}${ext}`)
|
|
2210
|
+
);
|
|
2211
|
+
if (foundExt) return `${localBin}${foundExt}`;
|
|
2212
|
+
return void 0;
|
|
2213
|
+
}
|
|
2214
|
+
this._checkForMissingMandatoryOptions();
|
|
2215
|
+
this._checkForConflictingOptions();
|
|
2216
|
+
let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
|
|
2217
|
+
let executableDir = this._executableDir || "";
|
|
2218
|
+
if (this._scriptPath) {
|
|
2219
|
+
let resolvedScriptPath;
|
|
2220
|
+
try {
|
|
2221
|
+
resolvedScriptPath = fs.realpathSync(this._scriptPath);
|
|
2222
|
+
} catch {
|
|
2223
|
+
resolvedScriptPath = this._scriptPath;
|
|
2224
|
+
}
|
|
2225
|
+
executableDir = path.resolve(
|
|
2226
|
+
path.dirname(resolvedScriptPath),
|
|
2227
|
+
executableDir
|
|
2228
|
+
);
|
|
2229
|
+
}
|
|
2230
|
+
if (executableDir) {
|
|
2231
|
+
let localFile = findFile(executableDir, executableFile);
|
|
2232
|
+
if (!localFile && !subcommand._executableFile && this._scriptPath) {
|
|
2233
|
+
const legacyName = path.basename(
|
|
2234
|
+
this._scriptPath,
|
|
2235
|
+
path.extname(this._scriptPath)
|
|
2236
|
+
);
|
|
2237
|
+
if (legacyName !== this._name) {
|
|
2238
|
+
localFile = findFile(
|
|
2239
|
+
executableDir,
|
|
2240
|
+
`${legacyName}-${subcommand._name}`
|
|
2241
|
+
);
|
|
2242
|
+
}
|
|
2243
|
+
}
|
|
2244
|
+
executableFile = localFile || executableFile;
|
|
2245
|
+
}
|
|
2246
|
+
launchWithNode = sourceExt.includes(path.extname(executableFile));
|
|
2247
|
+
let proc;
|
|
2248
|
+
if (process2.platform !== "win32") {
|
|
2249
|
+
if (launchWithNode) {
|
|
2250
|
+
args.unshift(executableFile);
|
|
2251
|
+
args = incrementNodeInspectorPort(process2.execArgv).concat(args);
|
|
2252
|
+
proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
|
|
2253
|
+
} else {
|
|
2254
|
+
proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
|
|
2255
|
+
}
|
|
2256
|
+
} else {
|
|
2257
|
+
this._checkForMissingExecutable(
|
|
2258
|
+
executableFile,
|
|
2259
|
+
executableDir,
|
|
2260
|
+
subcommand._name
|
|
2261
|
+
);
|
|
2262
|
+
args.unshift(executableFile);
|
|
2263
|
+
args = incrementNodeInspectorPort(process2.execArgv).concat(args);
|
|
2264
|
+
proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
|
|
2265
|
+
}
|
|
2266
|
+
if (!proc.killed) {
|
|
2267
|
+
const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
|
|
2268
|
+
signals.forEach((signal) => {
|
|
2269
|
+
process2.on(signal, () => {
|
|
2270
|
+
if (proc.killed === false && proc.exitCode === null) {
|
|
2271
|
+
proc.kill(signal);
|
|
2272
|
+
}
|
|
2273
|
+
});
|
|
2274
|
+
});
|
|
2275
|
+
}
|
|
2276
|
+
const exitCallback = this._exitCallback;
|
|
2277
|
+
proc.on("close", (code) => {
|
|
2278
|
+
code = code ?? 1;
|
|
2279
|
+
if (!exitCallback) {
|
|
2280
|
+
process2.exit(code);
|
|
2281
|
+
} else {
|
|
2282
|
+
exitCallback(
|
|
2283
|
+
new CommanderError2(
|
|
2284
|
+
code,
|
|
2285
|
+
"commander.executeSubCommandAsync",
|
|
2286
|
+
"(close)"
|
|
2287
|
+
)
|
|
2288
|
+
);
|
|
2289
|
+
}
|
|
2290
|
+
});
|
|
2291
|
+
proc.on("error", (err) => {
|
|
2292
|
+
if (err.code === "ENOENT") {
|
|
2293
|
+
this._checkForMissingExecutable(
|
|
2294
|
+
executableFile,
|
|
2295
|
+
executableDir,
|
|
2296
|
+
subcommand._name
|
|
2297
|
+
);
|
|
2298
|
+
} else if (err.code === "EACCES") {
|
|
2299
|
+
throw new Error(`'${executableFile}' not executable`);
|
|
2300
|
+
}
|
|
2301
|
+
if (!exitCallback) {
|
|
2302
|
+
process2.exit(1);
|
|
2303
|
+
} else {
|
|
2304
|
+
const wrappedError = new CommanderError2(
|
|
2305
|
+
1,
|
|
2306
|
+
"commander.executeSubCommandAsync",
|
|
2307
|
+
"(error)"
|
|
2308
|
+
);
|
|
2309
|
+
wrappedError.nestedError = err;
|
|
2310
|
+
exitCallback(wrappedError);
|
|
2311
|
+
}
|
|
2312
|
+
});
|
|
2313
|
+
this.runningCommand = proc;
|
|
2314
|
+
}
|
|
2315
|
+
/**
|
|
2316
|
+
* @private
|
|
2317
|
+
*/
|
|
2318
|
+
_dispatchSubcommand(commandName, operands, unknown) {
|
|
2319
|
+
const subCommand = this._findCommand(commandName);
|
|
2320
|
+
if (!subCommand) this.help({ error: true });
|
|
2321
|
+
subCommand._prepareForParse();
|
|
2322
|
+
let promiseChain;
|
|
2323
|
+
promiseChain = this._chainOrCallSubCommandHook(
|
|
2324
|
+
promiseChain,
|
|
2325
|
+
subCommand,
|
|
2326
|
+
"preSubcommand"
|
|
2327
|
+
);
|
|
2328
|
+
promiseChain = this._chainOrCall(promiseChain, () => {
|
|
2329
|
+
if (subCommand._executableHandler) {
|
|
2330
|
+
this._executeSubCommand(subCommand, operands.concat(unknown));
|
|
2331
|
+
} else {
|
|
2332
|
+
return subCommand._parseCommand(operands, unknown);
|
|
2333
|
+
}
|
|
2334
|
+
});
|
|
2335
|
+
return promiseChain;
|
|
2336
|
+
}
|
|
2337
|
+
/**
|
|
2338
|
+
* Invoke help directly if possible, or dispatch if necessary.
|
|
2339
|
+
* e.g. help foo
|
|
2340
|
+
*
|
|
2341
|
+
* @private
|
|
2342
|
+
*/
|
|
2343
|
+
_dispatchHelpCommand(subcommandName) {
|
|
2344
|
+
if (!subcommandName) {
|
|
2345
|
+
this.help();
|
|
2346
|
+
}
|
|
2347
|
+
const subCommand = this._findCommand(subcommandName);
|
|
2348
|
+
if (subCommand && !subCommand._executableHandler) {
|
|
2349
|
+
subCommand.help();
|
|
2350
|
+
}
|
|
2351
|
+
return this._dispatchSubcommand(
|
|
2352
|
+
subcommandName,
|
|
2353
|
+
[],
|
|
2354
|
+
[this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
|
|
2355
|
+
);
|
|
2356
|
+
}
|
|
2357
|
+
/**
|
|
2358
|
+
* Check this.args against expected this.registeredArguments.
|
|
2359
|
+
*
|
|
2360
|
+
* @private
|
|
2361
|
+
*/
|
|
2362
|
+
_checkNumberOfArguments() {
|
|
2363
|
+
this.registeredArguments.forEach((arg, i) => {
|
|
2364
|
+
if (arg.required && this.args[i] == null) {
|
|
2365
|
+
this.missingArgument(arg.name());
|
|
2366
|
+
}
|
|
2367
|
+
});
|
|
2368
|
+
if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
|
|
2369
|
+
return;
|
|
2370
|
+
}
|
|
2371
|
+
if (this.args.length > this.registeredArguments.length) {
|
|
2372
|
+
this._excessArguments(this.args);
|
|
2373
|
+
}
|
|
2374
|
+
}
|
|
2375
|
+
/**
|
|
2376
|
+
* Process this.args using this.registeredArguments and save as this.processedArgs!
|
|
2377
|
+
*
|
|
2378
|
+
* @private
|
|
2379
|
+
*/
|
|
2380
|
+
_processArguments() {
|
|
2381
|
+
const myParseArg = (argument, value, previous) => {
|
|
2382
|
+
let parsedValue = value;
|
|
2383
|
+
if (value !== null && argument.parseArg) {
|
|
2384
|
+
const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
|
|
2385
|
+
parsedValue = this._callParseArg(
|
|
2386
|
+
argument,
|
|
2387
|
+
value,
|
|
2388
|
+
previous,
|
|
2389
|
+
invalidValueMessage
|
|
2390
|
+
);
|
|
2391
|
+
}
|
|
2392
|
+
return parsedValue;
|
|
2393
|
+
};
|
|
2394
|
+
this._checkNumberOfArguments();
|
|
2395
|
+
const processedArgs = [];
|
|
2396
|
+
this.registeredArguments.forEach((declaredArg, index) => {
|
|
2397
|
+
let value = declaredArg.defaultValue;
|
|
2398
|
+
if (declaredArg.variadic) {
|
|
2399
|
+
if (index < this.args.length) {
|
|
2400
|
+
value = this.args.slice(index);
|
|
2401
|
+
if (declaredArg.parseArg) {
|
|
2402
|
+
value = value.reduce((processed, v) => {
|
|
2403
|
+
return myParseArg(declaredArg, v, processed);
|
|
2404
|
+
}, declaredArg.defaultValue);
|
|
2405
|
+
}
|
|
2406
|
+
} else if (value === void 0) {
|
|
2407
|
+
value = [];
|
|
2408
|
+
}
|
|
2409
|
+
} else if (index < this.args.length) {
|
|
2410
|
+
value = this.args[index];
|
|
2411
|
+
if (declaredArg.parseArg) {
|
|
2412
|
+
value = myParseArg(declaredArg, value, declaredArg.defaultValue);
|
|
2413
|
+
}
|
|
2414
|
+
}
|
|
2415
|
+
processedArgs[index] = value;
|
|
2416
|
+
});
|
|
2417
|
+
this.processedArgs = processedArgs;
|
|
2418
|
+
}
|
|
2419
|
+
/**
|
|
2420
|
+
* Once we have a promise we chain, but call synchronously until then.
|
|
2421
|
+
*
|
|
2422
|
+
* @param {(Promise|undefined)} promise
|
|
2423
|
+
* @param {Function} fn
|
|
2424
|
+
* @return {(Promise|undefined)}
|
|
2425
|
+
* @private
|
|
2426
|
+
*/
|
|
2427
|
+
_chainOrCall(promise, fn) {
|
|
2428
|
+
if (promise?.then && typeof promise.then === "function") {
|
|
2429
|
+
return promise.then(() => fn());
|
|
2430
|
+
}
|
|
2431
|
+
return fn();
|
|
2432
|
+
}
|
|
2433
|
+
/**
|
|
2434
|
+
*
|
|
2435
|
+
* @param {(Promise|undefined)} promise
|
|
2436
|
+
* @param {string} event
|
|
2437
|
+
* @return {(Promise|undefined)}
|
|
2438
|
+
* @private
|
|
2439
|
+
*/
|
|
2440
|
+
_chainOrCallHooks(promise, event) {
|
|
2441
|
+
let result = promise;
|
|
2442
|
+
const hooks = [];
|
|
2443
|
+
this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
|
|
2444
|
+
hookedCommand._lifeCycleHooks[event].forEach((callback) => {
|
|
2445
|
+
hooks.push({ hookedCommand, callback });
|
|
2446
|
+
});
|
|
2447
|
+
});
|
|
2448
|
+
if (event === "postAction") {
|
|
2449
|
+
hooks.reverse();
|
|
2450
|
+
}
|
|
2451
|
+
hooks.forEach((hookDetail) => {
|
|
2452
|
+
result = this._chainOrCall(result, () => {
|
|
2453
|
+
return hookDetail.callback(hookDetail.hookedCommand, this);
|
|
2454
|
+
});
|
|
2455
|
+
});
|
|
2456
|
+
return result;
|
|
2457
|
+
}
|
|
2458
|
+
/**
|
|
2459
|
+
*
|
|
2460
|
+
* @param {(Promise|undefined)} promise
|
|
2461
|
+
* @param {Command} subCommand
|
|
2462
|
+
* @param {string} event
|
|
2463
|
+
* @return {(Promise|undefined)}
|
|
2464
|
+
* @private
|
|
2465
|
+
*/
|
|
2466
|
+
_chainOrCallSubCommandHook(promise, subCommand, event) {
|
|
2467
|
+
let result = promise;
|
|
2468
|
+
if (this._lifeCycleHooks[event] !== void 0) {
|
|
2469
|
+
this._lifeCycleHooks[event].forEach((hook) => {
|
|
2470
|
+
result = this._chainOrCall(result, () => {
|
|
2471
|
+
return hook(this, subCommand);
|
|
2472
|
+
});
|
|
2473
|
+
});
|
|
2474
|
+
}
|
|
2475
|
+
return result;
|
|
2476
|
+
}
|
|
2477
|
+
/**
|
|
2478
|
+
* Process arguments in context of this command.
|
|
2479
|
+
* Returns action result, in case it is a promise.
|
|
2480
|
+
*
|
|
2481
|
+
* @private
|
|
2482
|
+
*/
|
|
2483
|
+
_parseCommand(operands, unknown) {
|
|
2484
|
+
const parsed = this.parseOptions(unknown);
|
|
2485
|
+
this._parseOptionsEnv();
|
|
2486
|
+
this._parseOptionsImplied();
|
|
2487
|
+
operands = operands.concat(parsed.operands);
|
|
2488
|
+
unknown = parsed.unknown;
|
|
2489
|
+
this.args = operands.concat(unknown);
|
|
2490
|
+
if (operands && this._findCommand(operands[0])) {
|
|
2491
|
+
return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
|
|
2492
|
+
}
|
|
2493
|
+
if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
|
|
2494
|
+
return this._dispatchHelpCommand(operands[1]);
|
|
2495
|
+
}
|
|
2496
|
+
if (this._defaultCommandName) {
|
|
2497
|
+
this._outputHelpIfRequested(unknown);
|
|
2498
|
+
return this._dispatchSubcommand(
|
|
2499
|
+
this._defaultCommandName,
|
|
2500
|
+
operands,
|
|
2501
|
+
unknown
|
|
2502
|
+
);
|
|
2503
|
+
}
|
|
2504
|
+
if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
|
|
2505
|
+
this.help({ error: true });
|
|
2506
|
+
}
|
|
2507
|
+
this._outputHelpIfRequested(parsed.unknown);
|
|
2508
|
+
this._checkForMissingMandatoryOptions();
|
|
2509
|
+
this._checkForConflictingOptions();
|
|
2510
|
+
const checkForUnknownOptions = () => {
|
|
2511
|
+
if (parsed.unknown.length > 0) {
|
|
2512
|
+
this.unknownOption(parsed.unknown[0]);
|
|
2513
|
+
}
|
|
2514
|
+
};
|
|
2515
|
+
const commandEvent = `command:${this.name()}`;
|
|
2516
|
+
if (this._actionHandler) {
|
|
2517
|
+
checkForUnknownOptions();
|
|
2518
|
+
this._processArguments();
|
|
2519
|
+
let promiseChain;
|
|
2520
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
|
|
2521
|
+
promiseChain = this._chainOrCall(
|
|
2522
|
+
promiseChain,
|
|
2523
|
+
() => this._actionHandler(this.processedArgs)
|
|
2524
|
+
);
|
|
2525
|
+
if (this.parent) {
|
|
2526
|
+
promiseChain = this._chainOrCall(promiseChain, () => {
|
|
2527
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
2528
|
+
});
|
|
2529
|
+
}
|
|
2530
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
|
|
2531
|
+
return promiseChain;
|
|
2532
|
+
}
|
|
2533
|
+
if (this.parent?.listenerCount(commandEvent)) {
|
|
2534
|
+
checkForUnknownOptions();
|
|
2535
|
+
this._processArguments();
|
|
2536
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
2537
|
+
} else if (operands.length) {
|
|
2538
|
+
if (this._findCommand("*")) {
|
|
2539
|
+
return this._dispatchSubcommand("*", operands, unknown);
|
|
2540
|
+
}
|
|
2541
|
+
if (this.listenerCount("command:*")) {
|
|
2542
|
+
this.emit("command:*", operands, unknown);
|
|
2543
|
+
} else if (this.commands.length) {
|
|
2544
|
+
this.unknownCommand();
|
|
2545
|
+
} else {
|
|
2546
|
+
checkForUnknownOptions();
|
|
2547
|
+
this._processArguments();
|
|
2548
|
+
}
|
|
2549
|
+
} else if (this.commands.length) {
|
|
2550
|
+
checkForUnknownOptions();
|
|
2551
|
+
this.help({ error: true });
|
|
2552
|
+
} else {
|
|
2553
|
+
checkForUnknownOptions();
|
|
2554
|
+
this._processArguments();
|
|
2555
|
+
}
|
|
2556
|
+
}
|
|
2557
|
+
/**
|
|
2558
|
+
* Find matching command.
|
|
2559
|
+
*
|
|
2560
|
+
* @private
|
|
2561
|
+
* @return {Command | undefined}
|
|
2562
|
+
*/
|
|
2563
|
+
_findCommand(name) {
|
|
2564
|
+
if (!name) return void 0;
|
|
2565
|
+
return this.commands.find(
|
|
2566
|
+
(cmd) => cmd._name === name || cmd._aliases.includes(name)
|
|
2567
|
+
);
|
|
2568
|
+
}
|
|
2569
|
+
/**
|
|
2570
|
+
* Return an option matching `arg` if any.
|
|
2571
|
+
*
|
|
2572
|
+
* @param {string} arg
|
|
2573
|
+
* @return {Option}
|
|
2574
|
+
* @package
|
|
2575
|
+
*/
|
|
2576
|
+
_findOption(arg) {
|
|
2577
|
+
return this.options.find((option) => option.is(arg));
|
|
2578
|
+
}
|
|
2579
|
+
/**
|
|
2580
|
+
* Display an error message if a mandatory option does not have a value.
|
|
2581
|
+
* Called after checking for help flags in leaf subcommand.
|
|
2582
|
+
*
|
|
2583
|
+
* @private
|
|
2584
|
+
*/
|
|
2585
|
+
_checkForMissingMandatoryOptions() {
|
|
2586
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
2587
|
+
cmd.options.forEach((anOption) => {
|
|
2588
|
+
if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
|
|
2589
|
+
cmd.missingMandatoryOptionValue(anOption);
|
|
2590
|
+
}
|
|
2591
|
+
});
|
|
2592
|
+
});
|
|
2593
|
+
}
|
|
2594
|
+
/**
|
|
2595
|
+
* Display an error message if conflicting options are used together in this.
|
|
2596
|
+
*
|
|
2597
|
+
* @private
|
|
2598
|
+
*/
|
|
2599
|
+
_checkForConflictingLocalOptions() {
|
|
2600
|
+
const definedNonDefaultOptions = this.options.filter((option) => {
|
|
2601
|
+
const optionKey = option.attributeName();
|
|
2602
|
+
if (this.getOptionValue(optionKey) === void 0) {
|
|
2603
|
+
return false;
|
|
2604
|
+
}
|
|
2605
|
+
return this.getOptionValueSource(optionKey) !== "default";
|
|
2606
|
+
});
|
|
2607
|
+
const optionsWithConflicting = definedNonDefaultOptions.filter(
|
|
2608
|
+
(option) => option.conflictsWith.length > 0
|
|
2609
|
+
);
|
|
2610
|
+
optionsWithConflicting.forEach((option) => {
|
|
2611
|
+
const conflictingAndDefined = definedNonDefaultOptions.find(
|
|
2612
|
+
(defined) => option.conflictsWith.includes(defined.attributeName())
|
|
2613
|
+
);
|
|
2614
|
+
if (conflictingAndDefined) {
|
|
2615
|
+
this._conflictingOption(option, conflictingAndDefined);
|
|
2616
|
+
}
|
|
2617
|
+
});
|
|
2618
|
+
}
|
|
2619
|
+
/**
|
|
2620
|
+
* Display an error message if conflicting options are used together.
|
|
2621
|
+
* Called after checking for help flags in leaf subcommand.
|
|
2622
|
+
*
|
|
2623
|
+
* @private
|
|
2624
|
+
*/
|
|
2625
|
+
_checkForConflictingOptions() {
|
|
2626
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
2627
|
+
cmd._checkForConflictingLocalOptions();
|
|
2628
|
+
});
|
|
2629
|
+
}
|
|
2630
|
+
/**
|
|
2631
|
+
* Parse options from `argv` removing known options,
|
|
2632
|
+
* and return argv split into operands and unknown arguments.
|
|
2633
|
+
*
|
|
2634
|
+
* Side effects: modifies command by storing options. Does not reset state if called again.
|
|
2635
|
+
*
|
|
2636
|
+
* Examples:
|
|
2637
|
+
*
|
|
2638
|
+
* argv => operands, unknown
|
|
2639
|
+
* --known kkk op => [op], []
|
|
2640
|
+
* op --known kkk => [op], []
|
|
2641
|
+
* sub --unknown uuu op => [sub], [--unknown uuu op]
|
|
2642
|
+
* sub -- --unknown uuu op => [sub --unknown uuu op], []
|
|
2643
|
+
*
|
|
2644
|
+
* @param {string[]} args
|
|
2645
|
+
* @return {{operands: string[], unknown: string[]}}
|
|
2646
|
+
*/
|
|
2647
|
+
parseOptions(args) {
|
|
2648
|
+
const operands = [];
|
|
2649
|
+
const unknown = [];
|
|
2650
|
+
let dest = operands;
|
|
2651
|
+
function maybeOption(arg) {
|
|
2652
|
+
return arg.length > 1 && arg[0] === "-";
|
|
2653
|
+
}
|
|
2654
|
+
const negativeNumberArg = (arg) => {
|
|
2655
|
+
if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
|
|
2656
|
+
return !this._getCommandAndAncestors().some(
|
|
2657
|
+
(cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short))
|
|
2658
|
+
);
|
|
2659
|
+
};
|
|
2660
|
+
let activeVariadicOption = null;
|
|
2661
|
+
let activeGroup = null;
|
|
2662
|
+
let i = 0;
|
|
2663
|
+
while (i < args.length || activeGroup) {
|
|
2664
|
+
const arg = activeGroup ?? args[i++];
|
|
2665
|
+
activeGroup = null;
|
|
2666
|
+
if (arg === "--") {
|
|
2667
|
+
if (dest === unknown) dest.push(arg);
|
|
2668
|
+
dest.push(...args.slice(i));
|
|
2669
|
+
break;
|
|
2670
|
+
}
|
|
2671
|
+
if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
|
|
2672
|
+
this.emit(`option:${activeVariadicOption.name()}`, arg);
|
|
2673
|
+
continue;
|
|
2674
|
+
}
|
|
2675
|
+
activeVariadicOption = null;
|
|
2676
|
+
if (maybeOption(arg)) {
|
|
2677
|
+
const option = this._findOption(arg);
|
|
2678
|
+
if (option) {
|
|
2679
|
+
if (option.required) {
|
|
2680
|
+
const value = args[i++];
|
|
2681
|
+
if (value === void 0) this.optionMissingArgument(option);
|
|
2682
|
+
this.emit(`option:${option.name()}`, value);
|
|
2683
|
+
} else if (option.optional) {
|
|
2684
|
+
let value = null;
|
|
2685
|
+
if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) {
|
|
2686
|
+
value = args[i++];
|
|
2687
|
+
}
|
|
2688
|
+
this.emit(`option:${option.name()}`, value);
|
|
2689
|
+
} else {
|
|
2690
|
+
this.emit(`option:${option.name()}`);
|
|
2691
|
+
}
|
|
2692
|
+
activeVariadicOption = option.variadic ? option : null;
|
|
2693
|
+
continue;
|
|
2694
|
+
}
|
|
2695
|
+
}
|
|
2696
|
+
if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
|
|
2697
|
+
const option = this._findOption(`-${arg[1]}`);
|
|
2698
|
+
if (option) {
|
|
2699
|
+
if (option.required || option.optional && this._combineFlagAndOptionalValue) {
|
|
2700
|
+
this.emit(`option:${option.name()}`, arg.slice(2));
|
|
2701
|
+
} else {
|
|
2702
|
+
this.emit(`option:${option.name()}`);
|
|
2703
|
+
activeGroup = `-${arg.slice(2)}`;
|
|
2704
|
+
}
|
|
2705
|
+
continue;
|
|
2706
|
+
}
|
|
2707
|
+
}
|
|
2708
|
+
if (/^--[^=]+=/.test(arg)) {
|
|
2709
|
+
const index = arg.indexOf("=");
|
|
2710
|
+
const option = this._findOption(arg.slice(0, index));
|
|
2711
|
+
if (option && (option.required || option.optional)) {
|
|
2712
|
+
this.emit(`option:${option.name()}`, arg.slice(index + 1));
|
|
2713
|
+
continue;
|
|
2714
|
+
}
|
|
2715
|
+
}
|
|
2716
|
+
if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) {
|
|
2717
|
+
dest = unknown;
|
|
2718
|
+
}
|
|
2719
|
+
if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
|
|
2720
|
+
if (this._findCommand(arg)) {
|
|
2721
|
+
operands.push(arg);
|
|
2722
|
+
unknown.push(...args.slice(i));
|
|
2723
|
+
break;
|
|
2724
|
+
} else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
|
|
2725
|
+
operands.push(arg, ...args.slice(i));
|
|
2726
|
+
break;
|
|
2727
|
+
} else if (this._defaultCommandName) {
|
|
2728
|
+
unknown.push(arg, ...args.slice(i));
|
|
2729
|
+
break;
|
|
2730
|
+
}
|
|
2731
|
+
}
|
|
2732
|
+
if (this._passThroughOptions) {
|
|
2733
|
+
dest.push(arg, ...args.slice(i));
|
|
2734
|
+
break;
|
|
2735
|
+
}
|
|
2736
|
+
dest.push(arg);
|
|
2737
|
+
}
|
|
2738
|
+
return { operands, unknown };
|
|
2739
|
+
}
|
|
2740
|
+
/**
|
|
2741
|
+
* Return an object containing local option values as key-value pairs.
|
|
2742
|
+
*
|
|
2743
|
+
* @return {object}
|
|
2744
|
+
*/
|
|
2745
|
+
opts() {
|
|
2746
|
+
if (this._storeOptionsAsProperties) {
|
|
2747
|
+
const result = {};
|
|
2748
|
+
const len = this.options.length;
|
|
2749
|
+
for (let i = 0; i < len; i++) {
|
|
2750
|
+
const key = this.options[i].attributeName();
|
|
2751
|
+
result[key] = key === this._versionOptionName ? this._version : this[key];
|
|
2752
|
+
}
|
|
2753
|
+
return result;
|
|
2754
|
+
}
|
|
2755
|
+
return this._optionValues;
|
|
2756
|
+
}
|
|
2757
|
+
/**
|
|
2758
|
+
* Return an object containing merged local and global option values as key-value pairs.
|
|
2759
|
+
*
|
|
2760
|
+
* @return {object}
|
|
2761
|
+
*/
|
|
2762
|
+
optsWithGlobals() {
|
|
2763
|
+
return this._getCommandAndAncestors().reduce(
|
|
2764
|
+
(combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
|
|
2765
|
+
{}
|
|
2766
|
+
);
|
|
2767
|
+
}
|
|
2768
|
+
/**
|
|
2769
|
+
* Display error message and exit (or call exitOverride).
|
|
2770
|
+
*
|
|
2771
|
+
* @param {string} message
|
|
2772
|
+
* @param {object} [errorOptions]
|
|
2773
|
+
* @param {string} [errorOptions.code] - an id string representing the error
|
|
2774
|
+
* @param {number} [errorOptions.exitCode] - used with process.exit
|
|
2775
|
+
*/
|
|
2776
|
+
error(message, errorOptions) {
|
|
2777
|
+
this._outputConfiguration.outputError(
|
|
2778
|
+
`${message}
|
|
2779
|
+
`,
|
|
2780
|
+
this._outputConfiguration.writeErr
|
|
2781
|
+
);
|
|
2782
|
+
if (typeof this._showHelpAfterError === "string") {
|
|
2783
|
+
this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
2784
|
+
`);
|
|
2785
|
+
} else if (this._showHelpAfterError) {
|
|
2786
|
+
this._outputConfiguration.writeErr("\n");
|
|
2787
|
+
this.outputHelp({ error: true });
|
|
2788
|
+
}
|
|
2789
|
+
const config = errorOptions || {};
|
|
2790
|
+
const exitCode = config.exitCode || 1;
|
|
2791
|
+
const code = config.code || "commander.error";
|
|
2792
|
+
this._exit(exitCode, code, message);
|
|
2793
|
+
}
|
|
2794
|
+
/**
|
|
2795
|
+
* Apply any option related environment variables, if option does
|
|
2796
|
+
* not have a value from cli or client code.
|
|
2797
|
+
*
|
|
2798
|
+
* @private
|
|
2799
|
+
*/
|
|
2800
|
+
_parseOptionsEnv() {
|
|
2801
|
+
this.options.forEach((option) => {
|
|
2802
|
+
if (option.envVar && option.envVar in process2.env) {
|
|
2803
|
+
const optionKey = option.attributeName();
|
|
2804
|
+
if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
|
|
2805
|
+
this.getOptionValueSource(optionKey)
|
|
2806
|
+
)) {
|
|
2807
|
+
if (option.required || option.optional) {
|
|
2808
|
+
this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
|
|
2809
|
+
} else {
|
|
2810
|
+
this.emit(`optionEnv:${option.name()}`);
|
|
2811
|
+
}
|
|
2812
|
+
}
|
|
2813
|
+
}
|
|
2814
|
+
});
|
|
2815
|
+
}
|
|
2816
|
+
/**
|
|
2817
|
+
* Apply any implied option values, if option is undefined or default value.
|
|
2818
|
+
*
|
|
2819
|
+
* @private
|
|
2820
|
+
*/
|
|
2821
|
+
_parseOptionsImplied() {
|
|
2822
|
+
const dualHelper = new DualOptions(this.options);
|
|
2823
|
+
const hasCustomOptionValue = (optionKey) => {
|
|
2824
|
+
return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
|
|
2825
|
+
};
|
|
2826
|
+
this.options.filter(
|
|
2827
|
+
(option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(
|
|
2828
|
+
this.getOptionValue(option.attributeName()),
|
|
2829
|
+
option
|
|
2830
|
+
)
|
|
2831
|
+
).forEach((option) => {
|
|
2832
|
+
Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
|
|
2833
|
+
this.setOptionValueWithSource(
|
|
2834
|
+
impliedKey,
|
|
2835
|
+
option.implied[impliedKey],
|
|
2836
|
+
"implied"
|
|
2837
|
+
);
|
|
2838
|
+
});
|
|
2839
|
+
});
|
|
2840
|
+
}
|
|
2841
|
+
/**
|
|
2842
|
+
* Argument `name` is missing.
|
|
2843
|
+
*
|
|
2844
|
+
* @param {string} name
|
|
2845
|
+
* @private
|
|
2846
|
+
*/
|
|
2847
|
+
missingArgument(name) {
|
|
2848
|
+
const message = `error: missing required argument '${name}'`;
|
|
2849
|
+
this.error(message, { code: "commander.missingArgument" });
|
|
2850
|
+
}
|
|
2851
|
+
/**
|
|
2852
|
+
* `Option` is missing an argument.
|
|
2853
|
+
*
|
|
2854
|
+
* @param {Option} option
|
|
2855
|
+
* @private
|
|
2856
|
+
*/
|
|
2857
|
+
optionMissingArgument(option) {
|
|
2858
|
+
const message = `error: option '${option.flags}' argument missing`;
|
|
2859
|
+
this.error(message, { code: "commander.optionMissingArgument" });
|
|
2860
|
+
}
|
|
2861
|
+
/**
|
|
2862
|
+
* `Option` does not have a value, and is a mandatory option.
|
|
2863
|
+
*
|
|
2864
|
+
* @param {Option} option
|
|
2865
|
+
* @private
|
|
2866
|
+
*/
|
|
2867
|
+
missingMandatoryOptionValue(option) {
|
|
2868
|
+
const message = `error: required option '${option.flags}' not specified`;
|
|
2869
|
+
this.error(message, { code: "commander.missingMandatoryOptionValue" });
|
|
2870
|
+
}
|
|
2871
|
+
/**
|
|
2872
|
+
* `Option` conflicts with another option.
|
|
2873
|
+
*
|
|
2874
|
+
* @param {Option} option
|
|
2875
|
+
* @param {Option} conflictingOption
|
|
2876
|
+
* @private
|
|
2877
|
+
*/
|
|
2878
|
+
_conflictingOption(option, conflictingOption) {
|
|
2879
|
+
const findBestOptionFromValue = (option2) => {
|
|
2880
|
+
const optionKey = option2.attributeName();
|
|
2881
|
+
const optionValue = this.getOptionValue(optionKey);
|
|
2882
|
+
const negativeOption = this.options.find(
|
|
2883
|
+
(target) => target.negate && optionKey === target.attributeName()
|
|
2884
|
+
);
|
|
2885
|
+
const positiveOption = this.options.find(
|
|
2886
|
+
(target) => !target.negate && optionKey === target.attributeName()
|
|
2887
|
+
);
|
|
2888
|
+
if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
|
|
2889
|
+
return negativeOption;
|
|
2890
|
+
}
|
|
2891
|
+
return positiveOption || option2;
|
|
2892
|
+
};
|
|
2893
|
+
const getErrorMessage = (option2) => {
|
|
2894
|
+
const bestOption = findBestOptionFromValue(option2);
|
|
2895
|
+
const optionKey = bestOption.attributeName();
|
|
2896
|
+
const source = this.getOptionValueSource(optionKey);
|
|
2897
|
+
if (source === "env") {
|
|
2898
|
+
return `environment variable '${bestOption.envVar}'`;
|
|
2899
|
+
}
|
|
2900
|
+
return `option '${bestOption.flags}'`;
|
|
2901
|
+
};
|
|
2902
|
+
const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
|
|
2903
|
+
this.error(message, { code: "commander.conflictingOption" });
|
|
2904
|
+
}
|
|
2905
|
+
/**
|
|
2906
|
+
* Unknown option `flag`.
|
|
2907
|
+
*
|
|
2908
|
+
* @param {string} flag
|
|
2909
|
+
* @private
|
|
2910
|
+
*/
|
|
2911
|
+
unknownOption(flag) {
|
|
2912
|
+
if (this._allowUnknownOption) return;
|
|
2913
|
+
let suggestion = "";
|
|
2914
|
+
if (flag.startsWith("--") && this._showSuggestionAfterError) {
|
|
2915
|
+
let candidateFlags = [];
|
|
2916
|
+
let command = this;
|
|
2917
|
+
do {
|
|
2918
|
+
const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
|
|
2919
|
+
candidateFlags = candidateFlags.concat(moreFlags);
|
|
2920
|
+
command = command.parent;
|
|
2921
|
+
} while (command && !command._enablePositionalOptions);
|
|
2922
|
+
suggestion = suggestSimilar(flag, candidateFlags);
|
|
2923
|
+
}
|
|
2924
|
+
const message = `error: unknown option '${flag}'${suggestion}`;
|
|
2925
|
+
this.error(message, { code: "commander.unknownOption" });
|
|
2926
|
+
}
|
|
2927
|
+
/**
|
|
2928
|
+
* Excess arguments, more than expected.
|
|
2929
|
+
*
|
|
2930
|
+
* @param {string[]} receivedArgs
|
|
2931
|
+
* @private
|
|
2932
|
+
*/
|
|
2933
|
+
_excessArguments(receivedArgs) {
|
|
2934
|
+
if (this._allowExcessArguments) return;
|
|
2935
|
+
const expected = this.registeredArguments.length;
|
|
2936
|
+
const s = expected === 1 ? "" : "s";
|
|
2937
|
+
const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
|
|
2938
|
+
const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
|
|
2939
|
+
this.error(message, { code: "commander.excessArguments" });
|
|
2940
|
+
}
|
|
2941
|
+
/**
|
|
2942
|
+
* Unknown command.
|
|
2943
|
+
*
|
|
2944
|
+
* @private
|
|
2945
|
+
*/
|
|
2946
|
+
unknownCommand() {
|
|
2947
|
+
const unknownName = this.args[0];
|
|
2948
|
+
let suggestion = "";
|
|
2949
|
+
if (this._showSuggestionAfterError) {
|
|
2950
|
+
const candidateNames = [];
|
|
2951
|
+
this.createHelp().visibleCommands(this).forEach((command) => {
|
|
2952
|
+
candidateNames.push(command.name());
|
|
2953
|
+
if (command.alias()) candidateNames.push(command.alias());
|
|
2954
|
+
});
|
|
2955
|
+
suggestion = suggestSimilar(unknownName, candidateNames);
|
|
2956
|
+
}
|
|
2957
|
+
const message = `error: unknown command '${unknownName}'${suggestion}`;
|
|
2958
|
+
this.error(message, { code: "commander.unknownCommand" });
|
|
2959
|
+
}
|
|
2960
|
+
/**
|
|
2961
|
+
* Get or set the program version.
|
|
2962
|
+
*
|
|
2963
|
+
* This method auto-registers the "-V, --version" option which will print the version number.
|
|
2964
|
+
*
|
|
2965
|
+
* You can optionally supply the flags and description to override the defaults.
|
|
2966
|
+
*
|
|
2967
|
+
* @param {string} [str]
|
|
2968
|
+
* @param {string} [flags]
|
|
2969
|
+
* @param {string} [description]
|
|
2970
|
+
* @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
|
|
2971
|
+
*/
|
|
2972
|
+
version(str, flags, description) {
|
|
2973
|
+
if (str === void 0) return this._version;
|
|
2974
|
+
this._version = str;
|
|
2975
|
+
flags = flags || "-V, --version";
|
|
2976
|
+
description = description || "output the version number";
|
|
2977
|
+
const versionOption = this.createOption(flags, description);
|
|
2978
|
+
this._versionOptionName = versionOption.attributeName();
|
|
2979
|
+
this._registerOption(versionOption);
|
|
2980
|
+
this.on("option:" + versionOption.name(), () => {
|
|
2981
|
+
this._outputConfiguration.writeOut(`${str}
|
|
2982
|
+
`);
|
|
2983
|
+
this._exit(0, "commander.version", str);
|
|
2984
|
+
});
|
|
2985
|
+
return this;
|
|
2986
|
+
}
|
|
2987
|
+
/**
|
|
2988
|
+
* Set the description.
|
|
2989
|
+
*
|
|
2990
|
+
* @param {string} [str]
|
|
2991
|
+
* @param {object} [argsDescription]
|
|
2992
|
+
* @return {(string|Command)}
|
|
2993
|
+
*/
|
|
2994
|
+
description(str, argsDescription) {
|
|
2995
|
+
if (str === void 0 && argsDescription === void 0)
|
|
2996
|
+
return this._description;
|
|
2997
|
+
this._description = str;
|
|
2998
|
+
if (argsDescription) {
|
|
2999
|
+
this._argsDescription = argsDescription;
|
|
3000
|
+
}
|
|
3001
|
+
return this;
|
|
3002
|
+
}
|
|
3003
|
+
/**
|
|
3004
|
+
* Set the summary. Used when listed as subcommand of parent.
|
|
3005
|
+
*
|
|
3006
|
+
* @param {string} [str]
|
|
3007
|
+
* @return {(string|Command)}
|
|
3008
|
+
*/
|
|
3009
|
+
summary(str) {
|
|
3010
|
+
if (str === void 0) return this._summary;
|
|
3011
|
+
this._summary = str;
|
|
3012
|
+
return this;
|
|
3013
|
+
}
|
|
3014
|
+
/**
|
|
3015
|
+
* Set an alias for the command.
|
|
3016
|
+
*
|
|
3017
|
+
* You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
|
|
3018
|
+
*
|
|
3019
|
+
* @param {string} [alias]
|
|
3020
|
+
* @return {(string|Command)}
|
|
3021
|
+
*/
|
|
3022
|
+
alias(alias) {
|
|
3023
|
+
if (alias === void 0) return this._aliases[0];
|
|
3024
|
+
let command = this;
|
|
3025
|
+
if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
|
|
3026
|
+
command = this.commands[this.commands.length - 1];
|
|
3027
|
+
}
|
|
3028
|
+
if (alias === command._name)
|
|
3029
|
+
throw new Error("Command alias can't be the same as its name");
|
|
3030
|
+
const matchingCommand = this.parent?._findCommand(alias);
|
|
3031
|
+
if (matchingCommand) {
|
|
3032
|
+
const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
|
|
3033
|
+
throw new Error(
|
|
3034
|
+
`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
|
|
3035
|
+
);
|
|
3036
|
+
}
|
|
3037
|
+
command._aliases.push(alias);
|
|
3038
|
+
return this;
|
|
3039
|
+
}
|
|
3040
|
+
/**
|
|
3041
|
+
* Set aliases for the command.
|
|
3042
|
+
*
|
|
3043
|
+
* Only the first alias is shown in the auto-generated help.
|
|
3044
|
+
*
|
|
3045
|
+
* @param {string[]} [aliases]
|
|
3046
|
+
* @return {(string[]|Command)}
|
|
3047
|
+
*/
|
|
3048
|
+
aliases(aliases) {
|
|
3049
|
+
if (aliases === void 0) return this._aliases;
|
|
3050
|
+
aliases.forEach((alias) => this.alias(alias));
|
|
3051
|
+
return this;
|
|
3052
|
+
}
|
|
3053
|
+
/**
|
|
3054
|
+
* Set / get the command usage `str`.
|
|
3055
|
+
*
|
|
3056
|
+
* @param {string} [str]
|
|
3057
|
+
* @return {(string|Command)}
|
|
3058
|
+
*/
|
|
3059
|
+
usage(str) {
|
|
3060
|
+
if (str === void 0) {
|
|
3061
|
+
if (this._usage) return this._usage;
|
|
3062
|
+
const args = this.registeredArguments.map((arg) => {
|
|
3063
|
+
return humanReadableArgName(arg);
|
|
3064
|
+
});
|
|
3065
|
+
return [].concat(
|
|
3066
|
+
this.options.length || this._helpOption !== null ? "[options]" : [],
|
|
3067
|
+
this.commands.length ? "[command]" : [],
|
|
3068
|
+
this.registeredArguments.length ? args : []
|
|
3069
|
+
).join(" ");
|
|
3070
|
+
}
|
|
3071
|
+
this._usage = str;
|
|
3072
|
+
return this;
|
|
3073
|
+
}
|
|
3074
|
+
/**
|
|
3075
|
+
* Get or set the name of the command.
|
|
3076
|
+
*
|
|
3077
|
+
* @param {string} [str]
|
|
3078
|
+
* @return {(string|Command)}
|
|
3079
|
+
*/
|
|
3080
|
+
name(str) {
|
|
3081
|
+
if (str === void 0) return this._name;
|
|
3082
|
+
this._name = str;
|
|
3083
|
+
return this;
|
|
3084
|
+
}
|
|
3085
|
+
/**
|
|
3086
|
+
* Set/get the help group heading for this subcommand in parent command's help.
|
|
3087
|
+
*
|
|
3088
|
+
* @param {string} [heading]
|
|
3089
|
+
* @return {Command | string}
|
|
3090
|
+
*/
|
|
3091
|
+
helpGroup(heading) {
|
|
3092
|
+
if (heading === void 0) return this._helpGroupHeading ?? "";
|
|
3093
|
+
this._helpGroupHeading = heading;
|
|
3094
|
+
return this;
|
|
3095
|
+
}
|
|
3096
|
+
/**
|
|
3097
|
+
* Set/get the default help group heading for subcommands added to this command.
|
|
3098
|
+
* (This does not override a group set directly on the subcommand using .helpGroup().)
|
|
3099
|
+
*
|
|
3100
|
+
* @example
|
|
3101
|
+
* program.commandsGroup('Development Commands:);
|
|
3102
|
+
* program.command('watch')...
|
|
3103
|
+
* program.command('lint')...
|
|
3104
|
+
* ...
|
|
3105
|
+
*
|
|
3106
|
+
* @param {string} [heading]
|
|
3107
|
+
* @returns {Command | string}
|
|
3108
|
+
*/
|
|
3109
|
+
commandsGroup(heading) {
|
|
3110
|
+
if (heading === void 0) return this._defaultCommandGroup ?? "";
|
|
3111
|
+
this._defaultCommandGroup = heading;
|
|
3112
|
+
return this;
|
|
3113
|
+
}
|
|
3114
|
+
/**
|
|
3115
|
+
* Set/get the default help group heading for options added to this command.
|
|
3116
|
+
* (This does not override a group set directly on the option using .helpGroup().)
|
|
3117
|
+
*
|
|
3118
|
+
* @example
|
|
3119
|
+
* program
|
|
3120
|
+
* .optionsGroup('Development Options:')
|
|
3121
|
+
* .option('-d, --debug', 'output extra debugging')
|
|
3122
|
+
* .option('-p, --profile', 'output profiling information')
|
|
3123
|
+
*
|
|
3124
|
+
* @param {string} [heading]
|
|
3125
|
+
* @returns {Command | string}
|
|
3126
|
+
*/
|
|
3127
|
+
optionsGroup(heading) {
|
|
3128
|
+
if (heading === void 0) return this._defaultOptionGroup ?? "";
|
|
3129
|
+
this._defaultOptionGroup = heading;
|
|
3130
|
+
return this;
|
|
3131
|
+
}
|
|
3132
|
+
/**
|
|
3133
|
+
* @param {Option} option
|
|
3134
|
+
* @private
|
|
3135
|
+
*/
|
|
3136
|
+
_initOptionGroup(option) {
|
|
3137
|
+
if (this._defaultOptionGroup && !option.helpGroupHeading)
|
|
3138
|
+
option.helpGroup(this._defaultOptionGroup);
|
|
3139
|
+
}
|
|
3140
|
+
/**
|
|
3141
|
+
* @param {Command} cmd
|
|
3142
|
+
* @private
|
|
3143
|
+
*/
|
|
3144
|
+
_initCommandGroup(cmd) {
|
|
3145
|
+
if (this._defaultCommandGroup && !cmd.helpGroup())
|
|
3146
|
+
cmd.helpGroup(this._defaultCommandGroup);
|
|
3147
|
+
}
|
|
3148
|
+
/**
|
|
3149
|
+
* Set the name of the command from script filename, such as process.argv[1],
|
|
3150
|
+
* or require.main.filename, or __filename.
|
|
3151
|
+
*
|
|
3152
|
+
* (Used internally and public although not documented in README.)
|
|
3153
|
+
*
|
|
3154
|
+
* @example
|
|
3155
|
+
* program.nameFromFilename(require.main.filename);
|
|
3156
|
+
*
|
|
3157
|
+
* @param {string} filename
|
|
3158
|
+
* @return {Command}
|
|
3159
|
+
*/
|
|
3160
|
+
nameFromFilename(filename) {
|
|
3161
|
+
this._name = path.basename(filename, path.extname(filename));
|
|
3162
|
+
return this;
|
|
3163
|
+
}
|
|
3164
|
+
/**
|
|
3165
|
+
* Get or set the directory for searching for executable subcommands of this command.
|
|
3166
|
+
*
|
|
3167
|
+
* @example
|
|
3168
|
+
* program.executableDir(__dirname);
|
|
3169
|
+
* // or
|
|
3170
|
+
* program.executableDir('subcommands');
|
|
3171
|
+
*
|
|
3172
|
+
* @param {string} [path]
|
|
3173
|
+
* @return {(string|null|Command)}
|
|
3174
|
+
*/
|
|
3175
|
+
executableDir(path2) {
|
|
3176
|
+
if (path2 === void 0) return this._executableDir;
|
|
3177
|
+
this._executableDir = path2;
|
|
3178
|
+
return this;
|
|
3179
|
+
}
|
|
3180
|
+
/**
|
|
3181
|
+
* Return program help documentation.
|
|
3182
|
+
*
|
|
3183
|
+
* @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
|
|
3184
|
+
* @return {string}
|
|
3185
|
+
*/
|
|
3186
|
+
helpInformation(contextOptions) {
|
|
3187
|
+
const helper = this.createHelp();
|
|
3188
|
+
const context = this._getOutputContext(contextOptions);
|
|
3189
|
+
helper.prepareContext({
|
|
3190
|
+
error: context.error,
|
|
3191
|
+
helpWidth: context.helpWidth,
|
|
3192
|
+
outputHasColors: context.hasColors
|
|
3193
|
+
});
|
|
3194
|
+
const text = helper.formatHelp(this, helper);
|
|
3195
|
+
if (context.hasColors) return text;
|
|
3196
|
+
return this._outputConfiguration.stripColor(text);
|
|
3197
|
+
}
|
|
3198
|
+
/**
|
|
3199
|
+
* @typedef HelpContext
|
|
3200
|
+
* @type {object}
|
|
3201
|
+
* @property {boolean} error
|
|
3202
|
+
* @property {number} helpWidth
|
|
3203
|
+
* @property {boolean} hasColors
|
|
3204
|
+
* @property {function} write - includes stripColor if needed
|
|
3205
|
+
*
|
|
3206
|
+
* @returns {HelpContext}
|
|
3207
|
+
* @private
|
|
3208
|
+
*/
|
|
3209
|
+
_getOutputContext(contextOptions) {
|
|
3210
|
+
contextOptions = contextOptions || {};
|
|
3211
|
+
const error = !!contextOptions.error;
|
|
3212
|
+
let baseWrite;
|
|
3213
|
+
let hasColors;
|
|
3214
|
+
let helpWidth;
|
|
3215
|
+
if (error) {
|
|
3216
|
+
baseWrite = (str) => this._outputConfiguration.writeErr(str);
|
|
3217
|
+
hasColors = this._outputConfiguration.getErrHasColors();
|
|
3218
|
+
helpWidth = this._outputConfiguration.getErrHelpWidth();
|
|
3219
|
+
} else {
|
|
3220
|
+
baseWrite = (str) => this._outputConfiguration.writeOut(str);
|
|
3221
|
+
hasColors = this._outputConfiguration.getOutHasColors();
|
|
3222
|
+
helpWidth = this._outputConfiguration.getOutHelpWidth();
|
|
3223
|
+
}
|
|
3224
|
+
const write = (str) => {
|
|
3225
|
+
if (!hasColors) str = this._outputConfiguration.stripColor(str);
|
|
3226
|
+
return baseWrite(str);
|
|
3227
|
+
};
|
|
3228
|
+
return { error, write, hasColors, helpWidth };
|
|
3229
|
+
}
|
|
3230
|
+
/**
|
|
3231
|
+
* Output help information for this command.
|
|
3232
|
+
*
|
|
3233
|
+
* Outputs built-in help, and custom text added using `.addHelpText()`.
|
|
3234
|
+
*
|
|
3235
|
+
* @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
|
|
3236
|
+
*/
|
|
3237
|
+
outputHelp(contextOptions) {
|
|
3238
|
+
let deprecatedCallback;
|
|
3239
|
+
if (typeof contextOptions === "function") {
|
|
3240
|
+
deprecatedCallback = contextOptions;
|
|
3241
|
+
contextOptions = void 0;
|
|
3242
|
+
}
|
|
3243
|
+
const outputContext = this._getOutputContext(contextOptions);
|
|
3244
|
+
const eventContext = {
|
|
3245
|
+
error: outputContext.error,
|
|
3246
|
+
write: outputContext.write,
|
|
3247
|
+
command: this
|
|
3248
|
+
};
|
|
3249
|
+
this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
|
|
3250
|
+
this.emit("beforeHelp", eventContext);
|
|
3251
|
+
let helpInformation = this.helpInformation({ error: outputContext.error });
|
|
3252
|
+
if (deprecatedCallback) {
|
|
3253
|
+
helpInformation = deprecatedCallback(helpInformation);
|
|
3254
|
+
if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
|
|
3255
|
+
throw new Error("outputHelp callback must return a string or a Buffer");
|
|
3256
|
+
}
|
|
3257
|
+
}
|
|
3258
|
+
outputContext.write(helpInformation);
|
|
3259
|
+
if (this._getHelpOption()?.long) {
|
|
3260
|
+
this.emit(this._getHelpOption().long);
|
|
3261
|
+
}
|
|
3262
|
+
this.emit("afterHelp", eventContext);
|
|
3263
|
+
this._getCommandAndAncestors().forEach(
|
|
3264
|
+
(command) => command.emit("afterAllHelp", eventContext)
|
|
3265
|
+
);
|
|
3266
|
+
}
|
|
3267
|
+
/**
|
|
3268
|
+
* You can pass in flags and a description to customise the built-in help option.
|
|
3269
|
+
* Pass in false to disable the built-in help option.
|
|
3270
|
+
*
|
|
3271
|
+
* @example
|
|
3272
|
+
* program.helpOption('-?, --help' 'show help'); // customise
|
|
3273
|
+
* program.helpOption(false); // disable
|
|
3274
|
+
*
|
|
3275
|
+
* @param {(string | boolean)} flags
|
|
3276
|
+
* @param {string} [description]
|
|
3277
|
+
* @return {Command} `this` command for chaining
|
|
3278
|
+
*/
|
|
3279
|
+
helpOption(flags, description) {
|
|
3280
|
+
if (typeof flags === "boolean") {
|
|
3281
|
+
if (flags) {
|
|
3282
|
+
if (this._helpOption === null) this._helpOption = void 0;
|
|
3283
|
+
if (this._defaultOptionGroup) {
|
|
3284
|
+
this._initOptionGroup(this._getHelpOption());
|
|
3285
|
+
}
|
|
3286
|
+
} else {
|
|
3287
|
+
this._helpOption = null;
|
|
3288
|
+
}
|
|
3289
|
+
return this;
|
|
3290
|
+
}
|
|
3291
|
+
this._helpOption = this.createOption(
|
|
3292
|
+
flags ?? "-h, --help",
|
|
3293
|
+
description ?? "display help for command"
|
|
3294
|
+
);
|
|
3295
|
+
if (flags || description) this._initOptionGroup(this._helpOption);
|
|
3296
|
+
return this;
|
|
3297
|
+
}
|
|
3298
|
+
/**
|
|
3299
|
+
* Lazy create help option.
|
|
3300
|
+
* Returns null if has been disabled with .helpOption(false).
|
|
3301
|
+
*
|
|
3302
|
+
* @returns {(Option | null)} the help option
|
|
3303
|
+
* @package
|
|
3304
|
+
*/
|
|
3305
|
+
_getHelpOption() {
|
|
3306
|
+
if (this._helpOption === void 0) {
|
|
3307
|
+
this.helpOption(void 0, void 0);
|
|
3308
|
+
}
|
|
3309
|
+
return this._helpOption;
|
|
3310
|
+
}
|
|
3311
|
+
/**
|
|
3312
|
+
* Supply your own option to use for the built-in help option.
|
|
3313
|
+
* This is an alternative to using helpOption() to customise the flags and description etc.
|
|
3314
|
+
*
|
|
3315
|
+
* @param {Option} option
|
|
3316
|
+
* @return {Command} `this` command for chaining
|
|
3317
|
+
*/
|
|
3318
|
+
addHelpOption(option) {
|
|
3319
|
+
this._helpOption = option;
|
|
3320
|
+
this._initOptionGroup(option);
|
|
3321
|
+
return this;
|
|
3322
|
+
}
|
|
3323
|
+
/**
|
|
3324
|
+
* Output help information and exit.
|
|
3325
|
+
*
|
|
3326
|
+
* Outputs built-in help, and custom text added using `.addHelpText()`.
|
|
3327
|
+
*
|
|
3328
|
+
* @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
|
|
3329
|
+
*/
|
|
3330
|
+
help(contextOptions) {
|
|
3331
|
+
this.outputHelp(contextOptions);
|
|
3332
|
+
let exitCode = Number(process2.exitCode ?? 0);
|
|
3333
|
+
if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
|
|
3334
|
+
exitCode = 1;
|
|
3335
|
+
}
|
|
3336
|
+
this._exit(exitCode, "commander.help", "(outputHelp)");
|
|
3337
|
+
}
|
|
3338
|
+
/**
|
|
3339
|
+
* // Do a little typing to coordinate emit and listener for the help text events.
|
|
3340
|
+
* @typedef HelpTextEventContext
|
|
3341
|
+
* @type {object}
|
|
3342
|
+
* @property {boolean} error
|
|
3343
|
+
* @property {Command} command
|
|
3344
|
+
* @property {function} write
|
|
3345
|
+
*/
|
|
3346
|
+
/**
|
|
3347
|
+
* Add additional text to be displayed with the built-in help.
|
|
3348
|
+
*
|
|
3349
|
+
* Position is 'before' or 'after' to affect just this command,
|
|
3350
|
+
* and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
|
|
3351
|
+
*
|
|
3352
|
+
* @param {string} position - before or after built-in help
|
|
3353
|
+
* @param {(string | Function)} text - string to add, or a function returning a string
|
|
3354
|
+
* @return {Command} `this` command for chaining
|
|
3355
|
+
*/
|
|
3356
|
+
addHelpText(position, text) {
|
|
3357
|
+
const allowedValues = ["beforeAll", "before", "after", "afterAll"];
|
|
3358
|
+
if (!allowedValues.includes(position)) {
|
|
3359
|
+
throw new Error(`Unexpected value for position to addHelpText.
|
|
3360
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
3361
|
+
}
|
|
3362
|
+
const helpEvent = `${position}Help`;
|
|
3363
|
+
this.on(helpEvent, (context) => {
|
|
3364
|
+
let helpStr;
|
|
3365
|
+
if (typeof text === "function") {
|
|
3366
|
+
helpStr = text({ error: context.error, command: context.command });
|
|
3367
|
+
} else {
|
|
3368
|
+
helpStr = text;
|
|
3369
|
+
}
|
|
3370
|
+
if (helpStr) {
|
|
3371
|
+
context.write(`${helpStr}
|
|
3372
|
+
`);
|
|
3373
|
+
}
|
|
3374
|
+
});
|
|
3375
|
+
return this;
|
|
3376
|
+
}
|
|
3377
|
+
/**
|
|
3378
|
+
* Output help information if help flags specified
|
|
3379
|
+
*
|
|
3380
|
+
* @param {Array} args - array of options to search for help flags
|
|
3381
|
+
* @private
|
|
3382
|
+
*/
|
|
3383
|
+
_outputHelpIfRequested(args) {
|
|
3384
|
+
const helpOption = this._getHelpOption();
|
|
3385
|
+
const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
|
|
3386
|
+
if (helpRequested) {
|
|
3387
|
+
this.outputHelp();
|
|
3388
|
+
this._exit(0, "commander.helpDisplayed", "(outputHelp)");
|
|
3389
|
+
}
|
|
3390
|
+
}
|
|
3391
|
+
};
|
|
3392
|
+
function incrementNodeInspectorPort(args) {
|
|
3393
|
+
return args.map((arg) => {
|
|
3394
|
+
if (!arg.startsWith("--inspect")) {
|
|
3395
|
+
return arg;
|
|
3396
|
+
}
|
|
3397
|
+
let debugOption;
|
|
3398
|
+
let debugHost = "127.0.0.1";
|
|
3399
|
+
let debugPort = "9229";
|
|
3400
|
+
let match;
|
|
3401
|
+
if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
|
|
3402
|
+
debugOption = match[1];
|
|
3403
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
|
|
3404
|
+
debugOption = match[1];
|
|
3405
|
+
if (/^\d+$/.test(match[3])) {
|
|
3406
|
+
debugPort = match[3];
|
|
3407
|
+
} else {
|
|
3408
|
+
debugHost = match[3];
|
|
3409
|
+
}
|
|
3410
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
|
|
3411
|
+
debugOption = match[1];
|
|
3412
|
+
debugHost = match[3];
|
|
3413
|
+
debugPort = match[4];
|
|
3414
|
+
}
|
|
3415
|
+
if (debugOption && debugPort !== "0") {
|
|
3416
|
+
return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
|
|
3417
|
+
}
|
|
3418
|
+
return arg;
|
|
3419
|
+
});
|
|
3420
|
+
}
|
|
3421
|
+
function useColor() {
|
|
3422
|
+
if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
|
|
3423
|
+
return false;
|
|
3424
|
+
if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== void 0)
|
|
3425
|
+
return true;
|
|
3426
|
+
return void 0;
|
|
3427
|
+
}
|
|
3428
|
+
exports2.Command = Command2;
|
|
3429
|
+
exports2.useColor = useColor;
|
|
3430
|
+
}
|
|
3431
|
+
});
|
|
3432
|
+
|
|
3433
|
+
// node_modules/commander/index.js
|
|
3434
|
+
var require_commander = __commonJS({
|
|
3435
|
+
"node_modules/commander/index.js"(exports2) {
|
|
3436
|
+
var { Argument: Argument2 } = require_argument();
|
|
3437
|
+
var { Command: Command2 } = require_command();
|
|
3438
|
+
var { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = require_error();
|
|
3439
|
+
var { Help: Help2 } = require_help();
|
|
3440
|
+
var { Option: Option2 } = require_option();
|
|
3441
|
+
exports2.program = new Command2();
|
|
3442
|
+
exports2.createCommand = (name) => new Command2(name);
|
|
3443
|
+
exports2.createOption = (flags, description) => new Option2(flags, description);
|
|
3444
|
+
exports2.createArgument = (name, description) => new Argument2(name, description);
|
|
3445
|
+
exports2.Command = Command2;
|
|
3446
|
+
exports2.Option = Option2;
|
|
3447
|
+
exports2.Argument = Argument2;
|
|
3448
|
+
exports2.Help = Help2;
|
|
3449
|
+
exports2.CommanderError = CommanderError2;
|
|
3450
|
+
exports2.InvalidArgumentError = InvalidArgumentError2;
|
|
3451
|
+
exports2.InvalidOptionArgumentError = InvalidArgumentError2;
|
|
3452
|
+
}
|
|
3453
|
+
});
|
|
3454
|
+
|
|
3455
|
+
// src/cli.ts
|
|
3456
|
+
var import_fs4 = require("fs");
|
|
3457
|
+
var import_path5 = require("path");
|
|
3458
|
+
var import_os2 = require("os");
|
|
3459
|
+
var import_child_process = require("child_process");
|
|
3460
|
+
|
|
3461
|
+
// node_modules/commander/esm.mjs
|
|
3462
|
+
var import_index = __toESM(require_commander(), 1);
|
|
3463
|
+
var {
|
|
3464
|
+
program,
|
|
3465
|
+
createCommand,
|
|
3466
|
+
createArgument,
|
|
3467
|
+
createOption,
|
|
3468
|
+
CommanderError,
|
|
3469
|
+
InvalidArgumentError,
|
|
3470
|
+
InvalidOptionArgumentError,
|
|
3471
|
+
// deprecated old name
|
|
3472
|
+
Command,
|
|
3473
|
+
Argument,
|
|
3474
|
+
Option,
|
|
3475
|
+
Help
|
|
3476
|
+
} = import_index.default;
|
|
3477
|
+
|
|
3478
|
+
// src/direct-unity-client.ts
|
|
3479
|
+
var net = __toESM(require("net"), 1);
|
|
3480
|
+
|
|
3481
|
+
// src/simple-framer.ts
|
|
3482
|
+
var CONTENT_LENGTH_HEADER = "Content-Length:";
|
|
3483
|
+
var HEADER_SEPARATOR = "\r\n\r\n";
|
|
3484
|
+
function createFrame(jsonContent) {
|
|
3485
|
+
const contentLength = Buffer.byteLength(jsonContent, "utf8");
|
|
3486
|
+
return `${CONTENT_LENGTH_HEADER} ${contentLength}${HEADER_SEPARATOR}${jsonContent}`;
|
|
3487
|
+
}
|
|
3488
|
+
function parseFrameFromBuffer(data) {
|
|
3489
|
+
if (!data || data.length === 0) {
|
|
3490
|
+
return { contentLength: -1, headerLength: -1, isComplete: false };
|
|
3491
|
+
}
|
|
3492
|
+
const separatorBuffer = Buffer.from(HEADER_SEPARATOR, "utf8");
|
|
3493
|
+
const separatorIndex = data.indexOf(separatorBuffer);
|
|
3494
|
+
if (separatorIndex === -1) {
|
|
3495
|
+
return { contentLength: -1, headerLength: -1, isComplete: false };
|
|
3496
|
+
}
|
|
3497
|
+
const headerSection = data.subarray(0, separatorIndex).toString("utf8");
|
|
3498
|
+
const headerLength = separatorIndex + separatorBuffer.length;
|
|
3499
|
+
const contentLength = parseContentLength(headerSection);
|
|
3500
|
+
if (contentLength === -1) {
|
|
3501
|
+
return { contentLength: -1, headerLength: -1, isComplete: false };
|
|
3502
|
+
}
|
|
3503
|
+
const expectedTotalLength = headerLength + contentLength;
|
|
3504
|
+
const isComplete = data.length >= expectedTotalLength;
|
|
3505
|
+
return { contentLength, headerLength, isComplete };
|
|
3506
|
+
}
|
|
3507
|
+
function extractFrameFromBuffer(data, contentLength, headerLength) {
|
|
3508
|
+
if (!data || data.length === 0 || contentLength < 0 || headerLength < 0) {
|
|
3509
|
+
return { jsonContent: null, remainingData: data || Buffer.alloc(0) };
|
|
3510
|
+
}
|
|
3511
|
+
const expectedTotalLength = headerLength + contentLength;
|
|
3512
|
+
if (data.length < expectedTotalLength) {
|
|
3513
|
+
return { jsonContent: null, remainingData: data };
|
|
3514
|
+
}
|
|
3515
|
+
const jsonContent = data.subarray(headerLength, headerLength + contentLength).toString("utf8");
|
|
3516
|
+
const remainingData = data.subarray(expectedTotalLength);
|
|
3517
|
+
return { jsonContent, remainingData };
|
|
3518
|
+
}
|
|
3519
|
+
function parseContentLength(headerSection) {
|
|
3520
|
+
const lines = headerSection.split(/\r?\n/);
|
|
3521
|
+
for (const line of lines) {
|
|
3522
|
+
const trimmedLine = line.trim();
|
|
3523
|
+
const lowerLine = trimmedLine.toLowerCase();
|
|
3524
|
+
if (lowerLine.startsWith("content-length:")) {
|
|
3525
|
+
const colonIndex = trimmedLine.indexOf(":");
|
|
3526
|
+
if (colonIndex === -1 || colonIndex >= trimmedLine.length - 1) {
|
|
3527
|
+
continue;
|
|
3528
|
+
}
|
|
3529
|
+
const valueString = trimmedLine.substring(colonIndex + 1).trim();
|
|
3530
|
+
const parsedValue = parseInt(valueString, 10);
|
|
3531
|
+
if (isNaN(parsedValue) || parsedValue < 0) {
|
|
3532
|
+
return -1;
|
|
3533
|
+
}
|
|
3534
|
+
return parsedValue;
|
|
3535
|
+
}
|
|
3536
|
+
}
|
|
3537
|
+
return -1;
|
|
3538
|
+
}
|
|
3539
|
+
|
|
3540
|
+
// src/direct-unity-client.ts
|
|
3541
|
+
var JSONRPC_VERSION = "2.0";
|
|
3542
|
+
var DEFAULT_HOST = "127.0.0.1";
|
|
3543
|
+
var NETWORK_TIMEOUT_MS = 18e4;
|
|
3544
|
+
var DirectUnityClient = class {
|
|
3545
|
+
constructor(port, host = DEFAULT_HOST) {
|
|
3546
|
+
this.port = port;
|
|
3547
|
+
this.host = host;
|
|
3548
|
+
}
|
|
3549
|
+
socket = null;
|
|
3550
|
+
requestId = 0;
|
|
3551
|
+
receiveBuffer = Buffer.alloc(0);
|
|
3552
|
+
async connect() {
|
|
3553
|
+
return new Promise((resolve, reject) => {
|
|
3554
|
+
this.socket = new net.Socket();
|
|
3555
|
+
this.socket.on("error", (error) => {
|
|
3556
|
+
reject(new Error(`Connection error: ${error.message}`));
|
|
3557
|
+
});
|
|
3558
|
+
this.socket.connect(this.port, this.host, () => {
|
|
3559
|
+
resolve();
|
|
3560
|
+
});
|
|
3561
|
+
});
|
|
3562
|
+
}
|
|
3563
|
+
async sendRequest(method, params) {
|
|
3564
|
+
if (!this.socket) {
|
|
3565
|
+
throw new Error("Not connected to Unity");
|
|
3566
|
+
}
|
|
3567
|
+
const request = {
|
|
3568
|
+
jsonrpc: JSONRPC_VERSION,
|
|
3569
|
+
method,
|
|
3570
|
+
params: params ?? {},
|
|
3571
|
+
id: ++this.requestId
|
|
3572
|
+
};
|
|
3573
|
+
const requestJson = JSON.stringify(request);
|
|
3574
|
+
const framedMessage = createFrame(requestJson);
|
|
3575
|
+
return new Promise((resolve, reject) => {
|
|
3576
|
+
const socket = this.socket;
|
|
3577
|
+
const timeoutId = setTimeout(() => {
|
|
3578
|
+
reject(new Error(`Request timed out after ${NETWORK_TIMEOUT_MS}ms`));
|
|
3579
|
+
}, NETWORK_TIMEOUT_MS);
|
|
3580
|
+
const onData = (chunk) => {
|
|
3581
|
+
this.receiveBuffer = Buffer.concat([this.receiveBuffer, chunk]);
|
|
3582
|
+
const parseResult = parseFrameFromBuffer(this.receiveBuffer);
|
|
3583
|
+
if (!parseResult.isComplete) {
|
|
3584
|
+
return;
|
|
3585
|
+
}
|
|
3586
|
+
const extractResult = extractFrameFromBuffer(
|
|
3587
|
+
this.receiveBuffer,
|
|
3588
|
+
parseResult.contentLength,
|
|
3589
|
+
parseResult.headerLength
|
|
3590
|
+
);
|
|
3591
|
+
if (extractResult.jsonContent === null) {
|
|
3592
|
+
return;
|
|
3593
|
+
}
|
|
3594
|
+
clearTimeout(timeoutId);
|
|
3595
|
+
socket.off("data", onData);
|
|
3596
|
+
this.receiveBuffer = extractResult.remainingData;
|
|
3597
|
+
const response = JSON.parse(extractResult.jsonContent);
|
|
3598
|
+
if (response.error) {
|
|
3599
|
+
reject(new Error(`Unity error: ${response.error.message}`));
|
|
3600
|
+
return;
|
|
3601
|
+
}
|
|
3602
|
+
resolve(response.result);
|
|
3603
|
+
};
|
|
3604
|
+
socket.on("data", onData);
|
|
3605
|
+
socket.write(framedMessage);
|
|
3606
|
+
});
|
|
3607
|
+
}
|
|
3608
|
+
disconnect() {
|
|
3609
|
+
if (this.socket) {
|
|
3610
|
+
this.socket.destroy();
|
|
3611
|
+
this.socket = null;
|
|
3612
|
+
}
|
|
3613
|
+
this.receiveBuffer = Buffer.alloc(0);
|
|
3614
|
+
}
|
|
3615
|
+
isConnected() {
|
|
3616
|
+
return this.socket !== null && !this.socket.destroyed;
|
|
3617
|
+
}
|
|
3618
|
+
};
|
|
3619
|
+
|
|
3620
|
+
// src/port-resolver.ts
|
|
3621
|
+
var import_promises = require("fs/promises");
|
|
3622
|
+
var import_path2 = require("path");
|
|
3623
|
+
|
|
3624
|
+
// src/project-root.ts
|
|
3625
|
+
var import_fs = require("fs");
|
|
3626
|
+
var import_path = require("path");
|
|
3627
|
+
function findUnityProjectRoot(startPath = process.cwd()) {
|
|
3628
|
+
let currentPath = startPath;
|
|
3629
|
+
while (true) {
|
|
3630
|
+
const hasAssets = (0, import_fs.existsSync)((0, import_path.join)(currentPath, "Assets"));
|
|
3631
|
+
const hasProjectSettings = (0, import_fs.existsSync)((0, import_path.join)(currentPath, "ProjectSettings"));
|
|
3632
|
+
if (hasAssets && hasProjectSettings) {
|
|
3633
|
+
return currentPath;
|
|
3634
|
+
}
|
|
3635
|
+
const parentPath = (0, import_path.dirname)(currentPath);
|
|
3636
|
+
if (parentPath === currentPath) {
|
|
3637
|
+
return null;
|
|
3638
|
+
}
|
|
3639
|
+
currentPath = parentPath;
|
|
3640
|
+
}
|
|
3641
|
+
}
|
|
3642
|
+
|
|
3643
|
+
// src/port-resolver.ts
|
|
3644
|
+
var DEFAULT_PORT = 8700;
|
|
3645
|
+
async function resolveUnityPort(explicitPort) {
|
|
3646
|
+
if (explicitPort !== void 0) {
|
|
3647
|
+
return explicitPort;
|
|
3648
|
+
}
|
|
3649
|
+
const settingsPort = await readPortFromSettings();
|
|
3650
|
+
if (settingsPort !== null) {
|
|
3651
|
+
return settingsPort;
|
|
3652
|
+
}
|
|
3653
|
+
return DEFAULT_PORT;
|
|
3654
|
+
}
|
|
3655
|
+
async function readPortFromSettings() {
|
|
3656
|
+
const projectRoot = findUnityProjectRoot();
|
|
3657
|
+
if (projectRoot === null) {
|
|
3658
|
+
return null;
|
|
3659
|
+
}
|
|
3660
|
+
const settingsPath = (0, import_path2.join)(projectRoot, "UserSettings/UnityMcpSettings.json");
|
|
3661
|
+
let content;
|
|
3662
|
+
try {
|
|
3663
|
+
content = await (0, import_promises.readFile)(settingsPath, "utf-8");
|
|
3664
|
+
} catch {
|
|
3665
|
+
return null;
|
|
3666
|
+
}
|
|
3667
|
+
let settings;
|
|
3668
|
+
try {
|
|
3669
|
+
settings = JSON.parse(content);
|
|
3670
|
+
} catch {
|
|
3671
|
+
return null;
|
|
3672
|
+
}
|
|
3673
|
+
if (typeof settings.serverPort === "number") {
|
|
3674
|
+
return settings.serverPort;
|
|
3675
|
+
}
|
|
3676
|
+
if (typeof settings.customPort === "number") {
|
|
3677
|
+
return settings.customPort;
|
|
3678
|
+
}
|
|
3679
|
+
return null;
|
|
3680
|
+
}
|
|
3681
|
+
|
|
3682
|
+
// src/tool-cache.ts
|
|
3683
|
+
var import_fs2 = require("fs");
|
|
3684
|
+
var import_path3 = require("path");
|
|
3685
|
+
|
|
3686
|
+
// src/default-tools.json
|
|
3687
|
+
var default_tools_default = {
|
|
3688
|
+
version: "0.44.1",
|
|
3689
|
+
tools: [
|
|
3690
|
+
{
|
|
3691
|
+
name: "compile",
|
|
3692
|
+
description: "Execute Unity project compilation",
|
|
3693
|
+
inputSchema: {
|
|
3694
|
+
type: "object",
|
|
3695
|
+
properties: {
|
|
3696
|
+
ForceRecompile: {
|
|
3697
|
+
type: "boolean",
|
|
3698
|
+
description: "Force full recompilation"
|
|
3699
|
+
}
|
|
3700
|
+
}
|
|
3701
|
+
}
|
|
3702
|
+
},
|
|
3703
|
+
{
|
|
3704
|
+
name: "get-logs",
|
|
3705
|
+
description: "Retrieve logs from Unity Console",
|
|
3706
|
+
inputSchema: {
|
|
3707
|
+
type: "object",
|
|
3708
|
+
properties: {
|
|
3709
|
+
LogType: {
|
|
3710
|
+
type: "string",
|
|
3711
|
+
description: "Log type filter",
|
|
3712
|
+
enum: [
|
|
3713
|
+
"Error",
|
|
3714
|
+
"Warning",
|
|
3715
|
+
"Log",
|
|
3716
|
+
"All"
|
|
3717
|
+
],
|
|
3718
|
+
default: "All"
|
|
3719
|
+
},
|
|
3720
|
+
MaxCount: {
|
|
3721
|
+
type: "integer",
|
|
3722
|
+
description: "Maximum number of logs to retrieve",
|
|
3723
|
+
default: 100
|
|
3724
|
+
},
|
|
3725
|
+
SearchText: {
|
|
3726
|
+
type: "string",
|
|
3727
|
+
description: "Text to search within logs"
|
|
3728
|
+
},
|
|
3729
|
+
IncludeStackTrace: {
|
|
3730
|
+
type: "boolean",
|
|
3731
|
+
description: "Include stack trace in output",
|
|
3732
|
+
default: true
|
|
3733
|
+
},
|
|
3734
|
+
UseRegex: {
|
|
3735
|
+
type: "boolean",
|
|
3736
|
+
description: "Use regex for search"
|
|
3737
|
+
},
|
|
3738
|
+
SearchInStackTrace: {
|
|
3739
|
+
type: "boolean",
|
|
3740
|
+
description: "Search within stack trace"
|
|
3741
|
+
}
|
|
3742
|
+
}
|
|
3743
|
+
}
|
|
3744
|
+
},
|
|
3745
|
+
{
|
|
3746
|
+
name: "run-tests",
|
|
3747
|
+
description: "Execute Unity Test Runner",
|
|
3748
|
+
inputSchema: {
|
|
3749
|
+
type: "object",
|
|
3750
|
+
properties: {
|
|
3751
|
+
TestMode: {
|
|
3752
|
+
type: "string",
|
|
3753
|
+
description: "Test mode",
|
|
3754
|
+
enum: [
|
|
3755
|
+
"EditMode",
|
|
3756
|
+
"PlayMode"
|
|
3757
|
+
],
|
|
3758
|
+
default: "EditMode"
|
|
3759
|
+
},
|
|
3760
|
+
FilterType: {
|
|
3761
|
+
type: "string",
|
|
3762
|
+
description: "Filter type",
|
|
3763
|
+
enum: [
|
|
3764
|
+
"all",
|
|
3765
|
+
"exact",
|
|
3766
|
+
"regex",
|
|
3767
|
+
"assembly"
|
|
3768
|
+
],
|
|
3769
|
+
default: "all"
|
|
3770
|
+
},
|
|
3771
|
+
FilterValue: {
|
|
3772
|
+
type: "string",
|
|
3773
|
+
description: "Filter value"
|
|
3774
|
+
},
|
|
3775
|
+
SaveXml: {
|
|
3776
|
+
type: "boolean",
|
|
3777
|
+
description: "Save test results as XML"
|
|
3778
|
+
}
|
|
3779
|
+
}
|
|
3780
|
+
}
|
|
3781
|
+
},
|
|
3782
|
+
{
|
|
3783
|
+
name: "clear-console",
|
|
3784
|
+
description: "Clear Unity console logs",
|
|
3785
|
+
inputSchema: {
|
|
3786
|
+
type: "object",
|
|
3787
|
+
properties: {
|
|
3788
|
+
AddConfirmationMessage: {
|
|
3789
|
+
type: "boolean",
|
|
3790
|
+
description: "Add confirmation message after clearing"
|
|
3791
|
+
}
|
|
3792
|
+
}
|
|
3793
|
+
}
|
|
3794
|
+
},
|
|
3795
|
+
{
|
|
3796
|
+
name: "focus-window",
|
|
3797
|
+
description: "Bring Unity Editor window to front",
|
|
3798
|
+
inputSchema: {
|
|
3799
|
+
type: "object",
|
|
3800
|
+
properties: {}
|
|
3801
|
+
}
|
|
3802
|
+
},
|
|
3803
|
+
{
|
|
3804
|
+
name: "get-hierarchy",
|
|
3805
|
+
description: "Get Unity Hierarchy structure",
|
|
3806
|
+
inputSchema: {
|
|
3807
|
+
type: "object",
|
|
3808
|
+
properties: {
|
|
3809
|
+
RootPath: {
|
|
3810
|
+
type: "string",
|
|
3811
|
+
description: "Root GameObject path"
|
|
3812
|
+
},
|
|
3813
|
+
MaxDepth: {
|
|
3814
|
+
type: "integer",
|
|
3815
|
+
description: "Maximum depth (-1 for unlimited)",
|
|
3816
|
+
default: -1
|
|
3817
|
+
},
|
|
3818
|
+
IncludeComponents: {
|
|
3819
|
+
type: "boolean",
|
|
3820
|
+
description: "Include component information",
|
|
3821
|
+
default: true
|
|
3822
|
+
},
|
|
3823
|
+
IncludeInactive: {
|
|
3824
|
+
type: "boolean",
|
|
3825
|
+
description: "Include inactive GameObjects",
|
|
3826
|
+
default: true
|
|
3827
|
+
},
|
|
3828
|
+
IncludePaths: {
|
|
3829
|
+
type: "boolean",
|
|
3830
|
+
description: "Include path information"
|
|
3831
|
+
}
|
|
3832
|
+
}
|
|
3833
|
+
}
|
|
3834
|
+
},
|
|
3835
|
+
{
|
|
3836
|
+
name: "unity-search",
|
|
3837
|
+
description: "Search Unity project",
|
|
3838
|
+
inputSchema: {
|
|
3839
|
+
type: "object",
|
|
3840
|
+
properties: {
|
|
3841
|
+
SearchQuery: {
|
|
3842
|
+
type: "string",
|
|
3843
|
+
description: "Search query"
|
|
3844
|
+
},
|
|
3845
|
+
Providers: {
|
|
3846
|
+
type: "array",
|
|
3847
|
+
description: "Search providers",
|
|
3848
|
+
items: {
|
|
3849
|
+
type: "string"
|
|
3850
|
+
}
|
|
3851
|
+
},
|
|
3852
|
+
MaxResults: {
|
|
3853
|
+
type: "integer",
|
|
3854
|
+
description: "Maximum number of results",
|
|
3855
|
+
default: 50
|
|
3856
|
+
},
|
|
3857
|
+
SaveToFile: {
|
|
3858
|
+
type: "boolean",
|
|
3859
|
+
description: "Save results to file"
|
|
3860
|
+
}
|
|
3861
|
+
}
|
|
3862
|
+
}
|
|
3863
|
+
},
|
|
3864
|
+
{
|
|
3865
|
+
name: "get-menu-items",
|
|
3866
|
+
description: "Retrieve Unity MenuItems",
|
|
3867
|
+
inputSchema: {
|
|
3868
|
+
type: "object",
|
|
3869
|
+
properties: {
|
|
3870
|
+
FilterText: {
|
|
3871
|
+
type: "string",
|
|
3872
|
+
description: "Filter text"
|
|
3873
|
+
},
|
|
3874
|
+
FilterType: {
|
|
3875
|
+
type: "string",
|
|
3876
|
+
description: "Filter type",
|
|
3877
|
+
enum: [
|
|
3878
|
+
"contains",
|
|
3879
|
+
"exact",
|
|
3880
|
+
"startswith"
|
|
3881
|
+
],
|
|
3882
|
+
default: "contains"
|
|
3883
|
+
},
|
|
3884
|
+
MaxCount: {
|
|
3885
|
+
type: "integer",
|
|
3886
|
+
description: "Maximum number of items",
|
|
3887
|
+
default: 200
|
|
3888
|
+
},
|
|
3889
|
+
IncludeValidation: {
|
|
3890
|
+
type: "boolean",
|
|
3891
|
+
description: "Include validation functions"
|
|
3892
|
+
}
|
|
3893
|
+
}
|
|
3894
|
+
}
|
|
3895
|
+
},
|
|
3896
|
+
{
|
|
3897
|
+
name: "execute-menu-item",
|
|
3898
|
+
description: "Execute Unity MenuItem",
|
|
3899
|
+
inputSchema: {
|
|
3900
|
+
type: "object",
|
|
3901
|
+
properties: {
|
|
3902
|
+
MenuItemPath: {
|
|
3903
|
+
type: "string",
|
|
3904
|
+
description: 'Menu item path (e.g., "GameObject/Create Empty")'
|
|
3905
|
+
},
|
|
3906
|
+
UseReflectionFallback: {
|
|
3907
|
+
type: "boolean",
|
|
3908
|
+
description: "Use reflection fallback",
|
|
3909
|
+
default: true
|
|
3910
|
+
}
|
|
3911
|
+
}
|
|
3912
|
+
}
|
|
3913
|
+
},
|
|
3914
|
+
{
|
|
3915
|
+
name: "find-game-objects",
|
|
3916
|
+
description: "Find GameObjects with search criteria",
|
|
3917
|
+
inputSchema: {
|
|
3918
|
+
type: "object",
|
|
3919
|
+
properties: {
|
|
3920
|
+
NamePattern: {
|
|
3921
|
+
type: "string",
|
|
3922
|
+
description: "Name pattern to search"
|
|
3923
|
+
},
|
|
3924
|
+
SearchMode: {
|
|
3925
|
+
type: "string",
|
|
3926
|
+
description: "Search mode",
|
|
3927
|
+
enum: [
|
|
3928
|
+
"Exact",
|
|
3929
|
+
"Path",
|
|
3930
|
+
"Regex",
|
|
3931
|
+
"Contains"
|
|
3932
|
+
],
|
|
3933
|
+
default: "Contains"
|
|
3934
|
+
},
|
|
3935
|
+
RequiredComponents: {
|
|
3936
|
+
type: "array",
|
|
3937
|
+
description: "Required components",
|
|
3938
|
+
items: {
|
|
3939
|
+
type: "string"
|
|
3940
|
+
}
|
|
3941
|
+
},
|
|
3942
|
+
Tag: {
|
|
3943
|
+
type: "string",
|
|
3944
|
+
description: "Tag filter"
|
|
3945
|
+
},
|
|
3946
|
+
Layer: {
|
|
3947
|
+
type: "string",
|
|
3948
|
+
description: "Layer filter"
|
|
3949
|
+
},
|
|
3950
|
+
MaxResults: {
|
|
3951
|
+
type: "integer",
|
|
3952
|
+
description: "Maximum number of results",
|
|
3953
|
+
default: 20
|
|
3954
|
+
},
|
|
3955
|
+
IncludeInactive: {
|
|
3956
|
+
type: "boolean",
|
|
3957
|
+
description: "Include inactive GameObjects"
|
|
3958
|
+
}
|
|
3959
|
+
}
|
|
3960
|
+
}
|
|
3961
|
+
},
|
|
3962
|
+
{
|
|
3963
|
+
name: "capture-gameview",
|
|
3964
|
+
description: "Capture Unity Game View as PNG",
|
|
3965
|
+
inputSchema: {
|
|
3966
|
+
type: "object",
|
|
3967
|
+
properties: {
|
|
3968
|
+
ResolutionScale: {
|
|
3969
|
+
type: "number",
|
|
3970
|
+
description: "Resolution scale (0.1 to 1.0)",
|
|
3971
|
+
default: 1
|
|
3972
|
+
}
|
|
3973
|
+
}
|
|
3974
|
+
}
|
|
3975
|
+
},
|
|
3976
|
+
{
|
|
3977
|
+
name: "execute-dynamic-code",
|
|
3978
|
+
description: "Execute C# code in Unity Editor",
|
|
3979
|
+
inputSchema: {
|
|
3980
|
+
type: "object",
|
|
3981
|
+
properties: {
|
|
3982
|
+
Code: {
|
|
3983
|
+
type: "string",
|
|
3984
|
+
description: "C# code to execute"
|
|
3985
|
+
},
|
|
3986
|
+
CompileOnly: {
|
|
3987
|
+
type: "boolean",
|
|
3988
|
+
description: "Compile only without execution"
|
|
3989
|
+
},
|
|
3990
|
+
AutoQualifyUnityTypesOnce: {
|
|
3991
|
+
type: "boolean",
|
|
3992
|
+
description: "Auto-qualify Unity types"
|
|
3993
|
+
}
|
|
3994
|
+
}
|
|
3995
|
+
}
|
|
3996
|
+
},
|
|
3997
|
+
{
|
|
3998
|
+
name: "get-provider-details",
|
|
3999
|
+
description: "Get Unity Search provider details",
|
|
4000
|
+
inputSchema: {
|
|
4001
|
+
type: "object",
|
|
4002
|
+
properties: {
|
|
4003
|
+
ProviderId: {
|
|
4004
|
+
type: "string",
|
|
4005
|
+
description: "Specific provider ID"
|
|
4006
|
+
},
|
|
4007
|
+
ActiveOnly: {
|
|
4008
|
+
type: "boolean",
|
|
4009
|
+
description: "Only active providers"
|
|
4010
|
+
},
|
|
4011
|
+
IncludeDescriptions: {
|
|
4012
|
+
type: "boolean",
|
|
4013
|
+
description: "Include descriptions",
|
|
4014
|
+
default: true
|
|
4015
|
+
},
|
|
4016
|
+
SortByPriority: {
|
|
4017
|
+
type: "boolean",
|
|
4018
|
+
description: "Sort by priority",
|
|
4019
|
+
default: true
|
|
4020
|
+
}
|
|
4021
|
+
}
|
|
4022
|
+
}
|
|
4023
|
+
},
|
|
4024
|
+
{
|
|
4025
|
+
name: "get-project-info",
|
|
4026
|
+
description: "Get Unity project information",
|
|
4027
|
+
inputSchema: {
|
|
4028
|
+
type: "object",
|
|
4029
|
+
properties: {}
|
|
4030
|
+
}
|
|
4031
|
+
},
|
|
4032
|
+
{
|
|
4033
|
+
name: "get-version",
|
|
4034
|
+
description: "Get uLoopMCP version information",
|
|
4035
|
+
inputSchema: {
|
|
4036
|
+
type: "object",
|
|
4037
|
+
properties: {}
|
|
4038
|
+
}
|
|
4039
|
+
}
|
|
4040
|
+
]
|
|
4041
|
+
};
|
|
4042
|
+
|
|
4043
|
+
// src/tool-cache.ts
|
|
4044
|
+
var CACHE_DIR = ".uloop";
|
|
4045
|
+
var CACHE_FILE = "tools.json";
|
|
4046
|
+
function getCacheDir() {
|
|
4047
|
+
const projectRoot = findUnityProjectRoot();
|
|
4048
|
+
if (projectRoot === null) {
|
|
4049
|
+
return (0, import_path3.join)(process.cwd(), CACHE_DIR);
|
|
4050
|
+
}
|
|
4051
|
+
return (0, import_path3.join)(projectRoot, CACHE_DIR);
|
|
4052
|
+
}
|
|
4053
|
+
function getCachePath() {
|
|
4054
|
+
return (0, import_path3.join)(getCacheDir(), CACHE_FILE);
|
|
4055
|
+
}
|
|
4056
|
+
function getDefaultTools() {
|
|
4057
|
+
return default_tools_default;
|
|
4058
|
+
}
|
|
4059
|
+
function loadToolsCache() {
|
|
4060
|
+
const cachePath = getCachePath();
|
|
4061
|
+
if ((0, import_fs2.existsSync)(cachePath)) {
|
|
4062
|
+
try {
|
|
4063
|
+
const content = (0, import_fs2.readFileSync)(cachePath, "utf-8");
|
|
4064
|
+
return JSON.parse(content);
|
|
4065
|
+
} catch {
|
|
4066
|
+
return getDefaultTools();
|
|
4067
|
+
}
|
|
4068
|
+
}
|
|
4069
|
+
return getDefaultTools();
|
|
4070
|
+
}
|
|
4071
|
+
function saveToolsCache(cache) {
|
|
4072
|
+
const cacheDir = getCacheDir();
|
|
4073
|
+
const cachePath = getCachePath();
|
|
4074
|
+
if (!(0, import_fs2.existsSync)(cacheDir)) {
|
|
4075
|
+
(0, import_fs2.mkdirSync)(cacheDir, { recursive: true });
|
|
4076
|
+
}
|
|
4077
|
+
const content = JSON.stringify(cache, null, 2);
|
|
4078
|
+
(0, import_fs2.writeFileSync)(cachePath, content, "utf-8");
|
|
4079
|
+
}
|
|
4080
|
+
function getCacheFilePath() {
|
|
4081
|
+
return getCachePath();
|
|
4082
|
+
}
|
|
4083
|
+
|
|
4084
|
+
// src/version.ts
|
|
4085
|
+
var VERSION = "0.44.1";
|
|
4086
|
+
|
|
4087
|
+
// src/execute-tool.ts
|
|
4088
|
+
async function executeToolCommand(toolName, params, globalOptions) {
|
|
4089
|
+
let portNumber;
|
|
4090
|
+
if (globalOptions.port) {
|
|
4091
|
+
const parsed = parseInt(globalOptions.port, 10);
|
|
4092
|
+
if (isNaN(parsed)) {
|
|
4093
|
+
throw new Error(`Invalid port number: ${globalOptions.port}`);
|
|
4094
|
+
}
|
|
4095
|
+
portNumber = parsed;
|
|
4096
|
+
}
|
|
4097
|
+
const port = await resolveUnityPort(portNumber);
|
|
4098
|
+
const client = new DirectUnityClient(port);
|
|
4099
|
+
try {
|
|
4100
|
+
await client.connect();
|
|
4101
|
+
const result = await client.sendRequest(toolName, params);
|
|
4102
|
+
console.log(JSON.stringify(result, null, 2));
|
|
4103
|
+
} finally {
|
|
4104
|
+
client.disconnect();
|
|
4105
|
+
}
|
|
4106
|
+
}
|
|
4107
|
+
async function listAvailableTools(globalOptions) {
|
|
4108
|
+
let portNumber;
|
|
4109
|
+
if (globalOptions.port) {
|
|
4110
|
+
const parsed = parseInt(globalOptions.port, 10);
|
|
4111
|
+
if (isNaN(parsed)) {
|
|
4112
|
+
throw new Error(`Invalid port number: ${globalOptions.port}`);
|
|
4113
|
+
}
|
|
4114
|
+
portNumber = parsed;
|
|
4115
|
+
}
|
|
4116
|
+
const port = await resolveUnityPort(portNumber);
|
|
4117
|
+
const client = new DirectUnityClient(port);
|
|
4118
|
+
try {
|
|
4119
|
+
await client.connect();
|
|
4120
|
+
const result = await client.sendRequest("get-tool-details", { IncludeDevelopmentOnly: false });
|
|
4121
|
+
if (!result.Tools || !Array.isArray(result.Tools)) {
|
|
4122
|
+
throw new Error("Unexpected response from Unity: missing Tools array");
|
|
4123
|
+
}
|
|
4124
|
+
for (const tool of result.Tools) {
|
|
4125
|
+
console.log(` - ${tool.name}`);
|
|
4126
|
+
}
|
|
4127
|
+
} finally {
|
|
4128
|
+
client.disconnect();
|
|
4129
|
+
}
|
|
4130
|
+
}
|
|
4131
|
+
function convertProperties(unityProps) {
|
|
4132
|
+
const result = {};
|
|
4133
|
+
for (const [key, prop] of Object.entries(unityProps)) {
|
|
4134
|
+
result[key] = {
|
|
4135
|
+
type: prop.Type?.toLowerCase() ?? "string",
|
|
4136
|
+
description: prop.Description,
|
|
4137
|
+
default: prop.DefaultValue,
|
|
4138
|
+
enum: prop.Enum ?? void 0
|
|
4139
|
+
};
|
|
4140
|
+
}
|
|
4141
|
+
return result;
|
|
4142
|
+
}
|
|
4143
|
+
async function syncTools(globalOptions) {
|
|
4144
|
+
let portNumber;
|
|
4145
|
+
if (globalOptions.port) {
|
|
4146
|
+
const parsed = parseInt(globalOptions.port, 10);
|
|
4147
|
+
if (isNaN(parsed)) {
|
|
4148
|
+
throw new Error(`Invalid port number: ${globalOptions.port}`);
|
|
4149
|
+
}
|
|
4150
|
+
portNumber = parsed;
|
|
4151
|
+
}
|
|
4152
|
+
const port = await resolveUnityPort(portNumber);
|
|
4153
|
+
const client = new DirectUnityClient(port);
|
|
4154
|
+
try {
|
|
4155
|
+
await client.connect();
|
|
4156
|
+
const result = await client.sendRequest("get-tool-details", { IncludeDevelopmentOnly: false });
|
|
4157
|
+
if (!result.Tools || !Array.isArray(result.Tools)) {
|
|
4158
|
+
throw new Error("Unexpected response from Unity: missing Tools array");
|
|
4159
|
+
}
|
|
4160
|
+
const cache = {
|
|
4161
|
+
version: VERSION,
|
|
4162
|
+
updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
4163
|
+
tools: result.Tools.map((tool) => ({
|
|
4164
|
+
name: tool.name,
|
|
4165
|
+
description: tool.description,
|
|
4166
|
+
inputSchema: {
|
|
4167
|
+
type: "object",
|
|
4168
|
+
properties: convertProperties(tool.parameterSchema.Properties),
|
|
4169
|
+
required: tool.parameterSchema.Required
|
|
4170
|
+
}
|
|
4171
|
+
}))
|
|
4172
|
+
};
|
|
4173
|
+
saveToolsCache(cache);
|
|
4174
|
+
console.log(`Synced ${cache.tools.length} tools to ${getCacheFilePath()}`);
|
|
4175
|
+
console.log("\nTools:");
|
|
4176
|
+
for (const tool of cache.tools) {
|
|
4177
|
+
console.log(` - ${tool.name}`);
|
|
4178
|
+
}
|
|
4179
|
+
} finally {
|
|
4180
|
+
client.disconnect();
|
|
4181
|
+
}
|
|
4182
|
+
}
|
|
4183
|
+
|
|
4184
|
+
// src/arg-parser.ts
|
|
4185
|
+
function pascalToKebabCase(pascal) {
|
|
4186
|
+
const kebab = pascal.replace(/([A-Z])/g, "-$1").toLowerCase();
|
|
4187
|
+
return kebab.startsWith("-") ? kebab.slice(1) : kebab;
|
|
4188
|
+
}
|
|
4189
|
+
|
|
4190
|
+
// src/skills/skills-manager.ts
|
|
4191
|
+
var import_fs3 = require("fs");
|
|
4192
|
+
var import_path4 = require("path");
|
|
4193
|
+
var import_os = require("os");
|
|
4194
|
+
|
|
4195
|
+
// src/skills/skill-definitions/uloop-compile/SKILL.md
|
|
4196
|
+
var SKILL_default = "---\nname: uloop-compile\ndescription: Compile Unity project via uloop CLI. Use when you need to: (1) Verify C# code compiles successfully after editing scripts, (2) Check for compile errors or warnings, (3) Validate script changes before running tests.\n---\n\n# uloop compile\n\nExecute Unity project compilation.\n\n## Usage\n\n```bash\nuloop compile [--force-recompile]\n```\n\n## Parameters\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `--force-recompile` | boolean | Force full recompilation (triggers Domain Reload) |\n\n## Examples\n\n```bash\n# Check compilation\nuloop compile\n\n# Force full recompilation\nuloop compile --force-recompile\n```\n\n## Output\n\nReturns JSON:\n- `Success`: boolean\n- `ErrorCount`: number\n- `WarningCount`: number\n";
|
|
4197
|
+
|
|
4198
|
+
// src/skills/skill-definitions/uloop-get-logs/SKILL.md
|
|
4199
|
+
var SKILL_default2 = '---\nname: uloop-get-logs\ndescription: Retrieve Unity Console logs via uloop CLI. Use when you need to: (1) Check for errors or warnings after operations, (2) Debug runtime issues in Unity Editor, (3) Investigate unexpected behavior or exceptions.\n---\n\n# uloop get-logs\n\nRetrieve logs from Unity Console.\n\n## Usage\n\n```bash\nuloop get-logs [options]\n```\n\n## Parameters\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `--log-type` | string | `All` | Log type filter: `Error`, `Warning`, `Log`, `All` |\n| `--max-count` | integer | `100` | Maximum number of logs to retrieve |\n| `--search-text` | string | - | Text to search within logs |\n| `--include-stack-trace` | boolean | `true` | Include stack trace in output |\n| `--use-regex` | boolean | `false` | Use regex for search |\n| `--search-in-stack-trace` | boolean | `false` | Search within stack trace |\n\n## Examples\n\n```bash\n# Get all logs\nuloop get-logs\n\n# Get only errors\nuloop get-logs --log-type Error\n\n# Search for specific text\nuloop get-logs --search-text "NullReference"\n\n# Regex search\nuloop get-logs --search-text "Missing.*Component" --use-regex\n```\n\n## Output\n\nReturns JSON array of log entries with message, type, and optional stack trace.\n';
|
|
4200
|
+
|
|
4201
|
+
// src/skills/skill-definitions/uloop-run-tests/SKILL.md
|
|
4202
|
+
var SKILL_default3 = '---\nname: uloop-run-tests\ndescription: Execute Unity Test Runner via uloop CLI. Use when you need to: (1) Run unit tests (EditMode tests), (2) Run integration tests (PlayMode tests), (3) Verify code changes don\'t break existing functionality.\n---\n\n# uloop run-tests\n\nExecute Unity Test Runner.\n\n## Usage\n\n```bash\nuloop run-tests [options]\n```\n\n## Parameters\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `--test-mode` | string | `EditMode` | Test mode: `EditMode`, `PlayMode` |\n| `--filter-type` | string | `all` | Filter type: `all`, `exact`, `regex`, `assembly` |\n| `--filter-value` | string | - | Filter value (test name, pattern, or assembly) |\n| `--save-xml` | boolean | `false` | Save test results as XML |\n\n## Examples\n\n```bash\n# Run all EditMode tests\nuloop run-tests\n\n# Run PlayMode tests\nuloop run-tests --test-mode PlayMode\n\n# Run specific test\nuloop run-tests --filter-type exact --filter-value "MyTest.TestMethod"\n\n# Run tests matching pattern\nuloop run-tests --filter-type regex --filter-value ".*Integration.*"\n```\n\n## Output\n\nReturns JSON with test results including pass/fail counts and details.\n';
|
|
4203
|
+
|
|
4204
|
+
// src/skills/skill-definitions/uloop-clear-console/SKILL.md
|
|
4205
|
+
var SKILL_default4 = "---\nname: uloop-clear-console\ndescription: Clear Unity console logs via uloop CLI. Use when you need to: (1) Clear the console before running tests, (2) Start a fresh debugging session, (3) Clean up log output for better readability.\n---\n\n# uloop clear-console\n\nClear Unity console logs.\n\n## Usage\n\n```bash\nuloop clear-console [--add-confirmation-message]\n```\n\n## Parameters\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `--add-confirmation-message` | boolean | `false` | Add confirmation message after clearing |\n\n## Examples\n\n```bash\n# Clear console\nuloop clear-console\n\n# Clear with confirmation\nuloop clear-console --add-confirmation-message\n```\n\n## Output\n\nReturns JSON confirming the console was cleared.\n";
|
|
4206
|
+
|
|
4207
|
+
// src/skills/skill-definitions/uloop-focus-window/SKILL.md
|
|
4208
|
+
var SKILL_default5 = "---\nname: uloop-focus-window\ndescription: Bring Unity Editor window to front via uloop CLI. Use when you need to: (1) Focus Unity Editor before capturing screenshots, (2) Ensure Unity window is visible for visual checks, (3) Bring Unity to foreground for user interaction.\n---\n\n# uloop focus-window\n\nBring Unity Editor window to front.\n\n## Usage\n\n```bash\nuloop focus-window\n```\n\n## Parameters\n\nNone.\n\n## Examples\n\n```bash\n# Focus Unity Editor\nuloop focus-window\n```\n\n## Output\n\nReturns JSON confirming the window was focused.\n\n## Notes\n\n- Useful before `uloop capture-gameview` to ensure Game View is visible\n- Brings the main Unity Editor window to the foreground\n";
|
|
4209
|
+
|
|
4210
|
+
// src/skills/skill-definitions/uloop-get-hierarchy/SKILL.md
|
|
4211
|
+
var SKILL_default6 = '---\nname: uloop-get-hierarchy\ndescription: Get Unity Hierarchy structure via uloop CLI. Use when you need to: (1) Inspect scene structure and GameObject tree, (2) Find GameObjects and their parent-child relationships, (3) Check component attachments on objects.\n---\n\n# uloop get-hierarchy\n\nGet Unity Hierarchy structure.\n\n## Usage\n\n```bash\nuloop get-hierarchy [options]\n```\n\n## Parameters\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `--root-path` | string | - | Root GameObject path to start from |\n| `--max-depth` | integer | `-1` | Maximum depth (-1 for unlimited) |\n| `--include-components` | boolean | `true` | Include component information |\n| `--include-inactive` | boolean | `true` | Include inactive GameObjects |\n| `--include-paths` | boolean | `false` | Include full path information |\n\n## Examples\n\n```bash\n# Get entire hierarchy\nuloop get-hierarchy\n\n# Get hierarchy from specific root\nuloop get-hierarchy --root-path "Canvas/UI"\n\n# Limit depth\nuloop get-hierarchy --max-depth 2\n\n# Without components\nuloop get-hierarchy --include-components false\n```\n\n## Output\n\nReturns JSON with hierarchical structure of GameObjects and their components.\n';
|
|
4212
|
+
|
|
4213
|
+
// src/skills/skill-definitions/uloop-unity-search/SKILL.md
|
|
4214
|
+
var SKILL_default7 = '---\nname: uloop-unity-search\ndescription: Search Unity project via uloop CLI. Use when you need to: (1) Find assets by name or type (scenes, prefabs, scripts, materials), (2) Search for project resources using Unity\'s search system, (3) Locate files within the Unity project.\n---\n\n# uloop unity-search\n\nSearch Unity project using Unity Search.\n\n## Usage\n\n```bash\nuloop unity-search [options]\n```\n\n## Parameters\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `--search-query` | string | - | Search query |\n| `--providers` | array | - | Search providers (e.g., `asset`, `scene`, `find`) |\n| `--max-results` | integer | `50` | Maximum number of results |\n| `--save-to-file` | boolean | `false` | Save results to file |\n\n## Examples\n\n```bash\n# Search for assets\nuloop unity-search --search-query "Player"\n\n# Search with specific provider\nuloop unity-search --search-query "t:Prefab" --providers asset\n\n# Limit results\nuloop unity-search --search-query "*.cs" --max-results 20\n```\n\n## Output\n\nReturns JSON array of search results with paths and metadata.\n\n## Notes\n\nUse `uloop get-provider-details` to discover available search providers.\n';
|
|
4215
|
+
|
|
4216
|
+
// src/skills/skill-definitions/uloop-get-menu-items/SKILL.md
|
|
4217
|
+
var SKILL_default8 = '---\nname: uloop-get-menu-items\ndescription: Retrieve Unity MenuItems via uloop CLI. Use when you need to: (1) Discover available menu commands in Unity Editor, (2) Find menu paths for automation, (3) Prepare for executing menu items programmatically.\n---\n\n# uloop get-menu-items\n\nRetrieve Unity MenuItems.\n\n## Usage\n\n```bash\nuloop get-menu-items [options]\n```\n\n## Parameters\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `--filter-text` | string | - | Filter text |\n| `--filter-type` | string | `contains` | Filter type: `contains`, `exact`, `startswith` |\n| `--max-count` | integer | `200` | Maximum number of items |\n| `--include-validation` | boolean | `false` | Include validation functions |\n\n## Examples\n\n```bash\n# List all menu items\nuloop get-menu-items\n\n# Filter by text\nuloop get-menu-items --filter-text "GameObject"\n\n# Exact match\nuloop get-menu-items --filter-text "File/Save" --filter-type exact\n```\n\n## Output\n\nReturns JSON array of menu items with paths and metadata.\n\n## Notes\n\nUse with `uloop execute-menu-item` to run discovered menu commands.\n';
|
|
4218
|
+
|
|
4219
|
+
// src/skills/skill-definitions/uloop-execute-menu-item/SKILL.md
|
|
4220
|
+
var SKILL_default9 = '---\nname: uloop-execute-menu-item\ndescription: Execute Unity MenuItem via uloop CLI. Use when you need to: (1) Trigger menu commands programmatically, (2) Automate editor actions (save, build, refresh), (3) Run custom menu items defined in scripts.\n---\n\n# uloop execute-menu-item\n\nExecute Unity MenuItem.\n\n## Usage\n\n```bash\nuloop execute-menu-item --menu-item-path "<path>"\n```\n\n## Parameters\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `--menu-item-path` | string | - | Menu item path (e.g., "GameObject/Create Empty") |\n| `--use-reflection-fallback` | boolean | `true` | Use reflection fallback |\n\n## Examples\n\n```bash\n# Create empty GameObject\nuloop execute-menu-item --menu-item-path "GameObject/Create Empty"\n\n# Save scene\nuloop execute-menu-item --menu-item-path "File/Save"\n\n# Open project settings\nuloop execute-menu-item --menu-item-path "Edit/Project Settings..."\n```\n\n## Output\n\nReturns JSON with execution result.\n\n## Notes\n\n- Use `uloop get-menu-items` to discover available menu paths\n- Some menu items may require specific context or selection\n';
|
|
4221
|
+
|
|
4222
|
+
// src/skills/skill-definitions/uloop-find-game-objects/SKILL.md
|
|
4223
|
+
var SKILL_default10 = '---\nname: uloop-find-game-objects\ndescription: Find GameObjects with search criteria via uloop CLI. Use when you need to: (1) Locate GameObjects by name pattern, (2) Find objects by tag or layer, (3) Search for objects with specific component types.\n---\n\n# uloop find-game-objects\n\nFind GameObjects with search criteria.\n\n## Usage\n\n```bash\nuloop find-game-objects [options]\n```\n\n## Parameters\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `--name-pattern` | string | - | Name pattern to search |\n| `--search-mode` | string | `Contains` | Search mode: `Exact`, `Path`, `Regex`, `Contains` |\n| `--required-components` | array | - | Required components |\n| `--tag` | string | - | Tag filter |\n| `--layer` | string | - | Layer filter |\n| `--max-results` | integer | `20` | Maximum number of results |\n| `--include-inactive` | boolean | `false` | Include inactive GameObjects |\n\n## Examples\n\n```bash\n# Find by name\nuloop find-game-objects --name-pattern "Player"\n\n# Find with component\nuloop find-game-objects --required-components Rigidbody\n\n# Find by tag\nuloop find-game-objects --tag "Enemy"\n\n# Regex search\nuloop find-game-objects --name-pattern "UI_.*" --search-mode Regex\n```\n\n## Output\n\nReturns JSON array of matching GameObjects with paths and components.\n';
|
|
4224
|
+
|
|
4225
|
+
// src/skills/skill-definitions/uloop-capture-gameview/SKILL.md
|
|
4226
|
+
var SKILL_default11 = "---\nname: uloop-capture-gameview\ndescription: Capture Unity Game View as PNG via uloop CLI. Use when you need to: (1) Take a screenshot of the current Game View, (2) Capture visual state for debugging or verification, (3) Save game output as an image file.\n---\n\n# uloop capture-gameview\n\nCapture Unity Game View and save as PNG image.\n\n## Usage\n\n```bash\nuloop capture-gameview [--resolution-scale <scale>]\n```\n\n## Parameters\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `--resolution-scale` | number | `1.0` | Resolution scale (0.1 to 1.0) |\n\n## Examples\n\n```bash\n# Capture at full resolution\nuloop capture-gameview\n\n# Capture at half resolution\nuloop capture-gameview --resolution-scale 0.5\n```\n\n## Output\n\nReturns JSON with file path to the saved PNG image.\n\n## Notes\n\n- Use `uloop focus-window` first if needed\n- Game View must be visible in Unity Editor\n";
|
|
4227
|
+
|
|
4228
|
+
// src/skills/skill-definitions/uloop-execute-dynamic-code/SKILL.md
|
|
4229
|
+
var SKILL_default12 = "---\nname: uloop-execute-dynamic-code\ndescription: Execute C# code dynamically in Unity Editor via uloop CLI. Use for editor automation: (1) Prefab/material wiring and AddComponent operations, (2) Reference wiring with SerializedObject, (3) Scene/hierarchy edits and batch operations. NOT for file I/O or script authoring.\n---\n\n# uloop execute-dynamic-code\n\nExecute C# code dynamically in Unity Editor.\n\n## Usage\n\n```bash\nuloop execute-dynamic-code --code '<c# code>'\n```\n\n## Parameters\n\n| Parameter | Type | Description |\n|-----------|------|-------------|\n| `--code` | string | C# code to execute (direct statements, no class wrapper) |\n| `--compile-only` | boolean | Compile without execution |\n| `--auto-qualify-unity-types-once` | boolean | Auto-qualify Unity types |\n\n## Code Format\n\nWrite direct statements only (no classes/namespaces/methods). Return is optional.\n\n```csharp\n// Using directives at top are hoisted\nusing UnityEngine;\nvar x = Mathf.PI;\nreturn x;\n```\n\n## String Literals (Shell-specific)\n\n| Shell | Method |\n|-------|--------|\n| bash/zsh/MINGW64/Git Bash | `'Debug.Log(\"Hello!\");'` |\n| PowerShell | `'Debug.Log(\"\"Hello!\"\");'` |\n\n## Allowed Operations\n\n- Prefab/material wiring (PrefabUtility)\n- AddComponent + reference wiring (SerializedObject)\n- Scene/hierarchy edits\n- Inspector modifications\n\n## Forbidden Operations\n\n- System.IO.* (File/Directory/Path)\n- AssetDatabase.CreateFolder / file writes\n- Create/edit .cs/.asmdef files\n\n## Examples\n\n### bash / zsh / MINGW64 / Git Bash\n\n```bash\nuloop execute-dynamic-code --code 'return Selection.activeGameObject?.name;'\nuloop execute-dynamic-code --code 'new GameObject(\"MyObject\");'\nuloop execute-dynamic-code --code 'UnityEngine.Debug.Log(\"Hello from CLI!\");'\n```\n\n### PowerShell\n\n```powershell\nuloop execute-dynamic-code --code 'return Selection.activeGameObject?.name;'\nuloop execute-dynamic-code --code 'new GameObject(\"\"MyObject\"\");'\nuloop execute-dynamic-code --code 'UnityEngine.Debug.Log(\"\"Hello from CLI!\"\");'\n```\n\n## Output\n\nReturns JSON with execution result or compile errors.\n\n## Notes\n\nFor file/directory operations, use terminal commands instead.\n";
|
|
4230
|
+
|
|
4231
|
+
// src/skills/skill-definitions/uloop-get-provider-details/SKILL.md
|
|
4232
|
+
var SKILL_default13 = "---\nname: uloop-get-provider-details\ndescription: Get Unity Search provider details via uloop CLI. Use when you need to: (1) Discover available search providers, (2) Understand search capabilities and filters, (3) Configure searches with specific provider options.\n---\n\n# uloop get-provider-details\n\nGet detailed information about Unity Search providers.\n\n## Usage\n\n```bash\nuloop get-provider-details [options]\n```\n\n## Parameters\n\n| Parameter | Type | Default | Description |\n|-----------|------|---------|-------------|\n| `--provider-id` | string | - | Specific provider ID to query |\n| `--active-only` | boolean | `false` | Only show active providers |\n| `--include-descriptions` | boolean | `true` | Include descriptions |\n| `--sort-by-priority` | boolean | `true` | Sort by priority |\n\n## Examples\n\n```bash\n# List all providers\nuloop get-provider-details\n\n# Get specific provider\nuloop get-provider-details --provider-id asset\n\n# Active providers only\nuloop get-provider-details --active-only\n```\n\n## Output\n\nReturns JSON:\n- `Providers`: array of provider info (ID, name, description, priority)\n\n## Notes\n\nUse provider IDs with `uloop unity-search --providers` option.\n";
|
|
4233
|
+
|
|
4234
|
+
// src/skills/bundled-skills.ts
|
|
4235
|
+
var BUNDLED_SKILLS = [
|
|
4236
|
+
{ name: "uloop-compile", dirName: "uloop-compile", content: SKILL_default },
|
|
4237
|
+
{ name: "uloop-get-logs", dirName: "uloop-get-logs", content: SKILL_default2 },
|
|
4238
|
+
{ name: "uloop-run-tests", dirName: "uloop-run-tests", content: SKILL_default3 },
|
|
4239
|
+
{ name: "uloop-clear-console", dirName: "uloop-clear-console", content: SKILL_default4 },
|
|
4240
|
+
{ name: "uloop-focus-window", dirName: "uloop-focus-window", content: SKILL_default5 },
|
|
4241
|
+
{ name: "uloop-get-hierarchy", dirName: "uloop-get-hierarchy", content: SKILL_default6 },
|
|
4242
|
+
{ name: "uloop-unity-search", dirName: "uloop-unity-search", content: SKILL_default7 },
|
|
4243
|
+
{ name: "uloop-get-menu-items", dirName: "uloop-get-menu-items", content: SKILL_default8 },
|
|
4244
|
+
{
|
|
4245
|
+
name: "uloop-execute-menu-item",
|
|
4246
|
+
dirName: "uloop-execute-menu-item",
|
|
4247
|
+
content: SKILL_default9
|
|
4248
|
+
},
|
|
4249
|
+
{
|
|
4250
|
+
name: "uloop-find-game-objects",
|
|
4251
|
+
dirName: "uloop-find-game-objects",
|
|
4252
|
+
content: SKILL_default10
|
|
4253
|
+
},
|
|
4254
|
+
{
|
|
4255
|
+
name: "uloop-capture-gameview",
|
|
4256
|
+
dirName: "uloop-capture-gameview",
|
|
4257
|
+
content: SKILL_default11
|
|
4258
|
+
},
|
|
4259
|
+
{
|
|
4260
|
+
name: "uloop-execute-dynamic-code",
|
|
4261
|
+
dirName: "uloop-execute-dynamic-code",
|
|
4262
|
+
content: SKILL_default12
|
|
4263
|
+
},
|
|
4264
|
+
{
|
|
4265
|
+
name: "uloop-get-provider-details",
|
|
4266
|
+
dirName: "uloop-get-provider-details",
|
|
4267
|
+
content: SKILL_default13
|
|
4268
|
+
}
|
|
4269
|
+
];
|
|
4270
|
+
|
|
4271
|
+
// src/skills/skills-manager.ts
|
|
4272
|
+
function getGlobalSkillsDir() {
|
|
4273
|
+
return (0, import_path4.join)((0, import_os.homedir)(), ".claude", "skills");
|
|
4274
|
+
}
|
|
4275
|
+
function getProjectSkillsDir() {
|
|
4276
|
+
return (0, import_path4.join)(process.cwd(), ".claude", "skills");
|
|
4277
|
+
}
|
|
4278
|
+
function getSkillPath(skillDirName, global) {
|
|
4279
|
+
const baseDir = global ? getGlobalSkillsDir() : getProjectSkillsDir();
|
|
4280
|
+
return (0, import_path4.join)(baseDir, skillDirName, "SKILL.md");
|
|
4281
|
+
}
|
|
4282
|
+
function isSkillInstalled(skill, global) {
|
|
4283
|
+
const skillPath = getSkillPath(skill.dirName, global);
|
|
4284
|
+
return (0, import_fs3.existsSync)(skillPath);
|
|
4285
|
+
}
|
|
4286
|
+
function isSkillOutdated(skill, global) {
|
|
4287
|
+
const skillPath = getSkillPath(skill.dirName, global);
|
|
4288
|
+
if (!(0, import_fs3.existsSync)(skillPath)) {
|
|
4289
|
+
return false;
|
|
4290
|
+
}
|
|
4291
|
+
const installedContent = (0, import_fs3.readFileSync)(skillPath, "utf-8");
|
|
4292
|
+
return installedContent !== skill.content;
|
|
4293
|
+
}
|
|
4294
|
+
function getSkillStatus(skill, global) {
|
|
4295
|
+
if (!isSkillInstalled(skill, global)) {
|
|
4296
|
+
return "not_installed";
|
|
4297
|
+
}
|
|
4298
|
+
if (isSkillOutdated(skill, global)) {
|
|
4299
|
+
return "outdated";
|
|
4300
|
+
}
|
|
4301
|
+
return "installed";
|
|
4302
|
+
}
|
|
4303
|
+
function getAllSkillStatuses(global) {
|
|
4304
|
+
return BUNDLED_SKILLS.map((skill) => ({
|
|
4305
|
+
name: skill.name,
|
|
4306
|
+
status: getSkillStatus(skill, global),
|
|
4307
|
+
path: isSkillInstalled(skill, global) ? getSkillPath(skill.dirName, global) : void 0
|
|
4308
|
+
}));
|
|
4309
|
+
}
|
|
4310
|
+
function installSkill(skill, global) {
|
|
4311
|
+
const baseDir = global ? getGlobalSkillsDir() : getProjectSkillsDir();
|
|
4312
|
+
const skillDir = (0, import_path4.join)(baseDir, skill.dirName);
|
|
4313
|
+
const skillPath = (0, import_path4.join)(skillDir, "SKILL.md");
|
|
4314
|
+
(0, import_fs3.mkdirSync)(skillDir, { recursive: true });
|
|
4315
|
+
(0, import_fs3.writeFileSync)(skillPath, skill.content, "utf-8");
|
|
4316
|
+
}
|
|
4317
|
+
function uninstallSkill(skill, global) {
|
|
4318
|
+
const baseDir = global ? getGlobalSkillsDir() : getProjectSkillsDir();
|
|
4319
|
+
const skillDir = (0, import_path4.join)(baseDir, skill.dirName);
|
|
4320
|
+
if (!(0, import_fs3.existsSync)(skillDir)) {
|
|
4321
|
+
return false;
|
|
4322
|
+
}
|
|
4323
|
+
(0, import_fs3.rmSync)(skillDir, { recursive: true, force: true });
|
|
4324
|
+
return true;
|
|
4325
|
+
}
|
|
4326
|
+
function installAllSkills(global) {
|
|
4327
|
+
const result = { installed: 0, updated: 0, skipped: 0 };
|
|
4328
|
+
for (const skill of BUNDLED_SKILLS) {
|
|
4329
|
+
const status = getSkillStatus(skill, global);
|
|
4330
|
+
if (status === "not_installed") {
|
|
4331
|
+
installSkill(skill, global);
|
|
4332
|
+
result.installed++;
|
|
4333
|
+
} else if (status === "outdated") {
|
|
4334
|
+
installSkill(skill, global);
|
|
4335
|
+
result.updated++;
|
|
4336
|
+
} else {
|
|
4337
|
+
result.skipped++;
|
|
4338
|
+
}
|
|
4339
|
+
}
|
|
4340
|
+
return result;
|
|
4341
|
+
}
|
|
4342
|
+
function uninstallAllSkills(global) {
|
|
4343
|
+
const result = { removed: 0, notFound: 0 };
|
|
4344
|
+
for (const skill of BUNDLED_SKILLS) {
|
|
4345
|
+
if (uninstallSkill(skill, global)) {
|
|
4346
|
+
result.removed++;
|
|
4347
|
+
} else {
|
|
4348
|
+
result.notFound++;
|
|
4349
|
+
}
|
|
4350
|
+
}
|
|
4351
|
+
return result;
|
|
4352
|
+
}
|
|
4353
|
+
function getInstallDir(global) {
|
|
4354
|
+
return global ? getGlobalSkillsDir() : getProjectSkillsDir();
|
|
4355
|
+
}
|
|
4356
|
+
function getTotalSkillCount() {
|
|
4357
|
+
return BUNDLED_SKILLS.length;
|
|
4358
|
+
}
|
|
4359
|
+
|
|
4360
|
+
// src/skills/skills-command.ts
|
|
4361
|
+
function registerSkillsCommand(program3) {
|
|
4362
|
+
const skillsCmd = program3.command("skills").description("Manage uloop skills for Claude Code");
|
|
4363
|
+
skillsCmd.command("list").description("List all uloop skills and their installation status").option("-g, --global", "Check global installation (~/.claude/skills/)").action((options) => {
|
|
4364
|
+
listSkills(options.global ?? false);
|
|
4365
|
+
});
|
|
4366
|
+
skillsCmd.command("install").description("Install all uloop skills").option("-g, --global", "Install to global location (~/.claude/skills/)").action((options) => {
|
|
4367
|
+
installSkills(options.global ?? false);
|
|
4368
|
+
});
|
|
4369
|
+
skillsCmd.command("uninstall").description("Uninstall all uloop skills").option("-g, --global", "Uninstall from global location (~/.claude/skills/)").action((options) => {
|
|
4370
|
+
uninstallSkills(options.global ?? false);
|
|
4371
|
+
});
|
|
4372
|
+
}
|
|
4373
|
+
function listSkills(global) {
|
|
4374
|
+
const location = global ? "Global" : "Project";
|
|
4375
|
+
const dir = getInstallDir(global);
|
|
4376
|
+
console.log(`
|
|
4377
|
+
uloop Skills Status (${location}):`);
|
|
4378
|
+
console.log(`Location: ${dir}`);
|
|
4379
|
+
console.log("=".repeat(50));
|
|
4380
|
+
console.log("");
|
|
4381
|
+
const statuses = getAllSkillStatuses(global);
|
|
4382
|
+
for (const skill of statuses) {
|
|
4383
|
+
const icon = getStatusIcon(skill.status);
|
|
4384
|
+
const statusText = getStatusText(skill.status);
|
|
4385
|
+
console.log(` ${icon} ${skill.name} (${statusText})`);
|
|
4386
|
+
}
|
|
4387
|
+
console.log("");
|
|
4388
|
+
console.log(`Total: ${getTotalSkillCount()} bundled skills`);
|
|
4389
|
+
}
|
|
4390
|
+
function getStatusIcon(status) {
|
|
4391
|
+
switch (status) {
|
|
4392
|
+
case "installed":
|
|
4393
|
+
return "\x1B[32m\u2713\x1B[0m";
|
|
4394
|
+
case "outdated":
|
|
4395
|
+
return "\x1B[33m\u2191\x1B[0m";
|
|
4396
|
+
case "not_installed":
|
|
4397
|
+
return "\x1B[31m\u2717\x1B[0m";
|
|
4398
|
+
default:
|
|
4399
|
+
return "?";
|
|
4400
|
+
}
|
|
4401
|
+
}
|
|
4402
|
+
function getStatusText(status) {
|
|
4403
|
+
switch (status) {
|
|
4404
|
+
case "installed":
|
|
4405
|
+
return "installed";
|
|
4406
|
+
case "outdated":
|
|
4407
|
+
return "outdated";
|
|
4408
|
+
case "not_installed":
|
|
4409
|
+
return "not installed";
|
|
4410
|
+
default:
|
|
4411
|
+
return "unknown";
|
|
4412
|
+
}
|
|
4413
|
+
}
|
|
4414
|
+
function installSkills(global) {
|
|
4415
|
+
const location = global ? "global" : "project";
|
|
4416
|
+
const dir = getInstallDir(global);
|
|
4417
|
+
console.log(`
|
|
4418
|
+
Installing uloop skills (${location})...`);
|
|
4419
|
+
console.log("");
|
|
4420
|
+
const result = installAllSkills(global);
|
|
4421
|
+
console.log(`\x1B[32m\u2713\x1B[0m Installed: ${result.installed}`);
|
|
4422
|
+
console.log(`\x1B[33m\u2191\x1B[0m Updated: ${result.updated}`);
|
|
4423
|
+
console.log(`\x1B[90m-\x1B[0m Skipped (up-to-date): ${result.skipped}`);
|
|
4424
|
+
console.log("");
|
|
4425
|
+
console.log(`Skills installed to ${dir}`);
|
|
4426
|
+
}
|
|
4427
|
+
function uninstallSkills(global) {
|
|
4428
|
+
const location = global ? "global" : "project";
|
|
4429
|
+
const dir = getInstallDir(global);
|
|
4430
|
+
console.log(`
|
|
4431
|
+
Uninstalling uloop skills (${location})...`);
|
|
4432
|
+
console.log("");
|
|
4433
|
+
const result = uninstallAllSkills(global);
|
|
4434
|
+
console.log(`\x1B[31m\u2717\x1B[0m Removed: ${result.removed}`);
|
|
4435
|
+
console.log(`\x1B[90m-\x1B[0m Not found: ${result.notFound}`);
|
|
4436
|
+
console.log("");
|
|
4437
|
+
console.log(`Skills removed from ${dir}`);
|
|
4438
|
+
}
|
|
4439
|
+
|
|
4440
|
+
// src/cli.ts
|
|
4441
|
+
var BUILTIN_COMMANDS = ["list", "sync", "completion", "update", "skills"];
|
|
4442
|
+
var program2 = new Command();
|
|
4443
|
+
program2.name("uloop").description("Unity MCP CLI - Direct communication with Unity Editor").version(VERSION, "-v, --version", "Output the version number");
|
|
4444
|
+
program2.option("--list-commands", "List all command names (for shell completion)");
|
|
4445
|
+
program2.option("--list-options <cmd>", "List options for a command (for shell completion)");
|
|
4446
|
+
program2.command("list").description("List all available tools from Unity").option("-p, --port <port>", "Unity TCP port").action(async (options) => {
|
|
4447
|
+
await runWithErrorHandling(() => listAvailableTools(options));
|
|
4448
|
+
});
|
|
4449
|
+
program2.command("sync").description("Sync tool definitions from Unity to local cache").option("-p, --port <port>", "Unity TCP port").action(async (options) => {
|
|
4450
|
+
await runWithErrorHandling(() => syncTools(options));
|
|
4451
|
+
});
|
|
4452
|
+
program2.command("completion").description("Setup shell completion").option("--install", "Install completion to shell config file").option("--shell <type>", "Shell type: bash, zsh, or powershell").action((options) => {
|
|
4453
|
+
handleCompletion(options.install ?? false, options.shell);
|
|
4454
|
+
});
|
|
4455
|
+
program2.command("update").description("Update uloop CLI to the latest version").action(() => {
|
|
4456
|
+
updateCli();
|
|
4457
|
+
});
|
|
4458
|
+
registerSkillsCommand(program2);
|
|
4459
|
+
var toolsCache = loadToolsCache();
|
|
4460
|
+
for (const tool of toolsCache.tools) {
|
|
4461
|
+
registerToolCommand(tool);
|
|
4462
|
+
}
|
|
4463
|
+
function registerToolCommand(tool) {
|
|
4464
|
+
const cmd = program2.command(tool.name).description(tool.description);
|
|
4465
|
+
const properties = tool.inputSchema.properties;
|
|
4466
|
+
for (const [propName, propInfo] of Object.entries(properties)) {
|
|
4467
|
+
const optionStr = generateOptionString(propName, propInfo);
|
|
4468
|
+
const description = buildOptionDescription(propInfo);
|
|
4469
|
+
const defaultValue = propInfo.default;
|
|
4470
|
+
if (defaultValue !== void 0) {
|
|
4471
|
+
cmd.option(optionStr, description, defaultValue);
|
|
4472
|
+
} else {
|
|
4473
|
+
cmd.option(optionStr, description);
|
|
4474
|
+
}
|
|
4475
|
+
}
|
|
4476
|
+
cmd.option("-p, --port <port>", "Unity TCP port");
|
|
4477
|
+
cmd.action(async (options) => {
|
|
4478
|
+
const params = buildParams(options, properties);
|
|
4479
|
+
if (tool.name === "execute-dynamic-code" && params["Code"]) {
|
|
4480
|
+
const code = params["Code"];
|
|
4481
|
+
params["Code"] = code.replace(/\\!/g, "!");
|
|
4482
|
+
}
|
|
4483
|
+
await runWithErrorHandling(
|
|
4484
|
+
() => executeToolCommand(tool.name, params, extractGlobalOptions(options))
|
|
4485
|
+
);
|
|
4486
|
+
});
|
|
4487
|
+
}
|
|
4488
|
+
function generateOptionString(propName, propInfo) {
|
|
4489
|
+
const kebabName = pascalToKebabCase(propName);
|
|
4490
|
+
const lowerType = propInfo.type.toLowerCase();
|
|
4491
|
+
if (lowerType === "boolean") {
|
|
4492
|
+
return `--${kebabName}`;
|
|
4493
|
+
}
|
|
4494
|
+
return `--${kebabName} <value>`;
|
|
4495
|
+
}
|
|
4496
|
+
function buildOptionDescription(propInfo) {
|
|
4497
|
+
let desc = propInfo.description || "";
|
|
4498
|
+
if (propInfo.enum && propInfo.enum.length > 0) {
|
|
4499
|
+
desc += ` (${propInfo.enum.join(", ")})`;
|
|
4500
|
+
}
|
|
4501
|
+
return desc;
|
|
4502
|
+
}
|
|
4503
|
+
function buildParams(options, properties) {
|
|
4504
|
+
const params = {};
|
|
4505
|
+
for (const propName of Object.keys(properties)) {
|
|
4506
|
+
const camelName = propName.charAt(0).toLowerCase() + propName.slice(1);
|
|
4507
|
+
const value = options[camelName];
|
|
4508
|
+
if (value !== void 0) {
|
|
4509
|
+
const propInfo = properties[propName];
|
|
4510
|
+
params[propName] = convertValue(value, propInfo);
|
|
4511
|
+
}
|
|
4512
|
+
}
|
|
4513
|
+
return params;
|
|
4514
|
+
}
|
|
4515
|
+
function convertValue(value, propInfo) {
|
|
4516
|
+
const lowerType = propInfo.type.toLowerCase();
|
|
4517
|
+
if (lowerType === "array" && typeof value === "string") {
|
|
4518
|
+
return value.split(",").map((s) => s.trim());
|
|
4519
|
+
}
|
|
4520
|
+
if (lowerType === "integer" && typeof value === "string") {
|
|
4521
|
+
const parsed = parseInt(value, 10);
|
|
4522
|
+
if (isNaN(parsed)) {
|
|
4523
|
+
throw new Error(`Invalid integer value: ${value}`);
|
|
4524
|
+
}
|
|
4525
|
+
return parsed;
|
|
4526
|
+
}
|
|
4527
|
+
if (lowerType === "number" && typeof value === "string") {
|
|
4528
|
+
const parsed = parseFloat(value);
|
|
4529
|
+
if (isNaN(parsed)) {
|
|
4530
|
+
throw new Error(`Invalid number value: ${value}`);
|
|
4531
|
+
}
|
|
4532
|
+
return parsed;
|
|
4533
|
+
}
|
|
4534
|
+
return value;
|
|
4535
|
+
}
|
|
4536
|
+
function extractGlobalOptions(options) {
|
|
4537
|
+
return {
|
|
4538
|
+
port: options["port"]
|
|
4539
|
+
};
|
|
4540
|
+
}
|
|
4541
|
+
function isDomainReloadLockFilePresent() {
|
|
4542
|
+
const projectRoot = findUnityProjectRoot();
|
|
4543
|
+
if (projectRoot === null) {
|
|
4544
|
+
return false;
|
|
4545
|
+
}
|
|
4546
|
+
const lockPath = (0, import_path5.join)(projectRoot, "Temp", "domainreload.lock");
|
|
4547
|
+
return (0, import_fs4.existsSync)(lockPath);
|
|
4548
|
+
}
|
|
4549
|
+
async function runWithErrorHandling(fn) {
|
|
4550
|
+
try {
|
|
4551
|
+
await fn();
|
|
4552
|
+
} catch (error) {
|
|
4553
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
4554
|
+
if (message.includes("ECONNREFUSED")) {
|
|
4555
|
+
if (isDomainReloadLockFilePresent()) {
|
|
4556
|
+
console.error("\x1B[33m\u23F3 Unity is reloading (Domain Reload in progress).\x1B[0m");
|
|
4557
|
+
console.error("Please wait a moment and try again.");
|
|
4558
|
+
} else {
|
|
4559
|
+
console.error("\x1B[31mError: Cannot connect to Unity.\x1B[0m");
|
|
4560
|
+
console.error("Make sure Unity is running with uLoopMCP installed.");
|
|
4561
|
+
}
|
|
4562
|
+
process.exit(1);
|
|
4563
|
+
}
|
|
4564
|
+
console.error(`\x1B[31mError: ${message}\x1B[0m`);
|
|
4565
|
+
process.exit(1);
|
|
4566
|
+
}
|
|
4567
|
+
}
|
|
4568
|
+
function detectShell() {
|
|
4569
|
+
const shell = process.env["SHELL"] || "";
|
|
4570
|
+
const shellName = (0, import_path5.basename)(shell).replace(/\.exe$/i, "");
|
|
4571
|
+
if (shellName === "zsh") {
|
|
4572
|
+
return "zsh";
|
|
4573
|
+
}
|
|
4574
|
+
if (shellName === "bash") {
|
|
4575
|
+
return "bash";
|
|
4576
|
+
}
|
|
4577
|
+
if (process.env["PSModulePath"]) {
|
|
4578
|
+
return "powershell";
|
|
4579
|
+
}
|
|
4580
|
+
return null;
|
|
4581
|
+
}
|
|
4582
|
+
function getShellConfigPath(shell) {
|
|
4583
|
+
const home = (0, import_os2.homedir)();
|
|
4584
|
+
if (shell === "zsh") {
|
|
4585
|
+
return (0, import_path5.join)(home, ".zshrc");
|
|
4586
|
+
}
|
|
4587
|
+
if (shell === "powershell") {
|
|
4588
|
+
return (0, import_path5.join)(home, "Documents", "WindowsPowerShell", "Microsoft.PowerShell_profile.ps1");
|
|
4589
|
+
}
|
|
4590
|
+
return (0, import_path5.join)(home, ".bashrc");
|
|
4591
|
+
}
|
|
4592
|
+
function getCompletionScript(shell) {
|
|
4593
|
+
if (shell === "bash") {
|
|
4594
|
+
return `# uloop bash completion
|
|
4595
|
+
_uloop_completions() {
|
|
4596
|
+
local cur="\${COMP_WORDS[COMP_CWORD]}"
|
|
4597
|
+
local cmd="\${COMP_WORDS[1]}"
|
|
4598
|
+
|
|
4599
|
+
if [[ \${COMP_CWORD} -eq 1 ]]; then
|
|
4600
|
+
COMPREPLY=($(compgen -W "$(uloop --list-commands 2>/dev/null)" -- "\${cur}"))
|
|
4601
|
+
elif [[ \${COMP_CWORD} -ge 2 ]]; then
|
|
4602
|
+
COMPREPLY=($(compgen -W "$(uloop --list-options \${cmd} 2>/dev/null)" -- "\${cur}"))
|
|
4603
|
+
fi
|
|
4604
|
+
}
|
|
4605
|
+
complete -F _uloop_completions uloop`;
|
|
4606
|
+
}
|
|
4607
|
+
if (shell === "powershell") {
|
|
4608
|
+
return `# uloop PowerShell completion
|
|
4609
|
+
Register-ArgumentCompleter -Native -CommandName uloop -ScriptBlock {
|
|
4610
|
+
param($wordToComplete, $commandAst, $cursorPosition)
|
|
4611
|
+
$commands = $commandAst.CommandElements
|
|
4612
|
+
if ($commands.Count -eq 1) {
|
|
4613
|
+
uloop --list-commands 2>$null | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object {
|
|
4614
|
+
[System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)
|
|
4615
|
+
}
|
|
4616
|
+
} elseif ($commands.Count -ge 2) {
|
|
4617
|
+
$cmd = $commands[1].ToString()
|
|
4618
|
+
uloop --list-options $cmd 2>$null | Where-Object { $_ -like "$wordToComplete*" } | ForEach-Object {
|
|
4619
|
+
[System.Management.Automation.CompletionResult]::new($_, $_, 'ParameterValue', $_)
|
|
4620
|
+
}
|
|
4621
|
+
}
|
|
4622
|
+
}`;
|
|
4623
|
+
}
|
|
4624
|
+
return `# uloop zsh completion
|
|
4625
|
+
_uloop() {
|
|
4626
|
+
local -a commands
|
|
4627
|
+
local -a options
|
|
4628
|
+
local -a used_options
|
|
4629
|
+
|
|
4630
|
+
if (( CURRENT == 2 )); then
|
|
4631
|
+
commands=(\${(f)"$(uloop --list-commands 2>/dev/null)"})
|
|
4632
|
+
_describe 'command' commands
|
|
4633
|
+
elif (( CURRENT >= 3 )); then
|
|
4634
|
+
options=(\${(f)"$(uloop --list-options \${words[2]} 2>/dev/null)"})
|
|
4635
|
+
used_options=(\${words:2})
|
|
4636
|
+
for opt in \${used_options}; do
|
|
4637
|
+
options=(\${options:#$opt})
|
|
4638
|
+
done
|
|
4639
|
+
_describe 'option' options
|
|
4640
|
+
fi
|
|
4641
|
+
}
|
|
4642
|
+
compdef _uloop uloop`;
|
|
4643
|
+
}
|
|
4644
|
+
function updateCli() {
|
|
4645
|
+
console.log("Updating uloop-cli to the latest version...");
|
|
4646
|
+
const npmCommand = process.platform === "win32" ? "npm.cmd" : "npm";
|
|
4647
|
+
const child = (0, import_child_process.spawn)(npmCommand, ["install", "-g", "uloop-cli@latest"], {
|
|
4648
|
+
stdio: "inherit",
|
|
4649
|
+
shell: true
|
|
4650
|
+
});
|
|
4651
|
+
child.on("close", (code) => {
|
|
4652
|
+
if (code === 0) {
|
|
4653
|
+
console.log("\n\u2705 uloop-cli has been updated successfully!");
|
|
4654
|
+
console.log('Run "uloop --version" to check the new version.');
|
|
4655
|
+
} else {
|
|
4656
|
+
console.error(`
|
|
4657
|
+
\u274C Update failed with exit code ${code}`);
|
|
4658
|
+
process.exit(1);
|
|
4659
|
+
}
|
|
4660
|
+
});
|
|
4661
|
+
child.on("error", (err) => {
|
|
4662
|
+
console.error(`\u274C Failed to run npm: ${err.message}`);
|
|
4663
|
+
process.exit(1);
|
|
4664
|
+
});
|
|
4665
|
+
}
|
|
4666
|
+
function handleCompletion(install, shellOverride) {
|
|
4667
|
+
let shell;
|
|
4668
|
+
if (shellOverride) {
|
|
4669
|
+
const normalized = shellOverride.toLowerCase();
|
|
4670
|
+
if (normalized === "bash" || normalized === "zsh" || normalized === "powershell") {
|
|
4671
|
+
shell = normalized;
|
|
4672
|
+
} else {
|
|
4673
|
+
console.error(`Unknown shell: ${shellOverride}. Supported: bash, zsh, powershell`);
|
|
4674
|
+
process.exit(1);
|
|
4675
|
+
}
|
|
4676
|
+
} else {
|
|
4677
|
+
shell = detectShell();
|
|
4678
|
+
}
|
|
4679
|
+
if (!shell) {
|
|
4680
|
+
console.error("Could not detect shell. Use --shell option: bash, zsh, or powershell");
|
|
4681
|
+
process.exit(1);
|
|
4682
|
+
}
|
|
4683
|
+
const script = getCompletionScript(shell);
|
|
4684
|
+
if (!install) {
|
|
4685
|
+
console.log(script);
|
|
4686
|
+
return;
|
|
4687
|
+
}
|
|
4688
|
+
const configPath = getShellConfigPath(shell);
|
|
4689
|
+
const configDir = (0, import_path5.dirname)(configPath);
|
|
4690
|
+
if (!(0, import_fs4.existsSync)(configDir)) {
|
|
4691
|
+
(0, import_fs4.mkdirSync)(configDir, { recursive: true });
|
|
4692
|
+
}
|
|
4693
|
+
let content = "";
|
|
4694
|
+
if ((0, import_fs4.existsSync)(configPath)) {
|
|
4695
|
+
content = (0, import_fs4.readFileSync)(configPath, "utf-8");
|
|
4696
|
+
content = content.replace(
|
|
4697
|
+
/\n?# >>> uloop completion >>>[\s\S]*?# <<< uloop completion <<<\n?/g,
|
|
4698
|
+
""
|
|
4699
|
+
);
|
|
4700
|
+
}
|
|
4701
|
+
const startMarker = "# >>> uloop completion >>>";
|
|
4702
|
+
const endMarker = "# <<< uloop completion <<<";
|
|
4703
|
+
if (shell === "powershell") {
|
|
4704
|
+
const lineToAdd = `
|
|
4705
|
+
${startMarker}
|
|
4706
|
+
${script}
|
|
4707
|
+
${endMarker}
|
|
4708
|
+
`;
|
|
4709
|
+
(0, import_fs4.writeFileSync)(configPath, content + lineToAdd, "utf-8");
|
|
4710
|
+
} else {
|
|
4711
|
+
const evalLine = `eval "$(uloop completion --shell ${shell})"`;
|
|
4712
|
+
const lineToAdd = `
|
|
4713
|
+
${startMarker}
|
|
4714
|
+
${evalLine}
|
|
4715
|
+
${endMarker}
|
|
4716
|
+
`;
|
|
4717
|
+
(0, import_fs4.writeFileSync)(configPath, content + lineToAdd, "utf-8");
|
|
4718
|
+
}
|
|
4719
|
+
console.log(`Completion installed to ${configPath}`);
|
|
4720
|
+
if (shell === "powershell") {
|
|
4721
|
+
console.log("Restart PowerShell to enable completion.");
|
|
4722
|
+
} else {
|
|
4723
|
+
console.log(`Run 'source ${configPath}' or restart your shell to enable completion.`);
|
|
4724
|
+
}
|
|
4725
|
+
}
|
|
4726
|
+
function handleCompletionOptions() {
|
|
4727
|
+
const args = process.argv.slice(2);
|
|
4728
|
+
if (args.includes("--list-commands")) {
|
|
4729
|
+
const tools = loadToolsCache();
|
|
4730
|
+
const allCommands = [...BUILTIN_COMMANDS, ...tools.tools.map((t) => t.name)];
|
|
4731
|
+
console.log(allCommands.join("\n"));
|
|
4732
|
+
return true;
|
|
4733
|
+
}
|
|
4734
|
+
const listOptionsIdx = args.indexOf("--list-options");
|
|
4735
|
+
if (listOptionsIdx !== -1 && args[listOptionsIdx + 1]) {
|
|
4736
|
+
const cmdName = args[listOptionsIdx + 1];
|
|
4737
|
+
listOptionsForCommand(cmdName);
|
|
4738
|
+
return true;
|
|
4739
|
+
}
|
|
4740
|
+
return false;
|
|
4741
|
+
}
|
|
4742
|
+
function listOptionsForCommand(cmdName) {
|
|
4743
|
+
if (BUILTIN_COMMANDS.includes(cmdName)) {
|
|
4744
|
+
return;
|
|
4745
|
+
}
|
|
4746
|
+
const tools = loadToolsCache();
|
|
4747
|
+
const tool = tools.tools.find((t) => t.name === cmdName);
|
|
4748
|
+
if (!tool) {
|
|
4749
|
+
return;
|
|
4750
|
+
}
|
|
4751
|
+
const options = [];
|
|
4752
|
+
for (const propName of Object.keys(tool.inputSchema.properties)) {
|
|
4753
|
+
const kebabName = pascalToKebabCase(propName);
|
|
4754
|
+
options.push(`--${kebabName}`);
|
|
4755
|
+
}
|
|
4756
|
+
console.log(options.join("\n"));
|
|
4757
|
+
}
|
|
4758
|
+
if (!handleCompletionOptions()) {
|
|
4759
|
+
program2.parse();
|
|
4760
|
+
}
|
|
4761
|
+
//# sourceMappingURL=cli.bundle.cjs.map
|