flavor-code 1.4.2 → 1.4.3-beta.2
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/README.md +28 -1
- package/README.zh-CN.md +28 -1
- package/dist/{app-4CUS3GEJ.js → app-G35YBHPR.js} +593 -536
- package/dist/apply-WOW3QU5I.js +51 -0
- package/dist/broker-cli-X5H46FZV.js +15 -0
- package/dist/check-CSKTV4O2.js +16 -0
- package/dist/chunk-3563SW4X.js +10513 -0
- package/dist/chunk-3UX2CGDW.js +1955 -0
- package/dist/chunk-4TMLXZVZ.js +75 -0
- package/dist/chunk-6F66UXBI.js +48 -0
- package/dist/{chunk-KMBDK4SN.js → chunk-6URQ7FIF.js} +24 -88
- package/dist/chunk-6X62CGMA.js +193 -0
- package/dist/chunk-7Y64WNBB.js +8930 -0
- package/dist/chunk-AA4QNKTF.js +501 -0
- package/dist/chunk-BDX777JR.js +11 -0
- package/dist/chunk-CVP5OUHD.js +103 -0
- package/dist/chunk-EWD7FWTH.js +14547 -0
- package/dist/chunk-FAJ6YDZK.js +630 -0
- package/dist/{chunk-N5MXHJKD.js → chunk-GTFP2R5I.js} +1 -1
- package/dist/{chunk-7YFHRORG.js → chunk-HGTCIHWA.js} +383 -172
- package/dist/chunk-IDJAHEG6.js +43501 -0
- package/dist/chunk-IQEEFDEE.js +389 -0
- package/dist/chunk-IU3UBETC.js +30 -0
- package/dist/chunk-K7UGGWJV.js +1003 -0
- package/dist/chunk-KRWWCVXA.js +74 -0
- package/dist/chunk-OKHV7CTB.js +482 -0
- package/dist/chunk-PULWAH6E.js +474 -0
- package/dist/chunk-PZ5NKRVA.js +85 -0
- package/dist/chunk-RBAZLFKB.js +1022 -0
- package/dist/chunk-RV3EXUXM.js +30 -0
- package/dist/chunk-SJUIIHIA.js +2130 -0
- package/dist/{chunk-W2TIY6JY.js → chunk-T6RE76D2.js} +1993 -493
- package/dist/chunk-TIEOVQW6.js +61 -0
- package/dist/chunk-WLZUAVVU.js +15 -0
- package/dist/chunk-X442CJJH.js +114 -0
- package/dist/{chunk-RAYH6K2H.js → chunk-Y7EH4NVO.js} +1 -1
- package/dist/{chunk-S32JRDZK.js → chunk-ZKKVSR37.js} +6 -1
- package/dist/{claude-ink-VQU3C5UL.js → claude-ink-BE56DB6N.js} +9 -4
- package/dist/cli-3MF6EL2H.js +163 -0
- package/dist/cli-main.js +3805 -473
- package/dist/cli.js +50 -4
- package/dist/config/load.d.ts +8 -0
- package/dist/config/schema.d.ts +11 -0
- package/dist/context/manager.d.ts +2 -0
- package/dist/desktop/main.js +4299 -1150
- package/dist/desktop/preload.cjs +30 -0
- package/dist/desktop-renderer/assets/index-BWklSoOO.css +1 -0
- package/dist/desktop-renderer/assets/index-DCqIrF1S.js +153 -0
- package/dist/desktop-renderer/assets/{interactive-terminal-ouQQ3brz.js → interactive-terminal-B6GbpzIn.js} +1 -1
- package/dist/desktop-renderer/index.html +2 -2
- package/dist/doctor-OHCGK52S.js +20 -0
- package/dist/load-QK6CMLDF.js +25 -0
- package/dist/log-ATFIPRNU.js +19 -0
- package/dist/manager-5SI4MPES.js +191 -0
- package/dist/models/anthropic.d.ts +3 -0
- package/dist/node-LOIXT44J.js +879 -0
- package/dist/plugin-worker-entry.js +1 -1
- package/dist/production-6DIZ6YLQ.js +46 -0
- package/dist/production.d.ts +28 -1
- package/dist/project-3QXE22TG.js +11 -0
- package/dist/react-M6JGXSJZ.js +7 -0
- package/dist/recorder-FAGJJH3N.js +11 -0
- package/dist/sdk/index.js +30 -8
- package/dist/server-2KLKPHPL.js +11 -0
- package/dist/session/store.d.ts +1 -0
- package/dist/store-ZIHN6363.js +18 -0
- package/dist/usage-summary-G5FBOJLK.js +13 -0
- package/dist/write-stream-CGD57URC.js +77 -0
- package/package.json +1 -1
- package/dist/chunk-B23V72YR.js +0 -170
- package/dist/chunk-QKND3FX7.js +0 -26103
- package/dist/desktop-renderer/assets/index-Bk6FYhyh.css +0 -1
- package/dist/desktop-renderer/assets/index-CPXrzFgv.js +0 -154
- package/dist/load-UPOG3XQR.js +0 -19
package/dist/cli-main.js
CHANGED
|
@@ -1,279 +1,3441 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { createRequire } from "node:module"; const require =
|
|
3
|
-
import {
|
|
4
|
-
FlavorRpcServer,
|
|
5
|
-
TraceRecorder
|
|
6
|
-
} from "./chunk-KMBDK4SN.js";
|
|
2
|
+
import { createRequire as createFlavorRequire } from "node:module"; const require = createFlavorRequire(import.meta.url);
|
|
7
3
|
import {
|
|
8
4
|
staticTaskLines
|
|
9
|
-
} from "./chunk-
|
|
5
|
+
} from "./chunk-Y7EH4NVO.js";
|
|
6
|
+
import {
|
|
7
|
+
source_default
|
|
8
|
+
} from "./chunk-AA4QNKTF.js";
|
|
10
9
|
import {
|
|
11
|
-
DEFAULT_MAX_OUTPUT_BYTES,
|
|
12
|
-
MAX_ALIAS_LENGTH,
|
|
13
10
|
MEMORY_TYPES,
|
|
14
11
|
MemoryStore,
|
|
15
|
-
NPM_PACKAGE_NAME,
|
|
16
|
-
PluginManifestSchema,
|
|
17
|
-
SkillRegistry,
|
|
18
12
|
classifyMemoryHeat,
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
runDoctor,
|
|
31
|
-
runPalBroker
|
|
32
|
-
} from "./chunk-QKND3FX7.js";
|
|
13
|
+
installCrashGuard
|
|
14
|
+
} from "./chunk-FAJ6YDZK.js";
|
|
15
|
+
import {
|
|
16
|
+
redactErrorText
|
|
17
|
+
} from "./chunk-WLZUAVVU.js";
|
|
18
|
+
import {
|
|
19
|
+
packageVersion
|
|
20
|
+
} from "./chunk-RV3EXUXM.js";
|
|
21
|
+
import {
|
|
22
|
+
MAX_ALIAS_LENGTH
|
|
23
|
+
} from "./chunk-IQEEFDEE.js";
|
|
33
24
|
import {
|
|
34
25
|
MEMORY_RESTART_EXIT_CODE
|
|
35
|
-
} from "./chunk-
|
|
26
|
+
} from "./chunk-GTFP2R5I.js";
|
|
36
27
|
import {
|
|
37
|
-
McpServerConfigSchema,
|
|
38
|
-
McpServerNameSchema,
|
|
39
|
-
SkillNameSchema,
|
|
40
28
|
loadConfig,
|
|
41
29
|
readRecoverableFile,
|
|
42
|
-
setProjectSkillDisabled,
|
|
43
30
|
updateProtectedFile
|
|
44
|
-
} from "./chunk-
|
|
31
|
+
} from "./chunk-HGTCIHWA.js";
|
|
45
32
|
import {
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
33
|
+
message
|
|
34
|
+
} from "./chunk-BDX777JR.js";
|
|
35
|
+
import {
|
|
36
|
+
McpServerConfigSchema,
|
|
37
|
+
McpServerNameSchema,
|
|
38
|
+
configPathSegments
|
|
39
|
+
} from "./chunk-6X62CGMA.js";
|
|
40
|
+
import "./chunk-EWD7FWTH.js";
|
|
41
|
+
import "./chunk-ZKKVSR37.js";
|
|
50
42
|
|
|
51
43
|
// src/cli.tsx
|
|
52
|
-
import { randomUUID
|
|
44
|
+
import { randomUUID } from "crypto";
|
|
53
45
|
import { realpathSync } from "fs";
|
|
54
46
|
import { homedir as homedir3 } from "os";
|
|
55
|
-
import { posix, resolve
|
|
47
|
+
import { posix, resolve } from "path";
|
|
56
48
|
import { fileURLToPath } from "url";
|
|
57
|
-
import { Command, Option } from "commander";
|
|
58
49
|
|
|
59
|
-
//
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
50
|
+
// node_modules/commander/lib/error.js
|
|
51
|
+
var CommanderError = class extends Error {
|
|
52
|
+
/**
|
|
53
|
+
* Constructs the CommanderError class
|
|
54
|
+
* @param {number} exitCode suggested exit code which could be used with process.exit
|
|
55
|
+
* @param {string} code an id string representing the error
|
|
56
|
+
* @param {string} message human-readable description of the error
|
|
57
|
+
*/
|
|
58
|
+
constructor(exitCode, code, message2) {
|
|
59
|
+
super(message2);
|
|
60
|
+
Error.captureStackTrace(this, this.constructor);
|
|
61
|
+
this.name = this.constructor.name;
|
|
62
|
+
this.code = code;
|
|
63
|
+
this.exitCode = exitCode;
|
|
64
|
+
this.nestedError = void 0;
|
|
65
|
+
}
|
|
66
|
+
};
|
|
67
|
+
var InvalidArgumentError = class extends CommanderError {
|
|
68
|
+
/**
|
|
69
|
+
* Constructs the InvalidArgumentError class
|
|
70
|
+
* @param {string} [message] explanation of why argument is invalid
|
|
71
|
+
*/
|
|
72
|
+
constructor(message2) {
|
|
73
|
+
super(1, "commander.invalidArgument", message2);
|
|
74
|
+
Error.captureStackTrace(this, this.constructor);
|
|
75
|
+
this.name = this.constructor.name;
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
// node_modules/commander/lib/argument.js
|
|
80
|
+
var Argument = class {
|
|
81
|
+
/**
|
|
82
|
+
* Initialize a new command argument with the given name and description.
|
|
83
|
+
* The default is that the argument is required, and you can explicitly
|
|
84
|
+
* indicate this with <> around the name. Put [] around the name for an optional argument.
|
|
85
|
+
*
|
|
86
|
+
* @param {string} name
|
|
87
|
+
* @param {string} [description]
|
|
88
|
+
*/
|
|
89
|
+
constructor(name, description) {
|
|
90
|
+
this.description = description || "";
|
|
91
|
+
this.variadic = false;
|
|
92
|
+
this.parseArg = void 0;
|
|
93
|
+
this.defaultValue = void 0;
|
|
94
|
+
this.defaultValueDescription = void 0;
|
|
95
|
+
this.argChoices = void 0;
|
|
96
|
+
switch (name[0]) {
|
|
97
|
+
case "<":
|
|
98
|
+
this.required = true;
|
|
99
|
+
this._name = name.slice(1, -1);
|
|
100
|
+
break;
|
|
101
|
+
case "[":
|
|
102
|
+
this.required = false;
|
|
103
|
+
this._name = name.slice(1, -1);
|
|
104
|
+
break;
|
|
105
|
+
default:
|
|
106
|
+
this.required = true;
|
|
107
|
+
this._name = name;
|
|
108
|
+
break;
|
|
109
|
+
}
|
|
110
|
+
if (this._name.endsWith("...")) {
|
|
111
|
+
this.variadic = true;
|
|
112
|
+
this._name = this._name.slice(0, -3);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Return argument name.
|
|
117
|
+
*
|
|
118
|
+
* @return {string}
|
|
119
|
+
*/
|
|
120
|
+
name() {
|
|
121
|
+
return this._name;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* @package
|
|
125
|
+
*/
|
|
126
|
+
_collectValue(value, previous) {
|
|
127
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) {
|
|
128
|
+
return [value];
|
|
129
|
+
}
|
|
130
|
+
previous.push(value);
|
|
131
|
+
return previous;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Set the default value, and optionally supply the description to be displayed in the help.
|
|
135
|
+
*
|
|
136
|
+
* @param {*} value
|
|
137
|
+
* @param {string} [description]
|
|
138
|
+
* @return {Argument}
|
|
139
|
+
*/
|
|
140
|
+
default(value, description) {
|
|
141
|
+
this.defaultValue = value;
|
|
142
|
+
this.defaultValueDescription = description;
|
|
143
|
+
return this;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Set the custom handler for processing CLI command arguments into argument values.
|
|
147
|
+
*
|
|
148
|
+
* @param {Function} [fn]
|
|
149
|
+
* @return {Argument}
|
|
150
|
+
*/
|
|
151
|
+
argParser(fn) {
|
|
152
|
+
this.parseArg = fn;
|
|
153
|
+
return this;
|
|
154
|
+
}
|
|
155
|
+
/**
|
|
156
|
+
* Only allow argument value to be one of choices.
|
|
157
|
+
*
|
|
158
|
+
* @param {string[]} values
|
|
159
|
+
* @return {Argument}
|
|
160
|
+
*/
|
|
161
|
+
choices(values) {
|
|
162
|
+
this.argChoices = values.slice();
|
|
163
|
+
this.parseArg = (arg, previous) => {
|
|
164
|
+
if (!this.argChoices.includes(arg)) {
|
|
165
|
+
throw new InvalidArgumentError(
|
|
166
|
+
`Allowed choices are ${this.argChoices.join(", ")}.`
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
if (this.variadic) {
|
|
170
|
+
return this._collectValue(arg, previous);
|
|
171
|
+
}
|
|
172
|
+
return arg;
|
|
173
|
+
};
|
|
174
|
+
return this;
|
|
175
|
+
}
|
|
176
|
+
/**
|
|
177
|
+
* Make argument required.
|
|
178
|
+
*
|
|
179
|
+
* @returns {Argument}
|
|
180
|
+
*/
|
|
181
|
+
argRequired() {
|
|
182
|
+
this.required = true;
|
|
183
|
+
return this;
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Make argument optional.
|
|
187
|
+
*
|
|
188
|
+
* @returns {Argument}
|
|
189
|
+
*/
|
|
190
|
+
argOptional() {
|
|
191
|
+
this.required = false;
|
|
192
|
+
return this;
|
|
193
|
+
}
|
|
194
|
+
};
|
|
195
|
+
function humanReadableArgName(arg) {
|
|
196
|
+
const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
|
|
197
|
+
return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
|
|
63
198
|
}
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
199
|
+
|
|
200
|
+
// node_modules/commander/lib/command.js
|
|
201
|
+
import { EventEmitter } from "events";
|
|
202
|
+
import childProcess from "child_process";
|
|
203
|
+
import path from "path";
|
|
204
|
+
import fs from "fs";
|
|
205
|
+
import process2 from "process";
|
|
206
|
+
import { stripVTControlCharacters as stripVTControlCharacters2 } from "util";
|
|
207
|
+
|
|
208
|
+
// node_modules/commander/lib/help.js
|
|
209
|
+
import { stripVTControlCharacters } from "util";
|
|
210
|
+
var Help = class {
|
|
211
|
+
constructor() {
|
|
212
|
+
this.helpWidth = void 0;
|
|
213
|
+
this.minWidthToWrap = 40;
|
|
214
|
+
this.sortSubcommands = false;
|
|
215
|
+
this.sortOptions = false;
|
|
216
|
+
this.showGlobalOptions = false;
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
|
|
220
|
+
* and just before calling `formatHelp()`.
|
|
221
|
+
*
|
|
222
|
+
* Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
|
|
223
|
+
*
|
|
224
|
+
* @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
|
|
225
|
+
*/
|
|
226
|
+
prepareContext(contextOptions) {
|
|
227
|
+
this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
|
|
231
|
+
*
|
|
232
|
+
* @param {Command} cmd
|
|
233
|
+
* @returns {Command[]}
|
|
234
|
+
*/
|
|
235
|
+
visibleCommands(cmd) {
|
|
236
|
+
const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
|
|
237
|
+
const helpCommand = cmd._getHelpCommand();
|
|
238
|
+
if (helpCommand && !helpCommand._hidden) {
|
|
239
|
+
visibleCommands.push(helpCommand);
|
|
240
|
+
}
|
|
241
|
+
if (this.sortSubcommands) {
|
|
242
|
+
visibleCommands.sort((a, b) => {
|
|
243
|
+
return a.name().localeCompare(b.name());
|
|
244
|
+
});
|
|
245
|
+
}
|
|
246
|
+
return visibleCommands;
|
|
247
|
+
}
|
|
248
|
+
/**
|
|
249
|
+
* Compare options for sort.
|
|
250
|
+
*
|
|
251
|
+
* @param {Option} a
|
|
252
|
+
* @param {Option} b
|
|
253
|
+
* @returns {number}
|
|
254
|
+
*/
|
|
255
|
+
compareOptions(a, b) {
|
|
256
|
+
const getSortKey = (option) => {
|
|
257
|
+
return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
|
|
258
|
+
};
|
|
259
|
+
return getSortKey(a).localeCompare(getSortKey(b));
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
|
|
263
|
+
*
|
|
264
|
+
* @param {Command} cmd
|
|
265
|
+
* @returns {Option[]}
|
|
266
|
+
*/
|
|
267
|
+
visibleOptions(cmd) {
|
|
268
|
+
const visibleOptions = cmd.options.filter((option) => !option.hidden);
|
|
269
|
+
const helpOption = cmd._getHelpOption();
|
|
270
|
+
if (helpOption && !helpOption.hidden) {
|
|
271
|
+
const removeShort = helpOption.short && cmd._findOption(helpOption.short);
|
|
272
|
+
const removeLong = helpOption.long && cmd._findOption(helpOption.long);
|
|
273
|
+
if (!removeShort && !removeLong) {
|
|
274
|
+
visibleOptions.push(helpOption);
|
|
275
|
+
} else if (helpOption.long && !removeLong) {
|
|
276
|
+
visibleOptions.push(
|
|
277
|
+
cmd.createOption(helpOption.long, helpOption.description)
|
|
278
|
+
);
|
|
279
|
+
} else if (helpOption.short && !removeShort) {
|
|
280
|
+
visibleOptions.push(
|
|
281
|
+
cmd.createOption(helpOption.short, helpOption.description)
|
|
282
|
+
);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
if (this.sortOptions) {
|
|
286
|
+
visibleOptions.sort(this.compareOptions);
|
|
287
|
+
}
|
|
288
|
+
return visibleOptions;
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* Get an array of the visible global options. (Not including help.)
|
|
292
|
+
*
|
|
293
|
+
* @param {Command} cmd
|
|
294
|
+
* @returns {Option[]}
|
|
295
|
+
*/
|
|
296
|
+
visibleGlobalOptions(cmd) {
|
|
297
|
+
if (!this.showGlobalOptions) return [];
|
|
298
|
+
const globalOptions = [];
|
|
299
|
+
for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
|
|
300
|
+
const visibleOptions = ancestorCmd.options.filter(
|
|
301
|
+
(option) => !option.hidden
|
|
302
|
+
);
|
|
303
|
+
globalOptions.push(...visibleOptions);
|
|
304
|
+
}
|
|
305
|
+
if (this.sortOptions) {
|
|
306
|
+
globalOptions.sort(this.compareOptions);
|
|
307
|
+
}
|
|
308
|
+
return globalOptions;
|
|
309
|
+
}
|
|
310
|
+
/**
|
|
311
|
+
* Get an array of the arguments if any have a description.
|
|
312
|
+
*
|
|
313
|
+
* @param {Command} cmd
|
|
314
|
+
* @returns {Argument[]}
|
|
315
|
+
*/
|
|
316
|
+
visibleArguments(cmd) {
|
|
317
|
+
if (cmd._argsDescription) {
|
|
318
|
+
cmd.registeredArguments.forEach((argument) => {
|
|
319
|
+
argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
|
|
320
|
+
});
|
|
321
|
+
}
|
|
322
|
+
if (cmd.registeredArguments.find((argument) => argument.description)) {
|
|
323
|
+
return cmd.registeredArguments;
|
|
324
|
+
}
|
|
325
|
+
return [];
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* Get the command term to show in the list of subcommands.
|
|
329
|
+
*
|
|
330
|
+
* @param {Command} cmd
|
|
331
|
+
* @returns {string}
|
|
332
|
+
*/
|
|
333
|
+
subcommandTerm(cmd) {
|
|
334
|
+
const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
|
|
335
|
+
return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
|
|
336
|
+
(args ? " " + args : "");
|
|
337
|
+
}
|
|
338
|
+
/**
|
|
339
|
+
* Get the option term to show in the list of options.
|
|
340
|
+
*
|
|
341
|
+
* @param {Option} option
|
|
342
|
+
* @returns {string}
|
|
343
|
+
*/
|
|
344
|
+
optionTerm(option) {
|
|
345
|
+
return option.flags;
|
|
346
|
+
}
|
|
347
|
+
/**
|
|
348
|
+
* Get the argument term to show in the list of arguments.
|
|
349
|
+
*
|
|
350
|
+
* @param {Argument} argument
|
|
351
|
+
* @returns {string}
|
|
352
|
+
*/
|
|
353
|
+
argumentTerm(argument) {
|
|
354
|
+
return argument.name();
|
|
355
|
+
}
|
|
356
|
+
/**
|
|
357
|
+
* Get the longest command term length.
|
|
358
|
+
*
|
|
359
|
+
* @param {Command} cmd
|
|
360
|
+
* @param {Help} helper
|
|
361
|
+
* @returns {number}
|
|
362
|
+
*/
|
|
363
|
+
longestSubcommandTermLength(cmd, helper) {
|
|
364
|
+
return helper.visibleCommands(cmd).reduce((max, command) => {
|
|
365
|
+
return Math.max(
|
|
366
|
+
max,
|
|
367
|
+
this.displayWidth(
|
|
368
|
+
helper.styleSubcommandTerm(helper.subcommandTerm(command))
|
|
369
|
+
)
|
|
370
|
+
);
|
|
371
|
+
}, 0);
|
|
372
|
+
}
|
|
373
|
+
/**
|
|
374
|
+
* Get the longest option term length.
|
|
375
|
+
*
|
|
376
|
+
* @param {Command} cmd
|
|
377
|
+
* @param {Help} helper
|
|
378
|
+
* @returns {number}
|
|
379
|
+
*/
|
|
380
|
+
longestOptionTermLength(cmd, helper) {
|
|
381
|
+
return helper.visibleOptions(cmd).reduce((max, option) => {
|
|
382
|
+
return Math.max(
|
|
383
|
+
max,
|
|
384
|
+
this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
|
|
385
|
+
);
|
|
386
|
+
}, 0);
|
|
387
|
+
}
|
|
388
|
+
/**
|
|
389
|
+
* Get the longest global option term length.
|
|
390
|
+
*
|
|
391
|
+
* @param {Command} cmd
|
|
392
|
+
* @param {Help} helper
|
|
393
|
+
* @returns {number}
|
|
394
|
+
*/
|
|
395
|
+
longestGlobalOptionTermLength(cmd, helper) {
|
|
396
|
+
return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
|
|
397
|
+
return Math.max(
|
|
398
|
+
max,
|
|
399
|
+
this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
|
|
400
|
+
);
|
|
401
|
+
}, 0);
|
|
402
|
+
}
|
|
403
|
+
/**
|
|
404
|
+
* Get the longest argument term length.
|
|
405
|
+
*
|
|
406
|
+
* @param {Command} cmd
|
|
407
|
+
* @param {Help} helper
|
|
408
|
+
* @returns {number}
|
|
409
|
+
*/
|
|
410
|
+
longestArgumentTermLength(cmd, helper) {
|
|
411
|
+
return helper.visibleArguments(cmd).reduce((max, argument) => {
|
|
412
|
+
return Math.max(
|
|
413
|
+
max,
|
|
414
|
+
this.displayWidth(
|
|
415
|
+
helper.styleArgumentTerm(helper.argumentTerm(argument))
|
|
416
|
+
)
|
|
417
|
+
);
|
|
418
|
+
}, 0);
|
|
419
|
+
}
|
|
420
|
+
/**
|
|
421
|
+
* Get the command usage to be displayed at the top of the built-in help.
|
|
422
|
+
*
|
|
423
|
+
* @param {Command} cmd
|
|
424
|
+
* @returns {string}
|
|
425
|
+
*/
|
|
426
|
+
commandUsage(cmd) {
|
|
427
|
+
let cmdName = cmd._name;
|
|
428
|
+
if (cmd._aliases[0]) {
|
|
429
|
+
cmdName = cmdName + "|" + cmd._aliases[0];
|
|
430
|
+
}
|
|
431
|
+
let ancestorCmdNames = "";
|
|
432
|
+
for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
|
|
433
|
+
ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
|
|
434
|
+
}
|
|
435
|
+
return ancestorCmdNames + cmdName + " " + cmd.usage();
|
|
436
|
+
}
|
|
437
|
+
/**
|
|
438
|
+
* Get the description for the command.
|
|
439
|
+
*
|
|
440
|
+
* @param {Command} cmd
|
|
441
|
+
* @returns {string}
|
|
442
|
+
*/
|
|
443
|
+
commandDescription(cmd) {
|
|
444
|
+
return cmd.description();
|
|
445
|
+
}
|
|
446
|
+
/**
|
|
447
|
+
* Get the subcommand summary to show in the list of subcommands.
|
|
448
|
+
* (Fallback to description for backwards compatibility.)
|
|
449
|
+
*
|
|
450
|
+
* @param {Command} cmd
|
|
451
|
+
* @returns {string}
|
|
452
|
+
*/
|
|
453
|
+
subcommandDescription(cmd) {
|
|
454
|
+
return cmd.summary() || cmd.description();
|
|
455
|
+
}
|
|
456
|
+
/**
|
|
457
|
+
* Get the option description to show in the list of options.
|
|
458
|
+
*
|
|
459
|
+
* @param {Option} option
|
|
460
|
+
* @return {string}
|
|
461
|
+
*/
|
|
462
|
+
optionDescription(option) {
|
|
463
|
+
const extraInfo = [];
|
|
464
|
+
if (option.argChoices) {
|
|
465
|
+
extraInfo.push(
|
|
466
|
+
// use stringify to match the display of the default value
|
|
467
|
+
`choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
|
|
468
|
+
);
|
|
469
|
+
}
|
|
470
|
+
if (option.defaultValue !== void 0) {
|
|
471
|
+
const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
|
|
472
|
+
if (showDefault) {
|
|
473
|
+
extraInfo.push(
|
|
474
|
+
`default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
|
|
475
|
+
);
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
if (option.presetArg !== void 0 && option.optional) {
|
|
479
|
+
extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
|
|
480
|
+
}
|
|
481
|
+
if (option.envVar !== void 0) {
|
|
482
|
+
extraInfo.push(`env: ${option.envVar}`);
|
|
483
|
+
}
|
|
484
|
+
if (extraInfo.length > 0) {
|
|
485
|
+
const extraDescription = `(${extraInfo.join(", ")})`;
|
|
486
|
+
if (option.description) {
|
|
487
|
+
return `${option.description} ${extraDescription}`;
|
|
488
|
+
}
|
|
489
|
+
return extraDescription;
|
|
490
|
+
}
|
|
491
|
+
return option.description;
|
|
492
|
+
}
|
|
493
|
+
/**
|
|
494
|
+
* Get the argument description to show in the list of arguments.
|
|
495
|
+
*
|
|
496
|
+
* @param {Argument} argument
|
|
497
|
+
* @return {string}
|
|
498
|
+
*/
|
|
499
|
+
argumentDescription(argument) {
|
|
500
|
+
const extraInfo = [];
|
|
501
|
+
if (argument.argChoices) {
|
|
502
|
+
extraInfo.push(
|
|
503
|
+
// use stringify to match the display of the default value
|
|
504
|
+
`choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
|
|
505
|
+
);
|
|
506
|
+
}
|
|
507
|
+
if (argument.defaultValue !== void 0) {
|
|
508
|
+
extraInfo.push(
|
|
509
|
+
`default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`
|
|
510
|
+
);
|
|
511
|
+
}
|
|
512
|
+
if (extraInfo.length > 0) {
|
|
513
|
+
const extraDescription = `(${extraInfo.join(", ")})`;
|
|
514
|
+
if (argument.description) {
|
|
515
|
+
return `${argument.description} ${extraDescription}`;
|
|
516
|
+
}
|
|
517
|
+
return extraDescription;
|
|
518
|
+
}
|
|
519
|
+
return argument.description;
|
|
520
|
+
}
|
|
521
|
+
/**
|
|
522
|
+
* Format a list of items, given a heading and an array of formatted items.
|
|
523
|
+
*
|
|
524
|
+
* @param {string} heading
|
|
525
|
+
* @param {string[]} items
|
|
526
|
+
* @param {Help} helper
|
|
527
|
+
* @returns string[]
|
|
528
|
+
*/
|
|
529
|
+
formatItemList(heading, items, helper) {
|
|
530
|
+
if (items.length === 0) return [];
|
|
531
|
+
return [helper.styleTitle(heading), ...items, ""];
|
|
532
|
+
}
|
|
533
|
+
/**
|
|
534
|
+
* Group items by their help group heading.
|
|
535
|
+
*
|
|
536
|
+
* @param {Command[] | Option[]} unsortedItems
|
|
537
|
+
* @param {Command[] | Option[]} visibleItems
|
|
538
|
+
* @param {Function} getGroup
|
|
539
|
+
* @returns {Map<string, Command[] | Option[]>}
|
|
540
|
+
*/
|
|
541
|
+
groupItems(unsortedItems, visibleItems, getGroup) {
|
|
542
|
+
const result = /* @__PURE__ */ new Map();
|
|
543
|
+
unsortedItems.forEach((item) => {
|
|
544
|
+
const group = getGroup(item);
|
|
545
|
+
if (!result.has(group)) result.set(group, []);
|
|
546
|
+
});
|
|
547
|
+
visibleItems.forEach((item) => {
|
|
548
|
+
const group = getGroup(item);
|
|
549
|
+
if (!result.has(group)) {
|
|
550
|
+
result.set(group, []);
|
|
551
|
+
}
|
|
552
|
+
result.get(group).push(item);
|
|
553
|
+
});
|
|
554
|
+
return result;
|
|
555
|
+
}
|
|
556
|
+
/**
|
|
557
|
+
* Generate the built-in help text.
|
|
558
|
+
*
|
|
559
|
+
* @param {Command} cmd
|
|
560
|
+
* @param {Help} helper
|
|
561
|
+
* @returns {string}
|
|
562
|
+
*/
|
|
563
|
+
formatHelp(cmd, helper) {
|
|
564
|
+
const termWidth = helper.padWidth(cmd, helper);
|
|
565
|
+
const helpWidth = helper.helpWidth ?? 80;
|
|
566
|
+
function callFormatItem(term, description) {
|
|
567
|
+
return helper.formatItem(term, termWidth, description, helper);
|
|
568
|
+
}
|
|
569
|
+
let output = [
|
|
570
|
+
`${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
|
|
571
|
+
""
|
|
572
|
+
];
|
|
573
|
+
const commandDescription = helper.commandDescription(cmd);
|
|
574
|
+
if (commandDescription.length > 0) {
|
|
575
|
+
output = output.concat([
|
|
576
|
+
helper.boxWrap(
|
|
577
|
+
helper.styleCommandDescription(commandDescription),
|
|
578
|
+
helpWidth
|
|
579
|
+
),
|
|
580
|
+
""
|
|
581
|
+
]);
|
|
582
|
+
}
|
|
583
|
+
const argumentList = helper.visibleArguments(cmd).map((argument) => {
|
|
584
|
+
return callFormatItem(
|
|
585
|
+
helper.styleArgumentTerm(helper.argumentTerm(argument)),
|
|
586
|
+
helper.styleArgumentDescription(helper.argumentDescription(argument))
|
|
587
|
+
);
|
|
588
|
+
});
|
|
589
|
+
output = output.concat(
|
|
590
|
+
this.formatItemList("Arguments:", argumentList, helper)
|
|
591
|
+
);
|
|
592
|
+
const optionGroups = this.groupItems(
|
|
593
|
+
cmd.options,
|
|
594
|
+
helper.visibleOptions(cmd),
|
|
595
|
+
(option) => option.helpGroupHeading ?? "Options:"
|
|
596
|
+
);
|
|
597
|
+
optionGroups.forEach((options, group) => {
|
|
598
|
+
const optionList = options.map((option) => {
|
|
599
|
+
return callFormatItem(
|
|
600
|
+
helper.styleOptionTerm(helper.optionTerm(option)),
|
|
601
|
+
helper.styleOptionDescription(helper.optionDescription(option))
|
|
602
|
+
);
|
|
603
|
+
});
|
|
604
|
+
output = output.concat(this.formatItemList(group, optionList, helper));
|
|
605
|
+
});
|
|
606
|
+
if (helper.showGlobalOptions) {
|
|
607
|
+
const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
|
|
608
|
+
return callFormatItem(
|
|
609
|
+
helper.styleOptionTerm(helper.optionTerm(option)),
|
|
610
|
+
helper.styleOptionDescription(helper.optionDescription(option))
|
|
611
|
+
);
|
|
612
|
+
});
|
|
613
|
+
output = output.concat(
|
|
614
|
+
this.formatItemList("Global Options:", globalOptionList, helper)
|
|
615
|
+
);
|
|
616
|
+
}
|
|
617
|
+
const commandGroups = this.groupItems(
|
|
618
|
+
cmd.commands,
|
|
619
|
+
helper.visibleCommands(cmd),
|
|
620
|
+
(sub) => sub.helpGroup() || "Commands:"
|
|
621
|
+
);
|
|
622
|
+
commandGroups.forEach((commands, group) => {
|
|
623
|
+
const commandList = commands.map((sub) => {
|
|
624
|
+
return callFormatItem(
|
|
625
|
+
helper.styleSubcommandTerm(helper.subcommandTerm(sub)),
|
|
626
|
+
helper.styleSubcommandDescription(helper.subcommandDescription(sub))
|
|
627
|
+
);
|
|
628
|
+
});
|
|
629
|
+
output = output.concat(this.formatItemList(group, commandList, helper));
|
|
630
|
+
});
|
|
631
|
+
return output.join("\n");
|
|
632
|
+
}
|
|
633
|
+
/**
|
|
634
|
+
* Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
|
|
635
|
+
*
|
|
636
|
+
* @param {string} str
|
|
637
|
+
* @returns {number}
|
|
638
|
+
*/
|
|
639
|
+
displayWidth(str) {
|
|
640
|
+
return stripVTControlCharacters(str).length;
|
|
641
|
+
}
|
|
642
|
+
/**
|
|
643
|
+
* Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
|
|
644
|
+
*
|
|
645
|
+
* @param {string} str
|
|
646
|
+
* @returns {string}
|
|
647
|
+
*/
|
|
648
|
+
styleTitle(str) {
|
|
649
|
+
return str;
|
|
650
|
+
}
|
|
651
|
+
styleUsage(str) {
|
|
652
|
+
return str.split(" ").map((word) => {
|
|
653
|
+
if (word === "[options]") return this.styleOptionText(word);
|
|
654
|
+
if (word === "[command]") return this.styleSubcommandText(word);
|
|
655
|
+
if (word[0] === "[" || word[0] === "<")
|
|
656
|
+
return this.styleArgumentText(word);
|
|
657
|
+
return this.styleCommandText(word);
|
|
658
|
+
}).join(" ");
|
|
659
|
+
}
|
|
660
|
+
styleCommandDescription(str) {
|
|
661
|
+
return this.styleDescriptionText(str);
|
|
662
|
+
}
|
|
663
|
+
styleOptionDescription(str) {
|
|
664
|
+
return this.styleDescriptionText(str);
|
|
665
|
+
}
|
|
666
|
+
styleSubcommandDescription(str) {
|
|
667
|
+
return this.styleDescriptionText(str);
|
|
668
|
+
}
|
|
669
|
+
styleArgumentDescription(str) {
|
|
670
|
+
return this.styleDescriptionText(str);
|
|
671
|
+
}
|
|
672
|
+
styleDescriptionText(str) {
|
|
673
|
+
return str;
|
|
674
|
+
}
|
|
675
|
+
styleOptionTerm(str) {
|
|
676
|
+
return this.styleOptionText(str);
|
|
677
|
+
}
|
|
678
|
+
styleSubcommandTerm(str) {
|
|
679
|
+
return str.split(" ").map((word) => {
|
|
680
|
+
if (word === "[options]") return this.styleOptionText(word);
|
|
681
|
+
if (word[0] === "[" || word[0] === "<")
|
|
682
|
+
return this.styleArgumentText(word);
|
|
683
|
+
return this.styleSubcommandText(word);
|
|
684
|
+
}).join(" ");
|
|
685
|
+
}
|
|
686
|
+
styleArgumentTerm(str) {
|
|
687
|
+
return this.styleArgumentText(str);
|
|
688
|
+
}
|
|
689
|
+
styleOptionText(str) {
|
|
690
|
+
return str;
|
|
691
|
+
}
|
|
692
|
+
styleArgumentText(str) {
|
|
693
|
+
return str;
|
|
694
|
+
}
|
|
695
|
+
styleSubcommandText(str) {
|
|
696
|
+
return str;
|
|
697
|
+
}
|
|
698
|
+
styleCommandText(str) {
|
|
699
|
+
return str;
|
|
700
|
+
}
|
|
701
|
+
/**
|
|
702
|
+
* Calculate the pad width from the maximum term length.
|
|
703
|
+
*
|
|
704
|
+
* @param {Command} cmd
|
|
705
|
+
* @param {Help} helper
|
|
706
|
+
* @returns {number}
|
|
707
|
+
*/
|
|
708
|
+
padWidth(cmd, helper) {
|
|
709
|
+
return Math.max(
|
|
710
|
+
helper.longestOptionTermLength(cmd, helper),
|
|
711
|
+
helper.longestGlobalOptionTermLength(cmd, helper),
|
|
712
|
+
helper.longestSubcommandTermLength(cmd, helper),
|
|
713
|
+
helper.longestArgumentTermLength(cmd, helper)
|
|
714
|
+
);
|
|
715
|
+
}
|
|
716
|
+
/**
|
|
717
|
+
* Detect manually wrapped and indented strings by checking for line break followed by whitespace.
|
|
718
|
+
*
|
|
719
|
+
* @param {string} str
|
|
720
|
+
* @returns {boolean}
|
|
721
|
+
*/
|
|
722
|
+
preformatted(str) {
|
|
723
|
+
return /\n[^\S\r\n]/.test(str);
|
|
724
|
+
}
|
|
725
|
+
/**
|
|
726
|
+
* Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
|
|
727
|
+
*
|
|
728
|
+
* So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
|
|
729
|
+
* TTT DDD DDDD
|
|
730
|
+
* DD DDD
|
|
731
|
+
*
|
|
732
|
+
* @param {string} term
|
|
733
|
+
* @param {number} termWidth
|
|
734
|
+
* @param {string} description
|
|
735
|
+
* @param {Help} helper
|
|
736
|
+
* @returns {string}
|
|
737
|
+
*/
|
|
738
|
+
formatItem(term, termWidth, description, helper) {
|
|
739
|
+
const itemIndent = 2;
|
|
740
|
+
const itemIndentStr = " ".repeat(itemIndent);
|
|
741
|
+
if (!description) return itemIndentStr + term;
|
|
742
|
+
const paddedTerm = term.padEnd(
|
|
743
|
+
termWidth + term.length - helper.displayWidth(term)
|
|
744
|
+
);
|
|
745
|
+
const spacerWidth = 2;
|
|
746
|
+
const helpWidth = this.helpWidth ?? 80;
|
|
747
|
+
const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
|
|
748
|
+
let formattedDescription;
|
|
749
|
+
if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
|
|
750
|
+
formattedDescription = description;
|
|
751
|
+
} else {
|
|
752
|
+
const wrappedDescription = helper.boxWrap(description, remainingWidth);
|
|
753
|
+
formattedDescription = wrappedDescription.replace(
|
|
754
|
+
/\n/g,
|
|
755
|
+
"\n" + " ".repeat(termWidth + spacerWidth)
|
|
756
|
+
);
|
|
757
|
+
}
|
|
758
|
+
return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
|
|
759
|
+
${itemIndentStr}`);
|
|
760
|
+
}
|
|
761
|
+
/**
|
|
762
|
+
* Wrap a string at whitespace, preserving existing line breaks.
|
|
763
|
+
* Wrapping is skipped if the width is less than `minWidthToWrap`.
|
|
764
|
+
*
|
|
765
|
+
* @param {string} str
|
|
766
|
+
* @param {number} width
|
|
767
|
+
* @returns {string}
|
|
768
|
+
*/
|
|
769
|
+
boxWrap(str, width) {
|
|
770
|
+
if (width < this.minWidthToWrap) return str;
|
|
771
|
+
const rawLines = str.split(/\r\n|\n/);
|
|
772
|
+
const chunkPattern = /[\s]*[^\s]+/g;
|
|
773
|
+
const wrappedLines = [];
|
|
774
|
+
rawLines.forEach((line) => {
|
|
775
|
+
const chunks = line.match(chunkPattern);
|
|
776
|
+
if (chunks === null) {
|
|
777
|
+
wrappedLines.push("");
|
|
778
|
+
return;
|
|
779
|
+
}
|
|
780
|
+
let sumChunks = [chunks.shift()];
|
|
781
|
+
let sumWidth = this.displayWidth(sumChunks[0]);
|
|
782
|
+
chunks.forEach((chunk) => {
|
|
783
|
+
const visibleWidth = this.displayWidth(chunk);
|
|
784
|
+
if (sumWidth + visibleWidth <= width) {
|
|
785
|
+
sumChunks.push(chunk);
|
|
786
|
+
sumWidth += visibleWidth;
|
|
787
|
+
return;
|
|
788
|
+
}
|
|
789
|
+
wrappedLines.push(sumChunks.join(""));
|
|
790
|
+
const nextChunk = chunk.trimStart();
|
|
791
|
+
sumChunks = [nextChunk];
|
|
792
|
+
sumWidth = this.displayWidth(nextChunk);
|
|
793
|
+
});
|
|
794
|
+
wrappedLines.push(sumChunks.join(""));
|
|
795
|
+
});
|
|
796
|
+
return wrappedLines.join("\n");
|
|
797
|
+
}
|
|
798
|
+
};
|
|
799
|
+
|
|
800
|
+
// node_modules/commander/lib/option.js
|
|
801
|
+
var Option = class {
|
|
802
|
+
/**
|
|
803
|
+
* Initialize a new `Option` with the given `flags` and `description`.
|
|
804
|
+
*
|
|
805
|
+
* @param {string} flags
|
|
806
|
+
* @param {string} [description]
|
|
807
|
+
*/
|
|
808
|
+
constructor(flags, description) {
|
|
809
|
+
this.flags = flags;
|
|
810
|
+
this.description = description || "";
|
|
811
|
+
this.required = flags.includes("<");
|
|
812
|
+
this.optional = flags.includes("[");
|
|
813
|
+
this.variadic = /\w\.\.\.[>\]]$/.test(flags);
|
|
814
|
+
this.mandatory = false;
|
|
815
|
+
const optionFlags = splitOptionFlags(flags);
|
|
816
|
+
this.short = optionFlags.shortFlag;
|
|
817
|
+
this.long = optionFlags.longFlag;
|
|
818
|
+
this.negate = false;
|
|
819
|
+
if (this.long) {
|
|
820
|
+
this.negate = this.long.startsWith("--no-");
|
|
821
|
+
}
|
|
822
|
+
this.defaultValue = void 0;
|
|
823
|
+
this.defaultValueDescription = void 0;
|
|
824
|
+
this.presetArg = void 0;
|
|
825
|
+
this.envVar = void 0;
|
|
826
|
+
this.parseArg = void 0;
|
|
827
|
+
this.hidden = false;
|
|
828
|
+
this.argChoices = void 0;
|
|
829
|
+
this.conflictsWith = [];
|
|
830
|
+
this.implied = void 0;
|
|
831
|
+
this.helpGroupHeading = void 0;
|
|
832
|
+
}
|
|
833
|
+
/**
|
|
834
|
+
* Set the default value, and optionally supply the description to be displayed in the help.
|
|
835
|
+
*
|
|
836
|
+
* @param {*} value
|
|
837
|
+
* @param {string} [description]
|
|
838
|
+
* @return {Option}
|
|
839
|
+
*/
|
|
840
|
+
default(value, description) {
|
|
841
|
+
this.defaultValue = value;
|
|
842
|
+
this.defaultValueDescription = description;
|
|
843
|
+
return this;
|
|
844
|
+
}
|
|
845
|
+
/**
|
|
846
|
+
* Preset to use when option used without option-argument, especially optional but also boolean and negated.
|
|
847
|
+
* The custom processing (parseArg) is called.
|
|
848
|
+
*
|
|
849
|
+
* @example
|
|
850
|
+
* new Option('--color').default('GREYSCALE').preset('RGB');
|
|
851
|
+
* new Option('--donate [amount]').preset('20').argParser(parseFloat);
|
|
852
|
+
*
|
|
853
|
+
* @param {*} arg
|
|
854
|
+
* @return {Option}
|
|
855
|
+
*/
|
|
856
|
+
preset(arg) {
|
|
857
|
+
this.presetArg = arg;
|
|
858
|
+
return this;
|
|
859
|
+
}
|
|
860
|
+
/**
|
|
861
|
+
* Add option name(s) that conflict with this option.
|
|
862
|
+
* An error will be displayed if conflicting options are found during parsing.
|
|
863
|
+
*
|
|
864
|
+
* @example
|
|
865
|
+
* new Option('--rgb').conflicts('cmyk');
|
|
866
|
+
* new Option('--js').conflicts(['ts', 'jsx']);
|
|
867
|
+
*
|
|
868
|
+
* @param {(string | string[])} names
|
|
869
|
+
* @return {Option}
|
|
870
|
+
*/
|
|
871
|
+
conflicts(names) {
|
|
872
|
+
this.conflictsWith = this.conflictsWith.concat(names);
|
|
873
|
+
return this;
|
|
874
|
+
}
|
|
875
|
+
/**
|
|
876
|
+
* Specify implied option values for when this option is set and the implied options are not.
|
|
877
|
+
*
|
|
878
|
+
* The custom processing (parseArg) is not called on the implied values.
|
|
879
|
+
*
|
|
880
|
+
* @example
|
|
881
|
+
* program
|
|
882
|
+
* .addOption(new Option('--log', 'write logging information to file'))
|
|
883
|
+
* .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
|
|
884
|
+
*
|
|
885
|
+
* @param {object} impliedOptionValues
|
|
886
|
+
* @return {Option}
|
|
887
|
+
*/
|
|
888
|
+
implies(impliedOptionValues) {
|
|
889
|
+
let newImplied = impliedOptionValues;
|
|
890
|
+
if (typeof impliedOptionValues === "string") {
|
|
891
|
+
newImplied = { [impliedOptionValues]: true };
|
|
892
|
+
}
|
|
893
|
+
this.implied = Object.assign(this.implied || {}, newImplied);
|
|
894
|
+
return this;
|
|
895
|
+
}
|
|
896
|
+
/**
|
|
897
|
+
* Set environment variable to check for option value.
|
|
898
|
+
*
|
|
899
|
+
* An environment variable is only used if when processed the current option value is
|
|
900
|
+
* undefined, or the source of the current value is 'default' or 'config' or 'env'.
|
|
901
|
+
*
|
|
902
|
+
* @param {string} name
|
|
903
|
+
* @return {Option}
|
|
904
|
+
*/
|
|
905
|
+
env(name) {
|
|
906
|
+
this.envVar = name;
|
|
907
|
+
return this;
|
|
908
|
+
}
|
|
909
|
+
/**
|
|
910
|
+
* Set the custom handler for processing CLI option arguments into option values.
|
|
911
|
+
*
|
|
912
|
+
* @param {Function} [fn]
|
|
913
|
+
* @return {Option}
|
|
914
|
+
*/
|
|
915
|
+
argParser(fn) {
|
|
916
|
+
this.parseArg = fn;
|
|
917
|
+
return this;
|
|
918
|
+
}
|
|
919
|
+
/**
|
|
920
|
+
* Whether the option is mandatory and must have a value after parsing.
|
|
921
|
+
*
|
|
922
|
+
* @param {boolean} [mandatory=true]
|
|
923
|
+
* @return {Option}
|
|
924
|
+
*/
|
|
925
|
+
makeOptionMandatory(mandatory = true) {
|
|
926
|
+
this.mandatory = !!mandatory;
|
|
927
|
+
return this;
|
|
928
|
+
}
|
|
929
|
+
/**
|
|
930
|
+
* Hide option in help.
|
|
931
|
+
*
|
|
932
|
+
* @param {boolean} [hide=true]
|
|
933
|
+
* @return {Option}
|
|
934
|
+
*/
|
|
935
|
+
hideHelp(hide = true) {
|
|
936
|
+
this.hidden = !!hide;
|
|
937
|
+
return this;
|
|
938
|
+
}
|
|
939
|
+
/**
|
|
940
|
+
* @package
|
|
941
|
+
*/
|
|
942
|
+
_collectValue(value, previous) {
|
|
943
|
+
if (previous === this.defaultValue || !Array.isArray(previous)) {
|
|
944
|
+
return [value];
|
|
945
|
+
}
|
|
946
|
+
previous.push(value);
|
|
947
|
+
return previous;
|
|
948
|
+
}
|
|
949
|
+
/**
|
|
950
|
+
* Only allow option value to be one of choices.
|
|
951
|
+
*
|
|
952
|
+
* @param {string[]} values
|
|
953
|
+
* @return {Option}
|
|
954
|
+
*/
|
|
955
|
+
choices(values) {
|
|
956
|
+
this.argChoices = values.slice();
|
|
957
|
+
this.parseArg = (arg, previous) => {
|
|
958
|
+
if (!this.argChoices.includes(arg)) {
|
|
959
|
+
throw new InvalidArgumentError(
|
|
960
|
+
`Allowed choices are ${this.argChoices.join(", ")}.`
|
|
961
|
+
);
|
|
962
|
+
}
|
|
963
|
+
if (this.variadic) {
|
|
964
|
+
return this._collectValue(arg, previous);
|
|
965
|
+
}
|
|
966
|
+
return arg;
|
|
967
|
+
};
|
|
968
|
+
return this;
|
|
969
|
+
}
|
|
970
|
+
/**
|
|
971
|
+
* Return option name.
|
|
972
|
+
*
|
|
973
|
+
* @return {string}
|
|
974
|
+
*/
|
|
975
|
+
name() {
|
|
976
|
+
if (this.long) {
|
|
977
|
+
return this.long.replace(/^--/, "");
|
|
978
|
+
}
|
|
979
|
+
return this.short.replace(/^-/, "");
|
|
980
|
+
}
|
|
981
|
+
/**
|
|
982
|
+
* Return option name, in a camelcase format that can be used
|
|
983
|
+
* as an object attribute key.
|
|
984
|
+
*
|
|
985
|
+
* @return {string}
|
|
986
|
+
*/
|
|
987
|
+
attributeName() {
|
|
988
|
+
if (this.negate) {
|
|
989
|
+
return camelcase(this.name().replace(/^no-/, ""));
|
|
990
|
+
}
|
|
991
|
+
return camelcase(this.name());
|
|
992
|
+
}
|
|
993
|
+
/**
|
|
994
|
+
* Set the help group heading.
|
|
995
|
+
*
|
|
996
|
+
* @param {string} heading
|
|
997
|
+
* @return {Option}
|
|
998
|
+
*/
|
|
999
|
+
helpGroup(heading) {
|
|
1000
|
+
this.helpGroupHeading = heading;
|
|
1001
|
+
return this;
|
|
1002
|
+
}
|
|
1003
|
+
/**
|
|
1004
|
+
* Check if `arg` matches the short or long flag.
|
|
1005
|
+
*
|
|
1006
|
+
* @param {string} arg
|
|
1007
|
+
* @return {boolean}
|
|
1008
|
+
* @package
|
|
1009
|
+
*/
|
|
1010
|
+
is(arg) {
|
|
1011
|
+
return this.short === arg || this.long === arg;
|
|
1012
|
+
}
|
|
1013
|
+
/**
|
|
1014
|
+
* Return whether a boolean option.
|
|
1015
|
+
*
|
|
1016
|
+
* Options are one of boolean, negated, required argument, or optional argument.
|
|
1017
|
+
*
|
|
1018
|
+
* @return {boolean}
|
|
1019
|
+
* @package
|
|
1020
|
+
*/
|
|
1021
|
+
isBoolean() {
|
|
1022
|
+
return !this.required && !this.optional && !this.negate;
|
|
1023
|
+
}
|
|
1024
|
+
};
|
|
1025
|
+
var DualOptions = class {
|
|
1026
|
+
/**
|
|
1027
|
+
* @param {Option[]} options
|
|
1028
|
+
*/
|
|
1029
|
+
constructor(options) {
|
|
1030
|
+
this.positiveOptions = /* @__PURE__ */ new Map();
|
|
1031
|
+
this.negativeOptions = /* @__PURE__ */ new Map();
|
|
1032
|
+
this.dualOptions = /* @__PURE__ */ new Set();
|
|
1033
|
+
options.forEach((option) => {
|
|
1034
|
+
if (option.negate) {
|
|
1035
|
+
this.negativeOptions.set(option.attributeName(), option);
|
|
1036
|
+
} else {
|
|
1037
|
+
this.positiveOptions.set(option.attributeName(), option);
|
|
1038
|
+
}
|
|
1039
|
+
});
|
|
1040
|
+
this.negativeOptions.forEach((value, key) => {
|
|
1041
|
+
if (this.positiveOptions.has(key)) {
|
|
1042
|
+
this.dualOptions.add(key);
|
|
1043
|
+
}
|
|
1044
|
+
});
|
|
1045
|
+
}
|
|
1046
|
+
/**
|
|
1047
|
+
* Did the value come from the option, and not from possible matching dual option?
|
|
1048
|
+
*
|
|
1049
|
+
* @param {*} value
|
|
1050
|
+
* @param {Option} option
|
|
1051
|
+
* @returns {boolean}
|
|
1052
|
+
*/
|
|
1053
|
+
valueFromOption(value, option) {
|
|
1054
|
+
const optionKey = option.attributeName();
|
|
1055
|
+
if (!this.dualOptions.has(optionKey)) return true;
|
|
1056
|
+
const preset = this.negativeOptions.get(optionKey).presetArg;
|
|
1057
|
+
const negativeValue = preset !== void 0 ? preset : false;
|
|
1058
|
+
return option.negate === (negativeValue === value);
|
|
1059
|
+
}
|
|
1060
|
+
};
|
|
1061
|
+
function camelcase(str) {
|
|
1062
|
+
return str.split("-").reduce((str2, word) => {
|
|
1063
|
+
return str2 + word[0].toUpperCase() + word.slice(1);
|
|
69
1064
|
});
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
const
|
|
75
|
-
const
|
|
76
|
-
|
|
77
|
-
if (
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
1065
|
+
}
|
|
1066
|
+
function splitOptionFlags(flags) {
|
|
1067
|
+
let shortFlag;
|
|
1068
|
+
let longFlag;
|
|
1069
|
+
const shortFlagExp = /^-[^-]$/;
|
|
1070
|
+
const longFlagExp = /^--[^-]/;
|
|
1071
|
+
const flagParts = flags.split(/[ |,]+/).concat("guard");
|
|
1072
|
+
if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
|
|
1073
|
+
if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
|
|
1074
|
+
if (!shortFlag && shortFlagExp.test(flagParts[0]))
|
|
1075
|
+
shortFlag = flagParts.shift();
|
|
1076
|
+
if (!shortFlag && longFlagExp.test(flagParts[0])) {
|
|
1077
|
+
shortFlag = longFlag;
|
|
1078
|
+
longFlag = flagParts.shift();
|
|
1079
|
+
}
|
|
1080
|
+
if (flagParts[0].startsWith("-")) {
|
|
1081
|
+
const unsupportedFlag = flagParts[0];
|
|
1082
|
+
const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
|
|
1083
|
+
if (/^-[^-][^-]/.test(unsupportedFlag))
|
|
1084
|
+
throw new Error(
|
|
1085
|
+
`${baseError}
|
|
1086
|
+
- a short flag is a single dash and a single character
|
|
1087
|
+
- either use a single dash and a single character (for a short flag)
|
|
1088
|
+
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`
|
|
1089
|
+
);
|
|
1090
|
+
if (shortFlagExp.test(unsupportedFlag))
|
|
1091
|
+
throw new Error(`${baseError}
|
|
1092
|
+
- too many short flags`);
|
|
1093
|
+
if (longFlagExp.test(unsupportedFlag))
|
|
1094
|
+
throw new Error(`${baseError}
|
|
1095
|
+
- too many long flags`);
|
|
1096
|
+
throw new Error(`${baseError}
|
|
1097
|
+
- unrecognised flag format`);
|
|
84
1098
|
}
|
|
85
|
-
|
|
1099
|
+
if (shortFlag === void 0 && longFlag === void 0)
|
|
1100
|
+
throw new Error(
|
|
1101
|
+
`option creation failed due to no flags found in '${flags}'.`
|
|
1102
|
+
);
|
|
1103
|
+
return { shortFlag, longFlag };
|
|
86
1104
|
}
|
|
87
1105
|
|
|
88
|
-
//
|
|
89
|
-
|
|
90
|
-
function
|
|
91
|
-
|
|
92
|
-
|
|
1106
|
+
// node_modules/commander/lib/suggestSimilar.js
|
|
1107
|
+
var maxDistance = 3;
|
|
1108
|
+
function editDistance(a, b) {
|
|
1109
|
+
if (Math.abs(a.length - b.length) > maxDistance)
|
|
1110
|
+
return Math.max(a.length, b.length);
|
|
1111
|
+
const d = [];
|
|
1112
|
+
for (let i = 0; i <= a.length; i++) {
|
|
1113
|
+
d[i] = [i];
|
|
1114
|
+
}
|
|
1115
|
+
for (let j = 0; j <= b.length; j++) {
|
|
1116
|
+
d[0][j] = j;
|
|
1117
|
+
}
|
|
1118
|
+
for (let j = 1; j <= b.length; j++) {
|
|
1119
|
+
for (let i = 1; i <= a.length; i++) {
|
|
1120
|
+
let cost;
|
|
1121
|
+
if (a[i - 1] === b[j - 1]) {
|
|
1122
|
+
cost = 0;
|
|
1123
|
+
} else {
|
|
1124
|
+
cost = 1;
|
|
1125
|
+
}
|
|
1126
|
+
d[i][j] = Math.min(
|
|
1127
|
+
d[i - 1][j] + 1,
|
|
1128
|
+
// deletion
|
|
1129
|
+
d[i][j - 1] + 1,
|
|
1130
|
+
// insertion
|
|
1131
|
+
d[i - 1][j - 1] + cost
|
|
1132
|
+
// substitution
|
|
1133
|
+
);
|
|
1134
|
+
if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
|
|
1135
|
+
d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
return d[a.length][b.length];
|
|
93
1140
|
}
|
|
94
|
-
function
|
|
95
|
-
if (!
|
|
96
|
-
|
|
1141
|
+
function suggestSimilar(word, candidates) {
|
|
1142
|
+
if (!candidates || candidates.length === 0) return "";
|
|
1143
|
+
candidates = Array.from(new Set(candidates));
|
|
1144
|
+
const searchingOptions = word.startsWith("--");
|
|
1145
|
+
if (searchingOptions) {
|
|
1146
|
+
word = word.slice(2);
|
|
1147
|
+
candidates = candidates.map((candidate) => candidate.slice(2));
|
|
1148
|
+
}
|
|
1149
|
+
let similar = [];
|
|
1150
|
+
let bestDistance = maxDistance;
|
|
1151
|
+
const minSimilarity = 0.4;
|
|
1152
|
+
candidates.forEach((candidate) => {
|
|
1153
|
+
if (candidate.length <= 1) return;
|
|
1154
|
+
const distance = editDistance(word, candidate);
|
|
1155
|
+
const length = Math.max(word.length, candidate.length);
|
|
1156
|
+
const similarity = (length - distance) / length;
|
|
1157
|
+
if (similarity > minSimilarity) {
|
|
1158
|
+
if (distance < bestDistance) {
|
|
1159
|
+
bestDistance = distance;
|
|
1160
|
+
similar = [candidate];
|
|
1161
|
+
} else if (distance === bestDistance) {
|
|
1162
|
+
similar.push(candidate);
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
});
|
|
1166
|
+
similar.sort((a, b) => a.localeCompare(b));
|
|
1167
|
+
if (searchingOptions) {
|
|
1168
|
+
similar = similar.map((candidate) => `--${candidate}`);
|
|
1169
|
+
}
|
|
1170
|
+
if (similar.length > 1) {
|
|
1171
|
+
return `
|
|
1172
|
+
(Did you mean one of ${similar.join(", ")}?)`;
|
|
1173
|
+
}
|
|
1174
|
+
if (similar.length === 1) {
|
|
1175
|
+
return `
|
|
1176
|
+
(Did you mean ${similar[0]}?)`;
|
|
1177
|
+
}
|
|
1178
|
+
return "";
|
|
1179
|
+
}
|
|
1180
|
+
|
|
1181
|
+
// node_modules/commander/lib/command.js
|
|
1182
|
+
var Command = class _Command extends EventEmitter {
|
|
1183
|
+
/**
|
|
1184
|
+
* Initialize a new `Command`.
|
|
1185
|
+
*
|
|
1186
|
+
* @param {string} [name]
|
|
1187
|
+
*/
|
|
1188
|
+
constructor(name) {
|
|
1189
|
+
super();
|
|
1190
|
+
this.commands = [];
|
|
1191
|
+
this.options = [];
|
|
1192
|
+
this.parent = null;
|
|
1193
|
+
this._allowUnknownOption = false;
|
|
1194
|
+
this._allowExcessArguments = false;
|
|
1195
|
+
this.registeredArguments = [];
|
|
1196
|
+
this._args = this.registeredArguments;
|
|
1197
|
+
this.args = [];
|
|
1198
|
+
this.rawArgs = [];
|
|
1199
|
+
this.processedArgs = [];
|
|
1200
|
+
this._scriptPath = null;
|
|
1201
|
+
this._name = name || "";
|
|
1202
|
+
this._optionValues = {};
|
|
1203
|
+
this._optionValueSources = {};
|
|
1204
|
+
this._storeOptionsAsProperties = false;
|
|
1205
|
+
this._actionHandler = null;
|
|
1206
|
+
this._executableHandler = false;
|
|
1207
|
+
this._executableFile = null;
|
|
1208
|
+
this._executableDir = null;
|
|
1209
|
+
this._defaultCommandName = null;
|
|
1210
|
+
this._exitCallback = null;
|
|
1211
|
+
this._aliases = [];
|
|
1212
|
+
this._combineFlagAndOptionalValue = true;
|
|
1213
|
+
this._description = "";
|
|
1214
|
+
this._summary = "";
|
|
1215
|
+
this._argsDescription = void 0;
|
|
1216
|
+
this._enablePositionalOptions = false;
|
|
1217
|
+
this._passThroughOptions = false;
|
|
1218
|
+
this._lifeCycleHooks = {};
|
|
1219
|
+
this._showHelpAfterError = false;
|
|
1220
|
+
this._showSuggestionAfterError = true;
|
|
1221
|
+
this._savedState = null;
|
|
1222
|
+
this._outputConfiguration = {
|
|
1223
|
+
writeOut: (str) => process2.stdout.write(str),
|
|
1224
|
+
writeErr: (str) => process2.stderr.write(str),
|
|
1225
|
+
outputError: (str, write) => write(str),
|
|
1226
|
+
getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
|
|
1227
|
+
getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
|
|
1228
|
+
getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
|
|
1229
|
+
getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
|
|
1230
|
+
stripColor: (str) => stripVTControlCharacters2(str)
|
|
1231
|
+
};
|
|
1232
|
+
this._hidden = false;
|
|
1233
|
+
this._helpOption = void 0;
|
|
1234
|
+
this._addImplicitHelpCommand = void 0;
|
|
1235
|
+
this._helpCommand = void 0;
|
|
1236
|
+
this._helpConfiguration = {};
|
|
1237
|
+
this._helpGroupHeading = void 0;
|
|
1238
|
+
this._defaultCommandGroup = void 0;
|
|
1239
|
+
this._defaultOptionGroup = void 0;
|
|
1240
|
+
}
|
|
1241
|
+
/**
|
|
1242
|
+
* Copy settings that are useful to have in common across root command and subcommands.
|
|
1243
|
+
*
|
|
1244
|
+
* (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
|
|
1245
|
+
*
|
|
1246
|
+
* @param {Command} sourceCommand
|
|
1247
|
+
* @return {Command} `this` command for chaining
|
|
1248
|
+
*/
|
|
1249
|
+
copyInheritedSettings(sourceCommand) {
|
|
1250
|
+
this._outputConfiguration = sourceCommand._outputConfiguration;
|
|
1251
|
+
this._helpOption = sourceCommand._helpOption;
|
|
1252
|
+
this._helpCommand = sourceCommand._helpCommand;
|
|
1253
|
+
this._helpConfiguration = sourceCommand._helpConfiguration;
|
|
1254
|
+
this._exitCallback = sourceCommand._exitCallback;
|
|
1255
|
+
this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
|
|
1256
|
+
this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
|
|
1257
|
+
this._allowExcessArguments = sourceCommand._allowExcessArguments;
|
|
1258
|
+
this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
|
|
1259
|
+
this._showHelpAfterError = sourceCommand._showHelpAfterError;
|
|
1260
|
+
this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
|
|
1261
|
+
return this;
|
|
1262
|
+
}
|
|
1263
|
+
/**
|
|
1264
|
+
* @returns {Command[]}
|
|
1265
|
+
* @private
|
|
1266
|
+
*/
|
|
1267
|
+
_getCommandAndAncestors() {
|
|
1268
|
+
const result = [];
|
|
1269
|
+
for (let command = this; command; command = command.parent) {
|
|
1270
|
+
result.push(command);
|
|
1271
|
+
}
|
|
1272
|
+
return result;
|
|
1273
|
+
}
|
|
1274
|
+
/**
|
|
1275
|
+
* Define a command.
|
|
1276
|
+
*
|
|
1277
|
+
* There are two styles of command: pay attention to where to put the description.
|
|
1278
|
+
*
|
|
1279
|
+
* @example
|
|
1280
|
+
* // Command implemented using action handler (description is supplied separately to `.command`)
|
|
1281
|
+
* program
|
|
1282
|
+
* .command('clone <source> [destination]')
|
|
1283
|
+
* .description('clone a repository into a newly created directory')
|
|
1284
|
+
* .action((source, destination) => {
|
|
1285
|
+
* console.log('clone command called');
|
|
1286
|
+
* });
|
|
1287
|
+
*
|
|
1288
|
+
* // Command implemented using separate executable file (description is second parameter to `.command`)
|
|
1289
|
+
* program
|
|
1290
|
+
* .command('start <service>', 'start named service')
|
|
1291
|
+
* .command('stop [service]', 'stop named service, or all if no name supplied');
|
|
1292
|
+
*
|
|
1293
|
+
* @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
|
|
1294
|
+
* @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
|
|
1295
|
+
* @param {object} [execOpts] - configuration options (for executable)
|
|
1296
|
+
* @return {Command} returns new command for action handler, or `this` for executable command
|
|
1297
|
+
*/
|
|
1298
|
+
command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
|
|
1299
|
+
let desc = actionOptsOrExecDesc;
|
|
1300
|
+
let opts = execOpts;
|
|
1301
|
+
if (typeof desc === "object" && desc !== null) {
|
|
1302
|
+
opts = desc;
|
|
1303
|
+
desc = null;
|
|
1304
|
+
}
|
|
1305
|
+
opts = opts || {};
|
|
1306
|
+
const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
|
|
1307
|
+
const cmd = this.createCommand(name);
|
|
1308
|
+
if (desc) {
|
|
1309
|
+
cmd.description(desc);
|
|
1310
|
+
cmd._executableHandler = true;
|
|
1311
|
+
}
|
|
1312
|
+
if (opts.isDefault) this._defaultCommandName = cmd._name;
|
|
1313
|
+
cmd._hidden = !!(opts.noHelp || opts.hidden);
|
|
1314
|
+
cmd._executableFile = opts.executableFile || null;
|
|
1315
|
+
if (args) cmd.arguments(args);
|
|
1316
|
+
this._registerCommand(cmd);
|
|
1317
|
+
cmd.parent = this;
|
|
1318
|
+
cmd.copyInheritedSettings(this);
|
|
1319
|
+
if (desc) return this;
|
|
1320
|
+
return cmd;
|
|
1321
|
+
}
|
|
1322
|
+
/**
|
|
1323
|
+
* Factory routine to create a new unattached command.
|
|
1324
|
+
*
|
|
1325
|
+
* See .command() for creating an attached subcommand, which uses this routine to
|
|
1326
|
+
* create the command. You can override createCommand to customise subcommands.
|
|
1327
|
+
*
|
|
1328
|
+
* @param {string} [name]
|
|
1329
|
+
* @return {Command} new command
|
|
1330
|
+
*/
|
|
1331
|
+
createCommand(name) {
|
|
1332
|
+
return new _Command(name);
|
|
1333
|
+
}
|
|
1334
|
+
/**
|
|
1335
|
+
* You can customise the help with a subclass of Help by overriding createHelp,
|
|
1336
|
+
* or by overriding Help properties using configureHelp().
|
|
1337
|
+
*
|
|
1338
|
+
* @return {Help}
|
|
1339
|
+
*/
|
|
1340
|
+
createHelp() {
|
|
1341
|
+
return Object.assign(new Help(), this.configureHelp());
|
|
1342
|
+
}
|
|
1343
|
+
/**
|
|
1344
|
+
* You can customise the help by overriding Help properties using configureHelp(),
|
|
1345
|
+
* or with a subclass of Help by overriding createHelp().
|
|
1346
|
+
*
|
|
1347
|
+
* @param {object} [configuration] - configuration options
|
|
1348
|
+
* @return {(Command | object)} `this` command for chaining, or stored configuration
|
|
1349
|
+
*/
|
|
1350
|
+
configureHelp(configuration) {
|
|
1351
|
+
if (configuration === void 0) return this._helpConfiguration;
|
|
1352
|
+
this._helpConfiguration = configuration;
|
|
1353
|
+
return this;
|
|
1354
|
+
}
|
|
1355
|
+
/**
|
|
1356
|
+
* The default output goes to stdout and stderr. You can customise this for special
|
|
1357
|
+
* applications. You can also customise the display of errors by overriding outputError.
|
|
1358
|
+
*
|
|
1359
|
+
* The configuration properties are all functions:
|
|
1360
|
+
*
|
|
1361
|
+
* // change how output being written, defaults to stdout and stderr
|
|
1362
|
+
* writeOut(str)
|
|
1363
|
+
* writeErr(str)
|
|
1364
|
+
* // change how output being written for errors, defaults to writeErr
|
|
1365
|
+
* outputError(str, write) // used for displaying errors and not used for displaying help
|
|
1366
|
+
* // specify width for wrapping help
|
|
1367
|
+
* getOutHelpWidth()
|
|
1368
|
+
* getErrHelpWidth()
|
|
1369
|
+
* // color support, currently only used with Help
|
|
1370
|
+
* getOutHasColors()
|
|
1371
|
+
* getErrHasColors()
|
|
1372
|
+
* stripColor() // used to remove ANSI escape codes if output does not have colors
|
|
1373
|
+
*
|
|
1374
|
+
* @param {object} [configuration] - configuration options
|
|
1375
|
+
* @return {(Command | object)} `this` command for chaining, or stored configuration
|
|
1376
|
+
*/
|
|
1377
|
+
configureOutput(configuration) {
|
|
1378
|
+
if (configuration === void 0) return this._outputConfiguration;
|
|
1379
|
+
this._outputConfiguration = {
|
|
1380
|
+
...this._outputConfiguration,
|
|
1381
|
+
...configuration
|
|
1382
|
+
};
|
|
1383
|
+
return this;
|
|
1384
|
+
}
|
|
1385
|
+
/**
|
|
1386
|
+
* Display the help or a custom message after an error occurs.
|
|
1387
|
+
*
|
|
1388
|
+
* @param {(boolean|string)} [displayHelp]
|
|
1389
|
+
* @return {Command} `this` command for chaining
|
|
1390
|
+
*/
|
|
1391
|
+
showHelpAfterError(displayHelp = true) {
|
|
1392
|
+
if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
|
|
1393
|
+
this._showHelpAfterError = displayHelp;
|
|
1394
|
+
return this;
|
|
1395
|
+
}
|
|
1396
|
+
/**
|
|
1397
|
+
* Display suggestion of similar commands for unknown commands, or options for unknown options.
|
|
1398
|
+
*
|
|
1399
|
+
* @param {boolean} [displaySuggestion]
|
|
1400
|
+
* @return {Command} `this` command for chaining
|
|
1401
|
+
*/
|
|
1402
|
+
showSuggestionAfterError(displaySuggestion = true) {
|
|
1403
|
+
this._showSuggestionAfterError = !!displaySuggestion;
|
|
1404
|
+
return this;
|
|
1405
|
+
}
|
|
1406
|
+
/**
|
|
1407
|
+
* Add a prepared subcommand.
|
|
1408
|
+
*
|
|
1409
|
+
* See .command() for creating an attached subcommand which inherits settings from its parent.
|
|
1410
|
+
*
|
|
1411
|
+
* @param {Command} cmd - new subcommand
|
|
1412
|
+
* @param {object} [opts] - configuration options
|
|
1413
|
+
* @return {Command} `this` command for chaining
|
|
1414
|
+
*/
|
|
1415
|
+
addCommand(cmd, opts) {
|
|
1416
|
+
if (!cmd._name) {
|
|
1417
|
+
throw new Error(`Command passed to .addCommand() must have a name
|
|
1418
|
+
- specify the name in Command constructor or using .name()`);
|
|
1419
|
+
}
|
|
1420
|
+
opts = opts || {};
|
|
1421
|
+
if (opts.isDefault) this._defaultCommandName = cmd._name;
|
|
1422
|
+
if (opts.noHelp || opts.hidden) cmd._hidden = true;
|
|
1423
|
+
this._registerCommand(cmd);
|
|
1424
|
+
cmd.parent = this;
|
|
1425
|
+
cmd._checkForBrokenPassThrough();
|
|
1426
|
+
return this;
|
|
1427
|
+
}
|
|
1428
|
+
/**
|
|
1429
|
+
* Factory routine to create a new unattached argument.
|
|
1430
|
+
*
|
|
1431
|
+
* See .argument() for creating an attached argument, which uses this routine to
|
|
1432
|
+
* create the argument. You can override createArgument to return a custom argument.
|
|
1433
|
+
*
|
|
1434
|
+
* @param {string} name
|
|
1435
|
+
* @param {string} [description]
|
|
1436
|
+
* @return {Argument} new argument
|
|
1437
|
+
*/
|
|
1438
|
+
createArgument(name, description) {
|
|
1439
|
+
return new Argument(name, description);
|
|
1440
|
+
}
|
|
1441
|
+
/**
|
|
1442
|
+
* Define argument syntax for command.
|
|
1443
|
+
*
|
|
1444
|
+
* The default is that the argument is required, and you can explicitly
|
|
1445
|
+
* indicate this with <> around the name. Put [] around the name for an optional argument.
|
|
1446
|
+
*
|
|
1447
|
+
* @example
|
|
1448
|
+
* program.argument('<input-file>');
|
|
1449
|
+
* program.argument('[output-file]');
|
|
1450
|
+
*
|
|
1451
|
+
* @param {string} name
|
|
1452
|
+
* @param {string} [description]
|
|
1453
|
+
* @param {(Function|*)} [parseArg] - custom argument processing function or default value
|
|
1454
|
+
* @param {*} [defaultValue]
|
|
1455
|
+
* @return {Command} `this` command for chaining
|
|
1456
|
+
*/
|
|
1457
|
+
argument(name, description, parseArg, defaultValue) {
|
|
1458
|
+
const argument = this.createArgument(name, description);
|
|
1459
|
+
if (typeof parseArg === "function") {
|
|
1460
|
+
argument.default(defaultValue).argParser(parseArg);
|
|
1461
|
+
} else {
|
|
1462
|
+
argument.default(parseArg);
|
|
1463
|
+
}
|
|
1464
|
+
this.addArgument(argument);
|
|
1465
|
+
return this;
|
|
1466
|
+
}
|
|
1467
|
+
/**
|
|
1468
|
+
* Define argument syntax for command, adding multiple at once (without descriptions).
|
|
1469
|
+
*
|
|
1470
|
+
* See also .argument().
|
|
1471
|
+
*
|
|
1472
|
+
* @example
|
|
1473
|
+
* program.arguments('<cmd> [env]');
|
|
1474
|
+
*
|
|
1475
|
+
* @param {string} names
|
|
1476
|
+
* @return {Command} `this` command for chaining
|
|
1477
|
+
*/
|
|
1478
|
+
arguments(names) {
|
|
1479
|
+
names.trim().split(/ +/).forEach((detail) => {
|
|
1480
|
+
this.argument(detail);
|
|
1481
|
+
});
|
|
1482
|
+
return this;
|
|
1483
|
+
}
|
|
1484
|
+
/**
|
|
1485
|
+
* Define argument syntax for command, adding a prepared argument.
|
|
1486
|
+
*
|
|
1487
|
+
* @param {Argument} argument
|
|
1488
|
+
* @return {Command} `this` command for chaining
|
|
1489
|
+
*/
|
|
1490
|
+
addArgument(argument) {
|
|
1491
|
+
const previousArgument = this.registeredArguments.slice(-1)[0];
|
|
1492
|
+
if (previousArgument?.variadic) {
|
|
1493
|
+
throw new Error(
|
|
1494
|
+
`only the last argument can be variadic '${previousArgument.name()}'`
|
|
1495
|
+
);
|
|
1496
|
+
}
|
|
1497
|
+
if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
|
|
1498
|
+
throw new Error(
|
|
1499
|
+
`a default value for a required argument is never used: '${argument.name()}'`
|
|
1500
|
+
);
|
|
1501
|
+
}
|
|
1502
|
+
this.registeredArguments.push(argument);
|
|
1503
|
+
return this;
|
|
1504
|
+
}
|
|
1505
|
+
/**
|
|
1506
|
+
* Customise or override default help command. By default a help command is automatically added if your command has subcommands.
|
|
1507
|
+
*
|
|
1508
|
+
* @example
|
|
1509
|
+
* program.helpCommand('help [cmd]');
|
|
1510
|
+
* program.helpCommand('help [cmd]', 'show help');
|
|
1511
|
+
* program.helpCommand(false); // suppress default help command
|
|
1512
|
+
* program.helpCommand(true); // add help command even if no subcommands
|
|
1513
|
+
*
|
|
1514
|
+
* @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
|
|
1515
|
+
* @param {string} [description] - custom description
|
|
1516
|
+
* @return {Command} `this` command for chaining
|
|
1517
|
+
*/
|
|
1518
|
+
helpCommand(enableOrNameAndArgs, description) {
|
|
1519
|
+
if (typeof enableOrNameAndArgs === "boolean") {
|
|
1520
|
+
this._addImplicitHelpCommand = enableOrNameAndArgs;
|
|
1521
|
+
if (enableOrNameAndArgs && this._defaultCommandGroup) {
|
|
1522
|
+
this._initCommandGroup(this._getHelpCommand());
|
|
1523
|
+
}
|
|
1524
|
+
return this;
|
|
1525
|
+
}
|
|
1526
|
+
const nameAndArgs = enableOrNameAndArgs ?? "help [command]";
|
|
1527
|
+
const [, helpName, helpArgs] = nameAndArgs.match(/([^ ]+) *(.*)/);
|
|
1528
|
+
const helpDescription = description ?? "display help for command";
|
|
1529
|
+
const helpCommand = this.createCommand(helpName);
|
|
1530
|
+
helpCommand.helpOption(false);
|
|
1531
|
+
if (helpArgs) helpCommand.arguments(helpArgs);
|
|
1532
|
+
if (helpDescription) helpCommand.description(helpDescription);
|
|
1533
|
+
this._addImplicitHelpCommand = true;
|
|
1534
|
+
this._helpCommand = helpCommand;
|
|
1535
|
+
if (enableOrNameAndArgs || description) this._initCommandGroup(helpCommand);
|
|
1536
|
+
return this;
|
|
1537
|
+
}
|
|
1538
|
+
/**
|
|
1539
|
+
* Add prepared custom help command.
|
|
1540
|
+
*
|
|
1541
|
+
* @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
|
|
1542
|
+
* @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
|
|
1543
|
+
* @return {Command} `this` command for chaining
|
|
1544
|
+
*/
|
|
1545
|
+
addHelpCommand(helpCommand, deprecatedDescription) {
|
|
1546
|
+
if (typeof helpCommand !== "object") {
|
|
1547
|
+
this.helpCommand(helpCommand, deprecatedDescription);
|
|
1548
|
+
return this;
|
|
1549
|
+
}
|
|
1550
|
+
this._addImplicitHelpCommand = true;
|
|
1551
|
+
this._helpCommand = helpCommand;
|
|
1552
|
+
this._initCommandGroup(helpCommand);
|
|
1553
|
+
return this;
|
|
1554
|
+
}
|
|
1555
|
+
/**
|
|
1556
|
+
* Lazy create help command.
|
|
1557
|
+
*
|
|
1558
|
+
* @return {(Command|null)}
|
|
1559
|
+
* @package
|
|
1560
|
+
*/
|
|
1561
|
+
_getHelpCommand() {
|
|
1562
|
+
const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
|
|
1563
|
+
if (hasImplicitHelpCommand) {
|
|
1564
|
+
if (this._helpCommand === void 0) {
|
|
1565
|
+
this.helpCommand(void 0, void 0);
|
|
1566
|
+
}
|
|
1567
|
+
return this._helpCommand;
|
|
1568
|
+
}
|
|
1569
|
+
return null;
|
|
1570
|
+
}
|
|
1571
|
+
/**
|
|
1572
|
+
* Add hook for life cycle event.
|
|
1573
|
+
*
|
|
1574
|
+
* @param {string} event
|
|
1575
|
+
* @param {Function} listener
|
|
1576
|
+
* @return {Command} `this` command for chaining
|
|
1577
|
+
*/
|
|
1578
|
+
hook(event, listener) {
|
|
1579
|
+
const allowedValues = ["preSubcommand", "preAction", "postAction"];
|
|
1580
|
+
if (!allowedValues.includes(event)) {
|
|
1581
|
+
throw new Error(`Unexpected value for event passed to hook : '${event}'.
|
|
1582
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
1583
|
+
}
|
|
1584
|
+
if (this._lifeCycleHooks[event]) {
|
|
1585
|
+
this._lifeCycleHooks[event].push(listener);
|
|
1586
|
+
} else {
|
|
1587
|
+
this._lifeCycleHooks[event] = [listener];
|
|
1588
|
+
}
|
|
1589
|
+
return this;
|
|
1590
|
+
}
|
|
1591
|
+
/**
|
|
1592
|
+
* Register callback to use as replacement for calling process.exit.
|
|
1593
|
+
*
|
|
1594
|
+
* @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
|
|
1595
|
+
* @return {Command} `this` command for chaining
|
|
1596
|
+
*/
|
|
1597
|
+
exitOverride(fn) {
|
|
1598
|
+
if (fn) {
|
|
1599
|
+
this._exitCallback = fn;
|
|
1600
|
+
} else {
|
|
1601
|
+
this._exitCallback = (err) => {
|
|
1602
|
+
if (err.code !== "commander.executeSubCommandAsync") {
|
|
1603
|
+
throw err;
|
|
1604
|
+
} else {
|
|
1605
|
+
}
|
|
1606
|
+
};
|
|
1607
|
+
}
|
|
1608
|
+
return this;
|
|
1609
|
+
}
|
|
1610
|
+
/**
|
|
1611
|
+
* Call process.exit, and _exitCallback if defined.
|
|
1612
|
+
*
|
|
1613
|
+
* @param {number} exitCode exit code for using with process.exit
|
|
1614
|
+
* @param {string} code an id string representing the error
|
|
1615
|
+
* @param {string} message human-readable description of the error
|
|
1616
|
+
* @return never
|
|
1617
|
+
* @private
|
|
1618
|
+
*/
|
|
1619
|
+
_exit(exitCode, code, message2) {
|
|
1620
|
+
if (this._exitCallback) {
|
|
1621
|
+
this._exitCallback(new CommanderError(exitCode, code, message2));
|
|
1622
|
+
}
|
|
1623
|
+
process2.exit(exitCode);
|
|
1624
|
+
}
|
|
1625
|
+
/**
|
|
1626
|
+
* Register callback `fn` for the command.
|
|
1627
|
+
*
|
|
1628
|
+
* @example
|
|
1629
|
+
* program
|
|
1630
|
+
* .command('serve')
|
|
1631
|
+
* .description('start service')
|
|
1632
|
+
* .action(function() {
|
|
1633
|
+
* // do work here
|
|
1634
|
+
* });
|
|
1635
|
+
*
|
|
1636
|
+
* @param {Function} fn
|
|
1637
|
+
* @return {Command} `this` command for chaining
|
|
1638
|
+
*/
|
|
1639
|
+
action(fn) {
|
|
1640
|
+
const listener = (args) => {
|
|
1641
|
+
const expectedArgsCount = this.registeredArguments.length;
|
|
1642
|
+
const actionArgs = args.slice(0, expectedArgsCount);
|
|
1643
|
+
if (this._storeOptionsAsProperties) {
|
|
1644
|
+
actionArgs[expectedArgsCount] = this;
|
|
1645
|
+
} else {
|
|
1646
|
+
actionArgs[expectedArgsCount] = this.opts();
|
|
1647
|
+
}
|
|
1648
|
+
actionArgs.push(this);
|
|
1649
|
+
return fn.apply(this, actionArgs);
|
|
1650
|
+
};
|
|
1651
|
+
this._actionHandler = listener;
|
|
1652
|
+
return this;
|
|
1653
|
+
}
|
|
1654
|
+
/**
|
|
1655
|
+
* Factory routine to create a new unattached option.
|
|
1656
|
+
*
|
|
1657
|
+
* See .option() for creating an attached option, which uses this routine to
|
|
1658
|
+
* create the option. You can override createOption to return a custom option.
|
|
1659
|
+
*
|
|
1660
|
+
* @param {string} flags
|
|
1661
|
+
* @param {string} [description]
|
|
1662
|
+
* @return {Option} new option
|
|
1663
|
+
*/
|
|
1664
|
+
createOption(flags, description) {
|
|
1665
|
+
return new Option(flags, description);
|
|
1666
|
+
}
|
|
1667
|
+
/**
|
|
1668
|
+
* Wrap parseArgs to catch 'commander.invalidArgument'.
|
|
1669
|
+
*
|
|
1670
|
+
* @param {(Option | Argument)} target
|
|
1671
|
+
* @param {string} value
|
|
1672
|
+
* @param {*} previous
|
|
1673
|
+
* @param {string} invalidArgumentMessage
|
|
1674
|
+
* @private
|
|
1675
|
+
*/
|
|
1676
|
+
_callParseArg(target, value, previous, invalidArgumentMessage) {
|
|
1677
|
+
try {
|
|
1678
|
+
return target.parseArg(value, previous);
|
|
1679
|
+
} catch (err) {
|
|
1680
|
+
if (err.code === "commander.invalidArgument") {
|
|
1681
|
+
const message2 = `${invalidArgumentMessage} ${err.message}`;
|
|
1682
|
+
this.error(message2, { exitCode: err.exitCode, code: err.code });
|
|
1683
|
+
}
|
|
1684
|
+
throw err;
|
|
1685
|
+
}
|
|
1686
|
+
}
|
|
1687
|
+
/**
|
|
1688
|
+
* Check for option flag conflicts.
|
|
1689
|
+
* Register option if no conflicts found, or throw on conflict.
|
|
1690
|
+
*
|
|
1691
|
+
* @param {Option} option
|
|
1692
|
+
* @private
|
|
1693
|
+
*/
|
|
1694
|
+
_registerOption(option) {
|
|
1695
|
+
const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
|
|
1696
|
+
if (matchingOption) {
|
|
1697
|
+
const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
|
|
1698
|
+
throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
|
|
1699
|
+
- already used by option '${matchingOption.flags}'`);
|
|
1700
|
+
}
|
|
1701
|
+
this._initOptionGroup(option);
|
|
1702
|
+
this.options.push(option);
|
|
1703
|
+
}
|
|
1704
|
+
/**
|
|
1705
|
+
* Check for command name and alias conflicts with existing commands.
|
|
1706
|
+
* Register command if no conflicts found, or throw on conflict.
|
|
1707
|
+
*
|
|
1708
|
+
* @param {Command} command
|
|
1709
|
+
* @private
|
|
1710
|
+
*/
|
|
1711
|
+
_registerCommand(command) {
|
|
1712
|
+
const knownBy = (cmd) => {
|
|
1713
|
+
return [cmd.name()].concat(cmd.aliases());
|
|
1714
|
+
};
|
|
1715
|
+
const alreadyUsed = knownBy(command).find(
|
|
1716
|
+
(name) => this._findCommand(name)
|
|
1717
|
+
);
|
|
1718
|
+
if (alreadyUsed) {
|
|
1719
|
+
const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
|
|
1720
|
+
const newCmd = knownBy(command).join("|");
|
|
1721
|
+
throw new Error(
|
|
1722
|
+
`cannot add command '${newCmd}' as already have command '${existingCmd}'`
|
|
1723
|
+
);
|
|
1724
|
+
}
|
|
1725
|
+
this._initCommandGroup(command);
|
|
1726
|
+
this.commands.push(command);
|
|
1727
|
+
}
|
|
1728
|
+
/**
|
|
1729
|
+
* Add an option.
|
|
1730
|
+
*
|
|
1731
|
+
* @param {Option} option
|
|
1732
|
+
* @return {Command} `this` command for chaining
|
|
1733
|
+
*/
|
|
1734
|
+
addOption(option) {
|
|
1735
|
+
this._registerOption(option);
|
|
1736
|
+
const oname = option.name();
|
|
1737
|
+
const name = option.attributeName();
|
|
1738
|
+
if (option.defaultValue !== void 0) {
|
|
1739
|
+
this.setOptionValueWithSource(name, option.defaultValue, "default");
|
|
1740
|
+
}
|
|
1741
|
+
const handleOptionValue = (val, invalidValueMessage, valueSource) => {
|
|
1742
|
+
if (val == null && option.presetArg !== void 0) {
|
|
1743
|
+
val = option.presetArg;
|
|
1744
|
+
}
|
|
1745
|
+
const oldValue = this.getOptionValue(name);
|
|
1746
|
+
if (val !== null && option.parseArg) {
|
|
1747
|
+
val = this._callParseArg(option, val, oldValue, invalidValueMessage);
|
|
1748
|
+
} else if (val !== null && option.variadic) {
|
|
1749
|
+
val = option._collectValue(val, oldValue);
|
|
1750
|
+
}
|
|
1751
|
+
if (val == null) {
|
|
1752
|
+
if (option.negate) {
|
|
1753
|
+
val = false;
|
|
1754
|
+
} else if (option.isBoolean() || option.optional) {
|
|
1755
|
+
val = true;
|
|
1756
|
+
} else {
|
|
1757
|
+
val = "";
|
|
1758
|
+
}
|
|
1759
|
+
}
|
|
1760
|
+
this.setOptionValueWithSource(name, val, valueSource);
|
|
1761
|
+
};
|
|
1762
|
+
this.on("option:" + oname, (val) => {
|
|
1763
|
+
const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
|
|
1764
|
+
handleOptionValue(val, invalidValueMessage, "cli");
|
|
1765
|
+
});
|
|
1766
|
+
if (option.envVar) {
|
|
1767
|
+
this.on("optionEnv:" + oname, (val) => {
|
|
1768
|
+
const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
|
|
1769
|
+
handleOptionValue(val, invalidValueMessage, "env");
|
|
1770
|
+
});
|
|
1771
|
+
}
|
|
1772
|
+
return this;
|
|
1773
|
+
}
|
|
1774
|
+
/**
|
|
1775
|
+
* Internal implementation shared by .option() and .requiredOption()
|
|
1776
|
+
*
|
|
1777
|
+
* @return {Command} `this` command for chaining
|
|
1778
|
+
* @private
|
|
1779
|
+
*/
|
|
1780
|
+
_optionEx(config, flags, description, fn, defaultValue) {
|
|
1781
|
+
if (typeof flags === "object" && flags instanceof Option) {
|
|
1782
|
+
throw new Error(
|
|
1783
|
+
"To add an Option object use addOption() instead of option() or requiredOption()"
|
|
1784
|
+
);
|
|
1785
|
+
}
|
|
1786
|
+
const option = this.createOption(flags, description);
|
|
1787
|
+
option.makeOptionMandatory(!!config.mandatory);
|
|
1788
|
+
if (typeof fn === "function") {
|
|
1789
|
+
option.default(defaultValue).argParser(fn);
|
|
1790
|
+
} else if (fn instanceof RegExp) {
|
|
1791
|
+
const regex = fn;
|
|
1792
|
+
fn = (val, def) => {
|
|
1793
|
+
const m = regex.exec(val);
|
|
1794
|
+
return m ? m[0] : def;
|
|
1795
|
+
};
|
|
1796
|
+
option.default(defaultValue).argParser(fn);
|
|
1797
|
+
} else {
|
|
1798
|
+
option.default(fn);
|
|
1799
|
+
}
|
|
1800
|
+
return this.addOption(option);
|
|
1801
|
+
}
|
|
1802
|
+
/**
|
|
1803
|
+
* Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
|
|
1804
|
+
*
|
|
1805
|
+
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
|
|
1806
|
+
* option-argument is indicated by `<>` and an optional option-argument by `[]`.
|
|
1807
|
+
*
|
|
1808
|
+
* See the README for more details, and see also addOption() and requiredOption().
|
|
1809
|
+
*
|
|
1810
|
+
* @example
|
|
1811
|
+
* program
|
|
1812
|
+
* .option('-p, --pepper', 'add pepper')
|
|
1813
|
+
* .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
|
|
1814
|
+
* .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
|
|
1815
|
+
* .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
|
|
1816
|
+
*
|
|
1817
|
+
* @param {string} flags
|
|
1818
|
+
* @param {string} [description]
|
|
1819
|
+
* @param {(Function|*)} [parseArg] - custom option processing function or default value
|
|
1820
|
+
* @param {*} [defaultValue]
|
|
1821
|
+
* @return {Command} `this` command for chaining
|
|
1822
|
+
*/
|
|
1823
|
+
option(flags, description, parseArg, defaultValue) {
|
|
1824
|
+
return this._optionEx({}, flags, description, parseArg, defaultValue);
|
|
1825
|
+
}
|
|
1826
|
+
/**
|
|
1827
|
+
* Add a required option which must have a value after parsing. This usually means
|
|
1828
|
+
* the option must be specified on the command line. (Otherwise the same as .option().)
|
|
1829
|
+
*
|
|
1830
|
+
* The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
|
|
1831
|
+
*
|
|
1832
|
+
* @param {string} flags
|
|
1833
|
+
* @param {string} [description]
|
|
1834
|
+
* @param {(Function|*)} [parseArg] - custom option processing function or default value
|
|
1835
|
+
* @param {*} [defaultValue]
|
|
1836
|
+
* @return {Command} `this` command for chaining
|
|
1837
|
+
*/
|
|
1838
|
+
requiredOption(flags, description, parseArg, defaultValue) {
|
|
1839
|
+
return this._optionEx(
|
|
1840
|
+
{ mandatory: true },
|
|
1841
|
+
flags,
|
|
1842
|
+
description,
|
|
1843
|
+
parseArg,
|
|
1844
|
+
defaultValue
|
|
1845
|
+
);
|
|
1846
|
+
}
|
|
1847
|
+
/**
|
|
1848
|
+
* Alter parsing of short flags with optional values.
|
|
1849
|
+
*
|
|
1850
|
+
* @example
|
|
1851
|
+
* // for `.option('-f,--flag [value]'):
|
|
1852
|
+
* program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
|
|
1853
|
+
* program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
|
|
1854
|
+
*
|
|
1855
|
+
* @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
|
|
1856
|
+
* @return {Command} `this` command for chaining
|
|
1857
|
+
*/
|
|
1858
|
+
combineFlagAndOptionalValue(combine = true) {
|
|
1859
|
+
this._combineFlagAndOptionalValue = !!combine;
|
|
1860
|
+
return this;
|
|
1861
|
+
}
|
|
1862
|
+
/**
|
|
1863
|
+
* Allow unknown options on the command line.
|
|
1864
|
+
*
|
|
1865
|
+
* @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
|
|
1866
|
+
* @return {Command} `this` command for chaining
|
|
1867
|
+
*/
|
|
1868
|
+
allowUnknownOption(allowUnknown = true) {
|
|
1869
|
+
this._allowUnknownOption = !!allowUnknown;
|
|
1870
|
+
return this;
|
|
1871
|
+
}
|
|
1872
|
+
/**
|
|
1873
|
+
* Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
|
|
1874
|
+
*
|
|
1875
|
+
* @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
|
|
1876
|
+
* @return {Command} `this` command for chaining
|
|
1877
|
+
*/
|
|
1878
|
+
allowExcessArguments(allowExcess = true) {
|
|
1879
|
+
this._allowExcessArguments = !!allowExcess;
|
|
1880
|
+
return this;
|
|
1881
|
+
}
|
|
1882
|
+
/**
|
|
1883
|
+
* Enable positional options. Positional means global options are specified before subcommands which lets
|
|
1884
|
+
* subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
|
|
1885
|
+
* The default behaviour is non-positional and global options may appear anywhere on the command line.
|
|
1886
|
+
*
|
|
1887
|
+
* @param {boolean} [positional]
|
|
1888
|
+
* @return {Command} `this` command for chaining
|
|
1889
|
+
*/
|
|
1890
|
+
enablePositionalOptions(positional = true) {
|
|
1891
|
+
this._enablePositionalOptions = !!positional;
|
|
1892
|
+
return this;
|
|
1893
|
+
}
|
|
1894
|
+
/**
|
|
1895
|
+
* Pass through options that come after command-arguments rather than treat them as command-options,
|
|
1896
|
+
* so actual command-options come before command-arguments. Turning this on for a subcommand requires
|
|
1897
|
+
* positional options to have been enabled on the program (parent commands).
|
|
1898
|
+
* The default behaviour is non-positional and options may appear before or after command-arguments.
|
|
1899
|
+
*
|
|
1900
|
+
* @param {boolean} [passThrough] for unknown options.
|
|
1901
|
+
* @return {Command} `this` command for chaining
|
|
1902
|
+
*/
|
|
1903
|
+
passThroughOptions(passThrough = true) {
|
|
1904
|
+
this._passThroughOptions = !!passThrough;
|
|
1905
|
+
this._checkForBrokenPassThrough();
|
|
1906
|
+
return this;
|
|
1907
|
+
}
|
|
1908
|
+
/**
|
|
1909
|
+
* @private
|
|
1910
|
+
*/
|
|
1911
|
+
_checkForBrokenPassThrough() {
|
|
1912
|
+
if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
|
|
1913
|
+
throw new Error(
|
|
1914
|
+
`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
|
|
1915
|
+
);
|
|
1916
|
+
}
|
|
1917
|
+
}
|
|
1918
|
+
/**
|
|
1919
|
+
* Whether to store option values as properties on command object,
|
|
1920
|
+
* or store separately (specify false). In both cases the option values can be accessed using .opts().
|
|
1921
|
+
*
|
|
1922
|
+
* @param {boolean} [storeAsProperties=true]
|
|
1923
|
+
* @return {Command} `this` command for chaining
|
|
1924
|
+
*/
|
|
1925
|
+
storeOptionsAsProperties(storeAsProperties = true) {
|
|
1926
|
+
if (this.options.length) {
|
|
1927
|
+
throw new Error("call .storeOptionsAsProperties() before adding options");
|
|
1928
|
+
}
|
|
1929
|
+
if (Object.keys(this._optionValues).length) {
|
|
1930
|
+
throw new Error(
|
|
1931
|
+
"call .storeOptionsAsProperties() before setting option values"
|
|
1932
|
+
);
|
|
1933
|
+
}
|
|
1934
|
+
this._storeOptionsAsProperties = !!storeAsProperties;
|
|
1935
|
+
return this;
|
|
1936
|
+
}
|
|
1937
|
+
/**
|
|
1938
|
+
* Retrieve option value.
|
|
1939
|
+
*
|
|
1940
|
+
* @param {string} key
|
|
1941
|
+
* @return {object} value
|
|
1942
|
+
*/
|
|
1943
|
+
getOptionValue(key) {
|
|
1944
|
+
if (this._storeOptionsAsProperties) {
|
|
1945
|
+
return this[key];
|
|
1946
|
+
}
|
|
1947
|
+
return this._optionValues[key];
|
|
1948
|
+
}
|
|
1949
|
+
/**
|
|
1950
|
+
* Store option value.
|
|
1951
|
+
*
|
|
1952
|
+
* @param {string} key
|
|
1953
|
+
* @param {object} value
|
|
1954
|
+
* @return {Command} `this` command for chaining
|
|
1955
|
+
*/
|
|
1956
|
+
setOptionValue(key, value) {
|
|
1957
|
+
return this.setOptionValueWithSource(key, value, void 0);
|
|
1958
|
+
}
|
|
1959
|
+
/**
|
|
1960
|
+
* Store option value and where the value came from.
|
|
1961
|
+
*
|
|
1962
|
+
* @param {string} key
|
|
1963
|
+
* @param {object} value
|
|
1964
|
+
* @param {string} source - expected values are default/config/env/cli/implied
|
|
1965
|
+
* @return {Command} `this` command for chaining
|
|
1966
|
+
*/
|
|
1967
|
+
setOptionValueWithSource(key, value, source) {
|
|
1968
|
+
if (this._storeOptionsAsProperties) {
|
|
1969
|
+
this[key] = value;
|
|
1970
|
+
} else {
|
|
1971
|
+
this._optionValues[key] = value;
|
|
1972
|
+
}
|
|
1973
|
+
this._optionValueSources[key] = source;
|
|
1974
|
+
return this;
|
|
1975
|
+
}
|
|
1976
|
+
/**
|
|
1977
|
+
* Get source of option value.
|
|
1978
|
+
* Expected values are default | config | env | cli | implied
|
|
1979
|
+
*
|
|
1980
|
+
* @param {string} key
|
|
1981
|
+
* @return {string}
|
|
1982
|
+
*/
|
|
1983
|
+
getOptionValueSource(key) {
|
|
1984
|
+
return this._optionValueSources[key];
|
|
1985
|
+
}
|
|
1986
|
+
/**
|
|
1987
|
+
* Get source of option value. See also .optsWithGlobals().
|
|
1988
|
+
* Expected values are default | config | env | cli | implied
|
|
1989
|
+
*
|
|
1990
|
+
* @param {string} key
|
|
1991
|
+
* @return {string}
|
|
1992
|
+
*/
|
|
1993
|
+
getOptionValueSourceWithGlobals(key) {
|
|
1994
|
+
let source;
|
|
1995
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
1996
|
+
if (cmd.getOptionValueSource(key) !== void 0) {
|
|
1997
|
+
source = cmd.getOptionValueSource(key);
|
|
1998
|
+
}
|
|
1999
|
+
});
|
|
2000
|
+
return source;
|
|
2001
|
+
}
|
|
2002
|
+
/**
|
|
2003
|
+
* Get user arguments from implied or explicit arguments.
|
|
2004
|
+
* Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
|
|
2005
|
+
*
|
|
2006
|
+
* @private
|
|
2007
|
+
*/
|
|
2008
|
+
_prepareUserArgs(argv, parseOptions) {
|
|
2009
|
+
if (argv !== void 0 && !Array.isArray(argv)) {
|
|
2010
|
+
throw new Error("first parameter to parse must be array or undefined");
|
|
2011
|
+
}
|
|
2012
|
+
parseOptions = parseOptions || {};
|
|
2013
|
+
if (argv === void 0 && parseOptions.from === void 0) {
|
|
2014
|
+
if (process2.versions?.electron) {
|
|
2015
|
+
parseOptions.from = "electron";
|
|
2016
|
+
}
|
|
2017
|
+
const execArgv = process2.execArgv ?? [];
|
|
2018
|
+
if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
|
|
2019
|
+
parseOptions.from = "eval";
|
|
2020
|
+
}
|
|
2021
|
+
}
|
|
2022
|
+
if (argv === void 0) {
|
|
2023
|
+
argv = process2.argv;
|
|
2024
|
+
}
|
|
2025
|
+
this.rawArgs = argv.slice();
|
|
2026
|
+
let userArgs;
|
|
2027
|
+
switch (parseOptions.from) {
|
|
2028
|
+
case void 0:
|
|
2029
|
+
case "node":
|
|
2030
|
+
this._scriptPath = argv[1];
|
|
2031
|
+
userArgs = argv.slice(2);
|
|
2032
|
+
break;
|
|
2033
|
+
case "electron":
|
|
2034
|
+
if (process2.defaultApp) {
|
|
2035
|
+
this._scriptPath = argv[1];
|
|
2036
|
+
userArgs = argv.slice(2);
|
|
2037
|
+
} else {
|
|
2038
|
+
userArgs = argv.slice(1);
|
|
2039
|
+
}
|
|
2040
|
+
break;
|
|
2041
|
+
case "user":
|
|
2042
|
+
userArgs = argv.slice(0);
|
|
2043
|
+
break;
|
|
2044
|
+
case "eval":
|
|
2045
|
+
userArgs = argv.slice(1);
|
|
2046
|
+
break;
|
|
2047
|
+
default:
|
|
2048
|
+
throw new Error(
|
|
2049
|
+
`unexpected parse option { from: '${parseOptions.from}' }`
|
|
2050
|
+
);
|
|
2051
|
+
}
|
|
2052
|
+
if (!this._name && this._scriptPath)
|
|
2053
|
+
this.nameFromFilename(this._scriptPath);
|
|
2054
|
+
this._name = this._name || "program";
|
|
2055
|
+
return userArgs;
|
|
2056
|
+
}
|
|
2057
|
+
/**
|
|
2058
|
+
* Parse `argv`, setting options and invoking commands when defined.
|
|
2059
|
+
*
|
|
2060
|
+
* Use parseAsync instead of parse if any of your action handlers are async.
|
|
2061
|
+
*
|
|
2062
|
+
* Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
|
|
2063
|
+
*
|
|
2064
|
+
* Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
|
|
2065
|
+
* - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
|
|
2066
|
+
* - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
|
|
2067
|
+
* - `'user'`: just user arguments
|
|
2068
|
+
*
|
|
2069
|
+
* @example
|
|
2070
|
+
* program.parse(); // parse process.argv and auto-detect electron and special node flags
|
|
2071
|
+
* program.parse(process.argv); // assume argv[0] is app and argv[1] is script
|
|
2072
|
+
* program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
|
|
2073
|
+
*
|
|
2074
|
+
* @param {string[]} [argv] - optional, defaults to process.argv
|
|
2075
|
+
* @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
|
|
2076
|
+
* @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
|
|
2077
|
+
* @return {Command} `this` command for chaining
|
|
2078
|
+
*/
|
|
2079
|
+
parse(argv, parseOptions) {
|
|
2080
|
+
this._prepareForParse();
|
|
2081
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
2082
|
+
this._parseCommand([], userArgs);
|
|
2083
|
+
return this;
|
|
2084
|
+
}
|
|
2085
|
+
/**
|
|
2086
|
+
* Parse `argv`, setting options and invoking commands when defined.
|
|
2087
|
+
*
|
|
2088
|
+
* Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
|
|
2089
|
+
*
|
|
2090
|
+
* Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
|
|
2091
|
+
* - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
|
|
2092
|
+
* - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
|
|
2093
|
+
* - `'user'`: just user arguments
|
|
2094
|
+
*
|
|
2095
|
+
* @example
|
|
2096
|
+
* await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
|
|
2097
|
+
* await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
|
|
2098
|
+
* await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
|
|
2099
|
+
*
|
|
2100
|
+
* @param {string[]} [argv]
|
|
2101
|
+
* @param {object} [parseOptions]
|
|
2102
|
+
* @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
|
|
2103
|
+
* @return {Promise}
|
|
2104
|
+
*/
|
|
2105
|
+
async parseAsync(argv, parseOptions) {
|
|
2106
|
+
this._prepareForParse();
|
|
2107
|
+
const userArgs = this._prepareUserArgs(argv, parseOptions);
|
|
2108
|
+
await this._parseCommand([], userArgs);
|
|
2109
|
+
return this;
|
|
2110
|
+
}
|
|
2111
|
+
_prepareForParse() {
|
|
2112
|
+
if (this._savedState === null) {
|
|
2113
|
+
this.options.filter(
|
|
2114
|
+
(option) => option.negate && option.defaultValue === void 0 && this.getOptionValue(option.attributeName()) === void 0
|
|
2115
|
+
).forEach((option) => {
|
|
2116
|
+
const positiveLongFlag = option.long.replace(/^--no-/, "--");
|
|
2117
|
+
if (!this._findOption(positiveLongFlag)) {
|
|
2118
|
+
this.setOptionValueWithSource(
|
|
2119
|
+
option.attributeName(),
|
|
2120
|
+
true,
|
|
2121
|
+
"default"
|
|
2122
|
+
);
|
|
2123
|
+
}
|
|
2124
|
+
});
|
|
2125
|
+
this.saveStateBeforeParse();
|
|
2126
|
+
} else {
|
|
2127
|
+
this.restoreStateBeforeParse();
|
|
2128
|
+
}
|
|
2129
|
+
}
|
|
2130
|
+
/**
|
|
2131
|
+
* Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
|
|
2132
|
+
* Not usually called directly, but available for subclasses to save their custom state.
|
|
2133
|
+
*
|
|
2134
|
+
* This is called in a lazy way. Only commands used in parsing chain will have state saved.
|
|
2135
|
+
*/
|
|
2136
|
+
saveStateBeforeParse() {
|
|
2137
|
+
this._savedState = {
|
|
2138
|
+
// name is stable if supplied by author, but may be unspecified for root command and deduced during parsing
|
|
2139
|
+
_name: this._name,
|
|
2140
|
+
// option values before parse have default values (including false for negated options)
|
|
2141
|
+
// shallow clones
|
|
2142
|
+
_optionValues: { ...this._optionValues },
|
|
2143
|
+
_optionValueSources: { ...this._optionValueSources }
|
|
2144
|
+
};
|
|
2145
|
+
}
|
|
2146
|
+
/**
|
|
2147
|
+
* Restore state before parse for calls after the first.
|
|
2148
|
+
* Not usually called directly, but available for subclasses to save their custom state.
|
|
2149
|
+
*
|
|
2150
|
+
* This is called in a lazy way. Only commands used in parsing chain will have state restored.
|
|
2151
|
+
*/
|
|
2152
|
+
restoreStateBeforeParse() {
|
|
2153
|
+
if (this._storeOptionsAsProperties)
|
|
2154
|
+
throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
|
|
2155
|
+
- either make a new Command for each call to parse, or stop storing options as properties`);
|
|
2156
|
+
this._name = this._savedState._name;
|
|
2157
|
+
this._scriptPath = null;
|
|
2158
|
+
this.rawArgs = [];
|
|
2159
|
+
this._optionValues = { ...this._savedState._optionValues };
|
|
2160
|
+
this._optionValueSources = { ...this._savedState._optionValueSources };
|
|
2161
|
+
this.args = [];
|
|
2162
|
+
this.processedArgs = [];
|
|
2163
|
+
}
|
|
2164
|
+
/**
|
|
2165
|
+
* Throw if expected executable is missing. Add lots of help for author.
|
|
2166
|
+
*
|
|
2167
|
+
* @param {string} executableFile
|
|
2168
|
+
* @param {string} executableDir
|
|
2169
|
+
* @param {string} subcommandName
|
|
2170
|
+
*/
|
|
2171
|
+
_checkForMissingExecutable(executableFile, executableDir, subcommandName) {
|
|
2172
|
+
if (fs.existsSync(executableFile)) return;
|
|
2173
|
+
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";
|
|
2174
|
+
const executableMissing = `'${executableFile}' does not exist
|
|
2175
|
+
- if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
|
|
2176
|
+
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
|
|
2177
|
+
- ${executableDirMessage}`;
|
|
2178
|
+
throw new Error(executableMissing);
|
|
2179
|
+
}
|
|
2180
|
+
/**
|
|
2181
|
+
* Execute a sub-command executable.
|
|
2182
|
+
*
|
|
2183
|
+
* @private
|
|
2184
|
+
*/
|
|
2185
|
+
_executeSubCommand(subcommand, args) {
|
|
2186
|
+
args = args.slice();
|
|
2187
|
+
const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
|
|
2188
|
+
function findFile(baseDir, baseName) {
|
|
2189
|
+
const localBin = path.resolve(baseDir, baseName);
|
|
2190
|
+
if (fs.existsSync(localBin)) return localBin;
|
|
2191
|
+
if (sourceExt.includes(path.extname(baseName))) return void 0;
|
|
2192
|
+
const foundExt = sourceExt.find(
|
|
2193
|
+
(ext) => fs.existsSync(`${localBin}${ext}`)
|
|
2194
|
+
);
|
|
2195
|
+
if (foundExt) return `${localBin}${foundExt}`;
|
|
2196
|
+
return void 0;
|
|
2197
|
+
}
|
|
2198
|
+
this._checkForMissingMandatoryOptions();
|
|
2199
|
+
this._checkForConflictingOptions();
|
|
2200
|
+
let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
|
|
2201
|
+
let executableDir = this._executableDir || "";
|
|
2202
|
+
if (this._scriptPath) {
|
|
2203
|
+
let resolvedScriptPath;
|
|
2204
|
+
try {
|
|
2205
|
+
resolvedScriptPath = fs.realpathSync(this._scriptPath);
|
|
2206
|
+
} catch {
|
|
2207
|
+
resolvedScriptPath = this._scriptPath;
|
|
2208
|
+
}
|
|
2209
|
+
executableDir = path.resolve(
|
|
2210
|
+
path.dirname(resolvedScriptPath),
|
|
2211
|
+
executableDir
|
|
2212
|
+
);
|
|
2213
|
+
}
|
|
2214
|
+
if (executableDir) {
|
|
2215
|
+
let localFile = findFile(executableDir, executableFile);
|
|
2216
|
+
if (!localFile && !subcommand._executableFile && this._scriptPath) {
|
|
2217
|
+
const legacyName = path.basename(
|
|
2218
|
+
this._scriptPath,
|
|
2219
|
+
path.extname(this._scriptPath)
|
|
2220
|
+
);
|
|
2221
|
+
if (legacyName !== this._name) {
|
|
2222
|
+
localFile = findFile(
|
|
2223
|
+
executableDir,
|
|
2224
|
+
`${legacyName}-${subcommand._name}`
|
|
2225
|
+
);
|
|
2226
|
+
}
|
|
2227
|
+
}
|
|
2228
|
+
executableFile = localFile || executableFile;
|
|
2229
|
+
}
|
|
2230
|
+
const launchWithNode = sourceExt.includes(path.extname(executableFile));
|
|
2231
|
+
let proc;
|
|
2232
|
+
if (process2.platform !== "win32") {
|
|
2233
|
+
if (launchWithNode) {
|
|
2234
|
+
args.unshift(executableFile);
|
|
2235
|
+
args = incrementNodeInspectorPort(process2.execArgv).concat(args);
|
|
2236
|
+
proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
|
|
2237
|
+
} else {
|
|
2238
|
+
proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
|
|
2239
|
+
}
|
|
2240
|
+
} else {
|
|
2241
|
+
this._checkForMissingExecutable(
|
|
2242
|
+
executableFile,
|
|
2243
|
+
executableDir,
|
|
2244
|
+
subcommand._name
|
|
2245
|
+
);
|
|
2246
|
+
args.unshift(executableFile);
|
|
2247
|
+
args = incrementNodeInspectorPort(process2.execArgv).concat(args);
|
|
2248
|
+
proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
|
|
2249
|
+
}
|
|
2250
|
+
if (!proc.killed) {
|
|
2251
|
+
const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
|
|
2252
|
+
signals.forEach((signal) => {
|
|
2253
|
+
process2.on(signal, () => {
|
|
2254
|
+
if (proc.killed === false && proc.exitCode === null) {
|
|
2255
|
+
proc.kill(signal);
|
|
2256
|
+
}
|
|
2257
|
+
});
|
|
2258
|
+
});
|
|
2259
|
+
}
|
|
2260
|
+
const exitCallback = this._exitCallback;
|
|
2261
|
+
proc.on("close", (code) => {
|
|
2262
|
+
code = code ?? 1;
|
|
2263
|
+
if (!exitCallback) {
|
|
2264
|
+
process2.exit(code);
|
|
2265
|
+
} else {
|
|
2266
|
+
exitCallback(
|
|
2267
|
+
new CommanderError(
|
|
2268
|
+
code,
|
|
2269
|
+
"commander.executeSubCommandAsync",
|
|
2270
|
+
"(close)"
|
|
2271
|
+
)
|
|
2272
|
+
);
|
|
2273
|
+
}
|
|
2274
|
+
});
|
|
2275
|
+
proc.on("error", (err) => {
|
|
2276
|
+
if (err.code === "ENOENT") {
|
|
2277
|
+
this._checkForMissingExecutable(
|
|
2278
|
+
executableFile,
|
|
2279
|
+
executableDir,
|
|
2280
|
+
subcommand._name
|
|
2281
|
+
);
|
|
2282
|
+
} else if (err.code === "EACCES") {
|
|
2283
|
+
throw new Error(`'${executableFile}' not executable`);
|
|
2284
|
+
}
|
|
2285
|
+
if (!exitCallback) {
|
|
2286
|
+
process2.exit(1);
|
|
2287
|
+
} else {
|
|
2288
|
+
const wrappedError = new CommanderError(
|
|
2289
|
+
1,
|
|
2290
|
+
"commander.executeSubCommandAsync",
|
|
2291
|
+
"(error)"
|
|
2292
|
+
);
|
|
2293
|
+
wrappedError.nestedError = err;
|
|
2294
|
+
exitCallback(wrappedError);
|
|
2295
|
+
}
|
|
2296
|
+
});
|
|
2297
|
+
this.runningCommand = proc;
|
|
2298
|
+
}
|
|
2299
|
+
/**
|
|
2300
|
+
* @private
|
|
2301
|
+
*/
|
|
2302
|
+
_dispatchSubcommand(commandName, operands, unknown) {
|
|
2303
|
+
const subCommand = this._findCommand(commandName);
|
|
2304
|
+
if (!subCommand) this.help({ error: true });
|
|
2305
|
+
subCommand._prepareForParse();
|
|
2306
|
+
let promiseChain;
|
|
2307
|
+
promiseChain = this._chainOrCallSubCommandHook(
|
|
2308
|
+
promiseChain,
|
|
2309
|
+
subCommand,
|
|
2310
|
+
"preSubcommand"
|
|
2311
|
+
);
|
|
2312
|
+
promiseChain = this._chainOrCall(promiseChain, () => {
|
|
2313
|
+
if (subCommand._executableHandler) {
|
|
2314
|
+
this._executeSubCommand(subCommand, operands.concat(unknown));
|
|
2315
|
+
} else {
|
|
2316
|
+
return subCommand._parseCommand(operands, unknown);
|
|
2317
|
+
}
|
|
2318
|
+
});
|
|
2319
|
+
return promiseChain;
|
|
2320
|
+
}
|
|
2321
|
+
/**
|
|
2322
|
+
* Invoke help directly if possible, or dispatch if necessary.
|
|
2323
|
+
* e.g. help foo
|
|
2324
|
+
*
|
|
2325
|
+
* @private
|
|
2326
|
+
*/
|
|
2327
|
+
_dispatchHelpCommand(subcommandName) {
|
|
2328
|
+
if (!subcommandName) {
|
|
2329
|
+
this.help();
|
|
2330
|
+
}
|
|
2331
|
+
const subCommand = this._findCommand(subcommandName);
|
|
2332
|
+
if (subCommand && !subCommand._executableHandler) {
|
|
2333
|
+
subCommand.help();
|
|
2334
|
+
}
|
|
2335
|
+
return this._dispatchSubcommand(
|
|
2336
|
+
subcommandName,
|
|
2337
|
+
[],
|
|
2338
|
+
[this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
|
|
2339
|
+
);
|
|
2340
|
+
}
|
|
2341
|
+
/**
|
|
2342
|
+
* Check this.args against expected this.registeredArguments.
|
|
2343
|
+
*
|
|
2344
|
+
* @private
|
|
2345
|
+
*/
|
|
2346
|
+
_checkNumberOfArguments() {
|
|
2347
|
+
this.registeredArguments.forEach((arg, i) => {
|
|
2348
|
+
if (arg.required && this.args[i] == null) {
|
|
2349
|
+
this.missingArgument(arg.name());
|
|
2350
|
+
}
|
|
2351
|
+
});
|
|
2352
|
+
if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
|
|
2353
|
+
return;
|
|
2354
|
+
}
|
|
2355
|
+
if (this.args.length > this.registeredArguments.length) {
|
|
2356
|
+
this._excessArguments(this.args);
|
|
2357
|
+
}
|
|
2358
|
+
}
|
|
2359
|
+
/**
|
|
2360
|
+
* Process this.args using this.registeredArguments and save as this.processedArgs!
|
|
2361
|
+
*
|
|
2362
|
+
* @private
|
|
2363
|
+
*/
|
|
2364
|
+
_processArguments() {
|
|
2365
|
+
const myParseArg = (argument, value, previous) => {
|
|
2366
|
+
let parsedValue = value;
|
|
2367
|
+
if (value !== null && argument.parseArg) {
|
|
2368
|
+
const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
|
|
2369
|
+
parsedValue = this._callParseArg(
|
|
2370
|
+
argument,
|
|
2371
|
+
value,
|
|
2372
|
+
previous,
|
|
2373
|
+
invalidValueMessage
|
|
2374
|
+
);
|
|
2375
|
+
}
|
|
2376
|
+
return parsedValue;
|
|
2377
|
+
};
|
|
2378
|
+
this._checkNumberOfArguments();
|
|
2379
|
+
const processedArgs = [];
|
|
2380
|
+
this.registeredArguments.forEach((declaredArg, index) => {
|
|
2381
|
+
let value = declaredArg.defaultValue;
|
|
2382
|
+
if (declaredArg.variadic) {
|
|
2383
|
+
if (index < this.args.length) {
|
|
2384
|
+
value = this.args.slice(index);
|
|
2385
|
+
if (declaredArg.parseArg) {
|
|
2386
|
+
value = value.reduce((processed, v) => {
|
|
2387
|
+
return myParseArg(declaredArg, v, processed);
|
|
2388
|
+
}, declaredArg.defaultValue);
|
|
2389
|
+
}
|
|
2390
|
+
} else if (value === void 0) {
|
|
2391
|
+
value = [];
|
|
2392
|
+
}
|
|
2393
|
+
} else if (index < this.args.length) {
|
|
2394
|
+
value = this.args[index];
|
|
2395
|
+
if (declaredArg.parseArg) {
|
|
2396
|
+
value = myParseArg(declaredArg, value, declaredArg.defaultValue);
|
|
2397
|
+
}
|
|
2398
|
+
}
|
|
2399
|
+
processedArgs[index] = value;
|
|
2400
|
+
});
|
|
2401
|
+
this.processedArgs = processedArgs;
|
|
2402
|
+
}
|
|
2403
|
+
/**
|
|
2404
|
+
* Once we have a promise we chain, but call synchronously until then.
|
|
2405
|
+
*
|
|
2406
|
+
* @param {(Promise|undefined)} promise
|
|
2407
|
+
* @param {Function} fn
|
|
2408
|
+
* @return {(Promise|undefined)}
|
|
2409
|
+
* @private
|
|
2410
|
+
*/
|
|
2411
|
+
_chainOrCall(promise, fn) {
|
|
2412
|
+
if (promise?.then && typeof promise.then === "function") {
|
|
2413
|
+
return promise.then(() => fn());
|
|
2414
|
+
}
|
|
2415
|
+
return fn();
|
|
2416
|
+
}
|
|
2417
|
+
/**
|
|
2418
|
+
*
|
|
2419
|
+
* @param {(Promise|undefined)} promise
|
|
2420
|
+
* @param {string} event
|
|
2421
|
+
* @return {(Promise|undefined)}
|
|
2422
|
+
* @private
|
|
2423
|
+
*/
|
|
2424
|
+
_chainOrCallHooks(promise, event) {
|
|
2425
|
+
let result = promise;
|
|
2426
|
+
const hooks = [];
|
|
2427
|
+
this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
|
|
2428
|
+
hookedCommand._lifeCycleHooks[event].forEach((callback) => {
|
|
2429
|
+
hooks.push({ hookedCommand, callback });
|
|
2430
|
+
});
|
|
2431
|
+
});
|
|
2432
|
+
if (event === "postAction") {
|
|
2433
|
+
hooks.reverse();
|
|
2434
|
+
}
|
|
2435
|
+
hooks.forEach((hookDetail) => {
|
|
2436
|
+
result = this._chainOrCall(result, () => {
|
|
2437
|
+
return hookDetail.callback(hookDetail.hookedCommand, this);
|
|
2438
|
+
});
|
|
2439
|
+
});
|
|
2440
|
+
return result;
|
|
2441
|
+
}
|
|
2442
|
+
/**
|
|
2443
|
+
*
|
|
2444
|
+
* @param {(Promise|undefined)} promise
|
|
2445
|
+
* @param {Command} subCommand
|
|
2446
|
+
* @param {string} event
|
|
2447
|
+
* @return {(Promise|undefined)}
|
|
2448
|
+
* @private
|
|
2449
|
+
*/
|
|
2450
|
+
_chainOrCallSubCommandHook(promise, subCommand, event) {
|
|
2451
|
+
let result = promise;
|
|
2452
|
+
if (this._lifeCycleHooks[event] !== void 0) {
|
|
2453
|
+
this._lifeCycleHooks[event].forEach((hook) => {
|
|
2454
|
+
result = this._chainOrCall(result, () => {
|
|
2455
|
+
return hook(this, subCommand);
|
|
2456
|
+
});
|
|
2457
|
+
});
|
|
2458
|
+
}
|
|
2459
|
+
return result;
|
|
2460
|
+
}
|
|
2461
|
+
/**
|
|
2462
|
+
* Process arguments in context of this command.
|
|
2463
|
+
* Returns action result, in case it is a promise.
|
|
2464
|
+
*
|
|
2465
|
+
* @private
|
|
2466
|
+
*/
|
|
2467
|
+
_parseCommand(operands, unknown) {
|
|
2468
|
+
const parsed = this.parseOptions(unknown);
|
|
2469
|
+
this._parseOptionsEnv();
|
|
2470
|
+
this._parseOptionsImplied();
|
|
2471
|
+
operands = operands.concat(parsed.operands);
|
|
2472
|
+
unknown = parsed.unknown;
|
|
2473
|
+
this.args = operands.concat(unknown);
|
|
2474
|
+
if (operands && this._findCommand(operands[0])) {
|
|
2475
|
+
return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
|
|
2476
|
+
}
|
|
2477
|
+
if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
|
|
2478
|
+
return this._dispatchHelpCommand(operands[1]);
|
|
2479
|
+
}
|
|
2480
|
+
if (this._defaultCommandName) {
|
|
2481
|
+
this._outputHelpIfRequested(unknown);
|
|
2482
|
+
return this._dispatchSubcommand(
|
|
2483
|
+
this._defaultCommandName,
|
|
2484
|
+
operands,
|
|
2485
|
+
unknown
|
|
2486
|
+
);
|
|
2487
|
+
}
|
|
2488
|
+
if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
|
|
2489
|
+
this.help({ error: true });
|
|
2490
|
+
}
|
|
2491
|
+
this._outputHelpIfRequested(parsed.unknown);
|
|
2492
|
+
this._checkForMissingMandatoryOptions();
|
|
2493
|
+
this._checkForConflictingOptions();
|
|
2494
|
+
const checkForUnknownOptions = () => {
|
|
2495
|
+
if (parsed.unknown.length > 0) {
|
|
2496
|
+
this.unknownOption(parsed.unknown[0]);
|
|
2497
|
+
}
|
|
2498
|
+
};
|
|
2499
|
+
const commandEvent = `command:${this.name()}`;
|
|
2500
|
+
if (this._actionHandler) {
|
|
2501
|
+
checkForUnknownOptions();
|
|
2502
|
+
this._processArguments();
|
|
2503
|
+
let promiseChain;
|
|
2504
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
|
|
2505
|
+
promiseChain = this._chainOrCall(
|
|
2506
|
+
promiseChain,
|
|
2507
|
+
() => this._actionHandler(this.processedArgs)
|
|
2508
|
+
);
|
|
2509
|
+
if (this.parent) {
|
|
2510
|
+
promiseChain = this._chainOrCall(promiseChain, () => {
|
|
2511
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
2512
|
+
});
|
|
2513
|
+
}
|
|
2514
|
+
promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
|
|
2515
|
+
return promiseChain;
|
|
2516
|
+
}
|
|
2517
|
+
if (this.parent?.listenerCount(commandEvent)) {
|
|
2518
|
+
checkForUnknownOptions();
|
|
2519
|
+
this._processArguments();
|
|
2520
|
+
this.parent.emit(commandEvent, operands, unknown);
|
|
2521
|
+
} else if (operands.length) {
|
|
2522
|
+
if (this._findCommand("*")) {
|
|
2523
|
+
return this._dispatchSubcommand("*", operands, unknown);
|
|
2524
|
+
}
|
|
2525
|
+
if (this.listenerCount("command:*")) {
|
|
2526
|
+
this.emit("command:*", operands, unknown);
|
|
2527
|
+
} else if (this.commands.length) {
|
|
2528
|
+
this.unknownCommand();
|
|
2529
|
+
} else {
|
|
2530
|
+
checkForUnknownOptions();
|
|
2531
|
+
this._processArguments();
|
|
2532
|
+
}
|
|
2533
|
+
} else if (this.commands.length) {
|
|
2534
|
+
checkForUnknownOptions();
|
|
2535
|
+
this.help({ error: true });
|
|
2536
|
+
} else {
|
|
2537
|
+
checkForUnknownOptions();
|
|
2538
|
+
this._processArguments();
|
|
2539
|
+
}
|
|
2540
|
+
}
|
|
2541
|
+
/**
|
|
2542
|
+
* Find matching command.
|
|
2543
|
+
*
|
|
2544
|
+
* @private
|
|
2545
|
+
* @return {Command | undefined}
|
|
2546
|
+
*/
|
|
2547
|
+
_findCommand(name) {
|
|
2548
|
+
if (!name) return void 0;
|
|
2549
|
+
return this.commands.find(
|
|
2550
|
+
(cmd) => cmd._name === name || cmd._aliases.includes(name)
|
|
2551
|
+
);
|
|
2552
|
+
}
|
|
2553
|
+
/**
|
|
2554
|
+
* Return an option matching `arg` if any.
|
|
2555
|
+
*
|
|
2556
|
+
* @param {string} arg
|
|
2557
|
+
* @return {Option}
|
|
2558
|
+
* @package
|
|
2559
|
+
*/
|
|
2560
|
+
_findOption(arg) {
|
|
2561
|
+
return this.options.find((option) => option.is(arg));
|
|
2562
|
+
}
|
|
2563
|
+
/**
|
|
2564
|
+
* Display an error message if a mandatory option does not have a value.
|
|
2565
|
+
* Called after checking for help flags in leaf subcommand.
|
|
2566
|
+
*
|
|
2567
|
+
* @private
|
|
2568
|
+
*/
|
|
2569
|
+
_checkForMissingMandatoryOptions() {
|
|
2570
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
2571
|
+
cmd.options.forEach((anOption) => {
|
|
2572
|
+
if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
|
|
2573
|
+
cmd.missingMandatoryOptionValue(anOption);
|
|
2574
|
+
}
|
|
2575
|
+
});
|
|
2576
|
+
});
|
|
2577
|
+
}
|
|
2578
|
+
/**
|
|
2579
|
+
* Display an error message if conflicting options are used together in this.
|
|
2580
|
+
*
|
|
2581
|
+
* @private
|
|
2582
|
+
*/
|
|
2583
|
+
_checkForConflictingLocalOptions() {
|
|
2584
|
+
const definedNonDefaultOptions = this.options.filter((option) => {
|
|
2585
|
+
const optionKey = option.attributeName();
|
|
2586
|
+
if (this.getOptionValue(optionKey) === void 0) {
|
|
2587
|
+
return false;
|
|
2588
|
+
}
|
|
2589
|
+
return this.getOptionValueSource(optionKey) !== "default";
|
|
2590
|
+
});
|
|
2591
|
+
const optionsWithConflicting = definedNonDefaultOptions.filter(
|
|
2592
|
+
(option) => option.conflictsWith.length > 0
|
|
2593
|
+
);
|
|
2594
|
+
optionsWithConflicting.forEach((option) => {
|
|
2595
|
+
const conflictingAndDefined = definedNonDefaultOptions.find(
|
|
2596
|
+
(defined) => option.conflictsWith.includes(defined.attributeName())
|
|
2597
|
+
);
|
|
2598
|
+
if (conflictingAndDefined) {
|
|
2599
|
+
this._conflictingOption(option, conflictingAndDefined);
|
|
2600
|
+
}
|
|
2601
|
+
});
|
|
2602
|
+
}
|
|
2603
|
+
/**
|
|
2604
|
+
* Display an error message if conflicting options are used together.
|
|
2605
|
+
* Called after checking for help flags in leaf subcommand.
|
|
2606
|
+
*
|
|
2607
|
+
* @private
|
|
2608
|
+
*/
|
|
2609
|
+
_checkForConflictingOptions() {
|
|
2610
|
+
this._getCommandAndAncestors().forEach((cmd) => {
|
|
2611
|
+
cmd._checkForConflictingLocalOptions();
|
|
2612
|
+
});
|
|
2613
|
+
}
|
|
2614
|
+
/**
|
|
2615
|
+
* Parse options from `argv` removing known options,
|
|
2616
|
+
* and return argv split into operands and unknown arguments.
|
|
2617
|
+
*
|
|
2618
|
+
* Side effects: modifies command by storing options. Does not reset state if called again.
|
|
2619
|
+
*
|
|
2620
|
+
* Examples:
|
|
2621
|
+
*
|
|
2622
|
+
* argv => operands, unknown
|
|
2623
|
+
* --known kkk op => [op], []
|
|
2624
|
+
* op --known kkk => [op], []
|
|
2625
|
+
* sub --unknown uuu op => [sub], [--unknown uuu op]
|
|
2626
|
+
* sub -- --unknown uuu op => [sub --unknown uuu op], []
|
|
2627
|
+
*
|
|
2628
|
+
* @param {string[]} args
|
|
2629
|
+
* @return {{operands: string[], unknown: string[]}}
|
|
2630
|
+
*/
|
|
2631
|
+
parseOptions(args) {
|
|
2632
|
+
const operands = [];
|
|
2633
|
+
const unknown = [];
|
|
2634
|
+
let dest = operands;
|
|
2635
|
+
function maybeOption(arg) {
|
|
2636
|
+
return arg.length > 1 && arg[0] === "-";
|
|
2637
|
+
}
|
|
2638
|
+
const negativeNumberArg = (arg) => {
|
|
2639
|
+
if (!/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(arg)) return false;
|
|
2640
|
+
return !this._getCommandAndAncestors().some(
|
|
2641
|
+
(cmd) => cmd.options.map((opt) => opt.short).some((short) => /^-\d$/.test(short))
|
|
2642
|
+
);
|
|
2643
|
+
};
|
|
2644
|
+
let activeVariadicOption = null;
|
|
2645
|
+
let activeGroup = null;
|
|
2646
|
+
let i = 0;
|
|
2647
|
+
while (i < args.length || activeGroup) {
|
|
2648
|
+
const arg = activeGroup ?? args[i++];
|
|
2649
|
+
activeGroup = null;
|
|
2650
|
+
if (arg === "--") {
|
|
2651
|
+
if (dest === unknown) dest.push(arg);
|
|
2652
|
+
dest.push(...args.slice(i));
|
|
2653
|
+
break;
|
|
2654
|
+
}
|
|
2655
|
+
if (activeVariadicOption && (!maybeOption(arg) || negativeNumberArg(arg))) {
|
|
2656
|
+
this.emit(`option:${activeVariadicOption.name()}`, arg);
|
|
2657
|
+
continue;
|
|
2658
|
+
}
|
|
2659
|
+
activeVariadicOption = null;
|
|
2660
|
+
if (maybeOption(arg)) {
|
|
2661
|
+
const option = this._findOption(arg);
|
|
2662
|
+
if (option) {
|
|
2663
|
+
if (option.required) {
|
|
2664
|
+
const value = args[i++];
|
|
2665
|
+
if (value === void 0) this.optionMissingArgument(option);
|
|
2666
|
+
this.emit(`option:${option.name()}`, value);
|
|
2667
|
+
} else if (option.optional) {
|
|
2668
|
+
let value = null;
|
|
2669
|
+
if (i < args.length && (!maybeOption(args[i]) || negativeNumberArg(args[i]))) {
|
|
2670
|
+
value = args[i++];
|
|
2671
|
+
}
|
|
2672
|
+
this.emit(`option:${option.name()}`, value);
|
|
2673
|
+
} else {
|
|
2674
|
+
this.emit(`option:${option.name()}`);
|
|
2675
|
+
}
|
|
2676
|
+
activeVariadicOption = option.variadic ? option : null;
|
|
2677
|
+
continue;
|
|
2678
|
+
}
|
|
2679
|
+
}
|
|
2680
|
+
if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
|
|
2681
|
+
const option = this._findOption(`-${arg[1]}`);
|
|
2682
|
+
if (option) {
|
|
2683
|
+
if (option.required || option.optional && this._combineFlagAndOptionalValue) {
|
|
2684
|
+
this.emit(`option:${option.name()}`, arg.slice(2));
|
|
2685
|
+
} else {
|
|
2686
|
+
this.emit(`option:${option.name()}`);
|
|
2687
|
+
activeGroup = `-${arg.slice(2)}`;
|
|
2688
|
+
}
|
|
2689
|
+
continue;
|
|
2690
|
+
}
|
|
2691
|
+
}
|
|
2692
|
+
if (/^--[^=]+=/.test(arg)) {
|
|
2693
|
+
const index = arg.indexOf("=");
|
|
2694
|
+
const option = this._findOption(arg.slice(0, index));
|
|
2695
|
+
if (option && (option.required || option.optional)) {
|
|
2696
|
+
this.emit(`option:${option.name()}`, arg.slice(index + 1));
|
|
2697
|
+
continue;
|
|
2698
|
+
}
|
|
2699
|
+
}
|
|
2700
|
+
if (dest === operands && maybeOption(arg) && !(this.commands.length === 0 && negativeNumberArg(arg))) {
|
|
2701
|
+
dest = unknown;
|
|
2702
|
+
}
|
|
2703
|
+
if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
|
|
2704
|
+
if (this._findCommand(arg)) {
|
|
2705
|
+
operands.push(arg);
|
|
2706
|
+
unknown.push(...args.slice(i));
|
|
2707
|
+
break;
|
|
2708
|
+
} else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
|
|
2709
|
+
operands.push(arg, ...args.slice(i));
|
|
2710
|
+
break;
|
|
2711
|
+
} else if (this._defaultCommandName) {
|
|
2712
|
+
unknown.push(arg, ...args.slice(i));
|
|
2713
|
+
break;
|
|
2714
|
+
}
|
|
2715
|
+
}
|
|
2716
|
+
if (this._passThroughOptions) {
|
|
2717
|
+
dest.push(arg, ...args.slice(i));
|
|
2718
|
+
break;
|
|
2719
|
+
}
|
|
2720
|
+
dest.push(arg);
|
|
2721
|
+
}
|
|
2722
|
+
return { operands, unknown };
|
|
2723
|
+
}
|
|
2724
|
+
/**
|
|
2725
|
+
* Return an object containing local option values as key-value pairs.
|
|
2726
|
+
*
|
|
2727
|
+
* @return {object}
|
|
2728
|
+
*/
|
|
2729
|
+
opts() {
|
|
2730
|
+
if (this._storeOptionsAsProperties) {
|
|
2731
|
+
const result = {};
|
|
2732
|
+
const len = this.options.length;
|
|
2733
|
+
for (let i = 0; i < len; i++) {
|
|
2734
|
+
const key = this.options[i].attributeName();
|
|
2735
|
+
result[key] = key === this._versionOptionName ? this._version : this[key];
|
|
2736
|
+
}
|
|
2737
|
+
return result;
|
|
2738
|
+
}
|
|
2739
|
+
return this._optionValues;
|
|
2740
|
+
}
|
|
2741
|
+
/**
|
|
2742
|
+
* Return an object containing merged local and global option values as key-value pairs.
|
|
2743
|
+
*
|
|
2744
|
+
* @return {object}
|
|
2745
|
+
*/
|
|
2746
|
+
optsWithGlobals() {
|
|
2747
|
+
return this._getCommandAndAncestors().reduce(
|
|
2748
|
+
(combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
|
|
2749
|
+
{}
|
|
2750
|
+
);
|
|
2751
|
+
}
|
|
2752
|
+
/**
|
|
2753
|
+
* Display error message and exit (or call exitOverride).
|
|
2754
|
+
*
|
|
2755
|
+
* @param {string} message
|
|
2756
|
+
* @param {object} [errorOptions]
|
|
2757
|
+
* @param {string} [errorOptions.code] - an id string representing the error
|
|
2758
|
+
* @param {number} [errorOptions.exitCode] - used with process.exit
|
|
2759
|
+
*/
|
|
2760
|
+
error(message2, errorOptions) {
|
|
2761
|
+
this._outputConfiguration.outputError(
|
|
2762
|
+
`${message2}
|
|
2763
|
+
`,
|
|
2764
|
+
this._outputConfiguration.writeErr
|
|
2765
|
+
);
|
|
2766
|
+
if (typeof this._showHelpAfterError === "string") {
|
|
2767
|
+
this._outputConfiguration.writeErr(`${this._showHelpAfterError}
|
|
2768
|
+
`);
|
|
2769
|
+
} else if (this._showHelpAfterError) {
|
|
2770
|
+
this._outputConfiguration.writeErr("\n");
|
|
2771
|
+
this.outputHelp({ error: true });
|
|
2772
|
+
}
|
|
2773
|
+
const config = errorOptions || {};
|
|
2774
|
+
const exitCode = config.exitCode || 1;
|
|
2775
|
+
const code = config.code || "commander.error";
|
|
2776
|
+
this._exit(exitCode, code, message2);
|
|
2777
|
+
}
|
|
2778
|
+
/**
|
|
2779
|
+
* Apply any option related environment variables, if option does
|
|
2780
|
+
* not have a value from cli or client code.
|
|
2781
|
+
*
|
|
2782
|
+
* @private
|
|
2783
|
+
*/
|
|
2784
|
+
_parseOptionsEnv() {
|
|
2785
|
+
this.options.forEach((option) => {
|
|
2786
|
+
if (option.envVar && option.envVar in process2.env) {
|
|
2787
|
+
const optionKey = option.attributeName();
|
|
2788
|
+
if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
|
|
2789
|
+
this.getOptionValueSource(optionKey)
|
|
2790
|
+
)) {
|
|
2791
|
+
if (option.required || option.optional) {
|
|
2792
|
+
this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
|
|
2793
|
+
} else {
|
|
2794
|
+
this.emit(`optionEnv:${option.name()}`);
|
|
2795
|
+
}
|
|
2796
|
+
}
|
|
2797
|
+
}
|
|
2798
|
+
});
|
|
97
2799
|
}
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
2800
|
+
/**
|
|
2801
|
+
* Apply any implied option values, if option is undefined or default value.
|
|
2802
|
+
*
|
|
2803
|
+
* @private
|
|
2804
|
+
*/
|
|
2805
|
+
_parseOptionsImplied() {
|
|
2806
|
+
const dualHelper = new DualOptions(this.options);
|
|
2807
|
+
const hasCustomOptionValue = (optionKey) => {
|
|
2808
|
+
return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
|
|
2809
|
+
};
|
|
2810
|
+
this.options.filter(
|
|
2811
|
+
(option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(
|
|
2812
|
+
this.getOptionValue(option.attributeName()),
|
|
2813
|
+
option
|
|
2814
|
+
)
|
|
2815
|
+
).forEach((option) => {
|
|
2816
|
+
Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
|
|
2817
|
+
this.setOptionValueWithSource(
|
|
2818
|
+
impliedKey,
|
|
2819
|
+
option.implied[impliedKey],
|
|
2820
|
+
"implied"
|
|
2821
|
+
);
|
|
2822
|
+
});
|
|
2823
|
+
});
|
|
118
2824
|
}
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
const
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
2825
|
+
/**
|
|
2826
|
+
* Argument `name` is missing.
|
|
2827
|
+
*
|
|
2828
|
+
* @param {string} name
|
|
2829
|
+
* @private
|
|
2830
|
+
*/
|
|
2831
|
+
missingArgument(name) {
|
|
2832
|
+
const message2 = `error: missing required argument '${name}'`;
|
|
2833
|
+
this.error(message2, { code: "commander.missingArgument" });
|
|
2834
|
+
}
|
|
2835
|
+
/**
|
|
2836
|
+
* `Option` is missing an argument.
|
|
2837
|
+
*
|
|
2838
|
+
* @param {Option} option
|
|
2839
|
+
* @private
|
|
2840
|
+
*/
|
|
2841
|
+
optionMissingArgument(option) {
|
|
2842
|
+
const message2 = `error: option '${option.flags}' argument missing`;
|
|
2843
|
+
this.error(message2, { code: "commander.optionMissingArgument" });
|
|
2844
|
+
}
|
|
2845
|
+
/**
|
|
2846
|
+
* `Option` does not have a value, and is a mandatory option.
|
|
2847
|
+
*
|
|
2848
|
+
* @param {Option} option
|
|
2849
|
+
* @private
|
|
2850
|
+
*/
|
|
2851
|
+
missingMandatoryOptionValue(option) {
|
|
2852
|
+
const message2 = `error: required option '${option.flags}' not specified`;
|
|
2853
|
+
this.error(message2, { code: "commander.missingMandatoryOptionValue" });
|
|
2854
|
+
}
|
|
2855
|
+
/**
|
|
2856
|
+
* `Option` conflicts with another option.
|
|
2857
|
+
*
|
|
2858
|
+
* @param {Option} option
|
|
2859
|
+
* @param {Option} conflictingOption
|
|
2860
|
+
* @private
|
|
2861
|
+
*/
|
|
2862
|
+
_conflictingOption(option, conflictingOption) {
|
|
2863
|
+
const findBestOptionFromValue = (option2) => {
|
|
2864
|
+
const optionKey = option2.attributeName();
|
|
2865
|
+
const optionValue = this.getOptionValue(optionKey);
|
|
2866
|
+
const negativeOption = this.options.find(
|
|
2867
|
+
(target) => target.negate && optionKey === target.attributeName()
|
|
2868
|
+
);
|
|
2869
|
+
const positiveOption = this.options.find(
|
|
2870
|
+
(target) => !target.negate && optionKey === target.attributeName()
|
|
2871
|
+
);
|
|
2872
|
+
if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
|
|
2873
|
+
return negativeOption;
|
|
2874
|
+
}
|
|
2875
|
+
return positiveOption || option2;
|
|
2876
|
+
};
|
|
2877
|
+
const getErrorMessage = (option2) => {
|
|
2878
|
+
const bestOption = findBestOptionFromValue(option2);
|
|
2879
|
+
const optionKey = bestOption.attributeName();
|
|
2880
|
+
const source = this.getOptionValueSource(optionKey);
|
|
2881
|
+
if (source === "env") {
|
|
2882
|
+
return `environment variable '${bestOption.envVar}'`;
|
|
2883
|
+
}
|
|
2884
|
+
return `option '${bestOption.flags}'`;
|
|
2885
|
+
};
|
|
2886
|
+
const message2 = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
|
|
2887
|
+
this.error(message2, { code: "commander.conflictingOption" });
|
|
2888
|
+
}
|
|
2889
|
+
/**
|
|
2890
|
+
* Unknown option `flag`.
|
|
2891
|
+
*
|
|
2892
|
+
* @param {string} flag
|
|
2893
|
+
* @private
|
|
2894
|
+
*/
|
|
2895
|
+
unknownOption(flag) {
|
|
2896
|
+
if (this._allowUnknownOption) return;
|
|
2897
|
+
let suggestion = "";
|
|
2898
|
+
if (flag.startsWith("--") && this._showSuggestionAfterError) {
|
|
2899
|
+
let candidateFlags = [];
|
|
2900
|
+
let command = this;
|
|
2901
|
+
do {
|
|
2902
|
+
const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
|
|
2903
|
+
candidateFlags = candidateFlags.concat(moreFlags);
|
|
2904
|
+
command = command.parent;
|
|
2905
|
+
} while (command && !command._enablePositionalOptions);
|
|
2906
|
+
suggestion = suggestSimilar(flag, candidateFlags);
|
|
140
2907
|
}
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
2908
|
+
const message2 = `error: unknown option '${flag}'${suggestion}`;
|
|
2909
|
+
this.error(message2, { code: "commander.unknownOption" });
|
|
2910
|
+
}
|
|
2911
|
+
/**
|
|
2912
|
+
* Excess arguments, more than expected.
|
|
2913
|
+
*
|
|
2914
|
+
* @param {string[]} receivedArgs
|
|
2915
|
+
* @private
|
|
2916
|
+
*/
|
|
2917
|
+
_excessArguments(receivedArgs) {
|
|
2918
|
+
if (this._allowExcessArguments) return;
|
|
2919
|
+
const expected = this.registeredArguments.length;
|
|
2920
|
+
const s = expected === 1 ? "" : "s";
|
|
2921
|
+
const received = receivedArgs.length;
|
|
2922
|
+
const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
|
|
2923
|
+
const details = receivedArgs.join(", ");
|
|
2924
|
+
const message2 = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${received}: ${details}.`;
|
|
2925
|
+
this.error(message2, { code: "commander.excessArguments" });
|
|
2926
|
+
}
|
|
2927
|
+
/**
|
|
2928
|
+
* Unknown command.
|
|
2929
|
+
*
|
|
2930
|
+
* @private
|
|
2931
|
+
*/
|
|
2932
|
+
unknownCommand() {
|
|
2933
|
+
const unknownName = this.args[0];
|
|
2934
|
+
let suggestion = "";
|
|
2935
|
+
if (this._showSuggestionAfterError) {
|
|
2936
|
+
const candidateNames = [];
|
|
2937
|
+
this.createHelp().visibleCommands(this).forEach((command) => {
|
|
2938
|
+
candidateNames.push(command.name());
|
|
2939
|
+
if (command.alias()) candidateNames.push(command.alias());
|
|
2940
|
+
});
|
|
2941
|
+
suggestion = suggestSimilar(unknownName, candidateNames);
|
|
148
2942
|
}
|
|
2943
|
+
const message2 = `error: unknown command '${unknownName}'${suggestion}`;
|
|
2944
|
+
this.error(message2, { code: "commander.unknownCommand" });
|
|
149
2945
|
}
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
2946
|
+
/**
|
|
2947
|
+
* Get or set the program version.
|
|
2948
|
+
*
|
|
2949
|
+
* This method auto-registers the "-V, --version" option which will print the version number.
|
|
2950
|
+
*
|
|
2951
|
+
* You can optionally supply the flags and description to override the defaults.
|
|
2952
|
+
*
|
|
2953
|
+
* @param {string} [str]
|
|
2954
|
+
* @param {string} [flags]
|
|
2955
|
+
* @param {string} [description]
|
|
2956
|
+
* @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
|
|
2957
|
+
*/
|
|
2958
|
+
version(str, flags, description) {
|
|
2959
|
+
if (str === void 0) return this._version;
|
|
2960
|
+
this._version = str;
|
|
2961
|
+
flags = flags || "-V, --version";
|
|
2962
|
+
description = description || "output the version number";
|
|
2963
|
+
const versionOption = this.createOption(flags, description);
|
|
2964
|
+
this._versionOptionName = versionOption.attributeName();
|
|
2965
|
+
this._registerOption(versionOption);
|
|
2966
|
+
this.on("option:" + versionOption.name(), () => {
|
|
2967
|
+
this._outputConfiguration.writeOut(`${str}
|
|
2968
|
+
`);
|
|
2969
|
+
this._exit(0, "commander.version", str);
|
|
158
2970
|
});
|
|
159
|
-
|
|
160
|
-
const skillFile = join(directory, "SKILL.md");
|
|
161
|
-
const fileInfo = await lstat(skillFile);
|
|
162
|
-
if (!fileInfo.isFile() || fileInfo.isSymbolicLink()) throw new Error(`Project skill file is not a real file: ${validName}`);
|
|
163
|
-
await writeFile(skillFile, renderSkill(value), { encoding: "utf8", mode: 384 });
|
|
164
|
-
return this.get(validName);
|
|
2971
|
+
return this;
|
|
165
2972
|
}
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
2973
|
+
/**
|
|
2974
|
+
* Set the description.
|
|
2975
|
+
*
|
|
2976
|
+
* @param {string} [str]
|
|
2977
|
+
* @param {object} [argsDescription]
|
|
2978
|
+
* @return {(string|Command)}
|
|
2979
|
+
*/
|
|
2980
|
+
description(str, argsDescription) {
|
|
2981
|
+
if (str === void 0 && argsDescription === void 0)
|
|
2982
|
+
return this._description;
|
|
2983
|
+
this._description = str;
|
|
2984
|
+
if (argsDescription) {
|
|
2985
|
+
this._argsDescription = argsDescription;
|
|
2986
|
+
}
|
|
2987
|
+
return this;
|
|
2988
|
+
}
|
|
2989
|
+
/**
|
|
2990
|
+
* Set the summary. Used when listed as subcommand of parent.
|
|
2991
|
+
*
|
|
2992
|
+
* @param {string} [str]
|
|
2993
|
+
* @return {(string|Command)}
|
|
2994
|
+
*/
|
|
2995
|
+
summary(str) {
|
|
2996
|
+
if (str === void 0) return this._summary;
|
|
2997
|
+
this._summary = str;
|
|
2998
|
+
return this;
|
|
2999
|
+
}
|
|
3000
|
+
/**
|
|
3001
|
+
* Set an alias for the command.
|
|
3002
|
+
*
|
|
3003
|
+
* You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
|
|
3004
|
+
*
|
|
3005
|
+
* @param {string} [alias]
|
|
3006
|
+
* @return {(string|Command)}
|
|
3007
|
+
*/
|
|
3008
|
+
alias(alias) {
|
|
3009
|
+
if (alias === void 0) return this._aliases[0];
|
|
3010
|
+
let command = this;
|
|
3011
|
+
if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
|
|
3012
|
+
command = this.commands[this.commands.length - 1];
|
|
3013
|
+
}
|
|
3014
|
+
if (alias === command._name)
|
|
3015
|
+
throw new Error("Command alias can't be the same as its name");
|
|
3016
|
+
const matchingCommand = this.parent?._findCommand(alias);
|
|
3017
|
+
if (matchingCommand) {
|
|
3018
|
+
const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
|
|
3019
|
+
throw new Error(
|
|
3020
|
+
`cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
|
|
3021
|
+
);
|
|
3022
|
+
}
|
|
3023
|
+
command._aliases.push(alias);
|
|
3024
|
+
return this;
|
|
3025
|
+
}
|
|
3026
|
+
/**
|
|
3027
|
+
* Set aliases for the command.
|
|
3028
|
+
*
|
|
3029
|
+
* Only the first alias is shown in the auto-generated help.
|
|
3030
|
+
*
|
|
3031
|
+
* @param {string[]} [aliases]
|
|
3032
|
+
* @return {(string[]|Command)}
|
|
3033
|
+
*/
|
|
3034
|
+
aliases(aliases) {
|
|
3035
|
+
if (aliases === void 0) return this._aliases;
|
|
3036
|
+
aliases.forEach((alias) => this.alias(alias));
|
|
3037
|
+
return this;
|
|
3038
|
+
}
|
|
3039
|
+
/**
|
|
3040
|
+
* Set / get the command usage `str`.
|
|
3041
|
+
*
|
|
3042
|
+
* @param {string} [str]
|
|
3043
|
+
* @return {(string|Command)}
|
|
3044
|
+
*/
|
|
3045
|
+
usage(str) {
|
|
3046
|
+
if (str === void 0) {
|
|
3047
|
+
if (this._usage) return this._usage;
|
|
3048
|
+
const args = this.registeredArguments.map((arg) => {
|
|
3049
|
+
return humanReadableArgName(arg);
|
|
3050
|
+
});
|
|
3051
|
+
return [].concat(
|
|
3052
|
+
this.options.length || this._helpOption !== null ? "[options]" : [],
|
|
3053
|
+
this.commands.length ? "[command]" : [],
|
|
3054
|
+
this.registeredArguments.length ? args : []
|
|
3055
|
+
).join(" ");
|
|
3056
|
+
}
|
|
3057
|
+
this._usage = str;
|
|
3058
|
+
return this;
|
|
3059
|
+
}
|
|
3060
|
+
/**
|
|
3061
|
+
* Get or set the name of the command.
|
|
3062
|
+
*
|
|
3063
|
+
* @param {string} [str]
|
|
3064
|
+
* @return {(string|Command)}
|
|
3065
|
+
*/
|
|
3066
|
+
name(str) {
|
|
3067
|
+
if (str === void 0) return this._name;
|
|
3068
|
+
this._name = str;
|
|
3069
|
+
return this;
|
|
3070
|
+
}
|
|
3071
|
+
/**
|
|
3072
|
+
* Set/get the help group heading for this subcommand in parent command's help.
|
|
3073
|
+
*
|
|
3074
|
+
* @param {string} [heading]
|
|
3075
|
+
* @return {Command | string}
|
|
3076
|
+
*/
|
|
3077
|
+
helpGroup(heading) {
|
|
3078
|
+
if (heading === void 0) return this._helpGroupHeading ?? "";
|
|
3079
|
+
this._helpGroupHeading = heading;
|
|
3080
|
+
return this;
|
|
3081
|
+
}
|
|
3082
|
+
/**
|
|
3083
|
+
* Set/get the default help group heading for subcommands added to this command.
|
|
3084
|
+
* (This does not override a group set directly on the subcommand using .helpGroup().)
|
|
3085
|
+
*
|
|
3086
|
+
* @example
|
|
3087
|
+
* program.commandsGroup('Development Commands:);
|
|
3088
|
+
* program.command('watch')...
|
|
3089
|
+
* program.command('lint')...
|
|
3090
|
+
* ...
|
|
3091
|
+
*
|
|
3092
|
+
* @param {string} [heading]
|
|
3093
|
+
* @returns {Command | string}
|
|
3094
|
+
*/
|
|
3095
|
+
commandsGroup(heading) {
|
|
3096
|
+
if (heading === void 0) return this._defaultCommandGroup ?? "";
|
|
3097
|
+
this._defaultCommandGroup = heading;
|
|
3098
|
+
return this;
|
|
3099
|
+
}
|
|
3100
|
+
/**
|
|
3101
|
+
* Set/get the default help group heading for options added to this command.
|
|
3102
|
+
* (This does not override a group set directly on the option using .helpGroup().)
|
|
3103
|
+
*
|
|
3104
|
+
* @example
|
|
3105
|
+
* program
|
|
3106
|
+
* .optionsGroup('Development Options:')
|
|
3107
|
+
* .option('-d, --debug', 'output extra debugging')
|
|
3108
|
+
* .option('-p, --profile', 'output profiling information')
|
|
3109
|
+
*
|
|
3110
|
+
* @param {string} [heading]
|
|
3111
|
+
* @returns {Command | string}
|
|
3112
|
+
*/
|
|
3113
|
+
optionsGroup(heading) {
|
|
3114
|
+
if (heading === void 0) return this._defaultOptionGroup ?? "";
|
|
3115
|
+
this._defaultOptionGroup = heading;
|
|
3116
|
+
return this;
|
|
3117
|
+
}
|
|
3118
|
+
/**
|
|
3119
|
+
* @param {Option} option
|
|
3120
|
+
* @private
|
|
3121
|
+
*/
|
|
3122
|
+
_initOptionGroup(option) {
|
|
3123
|
+
if (this._defaultOptionGroup && !option.helpGroupHeading)
|
|
3124
|
+
option.helpGroup(this._defaultOptionGroup);
|
|
3125
|
+
}
|
|
3126
|
+
/**
|
|
3127
|
+
* @param {Command} cmd
|
|
3128
|
+
* @private
|
|
3129
|
+
*/
|
|
3130
|
+
_initCommandGroup(cmd) {
|
|
3131
|
+
if (this._defaultCommandGroup && !cmd.helpGroup())
|
|
3132
|
+
cmd.helpGroup(this._defaultCommandGroup);
|
|
3133
|
+
}
|
|
3134
|
+
/**
|
|
3135
|
+
* Set the name of the command from script filename, such as process.argv[1],
|
|
3136
|
+
* or import.meta.filename.
|
|
3137
|
+
*
|
|
3138
|
+
* (Used internally and public although not documented in README.)
|
|
3139
|
+
*
|
|
3140
|
+
* @example
|
|
3141
|
+
* program.nameFromFilename(import.meta.filename);
|
|
3142
|
+
*
|
|
3143
|
+
* @param {string} filename
|
|
3144
|
+
* @return {Command}
|
|
3145
|
+
*/
|
|
3146
|
+
nameFromFilename(filename) {
|
|
3147
|
+
this._name = path.basename(filename, path.extname(filename));
|
|
3148
|
+
return this;
|
|
3149
|
+
}
|
|
3150
|
+
/**
|
|
3151
|
+
* Get or set the directory for searching for executable subcommands of this command.
|
|
3152
|
+
*
|
|
3153
|
+
* @example
|
|
3154
|
+
* program.executableDir(import.meta.dirname);
|
|
3155
|
+
* // or
|
|
3156
|
+
* program.executableDir('subcommands');
|
|
3157
|
+
*
|
|
3158
|
+
* @param {string} [path]
|
|
3159
|
+
* @return {(string|null|Command)}
|
|
3160
|
+
*/
|
|
3161
|
+
executableDir(path2) {
|
|
3162
|
+
if (path2 === void 0) return this._executableDir;
|
|
3163
|
+
this._executableDir = path2;
|
|
3164
|
+
return this;
|
|
3165
|
+
}
|
|
3166
|
+
/**
|
|
3167
|
+
* Return program help documentation.
|
|
3168
|
+
*
|
|
3169
|
+
* @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
|
|
3170
|
+
* @return {string}
|
|
3171
|
+
*/
|
|
3172
|
+
helpInformation(contextOptions) {
|
|
3173
|
+
const helper = this.createHelp();
|
|
3174
|
+
const context = this._getOutputContext(contextOptions);
|
|
3175
|
+
helper.prepareContext({
|
|
3176
|
+
error: context.error,
|
|
3177
|
+
helpWidth: context.helpWidth,
|
|
3178
|
+
outputHasColors: context.hasColors
|
|
172
3179
|
});
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
3180
|
+
const text = helper.formatHelp(this, helper);
|
|
3181
|
+
if (context.hasColors) return text;
|
|
3182
|
+
return this._outputConfiguration.stripColor(text);
|
|
176
3183
|
}
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
const
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
3184
|
+
/**
|
|
3185
|
+
* @typedef HelpContext
|
|
3186
|
+
* @type {object}
|
|
3187
|
+
* @property {boolean} error
|
|
3188
|
+
* @property {number} helpWidth
|
|
3189
|
+
* @property {boolean} hasColors
|
|
3190
|
+
* @property {function} write - includes stripColor if needed
|
|
3191
|
+
*
|
|
3192
|
+
* @returns {HelpContext}
|
|
3193
|
+
* @private
|
|
3194
|
+
*/
|
|
3195
|
+
_getOutputContext(contextOptions) {
|
|
3196
|
+
contextOptions = contextOptions || {};
|
|
3197
|
+
const error = !!contextOptions.error;
|
|
3198
|
+
let baseWrite;
|
|
3199
|
+
let hasColors;
|
|
3200
|
+
let helpWidth;
|
|
3201
|
+
if (error) {
|
|
3202
|
+
baseWrite = (str) => this._outputConfiguration.writeErr(str);
|
|
3203
|
+
hasColors = this._outputConfiguration.getErrHasColors();
|
|
3204
|
+
helpWidth = this._outputConfiguration.getErrHelpWidth();
|
|
3205
|
+
} else {
|
|
3206
|
+
baseWrite = (str) => this._outputConfiguration.writeOut(str);
|
|
3207
|
+
hasColors = this._outputConfiguration.getOutHasColors();
|
|
3208
|
+
helpWidth = this._outputConfiguration.getOutHelpWidth();
|
|
3209
|
+
}
|
|
3210
|
+
const write = (str) => {
|
|
3211
|
+
if (!hasColors) str = this._outputConfiguration.stripColor(str);
|
|
3212
|
+
return baseWrite(str);
|
|
201
3213
|
};
|
|
3214
|
+
return { error, write, hasColors, helpWidth };
|
|
202
3215
|
}
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
3216
|
+
/**
|
|
3217
|
+
* Output help information for this command.
|
|
3218
|
+
*
|
|
3219
|
+
* Outputs built-in help, and custom text added using `.addHelpText()`.
|
|
3220
|
+
*
|
|
3221
|
+
* @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
|
|
3222
|
+
*/
|
|
3223
|
+
outputHelp(contextOptions) {
|
|
3224
|
+
let deprecatedCallback;
|
|
3225
|
+
if (typeof contextOptions === "function") {
|
|
3226
|
+
deprecatedCallback = contextOptions;
|
|
3227
|
+
contextOptions = void 0;
|
|
3228
|
+
}
|
|
3229
|
+
const outputContext = this._getOutputContext(contextOptions);
|
|
3230
|
+
const eventContext = {
|
|
3231
|
+
error: outputContext.error,
|
|
3232
|
+
write: outputContext.write,
|
|
3233
|
+
command: this
|
|
210
3234
|
};
|
|
3235
|
+
this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
|
|
3236
|
+
this.emit("beforeHelp", eventContext);
|
|
3237
|
+
let helpInformation = this.helpInformation({ error: outputContext.error });
|
|
3238
|
+
if (deprecatedCallback) {
|
|
3239
|
+
helpInformation = deprecatedCallback(helpInformation);
|
|
3240
|
+
if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
|
|
3241
|
+
throw new Error("outputHelp callback must return a string or a Buffer");
|
|
3242
|
+
}
|
|
3243
|
+
}
|
|
3244
|
+
outputContext.write(helpInformation);
|
|
3245
|
+
if (this._getHelpOption()?.long) {
|
|
3246
|
+
this.emit(this._getHelpOption().long);
|
|
3247
|
+
}
|
|
3248
|
+
this.emit("afterHelp", eventContext);
|
|
3249
|
+
this._getCommandAndAncestors().forEach(
|
|
3250
|
+
(command) => command.emit("afterAllHelp", eventContext)
|
|
3251
|
+
);
|
|
3252
|
+
}
|
|
3253
|
+
/**
|
|
3254
|
+
* You can pass in flags and a description to customise the built-in help option.
|
|
3255
|
+
* Pass in false to disable the built-in help option.
|
|
3256
|
+
*
|
|
3257
|
+
* @example
|
|
3258
|
+
* program.helpOption('-?, --help' 'show help'); // customise
|
|
3259
|
+
* program.helpOption(false); // disable
|
|
3260
|
+
*
|
|
3261
|
+
* @param {(string | boolean)} flags
|
|
3262
|
+
* @param {string} [description]
|
|
3263
|
+
* @return {Command} `this` command for chaining
|
|
3264
|
+
*/
|
|
3265
|
+
helpOption(flags, description) {
|
|
3266
|
+
if (typeof flags === "boolean") {
|
|
3267
|
+
if (flags) {
|
|
3268
|
+
if (this._helpOption === null) this._helpOption = void 0;
|
|
3269
|
+
if (this._defaultOptionGroup) {
|
|
3270
|
+
this._initOptionGroup(this._getHelpOption());
|
|
3271
|
+
}
|
|
3272
|
+
} else {
|
|
3273
|
+
this._helpOption = null;
|
|
3274
|
+
}
|
|
3275
|
+
return this;
|
|
3276
|
+
}
|
|
3277
|
+
this._helpOption = this.createOption(
|
|
3278
|
+
flags ?? "-h, --help",
|
|
3279
|
+
description ?? "display help for command"
|
|
3280
|
+
);
|
|
3281
|
+
if (flags || description) this._initOptionGroup(this._helpOption);
|
|
3282
|
+
return this;
|
|
3283
|
+
}
|
|
3284
|
+
/**
|
|
3285
|
+
* Lazy create help option.
|
|
3286
|
+
* Returns null if has been disabled with .helpOption(false).
|
|
3287
|
+
*
|
|
3288
|
+
* @returns {(Option | null)} the help option
|
|
3289
|
+
* @package
|
|
3290
|
+
*/
|
|
3291
|
+
_getHelpOption() {
|
|
3292
|
+
if (this._helpOption === void 0) {
|
|
3293
|
+
this.helpOption(void 0, void 0);
|
|
3294
|
+
}
|
|
3295
|
+
return this._helpOption;
|
|
3296
|
+
}
|
|
3297
|
+
/**
|
|
3298
|
+
* Supply your own option to use for the built-in help option.
|
|
3299
|
+
* This is an alternative to using helpOption() to customise the flags and description etc.
|
|
3300
|
+
*
|
|
3301
|
+
* @param {Option} option
|
|
3302
|
+
* @return {Command} `this` command for chaining
|
|
3303
|
+
*/
|
|
3304
|
+
addHelpOption(option) {
|
|
3305
|
+
this._helpOption = option;
|
|
3306
|
+
this._initOptionGroup(option);
|
|
3307
|
+
return this;
|
|
211
3308
|
}
|
|
212
|
-
|
|
213
|
-
|
|
3309
|
+
/**
|
|
3310
|
+
* Output help information and exit.
|
|
3311
|
+
*
|
|
3312
|
+
* Outputs built-in help, and custom text added using `.addHelpText()`.
|
|
3313
|
+
*
|
|
3314
|
+
* @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
|
|
3315
|
+
*/
|
|
3316
|
+
help(contextOptions) {
|
|
3317
|
+
this.outputHelp(contextOptions);
|
|
3318
|
+
let exitCode = Number(process2.exitCode ?? 0);
|
|
3319
|
+
if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
|
|
3320
|
+
exitCode = 1;
|
|
3321
|
+
}
|
|
3322
|
+
this._exit(exitCode, "commander.help", "(outputHelp)");
|
|
3323
|
+
}
|
|
3324
|
+
/**
|
|
3325
|
+
* // Do a little typing to coordinate emit and listener for the help text events.
|
|
3326
|
+
* @typedef HelpTextEventContext
|
|
3327
|
+
* @type {object}
|
|
3328
|
+
* @property {boolean} error
|
|
3329
|
+
* @property {Command} command
|
|
3330
|
+
* @property {function} write
|
|
3331
|
+
*/
|
|
3332
|
+
/**
|
|
3333
|
+
* Add additional text to be displayed with the built-in help.
|
|
3334
|
+
*
|
|
3335
|
+
* Position is 'before' or 'after' to affect just this command,
|
|
3336
|
+
* and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
|
|
3337
|
+
*
|
|
3338
|
+
* @param {string} position - before or after built-in help
|
|
3339
|
+
* @param {(string | Function)} text - string to add, or a function returning a string
|
|
3340
|
+
* @return {Command} `this` command for chaining
|
|
3341
|
+
*/
|
|
3342
|
+
addHelpText(position, text) {
|
|
3343
|
+
const allowedValues = ["beforeAll", "before", "after", "afterAll"];
|
|
3344
|
+
if (!allowedValues.includes(position)) {
|
|
3345
|
+
throw new Error(`Unexpected value for position to addHelpText.
|
|
3346
|
+
Expecting one of '${allowedValues.join("', '")}'`);
|
|
3347
|
+
}
|
|
3348
|
+
const helpEvent = `${position}Help`;
|
|
3349
|
+
this.on(helpEvent, (context) => {
|
|
3350
|
+
let helpStr;
|
|
3351
|
+
if (typeof text === "function") {
|
|
3352
|
+
helpStr = text({ error: context.error, command: context.command });
|
|
3353
|
+
} else {
|
|
3354
|
+
helpStr = text;
|
|
3355
|
+
}
|
|
3356
|
+
if (helpStr) {
|
|
3357
|
+
context.write(`${helpStr}
|
|
3358
|
+
`);
|
|
3359
|
+
}
|
|
3360
|
+
});
|
|
3361
|
+
return this;
|
|
214
3362
|
}
|
|
215
|
-
|
|
216
|
-
|
|
3363
|
+
/**
|
|
3364
|
+
* Output help information if help flags specified
|
|
3365
|
+
*
|
|
3366
|
+
* @param {Array} args - array of options to search for help flags
|
|
3367
|
+
* @private
|
|
3368
|
+
*/
|
|
3369
|
+
_outputHelpIfRequested(args) {
|
|
3370
|
+
const helpOption = this._getHelpOption();
|
|
3371
|
+
const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
|
|
3372
|
+
if (helpRequested) {
|
|
3373
|
+
this.outputHelp();
|
|
3374
|
+
this._exit(0, "commander.helpDisplayed", "(outputHelp)");
|
|
3375
|
+
}
|
|
217
3376
|
}
|
|
218
3377
|
};
|
|
219
|
-
function
|
|
220
|
-
return
|
|
3378
|
+
function incrementNodeInspectorPort(args) {
|
|
3379
|
+
return args.map((arg) => {
|
|
3380
|
+
if (!arg.startsWith("--inspect")) {
|
|
3381
|
+
return arg;
|
|
3382
|
+
}
|
|
3383
|
+
let debugOption;
|
|
3384
|
+
let debugHost = "127.0.0.1";
|
|
3385
|
+
let debugPort = "9229";
|
|
3386
|
+
let match;
|
|
3387
|
+
if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
|
|
3388
|
+
debugOption = match[1];
|
|
3389
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
|
|
3390
|
+
debugOption = match[1];
|
|
3391
|
+
if (/^\d+$/.test(match[3])) {
|
|
3392
|
+
debugPort = match[3];
|
|
3393
|
+
} else {
|
|
3394
|
+
debugHost = match[3];
|
|
3395
|
+
}
|
|
3396
|
+
} else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
|
|
3397
|
+
debugOption = match[1];
|
|
3398
|
+
debugHost = match[3];
|
|
3399
|
+
debugPort = match[4];
|
|
3400
|
+
}
|
|
3401
|
+
if (debugOption && debugPort !== "0") {
|
|
3402
|
+
return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
|
|
3403
|
+
}
|
|
3404
|
+
return arg;
|
|
3405
|
+
});
|
|
221
3406
|
}
|
|
222
|
-
function
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
return { name, description, body, disableModelInvocation: draft.disableModelInvocation ?? false };
|
|
3407
|
+
function useColor() {
|
|
3408
|
+
if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
|
|
3409
|
+
return false;
|
|
3410
|
+
if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== void 0)
|
|
3411
|
+
return true;
|
|
3412
|
+
return void 0;
|
|
229
3413
|
}
|
|
230
|
-
function renderSkill(draft) {
|
|
231
|
-
const frontmatter = stringify({
|
|
232
|
-
name: draft.name,
|
|
233
|
-
description: draft.description,
|
|
234
|
-
"disable-model-invocation": draft.disableModelInvocation
|
|
235
|
-
}).trimEnd();
|
|
236
|
-
return `---
|
|
237
|
-
${frontmatter}
|
|
238
|
-
---
|
|
239
3414
|
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
3415
|
+
// node_modules/commander/index.js
|
|
3416
|
+
var program = new Command();
|
|
3417
|
+
|
|
3418
|
+
// src/ui/user-timing.ts
|
|
3419
|
+
import { performance } from "perf_hooks";
|
|
3420
|
+
function clearUiUserTimingEntries() {
|
|
3421
|
+
performance.clearMarks();
|
|
3422
|
+
performance.clearMeasures();
|
|
245
3423
|
}
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
entries = await readdir(directory, { withFileTypes: true });
|
|
250
|
-
} catch (error) {
|
|
251
|
-
if (isCode(error, "ENOENT")) return [];
|
|
252
|
-
throw error;
|
|
253
|
-
}
|
|
254
|
-
const roots = [];
|
|
255
|
-
for (const entry of entries) {
|
|
256
|
-
if (!entry.isDirectory() || entry.isSymbolicLink()) continue;
|
|
257
|
-
const pluginRoot = await realpath(join(directory, entry.name));
|
|
258
|
-
try {
|
|
259
|
-
const manifest = PluginManifestSchema.parse(JSON.parse(await readFile(join(pluginRoot, "flavor-plugin.json"), "utf8")));
|
|
260
|
-
for (const contribution of manifest.contributes.skillRoots) {
|
|
261
|
-
const candidate = resolve(pluginRoot, contribution.path);
|
|
262
|
-
const info = await lstat(candidate);
|
|
263
|
-
if (!info.isDirectory() || info.isSymbolicLink()) continue;
|
|
264
|
-
const physical = await realpath(candidate);
|
|
265
|
-
const relation = relative(pluginRoot, physical);
|
|
266
|
-
if (relation === ".." || relation.startsWith(`..${sep}`) || isAbsolute(relation)) continue;
|
|
267
|
-
roots.push(physical);
|
|
268
|
-
}
|
|
269
|
-
} catch {
|
|
270
|
-
}
|
|
3424
|
+
function installUiUserTimingSweeper(intervalMs = 250) {
|
|
3425
|
+
if (!Number.isSafeInteger(intervalMs) || intervalMs <= 0) {
|
|
3426
|
+
throw new Error("User Timing sweep interval must be a positive integer");
|
|
271
3427
|
}
|
|
272
|
-
|
|
3428
|
+
clearUiUserTimingEntries();
|
|
3429
|
+
const timer = setInterval(clearUiUserTimingEntries, intervalMs);
|
|
3430
|
+
timer.unref();
|
|
3431
|
+
return () => {
|
|
3432
|
+
clearInterval(timer);
|
|
3433
|
+
clearUiUserTimingEntries();
|
|
3434
|
+
};
|
|
273
3435
|
}
|
|
274
3436
|
|
|
275
3437
|
// src/memory/cli.ts
|
|
276
|
-
import { homedir
|
|
3438
|
+
import { homedir } from "os";
|
|
277
3439
|
|
|
278
3440
|
// src/memory/manager.ts
|
|
279
3441
|
var ProjectMemoryManager = class {
|
|
@@ -334,13 +3496,13 @@ async function createProjectMemoryManager(options) {
|
|
|
334
3496
|
}
|
|
335
3497
|
|
|
336
3498
|
// src/memory/cli.ts
|
|
337
|
-
function registerMemoryCommands(
|
|
3499
|
+
function registerMemoryCommands(program2, dependencies = {}) {
|
|
338
3500
|
const open = dependencies.open ?? createProjectMemoryManager;
|
|
339
3501
|
const cwd = dependencies.cwd ?? (() => process.cwd());
|
|
340
|
-
const home = dependencies.home ??
|
|
3502
|
+
const home = dependencies.home ?? homedir;
|
|
341
3503
|
const write = dependencies.write ?? ((text) => process.stdout.write(text));
|
|
342
3504
|
const manager = () => open({ workspace: cwd(), home: home() });
|
|
343
|
-
const memory =
|
|
3505
|
+
const memory = program2.command("memory").description("Inspect and maintain project long-term memory");
|
|
344
3506
|
memory.command("list", { isDefault: true }).description("List project memories").option("--json", "print a machine-readable snapshot").action(async (options) => {
|
|
345
3507
|
const snapshot = await (await manager()).snapshot();
|
|
346
3508
|
if (options.json) {
|
|
@@ -388,11 +3550,11 @@ function parseMemoryType(value) {
|
|
|
388
3550
|
}
|
|
389
3551
|
|
|
390
3552
|
// src/mcp/config-manager.ts
|
|
391
|
-
import { join
|
|
3553
|
+
import { join } from "path";
|
|
392
3554
|
var ProjectMcpConfigManager = class {
|
|
393
3555
|
path;
|
|
394
3556
|
constructor(workspace) {
|
|
395
|
-
this.path =
|
|
3557
|
+
this.path = join(workspace, ".flavor", "flavor.json");
|
|
396
3558
|
}
|
|
397
3559
|
async list() {
|
|
398
3560
|
const document = await readRecoverableFile(this.path, (raw) => parseDocument(this.path, raw));
|
|
@@ -459,20 +3621,20 @@ var ProjectMcpConfigManager = class {
|
|
|
459
3621
|
});
|
|
460
3622
|
}
|
|
461
3623
|
};
|
|
462
|
-
function parseDocument(
|
|
3624
|
+
function parseDocument(path2, raw) {
|
|
463
3625
|
const value = JSON.parse(raw);
|
|
464
|
-
if (!isRecord(value)) throw new Error(`Configuration file ${
|
|
3626
|
+
if (!isRecord(value)) throw new Error(`Configuration file ${path2} must contain a JSON object`);
|
|
465
3627
|
return value;
|
|
466
3628
|
}
|
|
467
|
-
function parseServers(
|
|
3629
|
+
function parseServers(path2, value) {
|
|
468
3630
|
if (value === void 0) return [];
|
|
469
|
-
if (!isRecord(value)) throw new Error(`Configuration field mcpServers in ${
|
|
3631
|
+
if (!isRecord(value)) throw new Error(`Configuration field mcpServers in ${path2} must be an object`);
|
|
470
3632
|
return Object.entries(value).map(([name, config]) => {
|
|
471
3633
|
try {
|
|
472
3634
|
return managedServer(McpServerNameSchema.parse(name), McpServerConfigSchema.parse(config));
|
|
473
3635
|
} catch (error) {
|
|
474
3636
|
const reason = error instanceof Error ? error.message : String(error);
|
|
475
|
-
throw new Error(`Invalid MCP service "${name}" in ${
|
|
3637
|
+
throw new Error(`Invalid MCP service "${name}" in ${path2}: ${reason}`);
|
|
476
3638
|
}
|
|
477
3639
|
}).sort((left, right) => left.name.localeCompare(right.name));
|
|
478
3640
|
}
|
|
@@ -489,12 +3651,12 @@ function isRecord(value) {
|
|
|
489
3651
|
}
|
|
490
3652
|
|
|
491
3653
|
// src/mcp/cli.ts
|
|
492
|
-
function registerMcpCommands(
|
|
3654
|
+
function registerMcpCommands(program2, dependencies) {
|
|
493
3655
|
const deps = {
|
|
494
3656
|
open: dependencies?.open ?? (() => new ProjectMcpConfigManager(process.cwd())),
|
|
495
3657
|
write: dependencies?.write ?? ((text) => process.stdout.write(text))
|
|
496
3658
|
};
|
|
497
|
-
const mcp =
|
|
3659
|
+
const mcp = program2.command("mcp").description("Manage project MCP service configurations");
|
|
498
3660
|
mcp.command("list", { isDefault: true }).option("--json", "print JSON").action(async (options) => {
|
|
499
3661
|
const services = await deps.open().list();
|
|
500
3662
|
if (options.json) deps.write(`${JSON.stringify(services, null, 2)}
|
|
@@ -575,208 +3737,259 @@ function keyValueRecord(entries, label) {
|
|
|
575
3737
|
}));
|
|
576
3738
|
}
|
|
577
3739
|
|
|
578
|
-
// src/
|
|
579
|
-
import {
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
if (
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
id,
|
|
596
|
-
path: proposal.path,
|
|
597
|
-
before: proposal.before,
|
|
598
|
-
totalBytes: Buffer.byteLength(proposal.after)
|
|
599
|
-
});
|
|
600
|
-
for (const delta of streamChunks(proposal.after)) this.#output({ type: "write-delta", id, delta });
|
|
601
|
-
this.#output({ type: "write-ready", id });
|
|
602
|
-
await new Promise((resolve4, reject) => {
|
|
603
|
-
const onAbort = () => {
|
|
604
|
-
this.#output({ type: "write-cancelled", id });
|
|
605
|
-
this.#clear(id);
|
|
606
|
-
reject(signal.reason);
|
|
607
|
-
};
|
|
608
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
609
|
-
this.#pending = {
|
|
610
|
-
id,
|
|
611
|
-
resolve: resolve4,
|
|
612
|
-
reject,
|
|
613
|
-
removeAbort: () => signal.removeEventListener("abort", onAbort)
|
|
614
|
-
};
|
|
615
|
-
});
|
|
616
|
-
}
|
|
617
|
-
commit(id) {
|
|
618
|
-
const pending = this.#pending;
|
|
619
|
-
if (pending === void 0 || pending.id !== id) throw new Error("Streamed write is no longer awaiting commit");
|
|
620
|
-
pending.removeAbort();
|
|
621
|
-
this.#pending = void 0;
|
|
622
|
-
pending.resolve();
|
|
623
|
-
}
|
|
624
|
-
dispose() {
|
|
625
|
-
const pending = this.#pending;
|
|
626
|
-
if (pending === void 0) return;
|
|
627
|
-
pending.removeAbort();
|
|
628
|
-
this.#pending = void 0;
|
|
629
|
-
pending.reject(new Error("Streamed write bridge disposed"));
|
|
630
|
-
}
|
|
631
|
-
#clear(id) {
|
|
632
|
-
if (this.#pending?.id !== id) return;
|
|
633
|
-
this.#pending.removeAbort();
|
|
634
|
-
this.#pending = void 0;
|
|
635
|
-
}
|
|
636
|
-
};
|
|
637
|
-
function streamChunks(content, maxChars = 2048) {
|
|
638
|
-
if (!content) return [];
|
|
639
|
-
const chunks = [];
|
|
640
|
-
for (const line of content.match(/[^\n]*\n|[^\n]+$/g) ?? []) {
|
|
641
|
-
for (let offset = 0; offset < line.length; offset += maxChars) {
|
|
642
|
-
chunks.push(line.slice(offset, offset + maxChars));
|
|
3740
|
+
// src/session/cli.ts
|
|
3741
|
+
import { join as join2 } from "path";
|
|
3742
|
+
function registerSessionCommands(program2, dependencies = {}) {
|
|
3743
|
+
const cwd = dependencies.cwd ?? (() => process.cwd());
|
|
3744
|
+
const write = dependencies.write ?? ((text) => process.stdout.write(text));
|
|
3745
|
+
const open = dependencies.open ?? (async ({ workspace }) => {
|
|
3746
|
+
const { SessionStore } = await import("./store-ZIHN6363.js");
|
|
3747
|
+
return new SessionStore({ workspace });
|
|
3748
|
+
});
|
|
3749
|
+
const store = () => open({ workspace: cwd() });
|
|
3750
|
+
const sessions = program2.command("sessions").description("List, inspect, export, and delete saved sessions");
|
|
3751
|
+
sessions.command("list", { isDefault: true }).description("List saved sessions, newest first").option("--json", "print a machine-readable snapshot").action(async (options) => {
|
|
3752
|
+
const entries = await (await store()).list();
|
|
3753
|
+
if (options.json) {
|
|
3754
|
+
write(`${JSON.stringify(entries, null, 2)}
|
|
3755
|
+
`);
|
|
3756
|
+
return;
|
|
643
3757
|
}
|
|
644
|
-
|
|
645
|
-
|
|
3758
|
+
if (entries.length === 0) {
|
|
3759
|
+
write("No saved sessions in this workspace.\n");
|
|
3760
|
+
return;
|
|
3761
|
+
}
|
|
3762
|
+
for (const entry of entries) {
|
|
3763
|
+
write(`${entry.updatedAt} ${entry.sessionId} ${entry.mainModel}
|
|
3764
|
+
`);
|
|
3765
|
+
}
|
|
3766
|
+
});
|
|
3767
|
+
sessions.command("show [session-id]").description("Show a summary of one session (the latest when id is omitted)").option("--json", "print the summary as JSON").action(async (sessionId, options) => {
|
|
3768
|
+
const document = await (await store()).load(sessionId);
|
|
3769
|
+
const summary = summarize(document);
|
|
3770
|
+
if (options.json) {
|
|
3771
|
+
write(`${JSON.stringify(summary, null, 2)}
|
|
3772
|
+
`);
|
|
3773
|
+
return;
|
|
3774
|
+
}
|
|
3775
|
+
write(renderSummary(summary));
|
|
3776
|
+
});
|
|
3777
|
+
sessions.command("delete <session-id>").description("Delete one saved session").action(async (sessionId) => {
|
|
3778
|
+
await (await store()).delete(sessionId);
|
|
3779
|
+
write(`Deleted session ${sessionId}.
|
|
3780
|
+
`);
|
|
3781
|
+
});
|
|
3782
|
+
sessions.command("export <session-id>").description("Export one session transcript to a file or stdout").option("--format <format>", "export format: md or json", "md").option("--output <path>", "write to a file instead of stdout").action(async (sessionId, options) => {
|
|
3783
|
+
const format = options.format === "json" ? "json" : options.format === "md" ? "md" : void 0;
|
|
3784
|
+
if (format === void 0) {
|
|
3785
|
+
throw new Error(`Unsupported export format: ${options.format}. Use md or json.`);
|
|
3786
|
+
}
|
|
3787
|
+
const document = await (await store()).load(sessionId);
|
|
3788
|
+
const body = format === "json" ? `${JSON.stringify(document, null, 2)}
|
|
3789
|
+
` : renderTranscript(document);
|
|
3790
|
+
if (options.output === void 0) {
|
|
3791
|
+
write(body);
|
|
3792
|
+
return;
|
|
3793
|
+
}
|
|
3794
|
+
const { writeFile } = await import("fs/promises");
|
|
3795
|
+
const { resolve: resolve2 } = await import("path");
|
|
3796
|
+
await writeFile(resolve2(options.output), body, "utf8");
|
|
3797
|
+
write(`Exported session ${sessionId} to ${resolve2(options.output)}
|
|
3798
|
+
`);
|
|
3799
|
+
});
|
|
3800
|
+
sessions.command("path").description("Print the sessions directory for the current workspace").action(() => write(`${join2(cwd(), ".flavor", "sessions")}
|
|
3801
|
+
`));
|
|
646
3802
|
}
|
|
3803
|
+
function summarize(document) {
|
|
3804
|
+
const turns = [...document.timeline.state.completed];
|
|
3805
|
+
if (document.timeline.state.active !== void 0) turns.push(document.timeline.state.active);
|
|
3806
|
+
return {
|
|
3807
|
+
sessionId: document.sessionId,
|
|
3808
|
+
workspace: document.workspace.path,
|
|
3809
|
+
createdAt: document.createdAt,
|
|
3810
|
+
updatedAt: document.updatedAt,
|
|
3811
|
+
mainModel: document.models.main,
|
|
3812
|
+
subagentModel: document.models.subagent,
|
|
3813
|
+
permissionMode: document.permissionMode,
|
|
3814
|
+
messageCount: document.conversation.messages.length,
|
|
3815
|
+
turnCount: turns.length,
|
|
3816
|
+
firstPrompt: turns[0]?.prompt ?? "",
|
|
3817
|
+
lastReply: turns.length > 0 ? turns[turns.length - 1]?.assistantText ?? "" : ""
|
|
3818
|
+
};
|
|
3819
|
+
}
|
|
3820
|
+
function renderSummary(summary) {
|
|
3821
|
+
const lines = [
|
|
3822
|
+
`Session ${summary.sessionId}`,
|
|
3823
|
+
` workspace: ${summary.workspace}`,
|
|
3824
|
+
` created: ${summary.createdAt}`,
|
|
3825
|
+
` updated: ${summary.updatedAt}`,
|
|
3826
|
+
` models: main=${summary.mainModel} subagent=${summary.subagentModel}`,
|
|
3827
|
+
` permission: ${summary.permissionMode}`,
|
|
3828
|
+
` messages: ${summary.messageCount} turns: ${summary.turnCount}`,
|
|
3829
|
+
` first prompt: ${snippet(summary.firstPrompt)}`,
|
|
3830
|
+
` last reply: ${snippet(summary.lastReply)}`
|
|
3831
|
+
];
|
|
3832
|
+
return `${lines.join("\n")}
|
|
3833
|
+
`;
|
|
3834
|
+
}
|
|
3835
|
+
function renderTranscript(document) {
|
|
3836
|
+
const turns = [...document.timeline.state.completed];
|
|
3837
|
+
if (document.timeline.state.active !== void 0) turns.push(document.timeline.state.active);
|
|
3838
|
+
const header = [
|
|
3839
|
+
`# Session ${document.sessionId}`,
|
|
3840
|
+
"",
|
|
3841
|
+
`- workspace: ${document.workspace.path}`,
|
|
3842
|
+
`- created: ${document.createdAt}`,
|
|
3843
|
+
`- updated: ${document.updatedAt}`,
|
|
3844
|
+
`- models: main=${document.models.main} subagent=${document.models.subagent}`,
|
|
3845
|
+
`- permission: ${document.permissionMode}`,
|
|
3846
|
+
""
|
|
3847
|
+
].join("\n");
|
|
3848
|
+
const body = turns.map((turn) => {
|
|
3849
|
+
const prompt = turn.prompt.trim().length > 0 ? turn.prompt.trim() : "(no prompt)";
|
|
3850
|
+
const reply = turn.assistantText.trim();
|
|
3851
|
+
return `## ${prompt}
|
|
647
3852
|
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
command: request.command,
|
|
659
|
-
args: [...request.args],
|
|
660
|
-
cwd: request.cwd,
|
|
661
|
-
...request.timeoutMs === void 0 ? {} : { timeoutMs: request.timeoutMs }
|
|
662
|
-
}, cancellation, DEFAULT_MAX_OUTPUT_BYTES);
|
|
663
|
-
}
|
|
664
|
-
async dispose() {
|
|
665
|
-
}
|
|
666
|
-
};
|
|
667
|
-
|
|
668
|
-
// src/eval/schema.ts
|
|
669
|
-
import { z } from "zod";
|
|
670
|
-
var EvaluationSpecSchema = z.object({
|
|
671
|
-
name: z.string().trim().min(1).max(256),
|
|
672
|
-
workspace: z.string().trim().min(1).max(32768),
|
|
673
|
-
prompt: z.string().trim().min(1).max(1e6),
|
|
674
|
-
verification: z.array(z.object({
|
|
675
|
-
command: z.string().trim().min(1).max(32768),
|
|
676
|
-
args: z.array(z.string()).max(1e3),
|
|
677
|
-
timeoutMs: z.number().int().positive().max(864e5).optional()
|
|
678
|
-
}).strict()).min(1).max(100),
|
|
679
|
-
maxTokens: z.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional()
|
|
680
|
-
}).strict();
|
|
3853
|
+
${reply.length > 0 ? reply : "_(no assistant text)_"}
|
|
3854
|
+
`;
|
|
3855
|
+
}).join("\n");
|
|
3856
|
+
return `${header}${body.length > 0 ? body : "_No turns recorded._\n"}`;
|
|
3857
|
+
}
|
|
3858
|
+
function snippet(text, max = 120) {
|
|
3859
|
+
const flat = text.replace(/\s+/gu, " ").trim();
|
|
3860
|
+
if (flat.length === 0) return "(empty)";
|
|
3861
|
+
return flat.length <= max ? flat : `${flat.slice(0, max - 1)}\u2026`;
|
|
3862
|
+
}
|
|
681
3863
|
|
|
682
|
-
// src/
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
const
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
const
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
3864
|
+
// src/config/cli.ts
|
|
3865
|
+
import { homedir as homedir2 } from "os";
|
|
3866
|
+
import { join as join3 } from "path";
|
|
3867
|
+
function registerConfigCommands(program2, dependencies = {}) {
|
|
3868
|
+
const cwd = dependencies.cwd ?? (() => process.cwd());
|
|
3869
|
+
const home = dependencies.home ?? homedir2;
|
|
3870
|
+
const write = dependencies.write ?? ((text) => process.stdout.write(text));
|
|
3871
|
+
const load = dependencies.load ?? (async ({ cwd: dir, home: homeDir }) => {
|
|
3872
|
+
const { loadConfig: loadConfig2 } = await import("./load-QK6CMLDF.js");
|
|
3873
|
+
return loadConfig2({ cwd: dir, home: homeDir });
|
|
3874
|
+
});
|
|
3875
|
+
const redactSecrets = dependencies.redact ?? (async (config2) => {
|
|
3876
|
+
const { redactConfig } = await import("./load-QK6CMLDF.js");
|
|
3877
|
+
return redactConfig(config2);
|
|
3878
|
+
});
|
|
3879
|
+
const setValue = dependencies.setValue ?? (async (dir, homeDir, key, value) => {
|
|
3880
|
+
const { setProjectConfigValue } = await import("./load-QK6CMLDF.js");
|
|
3881
|
+
return setProjectConfigValue(dir, homeDir, key, value);
|
|
3882
|
+
});
|
|
3883
|
+
const unsetValue = dependencies.unsetValue ?? (async (dir, key) => {
|
|
3884
|
+
const { unsetProjectConfigValue } = await import("./load-QK6CMLDF.js");
|
|
3885
|
+
return unsetProjectConfigValue(dir, key);
|
|
3886
|
+
});
|
|
3887
|
+
const config = program2.command("config").description("Inspect and edit Flavor configuration");
|
|
3888
|
+
config.command("list", { isDefault: true }).description("Print the effective (redacted) configuration").option("--json", "print only the redacted JSON object").option("--sources", "list the configuration files that were merged").action(async (options) => {
|
|
3889
|
+
const loaded = await load({ cwd: cwd(), home: home() });
|
|
3890
|
+
const redacted = await redactSecrets(loaded.config);
|
|
3891
|
+
if (options.json) {
|
|
3892
|
+
write(`${JSON.stringify(redacted, null, 2)}
|
|
3893
|
+
`);
|
|
3894
|
+
return;
|
|
699
3895
|
}
|
|
3896
|
+
if (options.sources) {
|
|
3897
|
+
if (loaded.sources.length === 0) write("No configuration files found; using defaults.\n");
|
|
3898
|
+
else for (const source of loaded.sources) write(`${source}
|
|
3899
|
+
`);
|
|
3900
|
+
return;
|
|
3901
|
+
}
|
|
3902
|
+
write(`Sources: ${loaded.sources.length > 0 ? loaded.sources.join(", ") : "(defaults only)"}
|
|
3903
|
+
`);
|
|
3904
|
+
write(`${JSON.stringify(redacted, null, 2)}
|
|
3905
|
+
`);
|
|
700
3906
|
});
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
await
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
3907
|
+
config.command("get <key>").description("Print one configuration value by dot path, e.g. context.windowTokens").action(async (key) => {
|
|
3908
|
+
const segments = configPathSegments(key);
|
|
3909
|
+
const loaded = await load({ cwd: cwd(), home: home() });
|
|
3910
|
+
const redacted = await redactSecrets(loaded.config);
|
|
3911
|
+
const found = dig(redacted, segments);
|
|
3912
|
+
if (!found.found) throw new Error(`No such configuration key: ${key}`);
|
|
3913
|
+
const value = found.value;
|
|
3914
|
+
write(typeof value === "string" ? `${value}
|
|
3915
|
+
` : `${JSON.stringify(value, null, 2)}
|
|
3916
|
+
`);
|
|
3917
|
+
});
|
|
3918
|
+
config.command("set <key> <value>").description('Set one project configuration value (JSON literals are parsed, e.g. 50, true, ["a"]').action(async (key, rawValue) => {
|
|
3919
|
+
const path2 = await setValue(cwd(), home(), key, parseConfigValue(rawValue));
|
|
3920
|
+
write(`Set ${key} in ${path2}
|
|
3921
|
+
`);
|
|
3922
|
+
});
|
|
3923
|
+
config.command("unset <key>").description("Remove one key from the project configuration").action(async (key) => {
|
|
3924
|
+
const path2 = await unsetValue(cwd(), key);
|
|
3925
|
+
write(`Removed ${key} from ${path2}
|
|
3926
|
+
`);
|
|
3927
|
+
});
|
|
3928
|
+
config.command("path").description("Print the project and global configuration paths").action(() => {
|
|
3929
|
+
write(`project: ${join3(cwd(), ".flavor", "flavor.json")}
|
|
3930
|
+
`);
|
|
3931
|
+
write(`global: ${join3(home(), ".flavor-code", "flavor.json")}
|
|
3932
|
+
`);
|
|
3933
|
+
});
|
|
3934
|
+
}
|
|
3935
|
+
function dig(root, segments) {
|
|
3936
|
+
let cursor = root;
|
|
3937
|
+
for (const segment of segments) {
|
|
3938
|
+
if (typeof cursor === "object" && cursor !== null && !Array.isArray(cursor) && segment in cursor) {
|
|
3939
|
+
cursor = cursor[segment];
|
|
3940
|
+
} else {
|
|
3941
|
+
return { found: false };
|
|
3942
|
+
}
|
|
723
3943
|
}
|
|
724
|
-
|
|
725
|
-
const withinBudget = spec.maxTokens === void 0 || total <= spec.maxTokens;
|
|
726
|
-
return {
|
|
727
|
-
name: spec.name,
|
|
728
|
-
workspace: spec.workspace,
|
|
729
|
-
passed: withinBudget && verification.every((item) => item.passed),
|
|
730
|
-
durationMs: Math.max(0, now() - started),
|
|
731
|
-
tokens: { input, output, total, withinBudget },
|
|
732
|
-
verification
|
|
733
|
-
};
|
|
3944
|
+
return { found: true, value: cursor };
|
|
734
3945
|
}
|
|
735
|
-
|
|
736
|
-
// src/eval/cli.ts
|
|
737
|
-
async function runEvaluationFile(path, outputPath) {
|
|
738
|
-
const specPath = resolve2(path);
|
|
739
|
-
const parsed = EvaluationSpecSchema.parse(JSON.parse(await readFile2(specPath, "utf8")));
|
|
740
|
-
const workspace = resolve2(dirname(specPath), parsed.workspace);
|
|
741
|
-
const spec = {
|
|
742
|
-
name: parsed.name,
|
|
743
|
-
prompt: parsed.prompt,
|
|
744
|
-
workspace,
|
|
745
|
-
verification: parsed.verification.map((step) => ({
|
|
746
|
-
command: step.command,
|
|
747
|
-
args: step.args,
|
|
748
|
-
...step.timeoutMs === void 0 ? {} : { timeoutMs: step.timeoutMs }
|
|
749
|
-
})),
|
|
750
|
-
...parsed.maxTokens === void 0 ? {} : { maxTokens: parsed.maxTokens }
|
|
751
|
-
};
|
|
752
|
-
const configured = await import("./load-UPOG3XQR.js").then(({ loadConfig: loadConfig2 }) => loadConfig2({ cwd: workspace, home: process.env.USERPROFILE ?? process.env.HOME ?? workspace }));
|
|
753
|
-
const environment = createExecutionEnvironment(workspace, configured.config.execution) ?? new LocalExecutionEnvironment();
|
|
754
|
-
let report;
|
|
3946
|
+
function parseConfigValue(raw) {
|
|
755
3947
|
try {
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
home: process.env.USERPROFILE ?? process.env.HOME ?? workspace,
|
|
760
|
-
approvalPolicy: "deny"
|
|
761
|
-
}),
|
|
762
|
-
executionEnvironment: environment
|
|
763
|
-
});
|
|
764
|
-
} finally {
|
|
765
|
-
await environment.dispose();
|
|
3948
|
+
return JSON.parse(raw);
|
|
3949
|
+
} catch {
|
|
3950
|
+
return raw;
|
|
766
3951
|
}
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
3952
|
+
}
|
|
3953
|
+
|
|
3954
|
+
// src/usage/cli.ts
|
|
3955
|
+
import { readFile } from "fs/promises";
|
|
3956
|
+
function registerUsageCommands(program2, dependencies = {}) {
|
|
3957
|
+
const write = dependencies.write ?? ((text) => process.stdout.write(text));
|
|
3958
|
+
const read = dependencies.read ?? (async () => {
|
|
3959
|
+
const { usageLogPath } = await import("./log-ATFIPRNU.js");
|
|
3960
|
+
try {
|
|
3961
|
+
return await readFile(usageLogPath(), "utf8");
|
|
3962
|
+
} catch (error) {
|
|
3963
|
+
if (typeof error === "object" && error !== null && error.code === "ENOENT") return "";
|
|
3964
|
+
throw error;
|
|
3965
|
+
}
|
|
3966
|
+
});
|
|
3967
|
+
program2.command("usage").description("Summarize token and cache usage for the current session").option("--json", "print the summary as JSON").option("--path", "print the usage log path and exit").action(async (options) => {
|
|
3968
|
+
if (options.path) {
|
|
3969
|
+
const { usageLogPath } = await import("./log-ATFIPRNU.js");
|
|
3970
|
+
write(`${usageLogPath()}
|
|
3971
|
+
`);
|
|
3972
|
+
return;
|
|
3973
|
+
}
|
|
3974
|
+
const raw = await read();
|
|
3975
|
+
const { parseUsageEntries, summarizeUsage, formatUsageSummary } = await import("./usage-summary-G5FBOJLK.js");
|
|
3976
|
+
const summary = summarizeUsage(parseUsageEntries(raw));
|
|
3977
|
+
if (options.json) write(`${JSON.stringify(summary, null, 2)}
|
|
3978
|
+
`);
|
|
3979
|
+
else write(`${formatUsageSummary(summary)}
|
|
3980
|
+
`);
|
|
3981
|
+
});
|
|
772
3982
|
}
|
|
773
3983
|
|
|
774
3984
|
// src/cli.tsx
|
|
3985
|
+
var OUTPUT_FORMATS = ["text", "json", "stream-json"];
|
|
3986
|
+
var PRINT_PERMISSION_MODES = ["default", "plan", "acceptEdits", "bypassPermissions"];
|
|
775
3987
|
function createProgram(dependencies = {}) {
|
|
776
|
-
const
|
|
777
|
-
|
|
778
|
-
const cwd = directory ?
|
|
3988
|
+
const program2 = new Command().name("flavor").description("Interactive coding agent").version(packageVersion()).option("-p, --print [prompt]", "run one prompt without the interactive UI (prompt may come from stdin)").option("--output-format <format>", `--print output format: ${OUTPUT_FORMATS.join(", ")}`, "text").option("--permission-mode <mode>", `--print permission mode: ${PRINT_PERMISSION_MODES.join(", ")}`).option("--allowed-tools <patterns>", 'comma-separated tools auto-approved in --print mode, e.g. "Read,Shell(npm test:*)"').option("--model <provider:model>", "override the main model for this run").option("--resume [session-id]", "resume a saved session (latest when id is omitted)").option("--mode <mode>", "runtime mode: interactive or rpc").option("--workspace <path>", "workspace path (RPC mode)").option("--rpc-approvals", "allow an RPC client to resolve interactive tool approvals").option("--rpc-streamed-writes", "stream proposed file writes to an RPC client before committing them").option("--trace <path>", "write a redacted JSONL execution trace").option("--pal-name <alias>", "name this interactive Flavor instance for /pals and /chat").addOption(new Option("--memory-restart").hideHelp()).addOption(new Option("--pals-broker <address>").hideHelp());
|
|
3989
|
+
program2.command("init [directory]").description("Initialize Flavor project files in a directory (defaults to cwd)").action(async (directory) => {
|
|
3990
|
+
const cwd = directory ? resolve(directory) : process.cwd();
|
|
779
3991
|
try {
|
|
3992
|
+
const { initializeFlavor } = await import("./project-3QXE22TG.js");
|
|
780
3993
|
const result = await initializeFlavor(cwd);
|
|
781
3994
|
process.stdout.write(`${result.created ? "Created" : "Updated"} ${result.path}
|
|
782
3995
|
`);
|
|
@@ -786,9 +3999,10 @@ function createProgram(dependencies = {}) {
|
|
|
786
3999
|
process.exitCode = 1;
|
|
787
4000
|
}
|
|
788
4001
|
});
|
|
789
|
-
|
|
4002
|
+
program2.command("update").description("Update the globally installed flavor-code package to the latest npm release").action(async () => {
|
|
4003
|
+
const { NPM_PACKAGE_NAME } = await import("./check-CSKTV4O2.js");
|
|
790
4004
|
try {
|
|
791
|
-
const outcome = await (dependencies.runUpdate ?? runUpdate)();
|
|
4005
|
+
const outcome = await (dependencies.runUpdate ?? (await import("./apply-WOW3QU5I.js")).runUpdate)();
|
|
792
4006
|
switch (outcome.status) {
|
|
793
4007
|
case "up-to-date":
|
|
794
4008
|
process.stdout.write(`${NPM_PACKAGE_NAME} is already up to date (v${outcome.current}).
|
|
@@ -814,14 +4028,15 @@ function createProgram(dependencies = {}) {
|
|
|
814
4028
|
process.exitCode = 1;
|
|
815
4029
|
}
|
|
816
4030
|
});
|
|
817
|
-
|
|
4031
|
+
program2.command("doctor [directory]").description("Diagnose the local Flavor runtime, configuration, tools, plugins, and npm access").option("--json", "print the report as JSON").action(async (directory, command) => {
|
|
818
4032
|
try {
|
|
819
|
-
const
|
|
820
|
-
|
|
4033
|
+
const doctor = await import("./doctor-OHCGK52S.js");
|
|
4034
|
+
const report = await (dependencies.runDoctor ?? doctor.runDoctor)({
|
|
4035
|
+
workspace: resolve(directory ?? process.cwd()),
|
|
821
4036
|
home: homedir3()
|
|
822
4037
|
});
|
|
823
4038
|
process.stdout.write(command.json ? `${JSON.stringify(report, null, 2)}
|
|
824
|
-
` : formatDoctorReport(report));
|
|
4039
|
+
` : doctor.formatDoctorReport(report));
|
|
825
4040
|
if (!report.ok) process.exitCode = 1;
|
|
826
4041
|
} catch (error) {
|
|
827
4042
|
process.stderr.write(`doctor: ${safeError(error)}
|
|
@@ -829,9 +4044,10 @@ function createProgram(dependencies = {}) {
|
|
|
829
4044
|
process.exitCode = 1;
|
|
830
4045
|
}
|
|
831
4046
|
});
|
|
832
|
-
const skills =
|
|
4047
|
+
const skills = program2.command("skills").description("List and enable or disable project skills");
|
|
833
4048
|
skills.command("list", { isDefault: true }).description("List skills visible in the current project").action(async () => {
|
|
834
4049
|
try {
|
|
4050
|
+
const { SkillManager } = await import("./manager-5SI4MPES.js");
|
|
835
4051
|
const entries = await new SkillManager({ workspace: process.cwd(), home: homedir3() }).list();
|
|
836
4052
|
if (entries.length === 0) process.stdout.write("No skills found.\n");
|
|
837
4053
|
else for (const skill of entries) {
|
|
@@ -848,6 +4064,7 @@ function createProgram(dependencies = {}) {
|
|
|
848
4064
|
const action = enabled ? "enable" : "disable";
|
|
849
4065
|
skills.command(`${action} <name>`).description(`${enabled ? "Enable" : "Disable"} a skill for this project`).action(async (name) => {
|
|
850
4066
|
try {
|
|
4067
|
+
const { SkillManager } = await import("./manager-5SI4MPES.js");
|
|
851
4068
|
await new SkillManager({ workspace: process.cwd(), home: homedir3() }).setEnabled(name, enabled);
|
|
852
4069
|
process.stdout.write(`${enabled ? "Enabled" : "Disabled"} ${name}.
|
|
853
4070
|
`);
|
|
@@ -858,16 +4075,21 @@ function createProgram(dependencies = {}) {
|
|
|
858
4075
|
}
|
|
859
4076
|
});
|
|
860
4077
|
}
|
|
861
|
-
registerMemoryCommands(
|
|
862
|
-
registerMcpCommands(
|
|
863
|
-
|
|
4078
|
+
registerMemoryCommands(program2);
|
|
4079
|
+
registerMcpCommands(program2);
|
|
4080
|
+
registerSessionCommands(program2);
|
|
4081
|
+
registerConfigCommands(program2);
|
|
4082
|
+
registerUsageCommands(program2);
|
|
4083
|
+
program2.command("eval <spec>").option("--output <path>", "write the JSON report to a file").description("run a repeatable coding-agent evaluation").action(async (spec, command) => {
|
|
4084
|
+
const { runEvaluationFile } = await import("./cli-3MF6EL2H.js");
|
|
864
4085
|
process.exitCode = await runEvaluationFile(spec, command.output);
|
|
865
4086
|
});
|
|
866
|
-
|
|
4087
|
+
program2.action(async (options) => {
|
|
867
4088
|
if (options.palsBroker !== void 0) {
|
|
868
4089
|
if (!isLocalPalBrokerAddress(options.palsBroker, process.platform)) {
|
|
869
4090
|
throw new Error("Invalid local pals broker address");
|
|
870
4091
|
}
|
|
4092
|
+
const { runPalBroker } = await import("./broker-cli-X5H46FZV.js");
|
|
871
4093
|
const broker = await (dependencies.runBroker ?? runPalBroker)({ address: options.palsBroker });
|
|
872
4094
|
await broker.closed;
|
|
873
4095
|
return;
|
|
@@ -875,9 +4097,9 @@ function createProgram(dependencies = {}) {
|
|
|
875
4097
|
const resumeSession = options.resume === true ? true : typeof options.resume === "string" ? options.resume : void 0;
|
|
876
4098
|
if (options.mode === "rpc") {
|
|
877
4099
|
process.exitCode = await runRpcMode({
|
|
878
|
-
workspace:
|
|
4100
|
+
workspace: resolve(options.workspace ?? process.cwd()),
|
|
879
4101
|
...resumeSession === void 0 ? {} : { resumeSession },
|
|
880
|
-
...options.trace === void 0 ? {} : { trace:
|
|
4102
|
+
...options.trace === void 0 ? {} : { trace: resolve(options.trace) },
|
|
881
4103
|
interactiveApprovals: options.rpcApprovals === true,
|
|
882
4104
|
streamedWrites: options.rpcStreamedWrites === true
|
|
883
4105
|
});
|
|
@@ -890,7 +4112,36 @@ function createProgram(dependencies = {}) {
|
|
|
890
4112
|
return;
|
|
891
4113
|
}
|
|
892
4114
|
if (options.print !== void 0) {
|
|
893
|
-
|
|
4115
|
+
const outputFormat = options.outputFormat ?? "text";
|
|
4116
|
+
if (!OUTPUT_FORMATS.includes(outputFormat)) {
|
|
4117
|
+
process.stderr.write(`Unsupported output format: ${outputFormat}
|
|
4118
|
+
`);
|
|
4119
|
+
process.exitCode = 2;
|
|
4120
|
+
return;
|
|
4121
|
+
}
|
|
4122
|
+
let permissionMode;
|
|
4123
|
+
if (options.permissionMode !== void 0) {
|
|
4124
|
+
if (!PRINT_PERMISSION_MODES.includes(options.permissionMode)) {
|
|
4125
|
+
process.stderr.write(`Unsupported permission mode: ${options.permissionMode}
|
|
4126
|
+
`);
|
|
4127
|
+
process.exitCode = 2;
|
|
4128
|
+
return;
|
|
4129
|
+
}
|
|
4130
|
+
permissionMode = options.permissionMode;
|
|
4131
|
+
}
|
|
4132
|
+
const prompt = typeof options.print === "string" ? options.print : await readStdinPrompt();
|
|
4133
|
+
if (prompt.trim().length === 0) {
|
|
4134
|
+
process.stderr.write("No prompt provided. Pass --print <prompt> or pipe text via stdin.\n");
|
|
4135
|
+
process.exitCode = 2;
|
|
4136
|
+
return;
|
|
4137
|
+
}
|
|
4138
|
+
const allowedTools = options.allowedTools === void 0 ? void 0 : options.allowedTools.split(",").map((pattern) => pattern.trim()).filter((pattern) => pattern.length > 0);
|
|
4139
|
+
process.exitCode = await runPrint(prompt, {}, resumeSession, options.memoryRestart === true, {
|
|
4140
|
+
outputFormat,
|
|
4141
|
+
...permissionMode === void 0 ? {} : { permissionMode },
|
|
4142
|
+
...allowedTools === void 0 ? {} : { allowedTools },
|
|
4143
|
+
...options.model === void 0 ? {} : { model: options.model }
|
|
4144
|
+
});
|
|
894
4145
|
return;
|
|
895
4146
|
}
|
|
896
4147
|
if (!(dependencies.isTTY?.() ?? process.stdin.isTTY)) {
|
|
@@ -904,7 +4155,7 @@ function createProgram(dependencies = {}) {
|
|
|
904
4155
|
workspace: process.cwd(),
|
|
905
4156
|
home: homedir3(),
|
|
906
4157
|
...resumeSession === void 0 ? {} : { resumeSession },
|
|
907
|
-
instanceId: (dependencies.randomUUID ??
|
|
4158
|
+
instanceId: (dependencies.randomUUID ?? randomUUID)(),
|
|
908
4159
|
...palAlias === void 0 ? {} : { palAlias }
|
|
909
4160
|
};
|
|
910
4161
|
if (dependencies.runInteractive !== void 0) {
|
|
@@ -913,25 +4164,32 @@ function createProgram(dependencies = {}) {
|
|
|
913
4164
|
}
|
|
914
4165
|
await runInteractiveCli(props);
|
|
915
4166
|
});
|
|
916
|
-
return
|
|
4167
|
+
return program2;
|
|
917
4168
|
}
|
|
918
4169
|
async function runInteractiveCli(props) {
|
|
919
4170
|
const disposeUserTimingSweeper = installUiUserTimingSweeper();
|
|
4171
|
+
let endedSessionId;
|
|
920
4172
|
try {
|
|
921
|
-
const [{ render, AlternateScreen }, {
|
|
922
|
-
import("./claude-ink-
|
|
923
|
-
import("react"),
|
|
924
|
-
import("./app-
|
|
4173
|
+
const [{ render, AlternateScreen }, { default: React }, { App }] = await Promise.all([
|
|
4174
|
+
import("./claude-ink-BE56DB6N.js"),
|
|
4175
|
+
import("./react-M6JGXSJZ.js"),
|
|
4176
|
+
import("./app-G35YBHPR.js")
|
|
925
4177
|
]);
|
|
926
|
-
const instance = await render(createElement(
|
|
4178
|
+
const instance = await render(React.createElement(
|
|
927
4179
|
AlternateScreen,
|
|
928
4180
|
{ mouseTracking: true },
|
|
929
|
-
createElement(App, props)
|
|
4181
|
+
React.createElement(App, { ...props, onSessionEnd: (sessionId) => {
|
|
4182
|
+
endedSessionId = sessionId;
|
|
4183
|
+
} })
|
|
930
4184
|
), { exitOnCtrlC: false });
|
|
931
4185
|
await instance.waitUntilExit();
|
|
932
4186
|
} finally {
|
|
933
4187
|
disposeUserTimingSweeper();
|
|
934
4188
|
}
|
|
4189
|
+
if (endedSessionId !== void 0) {
|
|
4190
|
+
process.stdout.write(`Resume later with: ${source_default.cyan(`flavor --resume ${endedSessionId}`)}
|
|
4191
|
+
`);
|
|
4192
|
+
}
|
|
935
4193
|
}
|
|
936
4194
|
function parsePalAlias(value) {
|
|
937
4195
|
const alias = value.trim();
|
|
@@ -950,6 +4208,12 @@ function isLocalPalBrokerAddress(address, platform) {
|
|
|
950
4208
|
return posix.normalize(address) === address && posix.basename(address) === "pals-v1.sock" && posix.dirname(address) !== "/";
|
|
951
4209
|
}
|
|
952
4210
|
async function runRpcMode(options) {
|
|
4211
|
+
const [{ FlavorRpcServer }, { RpcWriteStreamBridge }, { TraceRecorder: Recorder }, { createProductionRuntime }] = await Promise.all([
|
|
4212
|
+
import("./server-2KLKPHPL.js"),
|
|
4213
|
+
import("./write-stream-CGD57URC.js"),
|
|
4214
|
+
import("./recorder-FAGJJH3N.js"),
|
|
4215
|
+
import("./production-6DIZ6YLQ.js")
|
|
4216
|
+
]);
|
|
953
4217
|
let recorder;
|
|
954
4218
|
try {
|
|
955
4219
|
const server = new FlavorRpcServer({
|
|
@@ -977,7 +4241,7 @@ async function runRpcMode(options) {
|
|
|
977
4241
|
activeRuntime = runtime;
|
|
978
4242
|
Object.defineProperty(runtime, "rpcApprovals", { value: options.interactiveApprovals === true, enumerable: true });
|
|
979
4243
|
if (streamedWrites !== void 0) Object.defineProperty(runtime, "rpcWrites", { value: streamedWrites, enumerable: true });
|
|
980
|
-
if (options.trace !== void 0) recorder = new
|
|
4244
|
+
if (options.trace !== void 0) recorder = new Recorder({
|
|
981
4245
|
path: options.trace,
|
|
982
4246
|
sessionId: runtime.sessionId
|
|
983
4247
|
});
|
|
@@ -998,34 +4262,104 @@ async function runRpcMode(options) {
|
|
|
998
4262
|
function setInteractiveProcessTitle(target = process) {
|
|
999
4263
|
target.title = "Flavor Code";
|
|
1000
4264
|
}
|
|
1001
|
-
async function
|
|
4265
|
+
async function readStdinPrompt() {
|
|
4266
|
+
if (process.stdin.isTTY === true) return "";
|
|
4267
|
+
const chunks = [];
|
|
4268
|
+
for await (const chunk of process.stdin) chunks.push(chunk);
|
|
4269
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
4270
|
+
}
|
|
4271
|
+
function createPrintReporter(format, stdout, stderr, onError) {
|
|
4272
|
+
let text = "";
|
|
4273
|
+
let usage;
|
|
4274
|
+
const errors = [];
|
|
4275
|
+
let sessionId;
|
|
4276
|
+
const safeJson = (value) => JSON.stringify(value, (_key, item) => item instanceof Error ? { name: item.name, message: item.message } : item) ?? "null";
|
|
4277
|
+
const writeLine = (value) => stdout(`${safeJson(value)}
|
|
4278
|
+
`);
|
|
4279
|
+
const event = (incoming) => {
|
|
4280
|
+
if (incoming.type === "text") text += incoming.text;
|
|
4281
|
+
else if (incoming.type === "usage") {
|
|
4282
|
+
usage = {
|
|
4283
|
+
inputTokens: incoming.totalInputTokens,
|
|
4284
|
+
outputTokens: incoming.totalOutputTokens,
|
|
4285
|
+
...incoming.cacheReadTokens === void 0 ? {} : { cacheReadTokens: incoming.cacheReadTokens },
|
|
4286
|
+
...incoming.cacheCreationTokens === void 0 ? {} : { cacheCreationTokens: incoming.cacheCreationTokens }
|
|
4287
|
+
};
|
|
4288
|
+
} else if (incoming.type === "error") {
|
|
4289
|
+
errors.push(`${incoming.error.code}: ${incoming.error.message}`);
|
|
4290
|
+
onError?.();
|
|
4291
|
+
}
|
|
4292
|
+
if (format === "text") {
|
|
4293
|
+
if (incoming.type === "text") stdout(incoming.text);
|
|
4294
|
+
else if (incoming.type === "notice") stdout(`${incoming.message}
|
|
4295
|
+
`);
|
|
4296
|
+
else if (incoming.type === "tasks") {
|
|
4297
|
+
for (const line of staticTaskLines(incoming.snapshot)) stdout(`${line}
|
|
4298
|
+
`);
|
|
4299
|
+
} else if (incoming.type === "error") stderr(`${incoming.error.code}: ${incoming.error.message}
|
|
4300
|
+
`);
|
|
4301
|
+
return;
|
|
4302
|
+
}
|
|
4303
|
+
if (format === "stream-json") writeLine(incoming);
|
|
4304
|
+
};
|
|
4305
|
+
const startupError = (detail) => {
|
|
4306
|
+
errors.push(detail);
|
|
4307
|
+
if (format === "text") stderr(`${detail}
|
|
4308
|
+
`);
|
|
4309
|
+
else if (format === "stream-json") writeLine({ type: "error", error: { code: "startup", message: detail } });
|
|
4310
|
+
};
|
|
4311
|
+
const finish = (input) => {
|
|
4312
|
+
sessionId = input.sessionId ?? sessionId;
|
|
4313
|
+
if (format === "json") {
|
|
4314
|
+
writeLine({
|
|
4315
|
+
type: "result",
|
|
4316
|
+
subtype: input.code === 0 ? "success" : "error",
|
|
4317
|
+
...sessionId === void 0 ? {} : { sessionId },
|
|
4318
|
+
result: text,
|
|
4319
|
+
...usage === void 0 ? {} : { usage },
|
|
4320
|
+
...errors.length === 0 ? {} : { errors },
|
|
4321
|
+
exitCode: input.code
|
|
4322
|
+
});
|
|
4323
|
+
return;
|
|
4324
|
+
}
|
|
4325
|
+
if (format === "stream-json") {
|
|
4326
|
+
writeLine({
|
|
4327
|
+
type: "result",
|
|
4328
|
+
subtype: input.code === 0 ? "success" : "error",
|
|
4329
|
+
...sessionId === void 0 ? {} : { sessionId },
|
|
4330
|
+
...usage === void 0 ? {} : { usage },
|
|
4331
|
+
exitCode: input.code
|
|
4332
|
+
});
|
|
4333
|
+
return;
|
|
4334
|
+
}
|
|
4335
|
+
if (input.code === 0 && !input.restarting) stdout("\n");
|
|
4336
|
+
};
|
|
4337
|
+
return { event, startupError, finish };
|
|
4338
|
+
}
|
|
4339
|
+
async function runPrint(prompt, dependencies = {}, resumeSession, memoryRestart = false, printOptions = {}) {
|
|
1002
4340
|
let code = 0;
|
|
1003
4341
|
let runtime;
|
|
1004
4342
|
const stdout = dependencies.stdout ?? ((text) => process.stdout.write(text));
|
|
1005
4343
|
const stderr = dependencies.stderr ?? ((text) => process.stderr.write(text));
|
|
4344
|
+
const format = printOptions.outputFormat ?? "text";
|
|
4345
|
+
const reporter = createPrintReporter(format, stdout, stderr, () => {
|
|
4346
|
+
code = 1;
|
|
4347
|
+
});
|
|
1006
4348
|
try {
|
|
1007
|
-
|
|
4349
|
+
const createRuntime = dependencies.createRuntime ?? (await import("./production-6DIZ6YLQ.js")).createProductionRuntime;
|
|
4350
|
+
runtime = await createRuntime({
|
|
1008
4351
|
workspace: process.cwd(),
|
|
1009
4352
|
home: homedir3(),
|
|
1010
4353
|
approvalPolicy: "deny",
|
|
1011
4354
|
...resumeSession === void 0 ? {} : { resumeSession },
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
else if (event.type === "tasks") {
|
|
1017
|
-
for (const line of staticTaskLines(event.snapshot)) stdout(`${line}
|
|
1018
|
-
`);
|
|
1019
|
-
} else if (event.type === "error") {
|
|
1020
|
-
stderr(`${event.error.code}: ${event.error.message}
|
|
1021
|
-
`);
|
|
1022
|
-
code = 1;
|
|
1023
|
-
}
|
|
1024
|
-
}
|
|
4355
|
+
...printOptions.permissionMode === void 0 ? {} : { permissionMode: printOptions.permissionMode },
|
|
4356
|
+
...printOptions.allowedTools === void 0 ? {} : { headlessToolAllowlist: printOptions.allowedTools },
|
|
4357
|
+
...printOptions.model === void 0 ? {} : { modelOverride: printOptions.model },
|
|
4358
|
+
output: reporter.event
|
|
1025
4359
|
});
|
|
1026
4360
|
} catch (error) {
|
|
1027
|
-
|
|
1028
|
-
|
|
4361
|
+
reporter.startupError(`startup: ${safeError(error)}`);
|
|
4362
|
+
reporter.finish({ code: 2, restarting: false });
|
|
1029
4363
|
return 2;
|
|
1030
4364
|
}
|
|
1031
4365
|
try {
|
|
@@ -1036,28 +4370,26 @@ async function runPrint(prompt, dependencies = {}, resumeSession, memoryRestart
|
|
|
1036
4370
|
await runtime.session.submit(prompt);
|
|
1037
4371
|
}
|
|
1038
4372
|
} catch (error) {
|
|
1039
|
-
|
|
1040
|
-
`);
|
|
4373
|
+
reporter.startupError(`runtime: ${safeError(error)}`);
|
|
1041
4374
|
code = 1;
|
|
1042
4375
|
} finally {
|
|
1043
4376
|
try {
|
|
1044
4377
|
await runtime.session.close();
|
|
1045
4378
|
} catch (error) {
|
|
1046
|
-
|
|
1047
|
-
`);
|
|
4379
|
+
reporter.startupError(`runtime: ${safeError(error)}`);
|
|
1048
4380
|
code = 1;
|
|
1049
4381
|
}
|
|
1050
4382
|
try {
|
|
1051
4383
|
await runtime.dispose();
|
|
1052
4384
|
} catch (error) {
|
|
1053
|
-
|
|
1054
|
-
`);
|
|
4385
|
+
reporter.startupError(`runtime: ${safeError(error)}`);
|
|
1055
4386
|
code = 1;
|
|
1056
4387
|
}
|
|
1057
4388
|
}
|
|
1058
4389
|
const restarting = process.exitCode === MEMORY_RESTART_EXIT_CODE;
|
|
1059
|
-
|
|
1060
|
-
|
|
4390
|
+
const finalCode = restarting ? MEMORY_RESTART_EXIT_CODE : code;
|
|
4391
|
+
reporter.finish({ sessionId: runtime.sessionId, code: finalCode, restarting });
|
|
4392
|
+
return finalCode;
|
|
1061
4393
|
}
|
|
1062
4394
|
function safeError(error) {
|
|
1063
4395
|
return redactErrorText(message(error));
|