@nudojs/cli 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/dist/{chunk-3HCPXPEW.js → chunk-YDM4HHQ4.js} +1783 -1421
  2. package/dist/evaluator-api.d.ts +12 -1
  3. package/dist/evaluator-api.js +52 -2
  4. package/dist/index.d.ts +1 -2
  5. package/dist/index.js +366 -3572
  6. package/package.json +23 -11
  7. package/CHANGELOG.md +0 -41
  8. package/examples/real-world.js +0 -66
  9. package/examples/validate-real-world.ts +0 -160
  10. package/src/__tests__/builtin-advanced.test.ts +0 -292
  11. package/src/__tests__/builtin-api.test.ts +0 -308
  12. package/src/__tests__/builtin-functions.test.ts +0 -313
  13. package/src/__tests__/builtin-map.test.ts +0 -129
  14. package/src/__tests__/builtin-promise.test.ts +0 -150
  15. package/src/__tests__/builtin-regexp.test.ts +0 -133
  16. package/src/__tests__/builtin-set.test.ts +0 -163
  17. package/src/__tests__/builtin-url.test.ts +0 -256
  18. package/src/__tests__/builtin-web.test.ts +0 -340
  19. package/src/__tests__/combination-scenarios.test.ts +0 -384
  20. package/src/__tests__/edge-cases.test.ts +0 -749
  21. package/src/__tests__/evaluator-loops.test.ts +0 -283
  22. package/src/__tests__/evaluator-nullish-coalescing.test.ts +0 -86
  23. package/src/__tests__/evaluator-optional-chaining.test.ts +0 -37
  24. package/src/__tests__/evaluator-phase2.test.ts +0 -564
  25. package/src/__tests__/evaluator-phase3.test.ts +0 -864
  26. package/src/__tests__/evaluator-refined.test.ts +0 -121
  27. package/src/__tests__/evaluator-string-methods.test.ts +0 -151
  28. package/src/__tests__/evaluator.test.ts +0 -943
  29. package/src/__tests__/mock-arrow-function.test.ts +0 -169
  30. package/src/__tests__/mock-comparison.test.ts +0 -221
  31. package/src/__tests__/mock-comprehensive.test.ts +0 -250
  32. package/src/__tests__/mock-final-integration.test.ts +0 -263
  33. package/src/__tests__/mock-helpers.test.ts +0 -174
  34. package/src/__tests__/mock-realworld.test.ts +0 -191
  35. package/src/__tests__/mock-rest-debug.test.ts +0 -110
  36. package/src/__tests__/mock-rest-edge.test.ts +0 -176
  37. package/src/__tests__/mock-sinon-runtime.test.ts +0 -168
  38. package/src/__tests__/narrowing-discriminated.test.ts +0 -35
  39. package/src/__tests__/narrowing-in-operator.test.ts +0 -56
  40. package/src/__tests__/narrowing-switch.test.ts +0 -56
  41. package/src/__tests__/narrowing-truthiness.test.ts +0 -52
  42. package/src/__tests__/narrowing.test.ts +0 -82
  43. package/src/__tests__/nudo-mock-syntax.test.ts +0 -245
  44. package/src/__tests__/realworld-patterns.test.ts +0 -430
  45. package/src/__tests__/syntax-sugar.test.ts +0 -345
  46. package/src/builtins/builtin-intl.ts +0 -17
  47. package/src/builtins/builtin-map.ts +0 -174
  48. package/src/builtins/builtin-promise.ts +0 -116
  49. package/src/builtins/builtin-reflect.ts +0 -30
  50. package/src/builtins/builtin-regexp.ts +0 -34
  51. package/src/builtins/builtin-set.ts +0 -131
  52. package/src/builtins/builtin-symbol.ts +0 -16
  53. package/src/builtins/builtin-url.ts +0 -58
  54. package/src/builtins/builtin-weak.ts +0 -22
  55. package/src/builtins/builtin-web.ts +0 -111
  56. package/src/builtins/index.ts +0 -61
  57. package/src/config.ts +0 -32
  58. package/src/env-loader.ts +0 -174
  59. package/src/evaluator-api.ts +0 -36
  60. package/src/evaluator.ts +0 -5623
  61. package/src/index.ts +0 -931
  62. package/src/narrowing.ts +0 -537
  63. package/src/resolve-npm.ts +0 -63
  64. package/tsconfig.json +0 -9
package/dist/index.js CHANGED
@@ -1,3347 +1,20 @@
1
+ #!/usr/bin/env node
2
+ import { createRequire as __nudoCreateRequire } from "module";
3
+ const require = __nudoCreateRequire(import.meta.url);
1
4
  import {
2
- __commonJS,
3
- __require,
4
- __toESM,
5
- evaluateFunctionFull,
6
- evaluateProgram,
7
- resetMemo,
8
- resolveNpmNudo,
9
- setCurrentFileDir,
10
- setModuleResolver
11
- } from "./chunk-3HCPXPEW.js";
12
-
13
- // ../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/error.js
14
- var require_error = __commonJS({
15
- "../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/error.js"(exports) {
16
- "use strict";
17
- var CommanderError2 = class extends Error {
18
- /**
19
- * Constructs the CommanderError class
20
- * @param {number} exitCode suggested exit code which could be used with process.exit
21
- * @param {string} code an id string representing the error
22
- * @param {string} message human-readable description of the error
23
- */
24
- constructor(exitCode, code, message) {
25
- super(message);
26
- Error.captureStackTrace(this, this.constructor);
27
- this.name = this.constructor.name;
28
- this.code = code;
29
- this.exitCode = exitCode;
30
- this.nestedError = void 0;
31
- }
32
- };
33
- var InvalidArgumentError2 = class extends CommanderError2 {
34
- /**
35
- * Constructs the InvalidArgumentError class
36
- * @param {string} [message] explanation of why argument is invalid
37
- */
38
- constructor(message) {
39
- super(1, "commander.invalidArgument", message);
40
- Error.captureStackTrace(this, this.constructor);
41
- this.name = this.constructor.name;
42
- }
43
- };
44
- exports.CommanderError = CommanderError2;
45
- exports.InvalidArgumentError = InvalidArgumentError2;
46
- }
47
- });
48
-
49
- // ../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/argument.js
50
- var require_argument = __commonJS({
51
- "../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/argument.js"(exports) {
52
- "use strict";
53
- var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
54
- var Argument2 = class {
55
- /**
56
- * Initialize a new command argument with the given name and description.
57
- * The default is that the argument is required, and you can explicitly
58
- * indicate this with <> around the name. Put [] around the name for an optional argument.
59
- *
60
- * @param {string} name
61
- * @param {string} [description]
62
- */
63
- constructor(name, description) {
64
- this.description = description || "";
65
- this.variadic = false;
66
- this.parseArg = void 0;
67
- this.defaultValue = void 0;
68
- this.defaultValueDescription = void 0;
69
- this.argChoices = void 0;
70
- switch (name[0]) {
71
- case "<":
72
- this.required = true;
73
- this._name = name.slice(1, -1);
74
- break;
75
- case "[":
76
- this.required = false;
77
- this._name = name.slice(1, -1);
78
- break;
79
- default:
80
- this.required = true;
81
- this._name = name;
82
- break;
83
- }
84
- if (this._name.length > 3 && this._name.slice(-3) === "...") {
85
- this.variadic = true;
86
- this._name = this._name.slice(0, -3);
87
- }
88
- }
89
- /**
90
- * Return argument name.
91
- *
92
- * @return {string}
93
- */
94
- name() {
95
- return this._name;
96
- }
97
- /**
98
- * @package
99
- */
100
- _concatValue(value, previous) {
101
- if (previous === this.defaultValue || !Array.isArray(previous)) {
102
- return [value];
103
- }
104
- return previous.concat(value);
105
- }
106
- /**
107
- * Set the default value, and optionally supply the description to be displayed in the help.
108
- *
109
- * @param {*} value
110
- * @param {string} [description]
111
- * @return {Argument}
112
- */
113
- default(value, description) {
114
- this.defaultValue = value;
115
- this.defaultValueDescription = description;
116
- return this;
117
- }
118
- /**
119
- * Set the custom handler for processing CLI command arguments into argument values.
120
- *
121
- * @param {Function} [fn]
122
- * @return {Argument}
123
- */
124
- argParser(fn) {
125
- this.parseArg = fn;
126
- return this;
127
- }
128
- /**
129
- * Only allow argument value to be one of choices.
130
- *
131
- * @param {string[]} values
132
- * @return {Argument}
133
- */
134
- choices(values) {
135
- this.argChoices = values.slice();
136
- this.parseArg = (arg, previous) => {
137
- if (!this.argChoices.includes(arg)) {
138
- throw new InvalidArgumentError2(
139
- `Allowed choices are ${this.argChoices.join(", ")}.`
140
- );
141
- }
142
- if (this.variadic) {
143
- return this._concatValue(arg, previous);
144
- }
145
- return arg;
146
- };
147
- return this;
148
- }
149
- /**
150
- * Make argument required.
151
- *
152
- * @returns {Argument}
153
- */
154
- argRequired() {
155
- this.required = true;
156
- return this;
157
- }
158
- /**
159
- * Make argument optional.
160
- *
161
- * @returns {Argument}
162
- */
163
- argOptional() {
164
- this.required = false;
165
- return this;
166
- }
167
- };
168
- function humanReadableArgName(arg) {
169
- const nameOutput = arg.name() + (arg.variadic === true ? "..." : "");
170
- return arg.required ? "<" + nameOutput + ">" : "[" + nameOutput + "]";
171
- }
172
- exports.Argument = Argument2;
173
- exports.humanReadableArgName = humanReadableArgName;
174
- }
175
- });
176
-
177
- // ../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/help.js
178
- var require_help = __commonJS({
179
- "../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/help.js"(exports) {
180
- "use strict";
181
- var { humanReadableArgName } = require_argument();
182
- var Help2 = class {
183
- constructor() {
184
- this.helpWidth = void 0;
185
- this.minWidthToWrap = 40;
186
- this.sortSubcommands = false;
187
- this.sortOptions = false;
188
- this.showGlobalOptions = false;
189
- }
190
- /**
191
- * prepareContext is called by Commander after applying overrides from `Command.configureHelp()`
192
- * and just before calling `formatHelp()`.
193
- *
194
- * Commander just uses the helpWidth and the rest is provided for optional use by more complex subclasses.
195
- *
196
- * @param {{ error?: boolean, helpWidth?: number, outputHasColors?: boolean }} contextOptions
197
- */
198
- prepareContext(contextOptions) {
199
- this.helpWidth = this.helpWidth ?? contextOptions.helpWidth ?? 80;
200
- }
201
- /**
202
- * Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one.
203
- *
204
- * @param {Command} cmd
205
- * @returns {Command[]}
206
- */
207
- visibleCommands(cmd) {
208
- const visibleCommands = cmd.commands.filter((cmd2) => !cmd2._hidden);
209
- const helpCommand = cmd._getHelpCommand();
210
- if (helpCommand && !helpCommand._hidden) {
211
- visibleCommands.push(helpCommand);
212
- }
213
- if (this.sortSubcommands) {
214
- visibleCommands.sort((a, b) => {
215
- return a.name().localeCompare(b.name());
216
- });
217
- }
218
- return visibleCommands;
219
- }
220
- /**
221
- * Compare options for sort.
222
- *
223
- * @param {Option} a
224
- * @param {Option} b
225
- * @returns {number}
226
- */
227
- compareOptions(a, b) {
228
- const getSortKey = (option) => {
229
- return option.short ? option.short.replace(/^-/, "") : option.long.replace(/^--/, "");
230
- };
231
- return getSortKey(a).localeCompare(getSortKey(b));
232
- }
233
- /**
234
- * Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one.
235
- *
236
- * @param {Command} cmd
237
- * @returns {Option[]}
238
- */
239
- visibleOptions(cmd) {
240
- const visibleOptions = cmd.options.filter((option) => !option.hidden);
241
- const helpOption = cmd._getHelpOption();
242
- if (helpOption && !helpOption.hidden) {
243
- const removeShort = helpOption.short && cmd._findOption(helpOption.short);
244
- const removeLong = helpOption.long && cmd._findOption(helpOption.long);
245
- if (!removeShort && !removeLong) {
246
- visibleOptions.push(helpOption);
247
- } else if (helpOption.long && !removeLong) {
248
- visibleOptions.push(
249
- cmd.createOption(helpOption.long, helpOption.description)
250
- );
251
- } else if (helpOption.short && !removeShort) {
252
- visibleOptions.push(
253
- cmd.createOption(helpOption.short, helpOption.description)
254
- );
255
- }
256
- }
257
- if (this.sortOptions) {
258
- visibleOptions.sort(this.compareOptions);
259
- }
260
- return visibleOptions;
261
- }
262
- /**
263
- * Get an array of the visible global options. (Not including help.)
264
- *
265
- * @param {Command} cmd
266
- * @returns {Option[]}
267
- */
268
- visibleGlobalOptions(cmd) {
269
- if (!this.showGlobalOptions) return [];
270
- const globalOptions = [];
271
- for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
272
- const visibleOptions = ancestorCmd.options.filter(
273
- (option) => !option.hidden
274
- );
275
- globalOptions.push(...visibleOptions);
276
- }
277
- if (this.sortOptions) {
278
- globalOptions.sort(this.compareOptions);
279
- }
280
- return globalOptions;
281
- }
282
- /**
283
- * Get an array of the arguments if any have a description.
284
- *
285
- * @param {Command} cmd
286
- * @returns {Argument[]}
287
- */
288
- visibleArguments(cmd) {
289
- if (cmd._argsDescription) {
290
- cmd.registeredArguments.forEach((argument) => {
291
- argument.description = argument.description || cmd._argsDescription[argument.name()] || "";
292
- });
293
- }
294
- if (cmd.registeredArguments.find((argument) => argument.description)) {
295
- return cmd.registeredArguments;
296
- }
297
- return [];
298
- }
299
- /**
300
- * Get the command term to show in the list of subcommands.
301
- *
302
- * @param {Command} cmd
303
- * @returns {string}
304
- */
305
- subcommandTerm(cmd) {
306
- const args = cmd.registeredArguments.map((arg) => humanReadableArgName(arg)).join(" ");
307
- return cmd._name + (cmd._aliases[0] ? "|" + cmd._aliases[0] : "") + (cmd.options.length ? " [options]" : "") + // simplistic check for non-help option
308
- (args ? " " + args : "");
309
- }
310
- /**
311
- * Get the option term to show in the list of options.
312
- *
313
- * @param {Option} option
314
- * @returns {string}
315
- */
316
- optionTerm(option) {
317
- return option.flags;
318
- }
319
- /**
320
- * Get the argument term to show in the list of arguments.
321
- *
322
- * @param {Argument} argument
323
- * @returns {string}
324
- */
325
- argumentTerm(argument) {
326
- return argument.name();
327
- }
328
- /**
329
- * Get the longest command term length.
330
- *
331
- * @param {Command} cmd
332
- * @param {Help} helper
333
- * @returns {number}
334
- */
335
- longestSubcommandTermLength(cmd, helper) {
336
- return helper.visibleCommands(cmd).reduce((max, command) => {
337
- return Math.max(
338
- max,
339
- this.displayWidth(
340
- helper.styleSubcommandTerm(helper.subcommandTerm(command))
341
- )
342
- );
343
- }, 0);
344
- }
345
- /**
346
- * Get the longest option term length.
347
- *
348
- * @param {Command} cmd
349
- * @param {Help} helper
350
- * @returns {number}
351
- */
352
- longestOptionTermLength(cmd, helper) {
353
- return helper.visibleOptions(cmd).reduce((max, option) => {
354
- return Math.max(
355
- max,
356
- this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
357
- );
358
- }, 0);
359
- }
360
- /**
361
- * Get the longest global option term length.
362
- *
363
- * @param {Command} cmd
364
- * @param {Help} helper
365
- * @returns {number}
366
- */
367
- longestGlobalOptionTermLength(cmd, helper) {
368
- return helper.visibleGlobalOptions(cmd).reduce((max, option) => {
369
- return Math.max(
370
- max,
371
- this.displayWidth(helper.styleOptionTerm(helper.optionTerm(option)))
372
- );
373
- }, 0);
374
- }
375
- /**
376
- * Get the longest argument term length.
377
- *
378
- * @param {Command} cmd
379
- * @param {Help} helper
380
- * @returns {number}
381
- */
382
- longestArgumentTermLength(cmd, helper) {
383
- return helper.visibleArguments(cmd).reduce((max, argument) => {
384
- return Math.max(
385
- max,
386
- this.displayWidth(
387
- helper.styleArgumentTerm(helper.argumentTerm(argument))
388
- )
389
- );
390
- }, 0);
391
- }
392
- /**
393
- * Get the command usage to be displayed at the top of the built-in help.
394
- *
395
- * @param {Command} cmd
396
- * @returns {string}
397
- */
398
- commandUsage(cmd) {
399
- let cmdName = cmd._name;
400
- if (cmd._aliases[0]) {
401
- cmdName = cmdName + "|" + cmd._aliases[0];
402
- }
403
- let ancestorCmdNames = "";
404
- for (let ancestorCmd = cmd.parent; ancestorCmd; ancestorCmd = ancestorCmd.parent) {
405
- ancestorCmdNames = ancestorCmd.name() + " " + ancestorCmdNames;
406
- }
407
- return ancestorCmdNames + cmdName + " " + cmd.usage();
408
- }
409
- /**
410
- * Get the description for the command.
411
- *
412
- * @param {Command} cmd
413
- * @returns {string}
414
- */
415
- commandDescription(cmd) {
416
- return cmd.description();
417
- }
418
- /**
419
- * Get the subcommand summary to show in the list of subcommands.
420
- * (Fallback to description for backwards compatibility.)
421
- *
422
- * @param {Command} cmd
423
- * @returns {string}
424
- */
425
- subcommandDescription(cmd) {
426
- return cmd.summary() || cmd.description();
427
- }
428
- /**
429
- * Get the option description to show in the list of options.
430
- *
431
- * @param {Option} option
432
- * @return {string}
433
- */
434
- optionDescription(option) {
435
- const extraInfo = [];
436
- if (option.argChoices) {
437
- extraInfo.push(
438
- // use stringify to match the display of the default value
439
- `choices: ${option.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
440
- );
441
- }
442
- if (option.defaultValue !== void 0) {
443
- const showDefault = option.required || option.optional || option.isBoolean() && typeof option.defaultValue === "boolean";
444
- if (showDefault) {
445
- extraInfo.push(
446
- `default: ${option.defaultValueDescription || JSON.stringify(option.defaultValue)}`
447
- );
448
- }
449
- }
450
- if (option.presetArg !== void 0 && option.optional) {
451
- extraInfo.push(`preset: ${JSON.stringify(option.presetArg)}`);
452
- }
453
- if (option.envVar !== void 0) {
454
- extraInfo.push(`env: ${option.envVar}`);
455
- }
456
- if (extraInfo.length > 0) {
457
- return `${option.description} (${extraInfo.join(", ")})`;
458
- }
459
- return option.description;
460
- }
461
- /**
462
- * Get the argument description to show in the list of arguments.
463
- *
464
- * @param {Argument} argument
465
- * @return {string}
466
- */
467
- argumentDescription(argument) {
468
- const extraInfo = [];
469
- if (argument.argChoices) {
470
- extraInfo.push(
471
- // use stringify to match the display of the default value
472
- `choices: ${argument.argChoices.map((choice) => JSON.stringify(choice)).join(", ")}`
473
- );
474
- }
475
- if (argument.defaultValue !== void 0) {
476
- extraInfo.push(
477
- `default: ${argument.defaultValueDescription || JSON.stringify(argument.defaultValue)}`
478
- );
479
- }
480
- if (extraInfo.length > 0) {
481
- const extraDescription = `(${extraInfo.join(", ")})`;
482
- if (argument.description) {
483
- return `${argument.description} ${extraDescription}`;
484
- }
485
- return extraDescription;
486
- }
487
- return argument.description;
488
- }
489
- /**
490
- * Generate the built-in help text.
491
- *
492
- * @param {Command} cmd
493
- * @param {Help} helper
494
- * @returns {string}
495
- */
496
- formatHelp(cmd, helper) {
497
- const termWidth = helper.padWidth(cmd, helper);
498
- const helpWidth = helper.helpWidth ?? 80;
499
- function callFormatItem(term, description) {
500
- return helper.formatItem(term, termWidth, description, helper);
501
- }
502
- let output = [
503
- `${helper.styleTitle("Usage:")} ${helper.styleUsage(helper.commandUsage(cmd))}`,
504
- ""
505
- ];
506
- const commandDescription = helper.commandDescription(cmd);
507
- if (commandDescription.length > 0) {
508
- output = output.concat([
509
- helper.boxWrap(
510
- helper.styleCommandDescription(commandDescription),
511
- helpWidth
512
- ),
513
- ""
514
- ]);
515
- }
516
- const argumentList = helper.visibleArguments(cmd).map((argument) => {
517
- return callFormatItem(
518
- helper.styleArgumentTerm(helper.argumentTerm(argument)),
519
- helper.styleArgumentDescription(helper.argumentDescription(argument))
520
- );
521
- });
522
- if (argumentList.length > 0) {
523
- output = output.concat([
524
- helper.styleTitle("Arguments:"),
525
- ...argumentList,
526
- ""
527
- ]);
528
- }
529
- const optionList = helper.visibleOptions(cmd).map((option) => {
530
- return callFormatItem(
531
- helper.styleOptionTerm(helper.optionTerm(option)),
532
- helper.styleOptionDescription(helper.optionDescription(option))
533
- );
534
- });
535
- if (optionList.length > 0) {
536
- output = output.concat([
537
- helper.styleTitle("Options:"),
538
- ...optionList,
539
- ""
540
- ]);
541
- }
542
- if (helper.showGlobalOptions) {
543
- const globalOptionList = helper.visibleGlobalOptions(cmd).map((option) => {
544
- return callFormatItem(
545
- helper.styleOptionTerm(helper.optionTerm(option)),
546
- helper.styleOptionDescription(helper.optionDescription(option))
547
- );
548
- });
549
- if (globalOptionList.length > 0) {
550
- output = output.concat([
551
- helper.styleTitle("Global Options:"),
552
- ...globalOptionList,
553
- ""
554
- ]);
555
- }
556
- }
557
- const commandList = helper.visibleCommands(cmd).map((cmd2) => {
558
- return callFormatItem(
559
- helper.styleSubcommandTerm(helper.subcommandTerm(cmd2)),
560
- helper.styleSubcommandDescription(helper.subcommandDescription(cmd2))
561
- );
562
- });
563
- if (commandList.length > 0) {
564
- output = output.concat([
565
- helper.styleTitle("Commands:"),
566
- ...commandList,
567
- ""
568
- ]);
569
- }
570
- return output.join("\n");
571
- }
572
- /**
573
- * Return display width of string, ignoring ANSI escape sequences. Used in padding and wrapping calculations.
574
- *
575
- * @param {string} str
576
- * @returns {number}
577
- */
578
- displayWidth(str) {
579
- return stripColor(str).length;
580
- }
581
- /**
582
- * Style the title for displaying in the help. Called with 'Usage:', 'Options:', etc.
583
- *
584
- * @param {string} str
585
- * @returns {string}
586
- */
587
- styleTitle(str) {
588
- return str;
589
- }
590
- styleUsage(str) {
591
- return str.split(" ").map((word) => {
592
- if (word === "[options]") return this.styleOptionText(word);
593
- if (word === "[command]") return this.styleSubcommandText(word);
594
- if (word[0] === "[" || word[0] === "<")
595
- return this.styleArgumentText(word);
596
- return this.styleCommandText(word);
597
- }).join(" ");
598
- }
599
- styleCommandDescription(str) {
600
- return this.styleDescriptionText(str);
601
- }
602
- styleOptionDescription(str) {
603
- return this.styleDescriptionText(str);
604
- }
605
- styleSubcommandDescription(str) {
606
- return this.styleDescriptionText(str);
607
- }
608
- styleArgumentDescription(str) {
609
- return this.styleDescriptionText(str);
610
- }
611
- styleDescriptionText(str) {
612
- return str;
613
- }
614
- styleOptionTerm(str) {
615
- return this.styleOptionText(str);
616
- }
617
- styleSubcommandTerm(str) {
618
- return str.split(" ").map((word) => {
619
- if (word === "[options]") return this.styleOptionText(word);
620
- if (word[0] === "[" || word[0] === "<")
621
- return this.styleArgumentText(word);
622
- return this.styleSubcommandText(word);
623
- }).join(" ");
624
- }
625
- styleArgumentTerm(str) {
626
- return this.styleArgumentText(str);
627
- }
628
- styleOptionText(str) {
629
- return str;
630
- }
631
- styleArgumentText(str) {
632
- return str;
633
- }
634
- styleSubcommandText(str) {
635
- return str;
636
- }
637
- styleCommandText(str) {
638
- return str;
639
- }
640
- /**
641
- * Calculate the pad width from the maximum term length.
642
- *
643
- * @param {Command} cmd
644
- * @param {Help} helper
645
- * @returns {number}
646
- */
647
- padWidth(cmd, helper) {
648
- return Math.max(
649
- helper.longestOptionTermLength(cmd, helper),
650
- helper.longestGlobalOptionTermLength(cmd, helper),
651
- helper.longestSubcommandTermLength(cmd, helper),
652
- helper.longestArgumentTermLength(cmd, helper)
653
- );
654
- }
655
- /**
656
- * Detect manually wrapped and indented strings by checking for line break followed by whitespace.
657
- *
658
- * @param {string} str
659
- * @returns {boolean}
660
- */
661
- preformatted(str) {
662
- return /\n[^\S\r\n]/.test(str);
663
- }
664
- /**
665
- * Format the "item", which consists of a term and description. Pad the term and wrap the description, indenting the following lines.
666
- *
667
- * So "TTT", 5, "DDD DDDD DD DDD" might be formatted for this.helpWidth=17 like so:
668
- * TTT DDD DDDD
669
- * DD DDD
670
- *
671
- * @param {string} term
672
- * @param {number} termWidth
673
- * @param {string} description
674
- * @param {Help} helper
675
- * @returns {string}
676
- */
677
- formatItem(term, termWidth, description, helper) {
678
- const itemIndent = 2;
679
- const itemIndentStr = " ".repeat(itemIndent);
680
- if (!description) return itemIndentStr + term;
681
- const paddedTerm = term.padEnd(
682
- termWidth + term.length - helper.displayWidth(term)
683
- );
684
- const spacerWidth = 2;
685
- const helpWidth = this.helpWidth ?? 80;
686
- const remainingWidth = helpWidth - termWidth - spacerWidth - itemIndent;
687
- let formattedDescription;
688
- if (remainingWidth < this.minWidthToWrap || helper.preformatted(description)) {
689
- formattedDescription = description;
690
- } else {
691
- const wrappedDescription = helper.boxWrap(description, remainingWidth);
692
- formattedDescription = wrappedDescription.replace(
693
- /\n/g,
694
- "\n" + " ".repeat(termWidth + spacerWidth)
695
- );
696
- }
697
- return itemIndentStr + paddedTerm + " ".repeat(spacerWidth) + formattedDescription.replace(/\n/g, `
698
- ${itemIndentStr}`);
699
- }
700
- /**
701
- * Wrap a string at whitespace, preserving existing line breaks.
702
- * Wrapping is skipped if the width is less than `minWidthToWrap`.
703
- *
704
- * @param {string} str
705
- * @param {number} width
706
- * @returns {string}
707
- */
708
- boxWrap(str, width) {
709
- if (width < this.minWidthToWrap) return str;
710
- const rawLines = str.split(/\r\n|\n/);
711
- const chunkPattern = /[\s]*[^\s]+/g;
712
- const wrappedLines = [];
713
- rawLines.forEach((line) => {
714
- const chunks = line.match(chunkPattern);
715
- if (chunks === null) {
716
- wrappedLines.push("");
717
- return;
718
- }
719
- let sumChunks = [chunks.shift()];
720
- let sumWidth = this.displayWidth(sumChunks[0]);
721
- chunks.forEach((chunk) => {
722
- const visibleWidth = this.displayWidth(chunk);
723
- if (sumWidth + visibleWidth <= width) {
724
- sumChunks.push(chunk);
725
- sumWidth += visibleWidth;
726
- return;
727
- }
728
- wrappedLines.push(sumChunks.join(""));
729
- const nextChunk = chunk.trimStart();
730
- sumChunks = [nextChunk];
731
- sumWidth = this.displayWidth(nextChunk);
732
- });
733
- wrappedLines.push(sumChunks.join(""));
734
- });
735
- return wrappedLines.join("\n");
736
- }
737
- };
738
- function stripColor(str) {
739
- const sgrPattern = /\x1b\[\d*(;\d*)*m/g;
740
- return str.replace(sgrPattern, "");
741
- }
742
- exports.Help = Help2;
743
- exports.stripColor = stripColor;
744
- }
745
- });
746
-
747
- // ../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/option.js
748
- var require_option = __commonJS({
749
- "../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/option.js"(exports) {
750
- "use strict";
751
- var { InvalidArgumentError: InvalidArgumentError2 } = require_error();
752
- var Option2 = class {
753
- /**
754
- * Initialize a new `Option` with the given `flags` and `description`.
755
- *
756
- * @param {string} flags
757
- * @param {string} [description]
758
- */
759
- constructor(flags, description) {
760
- this.flags = flags;
761
- this.description = description || "";
762
- this.required = flags.includes("<");
763
- this.optional = flags.includes("[");
764
- this.variadic = /\w\.\.\.[>\]]$/.test(flags);
765
- this.mandatory = false;
766
- const optionFlags = splitOptionFlags(flags);
767
- this.short = optionFlags.shortFlag;
768
- this.long = optionFlags.longFlag;
769
- this.negate = false;
770
- if (this.long) {
771
- this.negate = this.long.startsWith("--no-");
772
- }
773
- this.defaultValue = void 0;
774
- this.defaultValueDescription = void 0;
775
- this.presetArg = void 0;
776
- this.envVar = void 0;
777
- this.parseArg = void 0;
778
- this.hidden = false;
779
- this.argChoices = void 0;
780
- this.conflictsWith = [];
781
- this.implied = void 0;
782
- }
783
- /**
784
- * Set the default value, and optionally supply the description to be displayed in the help.
785
- *
786
- * @param {*} value
787
- * @param {string} [description]
788
- * @return {Option}
789
- */
790
- default(value, description) {
791
- this.defaultValue = value;
792
- this.defaultValueDescription = description;
793
- return this;
794
- }
795
- /**
796
- * Preset to use when option used without option-argument, especially optional but also boolean and negated.
797
- * The custom processing (parseArg) is called.
798
- *
799
- * @example
800
- * new Option('--color').default('GREYSCALE').preset('RGB');
801
- * new Option('--donate [amount]').preset('20').argParser(parseFloat);
802
- *
803
- * @param {*} arg
804
- * @return {Option}
805
- */
806
- preset(arg) {
807
- this.presetArg = arg;
808
- return this;
809
- }
810
- /**
811
- * Add option name(s) that conflict with this option.
812
- * An error will be displayed if conflicting options are found during parsing.
813
- *
814
- * @example
815
- * new Option('--rgb').conflicts('cmyk');
816
- * new Option('--js').conflicts(['ts', 'jsx']);
817
- *
818
- * @param {(string | string[])} names
819
- * @return {Option}
820
- */
821
- conflicts(names) {
822
- this.conflictsWith = this.conflictsWith.concat(names);
823
- return this;
824
- }
825
- /**
826
- * Specify implied option values for when this option is set and the implied options are not.
827
- *
828
- * The custom processing (parseArg) is not called on the implied values.
829
- *
830
- * @example
831
- * program
832
- * .addOption(new Option('--log', 'write logging information to file'))
833
- * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
834
- *
835
- * @param {object} impliedOptionValues
836
- * @return {Option}
837
- */
838
- implies(impliedOptionValues) {
839
- let newImplied = impliedOptionValues;
840
- if (typeof impliedOptionValues === "string") {
841
- newImplied = { [impliedOptionValues]: true };
842
- }
843
- this.implied = Object.assign(this.implied || {}, newImplied);
844
- return this;
845
- }
846
- /**
847
- * Set environment variable to check for option value.
848
- *
849
- * An environment variable is only used if when processed the current option value is
850
- * undefined, or the source of the current value is 'default' or 'config' or 'env'.
851
- *
852
- * @param {string} name
853
- * @return {Option}
854
- */
855
- env(name) {
856
- this.envVar = name;
857
- return this;
858
- }
859
- /**
860
- * Set the custom handler for processing CLI option arguments into option values.
861
- *
862
- * @param {Function} [fn]
863
- * @return {Option}
864
- */
865
- argParser(fn) {
866
- this.parseArg = fn;
867
- return this;
868
- }
869
- /**
870
- * Whether the option is mandatory and must have a value after parsing.
871
- *
872
- * @param {boolean} [mandatory=true]
873
- * @return {Option}
874
- */
875
- makeOptionMandatory(mandatory = true) {
876
- this.mandatory = !!mandatory;
877
- return this;
878
- }
879
- /**
880
- * Hide option in help.
881
- *
882
- * @param {boolean} [hide=true]
883
- * @return {Option}
884
- */
885
- hideHelp(hide = true) {
886
- this.hidden = !!hide;
887
- return this;
888
- }
889
- /**
890
- * @package
891
- */
892
- _concatValue(value, previous) {
893
- if (previous === this.defaultValue || !Array.isArray(previous)) {
894
- return [value];
895
- }
896
- return previous.concat(value);
897
- }
898
- /**
899
- * Only allow option value to be one of choices.
900
- *
901
- * @param {string[]} values
902
- * @return {Option}
903
- */
904
- choices(values) {
905
- this.argChoices = values.slice();
906
- this.parseArg = (arg, previous) => {
907
- if (!this.argChoices.includes(arg)) {
908
- throw new InvalidArgumentError2(
909
- `Allowed choices are ${this.argChoices.join(", ")}.`
910
- );
911
- }
912
- if (this.variadic) {
913
- return this._concatValue(arg, previous);
914
- }
915
- return arg;
916
- };
917
- return this;
918
- }
919
- /**
920
- * Return option name.
921
- *
922
- * @return {string}
923
- */
924
- name() {
925
- if (this.long) {
926
- return this.long.replace(/^--/, "");
927
- }
928
- return this.short.replace(/^-/, "");
929
- }
930
- /**
931
- * Return option name, in a camelcase format that can be used
932
- * as an object attribute key.
933
- *
934
- * @return {string}
935
- */
936
- attributeName() {
937
- if (this.negate) {
938
- return camelcase(this.name().replace(/^no-/, ""));
939
- }
940
- return camelcase(this.name());
941
- }
942
- /**
943
- * Check if `arg` matches the short or long flag.
944
- *
945
- * @param {string} arg
946
- * @return {boolean}
947
- * @package
948
- */
949
- is(arg) {
950
- return this.short === arg || this.long === arg;
951
- }
952
- /**
953
- * Return whether a boolean option.
954
- *
955
- * Options are one of boolean, negated, required argument, or optional argument.
956
- *
957
- * @return {boolean}
958
- * @package
959
- */
960
- isBoolean() {
961
- return !this.required && !this.optional && !this.negate;
962
- }
963
- };
964
- var DualOptions = class {
965
- /**
966
- * @param {Option[]} options
967
- */
968
- constructor(options) {
969
- this.positiveOptions = /* @__PURE__ */ new Map();
970
- this.negativeOptions = /* @__PURE__ */ new Map();
971
- this.dualOptions = /* @__PURE__ */ new Set();
972
- options.forEach((option) => {
973
- if (option.negate) {
974
- this.negativeOptions.set(option.attributeName(), option);
975
- } else {
976
- this.positiveOptions.set(option.attributeName(), option);
977
- }
978
- });
979
- this.negativeOptions.forEach((value, key) => {
980
- if (this.positiveOptions.has(key)) {
981
- this.dualOptions.add(key);
982
- }
983
- });
984
- }
985
- /**
986
- * Did the value come from the option, and not from possible matching dual option?
987
- *
988
- * @param {*} value
989
- * @param {Option} option
990
- * @returns {boolean}
991
- */
992
- valueFromOption(value, option) {
993
- const optionKey = option.attributeName();
994
- if (!this.dualOptions.has(optionKey)) return true;
995
- const preset = this.negativeOptions.get(optionKey).presetArg;
996
- const negativeValue = preset !== void 0 ? preset : false;
997
- return option.negate === (negativeValue === value);
998
- }
999
- };
1000
- function camelcase(str) {
1001
- return str.split("-").reduce((str2, word) => {
1002
- return str2 + word[0].toUpperCase() + word.slice(1);
1003
- });
1004
- }
1005
- function splitOptionFlags(flags) {
1006
- let shortFlag;
1007
- let longFlag;
1008
- const shortFlagExp = /^-[^-]$/;
1009
- const longFlagExp = /^--[^-]/;
1010
- const flagParts = flags.split(/[ |,]+/).concat("guard");
1011
- if (shortFlagExp.test(flagParts[0])) shortFlag = flagParts.shift();
1012
- if (longFlagExp.test(flagParts[0])) longFlag = flagParts.shift();
1013
- if (!shortFlag && shortFlagExp.test(flagParts[0]))
1014
- shortFlag = flagParts.shift();
1015
- if (!shortFlag && longFlagExp.test(flagParts[0])) {
1016
- shortFlag = longFlag;
1017
- longFlag = flagParts.shift();
1018
- }
1019
- if (flagParts[0].startsWith("-")) {
1020
- const unsupportedFlag = flagParts[0];
1021
- const baseError = `option creation failed due to '${unsupportedFlag}' in option flags '${flags}'`;
1022
- if (/^-[^-][^-]/.test(unsupportedFlag))
1023
- throw new Error(
1024
- `${baseError}
1025
- - a short flag is a single dash and a single character
1026
- - either use a single dash and a single character (for a short flag)
1027
- - or use a double dash for a long option (and can have two, like '--ws, --workspace')`
1028
- );
1029
- if (shortFlagExp.test(unsupportedFlag))
1030
- throw new Error(`${baseError}
1031
- - too many short flags`);
1032
- if (longFlagExp.test(unsupportedFlag))
1033
- throw new Error(`${baseError}
1034
- - too many long flags`);
1035
- throw new Error(`${baseError}
1036
- - unrecognised flag format`);
1037
- }
1038
- if (shortFlag === void 0 && longFlag === void 0)
1039
- throw new Error(
1040
- `option creation failed due to no flags found in '${flags}'.`
1041
- );
1042
- return { shortFlag, longFlag };
1043
- }
1044
- exports.Option = Option2;
1045
- exports.DualOptions = DualOptions;
1046
- }
1047
- });
1048
-
1049
- // ../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/suggestSimilar.js
1050
- var require_suggestSimilar = __commonJS({
1051
- "../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/suggestSimilar.js"(exports) {
1052
- "use strict";
1053
- var maxDistance = 3;
1054
- function editDistance(a, b) {
1055
- if (Math.abs(a.length - b.length) > maxDistance)
1056
- return Math.max(a.length, b.length);
1057
- const d = [];
1058
- for (let i = 0; i <= a.length; i++) {
1059
- d[i] = [i];
1060
- }
1061
- for (let j = 0; j <= b.length; j++) {
1062
- d[0][j] = j;
1063
- }
1064
- for (let j = 1; j <= b.length; j++) {
1065
- for (let i = 1; i <= a.length; i++) {
1066
- let cost = 1;
1067
- if (a[i - 1] === b[j - 1]) {
1068
- cost = 0;
1069
- } else {
1070
- cost = 1;
1071
- }
1072
- d[i][j] = Math.min(
1073
- d[i - 1][j] + 1,
1074
- // deletion
1075
- d[i][j - 1] + 1,
1076
- // insertion
1077
- d[i - 1][j - 1] + cost
1078
- // substitution
1079
- );
1080
- if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
1081
- d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
1082
- }
1083
- }
1084
- }
1085
- return d[a.length][b.length];
1086
- }
1087
- function suggestSimilar(word, candidates) {
1088
- if (!candidates || candidates.length === 0) return "";
1089
- candidates = Array.from(new Set(candidates));
1090
- const searchingOptions = word.startsWith("--");
1091
- if (searchingOptions) {
1092
- word = word.slice(2);
1093
- candidates = candidates.map((candidate) => candidate.slice(2));
1094
- }
1095
- let similar = [];
1096
- let bestDistance = maxDistance;
1097
- const minSimilarity = 0.4;
1098
- candidates.forEach((candidate) => {
1099
- if (candidate.length <= 1) return;
1100
- const distance = editDistance(word, candidate);
1101
- const length = Math.max(word.length, candidate.length);
1102
- const similarity = (length - distance) / length;
1103
- if (similarity > minSimilarity) {
1104
- if (distance < bestDistance) {
1105
- bestDistance = distance;
1106
- similar = [candidate];
1107
- } else if (distance === bestDistance) {
1108
- similar.push(candidate);
1109
- }
1110
- }
1111
- });
1112
- similar.sort((a, b) => a.localeCompare(b));
1113
- if (searchingOptions) {
1114
- similar = similar.map((candidate) => `--${candidate}`);
1115
- }
1116
- if (similar.length > 1) {
1117
- return `
1118
- (Did you mean one of ${similar.join(", ")}?)`;
1119
- }
1120
- if (similar.length === 1) {
1121
- return `
1122
- (Did you mean ${similar[0]}?)`;
1123
- }
1124
- return "";
1125
- }
1126
- exports.suggestSimilar = suggestSimilar;
1127
- }
1128
- });
1129
-
1130
- // ../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/command.js
1131
- var require_command = __commonJS({
1132
- "../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/lib/command.js"(exports) {
1133
- "use strict";
1134
- var EventEmitter = __require("events").EventEmitter;
1135
- var childProcess = __require("child_process");
1136
- var path = __require("path");
1137
- var fs = __require("fs");
1138
- var process2 = __require("process");
1139
- var { Argument: Argument2, humanReadableArgName } = require_argument();
1140
- var { CommanderError: CommanderError2 } = require_error();
1141
- var { Help: Help2, stripColor } = require_help();
1142
- var { Option: Option2, DualOptions } = require_option();
1143
- var { suggestSimilar } = require_suggestSimilar();
1144
- var Command2 = class _Command extends EventEmitter {
1145
- /**
1146
- * Initialize a new `Command`.
1147
- *
1148
- * @param {string} [name]
1149
- */
1150
- constructor(name) {
1151
- super();
1152
- this.commands = [];
1153
- this.options = [];
1154
- this.parent = null;
1155
- this._allowUnknownOption = false;
1156
- this._allowExcessArguments = false;
1157
- this.registeredArguments = [];
1158
- this._args = this.registeredArguments;
1159
- this.args = [];
1160
- this.rawArgs = [];
1161
- this.processedArgs = [];
1162
- this._scriptPath = null;
1163
- this._name = name || "";
1164
- this._optionValues = {};
1165
- this._optionValueSources = {};
1166
- this._storeOptionsAsProperties = false;
1167
- this._actionHandler = null;
1168
- this._executableHandler = false;
1169
- this._executableFile = null;
1170
- this._executableDir = null;
1171
- this._defaultCommandName = null;
1172
- this._exitCallback = null;
1173
- this._aliases = [];
1174
- this._combineFlagAndOptionalValue = true;
1175
- this._description = "";
1176
- this._summary = "";
1177
- this._argsDescription = void 0;
1178
- this._enablePositionalOptions = false;
1179
- this._passThroughOptions = false;
1180
- this._lifeCycleHooks = {};
1181
- this._showHelpAfterError = false;
1182
- this._showSuggestionAfterError = true;
1183
- this._savedState = null;
1184
- this._outputConfiguration = {
1185
- writeOut: (str) => process2.stdout.write(str),
1186
- writeErr: (str) => process2.stderr.write(str),
1187
- outputError: (str, write) => write(str),
1188
- getOutHelpWidth: () => process2.stdout.isTTY ? process2.stdout.columns : void 0,
1189
- getErrHelpWidth: () => process2.stderr.isTTY ? process2.stderr.columns : void 0,
1190
- getOutHasColors: () => useColor() ?? (process2.stdout.isTTY && process2.stdout.hasColors?.()),
1191
- getErrHasColors: () => useColor() ?? (process2.stderr.isTTY && process2.stderr.hasColors?.()),
1192
- stripColor: (str) => stripColor(str)
1193
- };
1194
- this._hidden = false;
1195
- this._helpOption = void 0;
1196
- this._addImplicitHelpCommand = void 0;
1197
- this._helpCommand = void 0;
1198
- this._helpConfiguration = {};
1199
- }
1200
- /**
1201
- * Copy settings that are useful to have in common across root command and subcommands.
1202
- *
1203
- * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
1204
- *
1205
- * @param {Command} sourceCommand
1206
- * @return {Command} `this` command for chaining
1207
- */
1208
- copyInheritedSettings(sourceCommand) {
1209
- this._outputConfiguration = sourceCommand._outputConfiguration;
1210
- this._helpOption = sourceCommand._helpOption;
1211
- this._helpCommand = sourceCommand._helpCommand;
1212
- this._helpConfiguration = sourceCommand._helpConfiguration;
1213
- this._exitCallback = sourceCommand._exitCallback;
1214
- this._storeOptionsAsProperties = sourceCommand._storeOptionsAsProperties;
1215
- this._combineFlagAndOptionalValue = sourceCommand._combineFlagAndOptionalValue;
1216
- this._allowExcessArguments = sourceCommand._allowExcessArguments;
1217
- this._enablePositionalOptions = sourceCommand._enablePositionalOptions;
1218
- this._showHelpAfterError = sourceCommand._showHelpAfterError;
1219
- this._showSuggestionAfterError = sourceCommand._showSuggestionAfterError;
1220
- return this;
1221
- }
1222
- /**
1223
- * @returns {Command[]}
1224
- * @private
1225
- */
1226
- _getCommandAndAncestors() {
1227
- const result = [];
1228
- for (let command = this; command; command = command.parent) {
1229
- result.push(command);
1230
- }
1231
- return result;
1232
- }
1233
- /**
1234
- * Define a command.
1235
- *
1236
- * There are two styles of command: pay attention to where to put the description.
1237
- *
1238
- * @example
1239
- * // Command implemented using action handler (description is supplied separately to `.command`)
1240
- * program
1241
- * .command('clone <source> [destination]')
1242
- * .description('clone a repository into a newly created directory')
1243
- * .action((source, destination) => {
1244
- * console.log('clone command called');
1245
- * });
1246
- *
1247
- * // Command implemented using separate executable file (description is second parameter to `.command`)
1248
- * program
1249
- * .command('start <service>', 'start named service')
1250
- * .command('stop [service]', 'stop named service, or all if no name supplied');
1251
- *
1252
- * @param {string} nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
1253
- * @param {(object | string)} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable)
1254
- * @param {object} [execOpts] - configuration options (for executable)
1255
- * @return {Command} returns new command for action handler, or `this` for executable command
1256
- */
1257
- command(nameAndArgs, actionOptsOrExecDesc, execOpts) {
1258
- let desc = actionOptsOrExecDesc;
1259
- let opts = execOpts;
1260
- if (typeof desc === "object" && desc !== null) {
1261
- opts = desc;
1262
- desc = null;
1263
- }
1264
- opts = opts || {};
1265
- const [, name, args] = nameAndArgs.match(/([^ ]+) *(.*)/);
1266
- const cmd = this.createCommand(name);
1267
- if (desc) {
1268
- cmd.description(desc);
1269
- cmd._executableHandler = true;
1270
- }
1271
- if (opts.isDefault) this._defaultCommandName = cmd._name;
1272
- cmd._hidden = !!(opts.noHelp || opts.hidden);
1273
- cmd._executableFile = opts.executableFile || null;
1274
- if (args) cmd.arguments(args);
1275
- this._registerCommand(cmd);
1276
- cmd.parent = this;
1277
- cmd.copyInheritedSettings(this);
1278
- if (desc) return this;
1279
- return cmd;
1280
- }
1281
- /**
1282
- * Factory routine to create a new unattached command.
1283
- *
1284
- * See .command() for creating an attached subcommand, which uses this routine to
1285
- * create the command. You can override createCommand to customise subcommands.
1286
- *
1287
- * @param {string} [name]
1288
- * @return {Command} new command
1289
- */
1290
- createCommand(name) {
1291
- return new _Command(name);
1292
- }
1293
- /**
1294
- * You can customise the help with a subclass of Help by overriding createHelp,
1295
- * or by overriding Help properties using configureHelp().
1296
- *
1297
- * @return {Help}
1298
- */
1299
- createHelp() {
1300
- return Object.assign(new Help2(), this.configureHelp());
1301
- }
1302
- /**
1303
- * You can customise the help by overriding Help properties using configureHelp(),
1304
- * or with a subclass of Help by overriding createHelp().
1305
- *
1306
- * @param {object} [configuration] - configuration options
1307
- * @return {(Command | object)} `this` command for chaining, or stored configuration
1308
- */
1309
- configureHelp(configuration) {
1310
- if (configuration === void 0) return this._helpConfiguration;
1311
- this._helpConfiguration = configuration;
1312
- return this;
1313
- }
1314
- /**
1315
- * The default output goes to stdout and stderr. You can customise this for special
1316
- * applications. You can also customise the display of errors by overriding outputError.
1317
- *
1318
- * The configuration properties are all functions:
1319
- *
1320
- * // change how output being written, defaults to stdout and stderr
1321
- * writeOut(str)
1322
- * writeErr(str)
1323
- * // change how output being written for errors, defaults to writeErr
1324
- * outputError(str, write) // used for displaying errors and not used for displaying help
1325
- * // specify width for wrapping help
1326
- * getOutHelpWidth()
1327
- * getErrHelpWidth()
1328
- * // color support, currently only used with Help
1329
- * getOutHasColors()
1330
- * getErrHasColors()
1331
- * stripColor() // used to remove ANSI escape codes if output does not have colors
1332
- *
1333
- * @param {object} [configuration] - configuration options
1334
- * @return {(Command | object)} `this` command for chaining, or stored configuration
1335
- */
1336
- configureOutput(configuration) {
1337
- if (configuration === void 0) return this._outputConfiguration;
1338
- Object.assign(this._outputConfiguration, configuration);
1339
- return this;
1340
- }
1341
- /**
1342
- * Display the help or a custom message after an error occurs.
1343
- *
1344
- * @param {(boolean|string)} [displayHelp]
1345
- * @return {Command} `this` command for chaining
1346
- */
1347
- showHelpAfterError(displayHelp = true) {
1348
- if (typeof displayHelp !== "string") displayHelp = !!displayHelp;
1349
- this._showHelpAfterError = displayHelp;
1350
- return this;
1351
- }
1352
- /**
1353
- * Display suggestion of similar commands for unknown commands, or options for unknown options.
1354
- *
1355
- * @param {boolean} [displaySuggestion]
1356
- * @return {Command} `this` command for chaining
1357
- */
1358
- showSuggestionAfterError(displaySuggestion = true) {
1359
- this._showSuggestionAfterError = !!displaySuggestion;
1360
- return this;
1361
- }
1362
- /**
1363
- * Add a prepared subcommand.
1364
- *
1365
- * See .command() for creating an attached subcommand which inherits settings from its parent.
1366
- *
1367
- * @param {Command} cmd - new subcommand
1368
- * @param {object} [opts] - configuration options
1369
- * @return {Command} `this` command for chaining
1370
- */
1371
- addCommand(cmd, opts) {
1372
- if (!cmd._name) {
1373
- throw new Error(`Command passed to .addCommand() must have a name
1374
- - specify the name in Command constructor or using .name()`);
1375
- }
1376
- opts = opts || {};
1377
- if (opts.isDefault) this._defaultCommandName = cmd._name;
1378
- if (opts.noHelp || opts.hidden) cmd._hidden = true;
1379
- this._registerCommand(cmd);
1380
- cmd.parent = this;
1381
- cmd._checkForBrokenPassThrough();
1382
- return this;
1383
- }
1384
- /**
1385
- * Factory routine to create a new unattached argument.
1386
- *
1387
- * See .argument() for creating an attached argument, which uses this routine to
1388
- * create the argument. You can override createArgument to return a custom argument.
1389
- *
1390
- * @param {string} name
1391
- * @param {string} [description]
1392
- * @return {Argument} new argument
1393
- */
1394
- createArgument(name, description) {
1395
- return new Argument2(name, description);
1396
- }
1397
- /**
1398
- * Define argument syntax for command.
1399
- *
1400
- * The default is that the argument is required, and you can explicitly
1401
- * indicate this with <> around the name. Put [] around the name for an optional argument.
1402
- *
1403
- * @example
1404
- * program.argument('<input-file>');
1405
- * program.argument('[output-file]');
1406
- *
1407
- * @param {string} name
1408
- * @param {string} [description]
1409
- * @param {(Function|*)} [fn] - custom argument processing function
1410
- * @param {*} [defaultValue]
1411
- * @return {Command} `this` command for chaining
1412
- */
1413
- argument(name, description, fn, defaultValue) {
1414
- const argument = this.createArgument(name, description);
1415
- if (typeof fn === "function") {
1416
- argument.default(defaultValue).argParser(fn);
1417
- } else {
1418
- argument.default(fn);
1419
- }
1420
- this.addArgument(argument);
1421
- return this;
1422
- }
1423
- /**
1424
- * Define argument syntax for command, adding multiple at once (without descriptions).
1425
- *
1426
- * See also .argument().
1427
- *
1428
- * @example
1429
- * program.arguments('<cmd> [env]');
1430
- *
1431
- * @param {string} names
1432
- * @return {Command} `this` command for chaining
1433
- */
1434
- arguments(names) {
1435
- names.trim().split(/ +/).forEach((detail) => {
1436
- this.argument(detail);
1437
- });
1438
- return this;
1439
- }
1440
- /**
1441
- * Define argument syntax for command, adding a prepared argument.
1442
- *
1443
- * @param {Argument} argument
1444
- * @return {Command} `this` command for chaining
1445
- */
1446
- addArgument(argument) {
1447
- const previousArgument = this.registeredArguments.slice(-1)[0];
1448
- if (previousArgument && previousArgument.variadic) {
1449
- throw new Error(
1450
- `only the last argument can be variadic '${previousArgument.name()}'`
1451
- );
1452
- }
1453
- if (argument.required && argument.defaultValue !== void 0 && argument.parseArg === void 0) {
1454
- throw new Error(
1455
- `a default value for a required argument is never used: '${argument.name()}'`
1456
- );
1457
- }
1458
- this.registeredArguments.push(argument);
1459
- return this;
1460
- }
1461
- /**
1462
- * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
1463
- *
1464
- * @example
1465
- * program.helpCommand('help [cmd]');
1466
- * program.helpCommand('help [cmd]', 'show help');
1467
- * program.helpCommand(false); // suppress default help command
1468
- * program.helpCommand(true); // add help command even if no subcommands
1469
- *
1470
- * @param {string|boolean} enableOrNameAndArgs - enable with custom name and/or arguments, or boolean to override whether added
1471
- * @param {string} [description] - custom description
1472
- * @return {Command} `this` command for chaining
1473
- */
1474
- helpCommand(enableOrNameAndArgs, description) {
1475
- if (typeof enableOrNameAndArgs === "boolean") {
1476
- this._addImplicitHelpCommand = enableOrNameAndArgs;
1477
- return this;
1478
- }
1479
- enableOrNameAndArgs = enableOrNameAndArgs ?? "help [command]";
1480
- const [, helpName, helpArgs] = enableOrNameAndArgs.match(/([^ ]+) *(.*)/);
1481
- const helpDescription = description ?? "display help for command";
1482
- const helpCommand = this.createCommand(helpName);
1483
- helpCommand.helpOption(false);
1484
- if (helpArgs) helpCommand.arguments(helpArgs);
1485
- if (helpDescription) helpCommand.description(helpDescription);
1486
- this._addImplicitHelpCommand = true;
1487
- this._helpCommand = helpCommand;
1488
- return this;
1489
- }
1490
- /**
1491
- * Add prepared custom help command.
1492
- *
1493
- * @param {(Command|string|boolean)} helpCommand - custom help command, or deprecated enableOrNameAndArgs as for `.helpCommand()`
1494
- * @param {string} [deprecatedDescription] - deprecated custom description used with custom name only
1495
- * @return {Command} `this` command for chaining
1496
- */
1497
- addHelpCommand(helpCommand, deprecatedDescription) {
1498
- if (typeof helpCommand !== "object") {
1499
- this.helpCommand(helpCommand, deprecatedDescription);
1500
- return this;
1501
- }
1502
- this._addImplicitHelpCommand = true;
1503
- this._helpCommand = helpCommand;
1504
- return this;
1505
- }
1506
- /**
1507
- * Lazy create help command.
1508
- *
1509
- * @return {(Command|null)}
1510
- * @package
1511
- */
1512
- _getHelpCommand() {
1513
- const hasImplicitHelpCommand = this._addImplicitHelpCommand ?? (this.commands.length && !this._actionHandler && !this._findCommand("help"));
1514
- if (hasImplicitHelpCommand) {
1515
- if (this._helpCommand === void 0) {
1516
- this.helpCommand(void 0, void 0);
1517
- }
1518
- return this._helpCommand;
1519
- }
1520
- return null;
1521
- }
1522
- /**
1523
- * Add hook for life cycle event.
1524
- *
1525
- * @param {string} event
1526
- * @param {Function} listener
1527
- * @return {Command} `this` command for chaining
1528
- */
1529
- hook(event, listener) {
1530
- const allowedValues = ["preSubcommand", "preAction", "postAction"];
1531
- if (!allowedValues.includes(event)) {
1532
- throw new Error(`Unexpected value for event passed to hook : '${event}'.
1533
- Expecting one of '${allowedValues.join("', '")}'`);
1534
- }
1535
- if (this._lifeCycleHooks[event]) {
1536
- this._lifeCycleHooks[event].push(listener);
1537
- } else {
1538
- this._lifeCycleHooks[event] = [listener];
1539
- }
1540
- return this;
1541
- }
1542
- /**
1543
- * Register callback to use as replacement for calling process.exit.
1544
- *
1545
- * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing
1546
- * @return {Command} `this` command for chaining
1547
- */
1548
- exitOverride(fn) {
1549
- if (fn) {
1550
- this._exitCallback = fn;
1551
- } else {
1552
- this._exitCallback = (err) => {
1553
- if (err.code !== "commander.executeSubCommandAsync") {
1554
- throw err;
1555
- } else {
1556
- }
1557
- };
1558
- }
1559
- return this;
1560
- }
1561
- /**
1562
- * Call process.exit, and _exitCallback if defined.
1563
- *
1564
- * @param {number} exitCode exit code for using with process.exit
1565
- * @param {string} code an id string representing the error
1566
- * @param {string} message human-readable description of the error
1567
- * @return never
1568
- * @private
1569
- */
1570
- _exit(exitCode, code, message) {
1571
- if (this._exitCallback) {
1572
- this._exitCallback(new CommanderError2(exitCode, code, message));
1573
- }
1574
- process2.exit(exitCode);
1575
- }
1576
- /**
1577
- * Register callback `fn` for the command.
1578
- *
1579
- * @example
1580
- * program
1581
- * .command('serve')
1582
- * .description('start service')
1583
- * .action(function() {
1584
- * // do work here
1585
- * });
1586
- *
1587
- * @param {Function} fn
1588
- * @return {Command} `this` command for chaining
1589
- */
1590
- action(fn) {
1591
- const listener = (args) => {
1592
- const expectedArgsCount = this.registeredArguments.length;
1593
- const actionArgs = args.slice(0, expectedArgsCount);
1594
- if (this._storeOptionsAsProperties) {
1595
- actionArgs[expectedArgsCount] = this;
1596
- } else {
1597
- actionArgs[expectedArgsCount] = this.opts();
1598
- }
1599
- actionArgs.push(this);
1600
- return fn.apply(this, actionArgs);
1601
- };
1602
- this._actionHandler = listener;
1603
- return this;
1604
- }
1605
- /**
1606
- * Factory routine to create a new unattached option.
1607
- *
1608
- * See .option() for creating an attached option, which uses this routine to
1609
- * create the option. You can override createOption to return a custom option.
1610
- *
1611
- * @param {string} flags
1612
- * @param {string} [description]
1613
- * @return {Option} new option
1614
- */
1615
- createOption(flags, description) {
1616
- return new Option2(flags, description);
1617
- }
1618
- /**
1619
- * Wrap parseArgs to catch 'commander.invalidArgument'.
1620
- *
1621
- * @param {(Option | Argument)} target
1622
- * @param {string} value
1623
- * @param {*} previous
1624
- * @param {string} invalidArgumentMessage
1625
- * @private
1626
- */
1627
- _callParseArg(target, value, previous, invalidArgumentMessage) {
1628
- try {
1629
- return target.parseArg(value, previous);
1630
- } catch (err) {
1631
- if (err.code === "commander.invalidArgument") {
1632
- const message = `${invalidArgumentMessage} ${err.message}`;
1633
- this.error(message, { exitCode: err.exitCode, code: err.code });
1634
- }
1635
- throw err;
1636
- }
1637
- }
1638
- /**
1639
- * Check for option flag conflicts.
1640
- * Register option if no conflicts found, or throw on conflict.
1641
- *
1642
- * @param {Option} option
1643
- * @private
1644
- */
1645
- _registerOption(option) {
1646
- const matchingOption = option.short && this._findOption(option.short) || option.long && this._findOption(option.long);
1647
- if (matchingOption) {
1648
- const matchingFlag = option.long && this._findOption(option.long) ? option.long : option.short;
1649
- throw new Error(`Cannot add option '${option.flags}'${this._name && ` to command '${this._name}'`} due to conflicting flag '${matchingFlag}'
1650
- - already used by option '${matchingOption.flags}'`);
1651
- }
1652
- this.options.push(option);
1653
- }
1654
- /**
1655
- * Check for command name and alias conflicts with existing commands.
1656
- * Register command if no conflicts found, or throw on conflict.
1657
- *
1658
- * @param {Command} command
1659
- * @private
1660
- */
1661
- _registerCommand(command) {
1662
- const knownBy = (cmd) => {
1663
- return [cmd.name()].concat(cmd.aliases());
1664
- };
1665
- const alreadyUsed = knownBy(command).find(
1666
- (name) => this._findCommand(name)
1667
- );
1668
- if (alreadyUsed) {
1669
- const existingCmd = knownBy(this._findCommand(alreadyUsed)).join("|");
1670
- const newCmd = knownBy(command).join("|");
1671
- throw new Error(
1672
- `cannot add command '${newCmd}' as already have command '${existingCmd}'`
1673
- );
1674
- }
1675
- this.commands.push(command);
1676
- }
1677
- /**
1678
- * Add an option.
1679
- *
1680
- * @param {Option} option
1681
- * @return {Command} `this` command for chaining
1682
- */
1683
- addOption(option) {
1684
- this._registerOption(option);
1685
- const oname = option.name();
1686
- const name = option.attributeName();
1687
- if (option.negate) {
1688
- const positiveLongFlag = option.long.replace(/^--no-/, "--");
1689
- if (!this._findOption(positiveLongFlag)) {
1690
- this.setOptionValueWithSource(
1691
- name,
1692
- option.defaultValue === void 0 ? true : option.defaultValue,
1693
- "default"
1694
- );
1695
- }
1696
- } else if (option.defaultValue !== void 0) {
1697
- this.setOptionValueWithSource(name, option.defaultValue, "default");
1698
- }
1699
- const handleOptionValue = (val, invalidValueMessage, valueSource) => {
1700
- if (val == null && option.presetArg !== void 0) {
1701
- val = option.presetArg;
1702
- }
1703
- const oldValue = this.getOptionValue(name);
1704
- if (val !== null && option.parseArg) {
1705
- val = this._callParseArg(option, val, oldValue, invalidValueMessage);
1706
- } else if (val !== null && option.variadic) {
1707
- val = option._concatValue(val, oldValue);
1708
- }
1709
- if (val == null) {
1710
- if (option.negate) {
1711
- val = false;
1712
- } else if (option.isBoolean() || option.optional) {
1713
- val = true;
1714
- } else {
1715
- val = "";
1716
- }
1717
- }
1718
- this.setOptionValueWithSource(name, val, valueSource);
1719
- };
1720
- this.on("option:" + oname, (val) => {
1721
- const invalidValueMessage = `error: option '${option.flags}' argument '${val}' is invalid.`;
1722
- handleOptionValue(val, invalidValueMessage, "cli");
1723
- });
1724
- if (option.envVar) {
1725
- this.on("optionEnv:" + oname, (val) => {
1726
- const invalidValueMessage = `error: option '${option.flags}' value '${val}' from env '${option.envVar}' is invalid.`;
1727
- handleOptionValue(val, invalidValueMessage, "env");
1728
- });
1729
- }
1730
- return this;
1731
- }
1732
- /**
1733
- * Internal implementation shared by .option() and .requiredOption()
1734
- *
1735
- * @return {Command} `this` command for chaining
1736
- * @private
1737
- */
1738
- _optionEx(config, flags, description, fn, defaultValue) {
1739
- if (typeof flags === "object" && flags instanceof Option2) {
1740
- throw new Error(
1741
- "To add an Option object use addOption() instead of option() or requiredOption()"
1742
- );
1743
- }
1744
- const option = this.createOption(flags, description);
1745
- option.makeOptionMandatory(!!config.mandatory);
1746
- if (typeof fn === "function") {
1747
- option.default(defaultValue).argParser(fn);
1748
- } else if (fn instanceof RegExp) {
1749
- const regex = fn;
1750
- fn = (val, def) => {
1751
- const m = regex.exec(val);
1752
- return m ? m[0] : def;
1753
- };
1754
- option.default(defaultValue).argParser(fn);
1755
- } else {
1756
- option.default(fn);
1757
- }
1758
- return this.addOption(option);
1759
- }
1760
- /**
1761
- * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
1762
- *
1763
- * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
1764
- * option-argument is indicated by `<>` and an optional option-argument by `[]`.
1765
- *
1766
- * See the README for more details, and see also addOption() and requiredOption().
1767
- *
1768
- * @example
1769
- * program
1770
- * .option('-p, --pepper', 'add pepper')
1771
- * .option('--pt, --pizza-type <TYPE>', 'type of pizza') // required option-argument
1772
- * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
1773
- * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
1774
- *
1775
- * @param {string} flags
1776
- * @param {string} [description]
1777
- * @param {(Function|*)} [parseArg] - custom option processing function or default value
1778
- * @param {*} [defaultValue]
1779
- * @return {Command} `this` command for chaining
1780
- */
1781
- option(flags, description, parseArg, defaultValue) {
1782
- return this._optionEx({}, flags, description, parseArg, defaultValue);
1783
- }
1784
- /**
1785
- * Add a required option which must have a value after parsing. This usually means
1786
- * the option must be specified on the command line. (Otherwise the same as .option().)
1787
- *
1788
- * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
1789
- *
1790
- * @param {string} flags
1791
- * @param {string} [description]
1792
- * @param {(Function|*)} [parseArg] - custom option processing function or default value
1793
- * @param {*} [defaultValue]
1794
- * @return {Command} `this` command for chaining
1795
- */
1796
- requiredOption(flags, description, parseArg, defaultValue) {
1797
- return this._optionEx(
1798
- { mandatory: true },
1799
- flags,
1800
- description,
1801
- parseArg,
1802
- defaultValue
1803
- );
1804
- }
1805
- /**
1806
- * Alter parsing of short flags with optional values.
1807
- *
1808
- * @example
1809
- * // for `.option('-f,--flag [value]'):
1810
- * program.combineFlagAndOptionalValue(true); // `-f80` is treated like `--flag=80`, this is the default behaviour
1811
- * program.combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
1812
- *
1813
- * @param {boolean} [combine] - if `true` or omitted, an optional value can be specified directly after the flag.
1814
- * @return {Command} `this` command for chaining
1815
- */
1816
- combineFlagAndOptionalValue(combine = true) {
1817
- this._combineFlagAndOptionalValue = !!combine;
1818
- return this;
1819
- }
1820
- /**
1821
- * Allow unknown options on the command line.
1822
- *
1823
- * @param {boolean} [allowUnknown] - if `true` or omitted, no error will be thrown for unknown options.
1824
- * @return {Command} `this` command for chaining
1825
- */
1826
- allowUnknownOption(allowUnknown = true) {
1827
- this._allowUnknownOption = !!allowUnknown;
1828
- return this;
1829
- }
1830
- /**
1831
- * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
1832
- *
1833
- * @param {boolean} [allowExcess] - if `true` or omitted, no error will be thrown for excess arguments.
1834
- * @return {Command} `this` command for chaining
1835
- */
1836
- allowExcessArguments(allowExcess = true) {
1837
- this._allowExcessArguments = !!allowExcess;
1838
- return this;
1839
- }
1840
- /**
1841
- * Enable positional options. Positional means global options are specified before subcommands which lets
1842
- * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
1843
- * The default behaviour is non-positional and global options may appear anywhere on the command line.
1844
- *
1845
- * @param {boolean} [positional]
1846
- * @return {Command} `this` command for chaining
1847
- */
1848
- enablePositionalOptions(positional = true) {
1849
- this._enablePositionalOptions = !!positional;
1850
- return this;
1851
- }
1852
- /**
1853
- * Pass through options that come after command-arguments rather than treat them as command-options,
1854
- * so actual command-options come before command-arguments. Turning this on for a subcommand requires
1855
- * positional options to have been enabled on the program (parent commands).
1856
- * The default behaviour is non-positional and options may appear before or after command-arguments.
1857
- *
1858
- * @param {boolean} [passThrough] for unknown options.
1859
- * @return {Command} `this` command for chaining
1860
- */
1861
- passThroughOptions(passThrough = true) {
1862
- this._passThroughOptions = !!passThrough;
1863
- this._checkForBrokenPassThrough();
1864
- return this;
1865
- }
1866
- /**
1867
- * @private
1868
- */
1869
- _checkForBrokenPassThrough() {
1870
- if (this.parent && this._passThroughOptions && !this.parent._enablePositionalOptions) {
1871
- throw new Error(
1872
- `passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`
1873
- );
1874
- }
1875
- }
1876
- /**
1877
- * Whether to store option values as properties on command object,
1878
- * or store separately (specify false). In both cases the option values can be accessed using .opts().
1879
- *
1880
- * @param {boolean} [storeAsProperties=true]
1881
- * @return {Command} `this` command for chaining
1882
- */
1883
- storeOptionsAsProperties(storeAsProperties = true) {
1884
- if (this.options.length) {
1885
- throw new Error("call .storeOptionsAsProperties() before adding options");
1886
- }
1887
- if (Object.keys(this._optionValues).length) {
1888
- throw new Error(
1889
- "call .storeOptionsAsProperties() before setting option values"
1890
- );
1891
- }
1892
- this._storeOptionsAsProperties = !!storeAsProperties;
1893
- return this;
1894
- }
1895
- /**
1896
- * Retrieve option value.
1897
- *
1898
- * @param {string} key
1899
- * @return {object} value
1900
- */
1901
- getOptionValue(key) {
1902
- if (this._storeOptionsAsProperties) {
1903
- return this[key];
1904
- }
1905
- return this._optionValues[key];
1906
- }
1907
- /**
1908
- * Store option value.
1909
- *
1910
- * @param {string} key
1911
- * @param {object} value
1912
- * @return {Command} `this` command for chaining
1913
- */
1914
- setOptionValue(key, value) {
1915
- return this.setOptionValueWithSource(key, value, void 0);
1916
- }
1917
- /**
1918
- * Store option value and where the value came from.
1919
- *
1920
- * @param {string} key
1921
- * @param {object} value
1922
- * @param {string} source - expected values are default/config/env/cli/implied
1923
- * @return {Command} `this` command for chaining
1924
- */
1925
- setOptionValueWithSource(key, value, source) {
1926
- if (this._storeOptionsAsProperties) {
1927
- this[key] = value;
1928
- } else {
1929
- this._optionValues[key] = value;
1930
- }
1931
- this._optionValueSources[key] = source;
1932
- return this;
1933
- }
1934
- /**
1935
- * Get source of option value.
1936
- * Expected values are default | config | env | cli | implied
1937
- *
1938
- * @param {string} key
1939
- * @return {string}
1940
- */
1941
- getOptionValueSource(key) {
1942
- return this._optionValueSources[key];
1943
- }
1944
- /**
1945
- * Get source of option value. See also .optsWithGlobals().
1946
- * Expected values are default | config | env | cli | implied
1947
- *
1948
- * @param {string} key
1949
- * @return {string}
1950
- */
1951
- getOptionValueSourceWithGlobals(key) {
1952
- let source;
1953
- this._getCommandAndAncestors().forEach((cmd) => {
1954
- if (cmd.getOptionValueSource(key) !== void 0) {
1955
- source = cmd.getOptionValueSource(key);
1956
- }
1957
- });
1958
- return source;
1959
- }
1960
- /**
1961
- * Get user arguments from implied or explicit arguments.
1962
- * Side-effects: set _scriptPath if args included script. Used for default program name, and subcommand searches.
1963
- *
1964
- * @private
1965
- */
1966
- _prepareUserArgs(argv, parseOptions) {
1967
- if (argv !== void 0 && !Array.isArray(argv)) {
1968
- throw new Error("first parameter to parse must be array or undefined");
1969
- }
1970
- parseOptions = parseOptions || {};
1971
- if (argv === void 0 && parseOptions.from === void 0) {
1972
- if (process2.versions?.electron) {
1973
- parseOptions.from = "electron";
1974
- }
1975
- const execArgv = process2.execArgv ?? [];
1976
- if (execArgv.includes("-e") || execArgv.includes("--eval") || execArgv.includes("-p") || execArgv.includes("--print")) {
1977
- parseOptions.from = "eval";
1978
- }
1979
- }
1980
- if (argv === void 0) {
1981
- argv = process2.argv;
1982
- }
1983
- this.rawArgs = argv.slice();
1984
- let userArgs;
1985
- switch (parseOptions.from) {
1986
- case void 0:
1987
- case "node":
1988
- this._scriptPath = argv[1];
1989
- userArgs = argv.slice(2);
1990
- break;
1991
- case "electron":
1992
- if (process2.defaultApp) {
1993
- this._scriptPath = argv[1];
1994
- userArgs = argv.slice(2);
1995
- } else {
1996
- userArgs = argv.slice(1);
1997
- }
1998
- break;
1999
- case "user":
2000
- userArgs = argv.slice(0);
2001
- break;
2002
- case "eval":
2003
- userArgs = argv.slice(1);
2004
- break;
2005
- default:
2006
- throw new Error(
2007
- `unexpected parse option { from: '${parseOptions.from}' }`
2008
- );
2009
- }
2010
- if (!this._name && this._scriptPath)
2011
- this.nameFromFilename(this._scriptPath);
2012
- this._name = this._name || "program";
2013
- return userArgs;
2014
- }
2015
- /**
2016
- * Parse `argv`, setting options and invoking commands when defined.
2017
- *
2018
- * Use parseAsync instead of parse if any of your action handlers are async.
2019
- *
2020
- * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2021
- *
2022
- * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2023
- * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2024
- * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2025
- * - `'user'`: just user arguments
2026
- *
2027
- * @example
2028
- * program.parse(); // parse process.argv and auto-detect electron and special node flags
2029
- * program.parse(process.argv); // assume argv[0] is app and argv[1] is script
2030
- * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2031
- *
2032
- * @param {string[]} [argv] - optional, defaults to process.argv
2033
- * @param {object} [parseOptions] - optionally specify style of options with from: node/user/electron
2034
- * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron'
2035
- * @return {Command} `this` command for chaining
2036
- */
2037
- parse(argv, parseOptions) {
2038
- this._prepareForParse();
2039
- const userArgs = this._prepareUserArgs(argv, parseOptions);
2040
- this._parseCommand([], userArgs);
2041
- return this;
2042
- }
2043
- /**
2044
- * Parse `argv`, setting options and invoking commands when defined.
2045
- *
2046
- * Call with no parameters to parse `process.argv`. Detects Electron and special node options like `node --eval`. Easy mode!
2047
- *
2048
- * Or call with an array of strings to parse, and optionally where the user arguments start by specifying where the arguments are `from`:
2049
- * - `'node'`: default, `argv[0]` is the application and `argv[1]` is the script being run, with user arguments after that
2050
- * - `'electron'`: `argv[0]` is the application and `argv[1]` varies depending on whether the electron application is packaged
2051
- * - `'user'`: just user arguments
2052
- *
2053
- * @example
2054
- * await program.parseAsync(); // parse process.argv and auto-detect electron and special node flags
2055
- * await program.parseAsync(process.argv); // assume argv[0] is app and argv[1] is script
2056
- * await program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
2057
- *
2058
- * @param {string[]} [argv]
2059
- * @param {object} [parseOptions]
2060
- * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron'
2061
- * @return {Promise}
2062
- */
2063
- async parseAsync(argv, parseOptions) {
2064
- this._prepareForParse();
2065
- const userArgs = this._prepareUserArgs(argv, parseOptions);
2066
- await this._parseCommand([], userArgs);
2067
- return this;
2068
- }
2069
- _prepareForParse() {
2070
- if (this._savedState === null) {
2071
- this.saveStateBeforeParse();
2072
- } else {
2073
- this.restoreStateBeforeParse();
2074
- }
2075
- }
2076
- /**
2077
- * Called the first time parse is called to save state and allow a restore before subsequent calls to parse.
2078
- * Not usually called directly, but available for subclasses to save their custom state.
2079
- *
2080
- * This is called in a lazy way. Only commands used in parsing chain will have state saved.
2081
- */
2082
- saveStateBeforeParse() {
2083
- this._savedState = {
2084
- // name is stable if supplied by author, but may be unspecified for root command and deduced during parsing
2085
- _name: this._name,
2086
- // option values before parse have default values (including false for negated options)
2087
- // shallow clones
2088
- _optionValues: { ...this._optionValues },
2089
- _optionValueSources: { ...this._optionValueSources }
2090
- };
2091
- }
2092
- /**
2093
- * Restore state before parse for calls after the first.
2094
- * Not usually called directly, but available for subclasses to save their custom state.
2095
- *
2096
- * This is called in a lazy way. Only commands used in parsing chain will have state restored.
2097
- */
2098
- restoreStateBeforeParse() {
2099
- if (this._storeOptionsAsProperties)
2100
- throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
2101
- - either make a new Command for each call to parse, or stop storing options as properties`);
2102
- this._name = this._savedState._name;
2103
- this._scriptPath = null;
2104
- this.rawArgs = [];
2105
- this._optionValues = { ...this._savedState._optionValues };
2106
- this._optionValueSources = { ...this._savedState._optionValueSources };
2107
- this.args = [];
2108
- this.processedArgs = [];
2109
- }
2110
- /**
2111
- * Throw if expected executable is missing. Add lots of help for author.
2112
- *
2113
- * @param {string} executableFile
2114
- * @param {string} executableDir
2115
- * @param {string} subcommandName
2116
- */
2117
- _checkForMissingExecutable(executableFile, executableDir, subcommandName) {
2118
- if (fs.existsSync(executableFile)) return;
2119
- 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";
2120
- const executableMissing = `'${executableFile}' does not exist
2121
- - if '${subcommandName}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
2122
- - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
2123
- - ${executableDirMessage}`;
2124
- throw new Error(executableMissing);
2125
- }
2126
- /**
2127
- * Execute a sub-command executable.
2128
- *
2129
- * @private
2130
- */
2131
- _executeSubCommand(subcommand, args) {
2132
- args = args.slice();
2133
- let launchWithNode = false;
2134
- const sourceExt = [".js", ".ts", ".tsx", ".mjs", ".cjs"];
2135
- function findFile(baseDir, baseName) {
2136
- const localBin = path.resolve(baseDir, baseName);
2137
- if (fs.existsSync(localBin)) return localBin;
2138
- if (sourceExt.includes(path.extname(baseName))) return void 0;
2139
- const foundExt = sourceExt.find(
2140
- (ext) => fs.existsSync(`${localBin}${ext}`)
2141
- );
2142
- if (foundExt) return `${localBin}${foundExt}`;
2143
- return void 0;
2144
- }
2145
- this._checkForMissingMandatoryOptions();
2146
- this._checkForConflictingOptions();
2147
- let executableFile = subcommand._executableFile || `${this._name}-${subcommand._name}`;
2148
- let executableDir = this._executableDir || "";
2149
- if (this._scriptPath) {
2150
- let resolvedScriptPath;
2151
- try {
2152
- resolvedScriptPath = fs.realpathSync(this._scriptPath);
2153
- } catch {
2154
- resolvedScriptPath = this._scriptPath;
2155
- }
2156
- executableDir = path.resolve(
2157
- path.dirname(resolvedScriptPath),
2158
- executableDir
2159
- );
2160
- }
2161
- if (executableDir) {
2162
- let localFile = findFile(executableDir, executableFile);
2163
- if (!localFile && !subcommand._executableFile && this._scriptPath) {
2164
- const legacyName = path.basename(
2165
- this._scriptPath,
2166
- path.extname(this._scriptPath)
2167
- );
2168
- if (legacyName !== this._name) {
2169
- localFile = findFile(
2170
- executableDir,
2171
- `${legacyName}-${subcommand._name}`
2172
- );
2173
- }
2174
- }
2175
- executableFile = localFile || executableFile;
2176
- }
2177
- launchWithNode = sourceExt.includes(path.extname(executableFile));
2178
- let proc;
2179
- if (process2.platform !== "win32") {
2180
- if (launchWithNode) {
2181
- args.unshift(executableFile);
2182
- args = incrementNodeInspectorPort(process2.execArgv).concat(args);
2183
- proc = childProcess.spawn(process2.argv[0], args, { stdio: "inherit" });
2184
- } else {
2185
- proc = childProcess.spawn(executableFile, args, { stdio: "inherit" });
2186
- }
2187
- } else {
2188
- this._checkForMissingExecutable(
2189
- executableFile,
2190
- executableDir,
2191
- subcommand._name
2192
- );
2193
- args.unshift(executableFile);
2194
- args = incrementNodeInspectorPort(process2.execArgv).concat(args);
2195
- proc = childProcess.spawn(process2.execPath, args, { stdio: "inherit" });
2196
- }
2197
- if (!proc.killed) {
2198
- const signals = ["SIGUSR1", "SIGUSR2", "SIGTERM", "SIGINT", "SIGHUP"];
2199
- signals.forEach((signal) => {
2200
- process2.on(signal, () => {
2201
- if (proc.killed === false && proc.exitCode === null) {
2202
- proc.kill(signal);
2203
- }
2204
- });
2205
- });
2206
- }
2207
- const exitCallback = this._exitCallback;
2208
- proc.on("close", (code) => {
2209
- code = code ?? 1;
2210
- if (!exitCallback) {
2211
- process2.exit(code);
2212
- } else {
2213
- exitCallback(
2214
- new CommanderError2(
2215
- code,
2216
- "commander.executeSubCommandAsync",
2217
- "(close)"
2218
- )
2219
- );
2220
- }
2221
- });
2222
- proc.on("error", (err) => {
2223
- if (err.code === "ENOENT") {
2224
- this._checkForMissingExecutable(
2225
- executableFile,
2226
- executableDir,
2227
- subcommand._name
2228
- );
2229
- } else if (err.code === "EACCES") {
2230
- throw new Error(`'${executableFile}' not executable`);
2231
- }
2232
- if (!exitCallback) {
2233
- process2.exit(1);
2234
- } else {
2235
- const wrappedError = new CommanderError2(
2236
- 1,
2237
- "commander.executeSubCommandAsync",
2238
- "(error)"
2239
- );
2240
- wrappedError.nestedError = err;
2241
- exitCallback(wrappedError);
2242
- }
2243
- });
2244
- this.runningCommand = proc;
2245
- }
2246
- /**
2247
- * @private
2248
- */
2249
- _dispatchSubcommand(commandName, operands, unknown) {
2250
- const subCommand = this._findCommand(commandName);
2251
- if (!subCommand) this.help({ error: true });
2252
- subCommand._prepareForParse();
2253
- let promiseChain;
2254
- promiseChain = this._chainOrCallSubCommandHook(
2255
- promiseChain,
2256
- subCommand,
2257
- "preSubcommand"
2258
- );
2259
- promiseChain = this._chainOrCall(promiseChain, () => {
2260
- if (subCommand._executableHandler) {
2261
- this._executeSubCommand(subCommand, operands.concat(unknown));
2262
- } else {
2263
- return subCommand._parseCommand(operands, unknown);
2264
- }
2265
- });
2266
- return promiseChain;
2267
- }
2268
- /**
2269
- * Invoke help directly if possible, or dispatch if necessary.
2270
- * e.g. help foo
2271
- *
2272
- * @private
2273
- */
2274
- _dispatchHelpCommand(subcommandName) {
2275
- if (!subcommandName) {
2276
- this.help();
2277
- }
2278
- const subCommand = this._findCommand(subcommandName);
2279
- if (subCommand && !subCommand._executableHandler) {
2280
- subCommand.help();
2281
- }
2282
- return this._dispatchSubcommand(
2283
- subcommandName,
2284
- [],
2285
- [this._getHelpOption()?.long ?? this._getHelpOption()?.short ?? "--help"]
2286
- );
2287
- }
2288
- /**
2289
- * Check this.args against expected this.registeredArguments.
2290
- *
2291
- * @private
2292
- */
2293
- _checkNumberOfArguments() {
2294
- this.registeredArguments.forEach((arg, i) => {
2295
- if (arg.required && this.args[i] == null) {
2296
- this.missingArgument(arg.name());
2297
- }
2298
- });
2299
- if (this.registeredArguments.length > 0 && this.registeredArguments[this.registeredArguments.length - 1].variadic) {
2300
- return;
2301
- }
2302
- if (this.args.length > this.registeredArguments.length) {
2303
- this._excessArguments(this.args);
2304
- }
2305
- }
2306
- /**
2307
- * Process this.args using this.registeredArguments and save as this.processedArgs!
2308
- *
2309
- * @private
2310
- */
2311
- _processArguments() {
2312
- const myParseArg = (argument, value, previous) => {
2313
- let parsedValue = value;
2314
- if (value !== null && argument.parseArg) {
2315
- const invalidValueMessage = `error: command-argument value '${value}' is invalid for argument '${argument.name()}'.`;
2316
- parsedValue = this._callParseArg(
2317
- argument,
2318
- value,
2319
- previous,
2320
- invalidValueMessage
2321
- );
2322
- }
2323
- return parsedValue;
2324
- };
2325
- this._checkNumberOfArguments();
2326
- const processedArgs = [];
2327
- this.registeredArguments.forEach((declaredArg, index) => {
2328
- let value = declaredArg.defaultValue;
2329
- if (declaredArg.variadic) {
2330
- if (index < this.args.length) {
2331
- value = this.args.slice(index);
2332
- if (declaredArg.parseArg) {
2333
- value = value.reduce((processed, v) => {
2334
- return myParseArg(declaredArg, v, processed);
2335
- }, declaredArg.defaultValue);
2336
- }
2337
- } else if (value === void 0) {
2338
- value = [];
2339
- }
2340
- } else if (index < this.args.length) {
2341
- value = this.args[index];
2342
- if (declaredArg.parseArg) {
2343
- value = myParseArg(declaredArg, value, declaredArg.defaultValue);
2344
- }
2345
- }
2346
- processedArgs[index] = value;
2347
- });
2348
- this.processedArgs = processedArgs;
2349
- }
2350
- /**
2351
- * Once we have a promise we chain, but call synchronously until then.
2352
- *
2353
- * @param {(Promise|undefined)} promise
2354
- * @param {Function} fn
2355
- * @return {(Promise|undefined)}
2356
- * @private
2357
- */
2358
- _chainOrCall(promise, fn) {
2359
- if (promise && promise.then && typeof promise.then === "function") {
2360
- return promise.then(() => fn());
2361
- }
2362
- return fn();
2363
- }
2364
- /**
2365
- *
2366
- * @param {(Promise|undefined)} promise
2367
- * @param {string} event
2368
- * @return {(Promise|undefined)}
2369
- * @private
2370
- */
2371
- _chainOrCallHooks(promise, event) {
2372
- let result = promise;
2373
- const hooks = [];
2374
- this._getCommandAndAncestors().reverse().filter((cmd) => cmd._lifeCycleHooks[event] !== void 0).forEach((hookedCommand) => {
2375
- hookedCommand._lifeCycleHooks[event].forEach((callback) => {
2376
- hooks.push({ hookedCommand, callback });
2377
- });
2378
- });
2379
- if (event === "postAction") {
2380
- hooks.reverse();
2381
- }
2382
- hooks.forEach((hookDetail) => {
2383
- result = this._chainOrCall(result, () => {
2384
- return hookDetail.callback(hookDetail.hookedCommand, this);
2385
- });
2386
- });
2387
- return result;
2388
- }
2389
- /**
2390
- *
2391
- * @param {(Promise|undefined)} promise
2392
- * @param {Command} subCommand
2393
- * @param {string} event
2394
- * @return {(Promise|undefined)}
2395
- * @private
2396
- */
2397
- _chainOrCallSubCommandHook(promise, subCommand, event) {
2398
- let result = promise;
2399
- if (this._lifeCycleHooks[event] !== void 0) {
2400
- this._lifeCycleHooks[event].forEach((hook) => {
2401
- result = this._chainOrCall(result, () => {
2402
- return hook(this, subCommand);
2403
- });
2404
- });
2405
- }
2406
- return result;
2407
- }
2408
- /**
2409
- * Process arguments in context of this command.
2410
- * Returns action result, in case it is a promise.
2411
- *
2412
- * @private
2413
- */
2414
- _parseCommand(operands, unknown) {
2415
- const parsed = this.parseOptions(unknown);
2416
- this._parseOptionsEnv();
2417
- this._parseOptionsImplied();
2418
- operands = operands.concat(parsed.operands);
2419
- unknown = parsed.unknown;
2420
- this.args = operands.concat(unknown);
2421
- if (operands && this._findCommand(operands[0])) {
2422
- return this._dispatchSubcommand(operands[0], operands.slice(1), unknown);
2423
- }
2424
- if (this._getHelpCommand() && operands[0] === this._getHelpCommand().name()) {
2425
- return this._dispatchHelpCommand(operands[1]);
2426
- }
2427
- if (this._defaultCommandName) {
2428
- this._outputHelpIfRequested(unknown);
2429
- return this._dispatchSubcommand(
2430
- this._defaultCommandName,
2431
- operands,
2432
- unknown
2433
- );
2434
- }
2435
- if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) {
2436
- this.help({ error: true });
2437
- }
2438
- this._outputHelpIfRequested(parsed.unknown);
2439
- this._checkForMissingMandatoryOptions();
2440
- this._checkForConflictingOptions();
2441
- const checkForUnknownOptions = () => {
2442
- if (parsed.unknown.length > 0) {
2443
- this.unknownOption(parsed.unknown[0]);
2444
- }
2445
- };
2446
- const commandEvent = `command:${this.name()}`;
2447
- if (this._actionHandler) {
2448
- checkForUnknownOptions();
2449
- this._processArguments();
2450
- let promiseChain;
2451
- promiseChain = this._chainOrCallHooks(promiseChain, "preAction");
2452
- promiseChain = this._chainOrCall(
2453
- promiseChain,
2454
- () => this._actionHandler(this.processedArgs)
2455
- );
2456
- if (this.parent) {
2457
- promiseChain = this._chainOrCall(promiseChain, () => {
2458
- this.parent.emit(commandEvent, operands, unknown);
2459
- });
2460
- }
2461
- promiseChain = this._chainOrCallHooks(promiseChain, "postAction");
2462
- return promiseChain;
2463
- }
2464
- if (this.parent && this.parent.listenerCount(commandEvent)) {
2465
- checkForUnknownOptions();
2466
- this._processArguments();
2467
- this.parent.emit(commandEvent, operands, unknown);
2468
- } else if (operands.length) {
2469
- if (this._findCommand("*")) {
2470
- return this._dispatchSubcommand("*", operands, unknown);
2471
- }
2472
- if (this.listenerCount("command:*")) {
2473
- this.emit("command:*", operands, unknown);
2474
- } else if (this.commands.length) {
2475
- this.unknownCommand();
2476
- } else {
2477
- checkForUnknownOptions();
2478
- this._processArguments();
2479
- }
2480
- } else if (this.commands.length) {
2481
- checkForUnknownOptions();
2482
- this.help({ error: true });
2483
- } else {
2484
- checkForUnknownOptions();
2485
- this._processArguments();
2486
- }
2487
- }
2488
- /**
2489
- * Find matching command.
2490
- *
2491
- * @private
2492
- * @return {Command | undefined}
2493
- */
2494
- _findCommand(name) {
2495
- if (!name) return void 0;
2496
- return this.commands.find(
2497
- (cmd) => cmd._name === name || cmd._aliases.includes(name)
2498
- );
2499
- }
2500
- /**
2501
- * Return an option matching `arg` if any.
2502
- *
2503
- * @param {string} arg
2504
- * @return {Option}
2505
- * @package
2506
- */
2507
- _findOption(arg) {
2508
- return this.options.find((option) => option.is(arg));
2509
- }
2510
- /**
2511
- * Display an error message if a mandatory option does not have a value.
2512
- * Called after checking for help flags in leaf subcommand.
2513
- *
2514
- * @private
2515
- */
2516
- _checkForMissingMandatoryOptions() {
2517
- this._getCommandAndAncestors().forEach((cmd) => {
2518
- cmd.options.forEach((anOption) => {
2519
- if (anOption.mandatory && cmd.getOptionValue(anOption.attributeName()) === void 0) {
2520
- cmd.missingMandatoryOptionValue(anOption);
2521
- }
2522
- });
2523
- });
2524
- }
2525
- /**
2526
- * Display an error message if conflicting options are used together in this.
2527
- *
2528
- * @private
2529
- */
2530
- _checkForConflictingLocalOptions() {
2531
- const definedNonDefaultOptions = this.options.filter((option) => {
2532
- const optionKey = option.attributeName();
2533
- if (this.getOptionValue(optionKey) === void 0) {
2534
- return false;
2535
- }
2536
- return this.getOptionValueSource(optionKey) !== "default";
2537
- });
2538
- const optionsWithConflicting = definedNonDefaultOptions.filter(
2539
- (option) => option.conflictsWith.length > 0
2540
- );
2541
- optionsWithConflicting.forEach((option) => {
2542
- const conflictingAndDefined = definedNonDefaultOptions.find(
2543
- (defined) => option.conflictsWith.includes(defined.attributeName())
2544
- );
2545
- if (conflictingAndDefined) {
2546
- this._conflictingOption(option, conflictingAndDefined);
2547
- }
2548
- });
2549
- }
2550
- /**
2551
- * Display an error message if conflicting options are used together.
2552
- * Called after checking for help flags in leaf subcommand.
2553
- *
2554
- * @private
2555
- */
2556
- _checkForConflictingOptions() {
2557
- this._getCommandAndAncestors().forEach((cmd) => {
2558
- cmd._checkForConflictingLocalOptions();
2559
- });
2560
- }
2561
- /**
2562
- * Parse options from `argv` removing known options,
2563
- * and return argv split into operands and unknown arguments.
2564
- *
2565
- * Side effects: modifies command by storing options. Does not reset state if called again.
2566
- *
2567
- * Examples:
2568
- *
2569
- * argv => operands, unknown
2570
- * --known kkk op => [op], []
2571
- * op --known kkk => [op], []
2572
- * sub --unknown uuu op => [sub], [--unknown uuu op]
2573
- * sub -- --unknown uuu op => [sub --unknown uuu op], []
2574
- *
2575
- * @param {string[]} argv
2576
- * @return {{operands: string[], unknown: string[]}}
2577
- */
2578
- parseOptions(argv) {
2579
- const operands = [];
2580
- const unknown = [];
2581
- let dest = operands;
2582
- const args = argv.slice();
2583
- function maybeOption(arg) {
2584
- return arg.length > 1 && arg[0] === "-";
2585
- }
2586
- let activeVariadicOption = null;
2587
- while (args.length) {
2588
- const arg = args.shift();
2589
- if (arg === "--") {
2590
- if (dest === unknown) dest.push(arg);
2591
- dest.push(...args);
2592
- break;
2593
- }
2594
- if (activeVariadicOption && !maybeOption(arg)) {
2595
- this.emit(`option:${activeVariadicOption.name()}`, arg);
2596
- continue;
2597
- }
2598
- activeVariadicOption = null;
2599
- if (maybeOption(arg)) {
2600
- const option = this._findOption(arg);
2601
- if (option) {
2602
- if (option.required) {
2603
- const value = args.shift();
2604
- if (value === void 0) this.optionMissingArgument(option);
2605
- this.emit(`option:${option.name()}`, value);
2606
- } else if (option.optional) {
2607
- let value = null;
2608
- if (args.length > 0 && !maybeOption(args[0])) {
2609
- value = args.shift();
2610
- }
2611
- this.emit(`option:${option.name()}`, value);
2612
- } else {
2613
- this.emit(`option:${option.name()}`);
2614
- }
2615
- activeVariadicOption = option.variadic ? option : null;
2616
- continue;
2617
- }
2618
- }
2619
- if (arg.length > 2 && arg[0] === "-" && arg[1] !== "-") {
2620
- const option = this._findOption(`-${arg[1]}`);
2621
- if (option) {
2622
- if (option.required || option.optional && this._combineFlagAndOptionalValue) {
2623
- this.emit(`option:${option.name()}`, arg.slice(2));
2624
- } else {
2625
- this.emit(`option:${option.name()}`);
2626
- args.unshift(`-${arg.slice(2)}`);
2627
- }
2628
- continue;
2629
- }
2630
- }
2631
- if (/^--[^=]+=/.test(arg)) {
2632
- const index = arg.indexOf("=");
2633
- const option = this._findOption(arg.slice(0, index));
2634
- if (option && (option.required || option.optional)) {
2635
- this.emit(`option:${option.name()}`, arg.slice(index + 1));
2636
- continue;
2637
- }
2638
- }
2639
- if (maybeOption(arg)) {
2640
- dest = unknown;
2641
- }
2642
- if ((this._enablePositionalOptions || this._passThroughOptions) && operands.length === 0 && unknown.length === 0) {
2643
- if (this._findCommand(arg)) {
2644
- operands.push(arg);
2645
- if (args.length > 0) unknown.push(...args);
2646
- break;
2647
- } else if (this._getHelpCommand() && arg === this._getHelpCommand().name()) {
2648
- operands.push(arg);
2649
- if (args.length > 0) operands.push(...args);
2650
- break;
2651
- } else if (this._defaultCommandName) {
2652
- unknown.push(arg);
2653
- if (args.length > 0) unknown.push(...args);
2654
- break;
2655
- }
2656
- }
2657
- if (this._passThroughOptions) {
2658
- dest.push(arg);
2659
- if (args.length > 0) dest.push(...args);
2660
- break;
2661
- }
2662
- dest.push(arg);
2663
- }
2664
- return { operands, unknown };
2665
- }
2666
- /**
2667
- * Return an object containing local option values as key-value pairs.
2668
- *
2669
- * @return {object}
2670
- */
2671
- opts() {
2672
- if (this._storeOptionsAsProperties) {
2673
- const result = {};
2674
- const len = this.options.length;
2675
- for (let i = 0; i < len; i++) {
2676
- const key = this.options[i].attributeName();
2677
- result[key] = key === this._versionOptionName ? this._version : this[key];
2678
- }
2679
- return result;
2680
- }
2681
- return this._optionValues;
2682
- }
2683
- /**
2684
- * Return an object containing merged local and global option values as key-value pairs.
2685
- *
2686
- * @return {object}
2687
- */
2688
- optsWithGlobals() {
2689
- return this._getCommandAndAncestors().reduce(
2690
- (combinedOptions, cmd) => Object.assign(combinedOptions, cmd.opts()),
2691
- {}
2692
- );
2693
- }
2694
- /**
2695
- * Display error message and exit (or call exitOverride).
2696
- *
2697
- * @param {string} message
2698
- * @param {object} [errorOptions]
2699
- * @param {string} [errorOptions.code] - an id string representing the error
2700
- * @param {number} [errorOptions.exitCode] - used with process.exit
2701
- */
2702
- error(message, errorOptions) {
2703
- this._outputConfiguration.outputError(
2704
- `${message}
2705
- `,
2706
- this._outputConfiguration.writeErr
2707
- );
2708
- if (typeof this._showHelpAfterError === "string") {
2709
- this._outputConfiguration.writeErr(`${this._showHelpAfterError}
2710
- `);
2711
- } else if (this._showHelpAfterError) {
2712
- this._outputConfiguration.writeErr("\n");
2713
- this.outputHelp({ error: true });
2714
- }
2715
- const config = errorOptions || {};
2716
- const exitCode = config.exitCode || 1;
2717
- const code = config.code || "commander.error";
2718
- this._exit(exitCode, code, message);
2719
- }
2720
- /**
2721
- * Apply any option related environment variables, if option does
2722
- * not have a value from cli or client code.
2723
- *
2724
- * @private
2725
- */
2726
- _parseOptionsEnv() {
2727
- this.options.forEach((option) => {
2728
- if (option.envVar && option.envVar in process2.env) {
2729
- const optionKey = option.attributeName();
2730
- if (this.getOptionValue(optionKey) === void 0 || ["default", "config", "env"].includes(
2731
- this.getOptionValueSource(optionKey)
2732
- )) {
2733
- if (option.required || option.optional) {
2734
- this.emit(`optionEnv:${option.name()}`, process2.env[option.envVar]);
2735
- } else {
2736
- this.emit(`optionEnv:${option.name()}`);
2737
- }
2738
- }
2739
- }
2740
- });
2741
- }
2742
- /**
2743
- * Apply any implied option values, if option is undefined or default value.
2744
- *
2745
- * @private
2746
- */
2747
- _parseOptionsImplied() {
2748
- const dualHelper = new DualOptions(this.options);
2749
- const hasCustomOptionValue = (optionKey) => {
2750
- return this.getOptionValue(optionKey) !== void 0 && !["default", "implied"].includes(this.getOptionValueSource(optionKey));
2751
- };
2752
- this.options.filter(
2753
- (option) => option.implied !== void 0 && hasCustomOptionValue(option.attributeName()) && dualHelper.valueFromOption(
2754
- this.getOptionValue(option.attributeName()),
2755
- option
2756
- )
2757
- ).forEach((option) => {
2758
- Object.keys(option.implied).filter((impliedKey) => !hasCustomOptionValue(impliedKey)).forEach((impliedKey) => {
2759
- this.setOptionValueWithSource(
2760
- impliedKey,
2761
- option.implied[impliedKey],
2762
- "implied"
2763
- );
2764
- });
2765
- });
2766
- }
2767
- /**
2768
- * Argument `name` is missing.
2769
- *
2770
- * @param {string} name
2771
- * @private
2772
- */
2773
- missingArgument(name) {
2774
- const message = `error: missing required argument '${name}'`;
2775
- this.error(message, { code: "commander.missingArgument" });
2776
- }
2777
- /**
2778
- * `Option` is missing an argument.
2779
- *
2780
- * @param {Option} option
2781
- * @private
2782
- */
2783
- optionMissingArgument(option) {
2784
- const message = `error: option '${option.flags}' argument missing`;
2785
- this.error(message, { code: "commander.optionMissingArgument" });
2786
- }
2787
- /**
2788
- * `Option` does not have a value, and is a mandatory option.
2789
- *
2790
- * @param {Option} option
2791
- * @private
2792
- */
2793
- missingMandatoryOptionValue(option) {
2794
- const message = `error: required option '${option.flags}' not specified`;
2795
- this.error(message, { code: "commander.missingMandatoryOptionValue" });
2796
- }
2797
- /**
2798
- * `Option` conflicts with another option.
2799
- *
2800
- * @param {Option} option
2801
- * @param {Option} conflictingOption
2802
- * @private
2803
- */
2804
- _conflictingOption(option, conflictingOption) {
2805
- const findBestOptionFromValue = (option2) => {
2806
- const optionKey = option2.attributeName();
2807
- const optionValue = this.getOptionValue(optionKey);
2808
- const negativeOption = this.options.find(
2809
- (target) => target.negate && optionKey === target.attributeName()
2810
- );
2811
- const positiveOption = this.options.find(
2812
- (target) => !target.negate && optionKey === target.attributeName()
2813
- );
2814
- if (negativeOption && (negativeOption.presetArg === void 0 && optionValue === false || negativeOption.presetArg !== void 0 && optionValue === negativeOption.presetArg)) {
2815
- return negativeOption;
2816
- }
2817
- return positiveOption || option2;
2818
- };
2819
- const getErrorMessage = (option2) => {
2820
- const bestOption = findBestOptionFromValue(option2);
2821
- const optionKey = bestOption.attributeName();
2822
- const source = this.getOptionValueSource(optionKey);
2823
- if (source === "env") {
2824
- return `environment variable '${bestOption.envVar}'`;
2825
- }
2826
- return `option '${bestOption.flags}'`;
2827
- };
2828
- const message = `error: ${getErrorMessage(option)} cannot be used with ${getErrorMessage(conflictingOption)}`;
2829
- this.error(message, { code: "commander.conflictingOption" });
2830
- }
2831
- /**
2832
- * Unknown option `flag`.
2833
- *
2834
- * @param {string} flag
2835
- * @private
2836
- */
2837
- unknownOption(flag) {
2838
- if (this._allowUnknownOption) return;
2839
- let suggestion = "";
2840
- if (flag.startsWith("--") && this._showSuggestionAfterError) {
2841
- let candidateFlags = [];
2842
- let command = this;
2843
- do {
2844
- const moreFlags = command.createHelp().visibleOptions(command).filter((option) => option.long).map((option) => option.long);
2845
- candidateFlags = candidateFlags.concat(moreFlags);
2846
- command = command.parent;
2847
- } while (command && !command._enablePositionalOptions);
2848
- suggestion = suggestSimilar(flag, candidateFlags);
2849
- }
2850
- const message = `error: unknown option '${flag}'${suggestion}`;
2851
- this.error(message, { code: "commander.unknownOption" });
2852
- }
2853
- /**
2854
- * Excess arguments, more than expected.
2855
- *
2856
- * @param {string[]} receivedArgs
2857
- * @private
2858
- */
2859
- _excessArguments(receivedArgs) {
2860
- if (this._allowExcessArguments) return;
2861
- const expected = this.registeredArguments.length;
2862
- const s = expected === 1 ? "" : "s";
2863
- const forSubcommand = this.parent ? ` for '${this.name()}'` : "";
2864
- const message = `error: too many arguments${forSubcommand}. Expected ${expected} argument${s} but got ${receivedArgs.length}.`;
2865
- this.error(message, { code: "commander.excessArguments" });
2866
- }
2867
- /**
2868
- * Unknown command.
2869
- *
2870
- * @private
2871
- */
2872
- unknownCommand() {
2873
- const unknownName = this.args[0];
2874
- let suggestion = "";
2875
- if (this._showSuggestionAfterError) {
2876
- const candidateNames = [];
2877
- this.createHelp().visibleCommands(this).forEach((command) => {
2878
- candidateNames.push(command.name());
2879
- if (command.alias()) candidateNames.push(command.alias());
2880
- });
2881
- suggestion = suggestSimilar(unknownName, candidateNames);
2882
- }
2883
- const message = `error: unknown command '${unknownName}'${suggestion}`;
2884
- this.error(message, { code: "commander.unknownCommand" });
2885
- }
2886
- /**
2887
- * Get or set the program version.
2888
- *
2889
- * This method auto-registers the "-V, --version" option which will print the version number.
2890
- *
2891
- * You can optionally supply the flags and description to override the defaults.
2892
- *
2893
- * @param {string} [str]
2894
- * @param {string} [flags]
2895
- * @param {string} [description]
2896
- * @return {(this | string | undefined)} `this` command for chaining, or version string if no arguments
2897
- */
2898
- version(str, flags, description) {
2899
- if (str === void 0) return this._version;
2900
- this._version = str;
2901
- flags = flags || "-V, --version";
2902
- description = description || "output the version number";
2903
- const versionOption = this.createOption(flags, description);
2904
- this._versionOptionName = versionOption.attributeName();
2905
- this._registerOption(versionOption);
2906
- this.on("option:" + versionOption.name(), () => {
2907
- this._outputConfiguration.writeOut(`${str}
2908
- `);
2909
- this._exit(0, "commander.version", str);
2910
- });
2911
- return this;
2912
- }
2913
- /**
2914
- * Set the description.
2915
- *
2916
- * @param {string} [str]
2917
- * @param {object} [argsDescription]
2918
- * @return {(string|Command)}
2919
- */
2920
- description(str, argsDescription) {
2921
- if (str === void 0 && argsDescription === void 0)
2922
- return this._description;
2923
- this._description = str;
2924
- if (argsDescription) {
2925
- this._argsDescription = argsDescription;
2926
- }
2927
- return this;
2928
- }
2929
- /**
2930
- * Set the summary. Used when listed as subcommand of parent.
2931
- *
2932
- * @param {string} [str]
2933
- * @return {(string|Command)}
2934
- */
2935
- summary(str) {
2936
- if (str === void 0) return this._summary;
2937
- this._summary = str;
2938
- return this;
2939
- }
2940
- /**
2941
- * Set an alias for the command.
2942
- *
2943
- * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
2944
- *
2945
- * @param {string} [alias]
2946
- * @return {(string|Command)}
2947
- */
2948
- alias(alias) {
2949
- if (alias === void 0) return this._aliases[0];
2950
- let command = this;
2951
- if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) {
2952
- command = this.commands[this.commands.length - 1];
2953
- }
2954
- if (alias === command._name)
2955
- throw new Error("Command alias can't be the same as its name");
2956
- const matchingCommand = this.parent?._findCommand(alias);
2957
- if (matchingCommand) {
2958
- const existingCmd = [matchingCommand.name()].concat(matchingCommand.aliases()).join("|");
2959
- throw new Error(
2960
- `cannot add alias '${alias}' to command '${this.name()}' as already have command '${existingCmd}'`
2961
- );
2962
- }
2963
- command._aliases.push(alias);
2964
- return this;
2965
- }
2966
- /**
2967
- * Set aliases for the command.
2968
- *
2969
- * Only the first alias is shown in the auto-generated help.
2970
- *
2971
- * @param {string[]} [aliases]
2972
- * @return {(string[]|Command)}
2973
- */
2974
- aliases(aliases) {
2975
- if (aliases === void 0) return this._aliases;
2976
- aliases.forEach((alias) => this.alias(alias));
2977
- return this;
2978
- }
2979
- /**
2980
- * Set / get the command usage `str`.
2981
- *
2982
- * @param {string} [str]
2983
- * @return {(string|Command)}
2984
- */
2985
- usage(str) {
2986
- if (str === void 0) {
2987
- if (this._usage) return this._usage;
2988
- const args = this.registeredArguments.map((arg) => {
2989
- return humanReadableArgName(arg);
2990
- });
2991
- return [].concat(
2992
- this.options.length || this._helpOption !== null ? "[options]" : [],
2993
- this.commands.length ? "[command]" : [],
2994
- this.registeredArguments.length ? args : []
2995
- ).join(" ");
2996
- }
2997
- this._usage = str;
2998
- return this;
2999
- }
3000
- /**
3001
- * Get or set the name of the command.
3002
- *
3003
- * @param {string} [str]
3004
- * @return {(string|Command)}
3005
- */
3006
- name(str) {
3007
- if (str === void 0) return this._name;
3008
- this._name = str;
3009
- return this;
3010
- }
3011
- /**
3012
- * Set the name of the command from script filename, such as process.argv[1],
3013
- * or require.main.filename, or __filename.
3014
- *
3015
- * (Used internally and public although not documented in README.)
3016
- *
3017
- * @example
3018
- * program.nameFromFilename(require.main.filename);
3019
- *
3020
- * @param {string} filename
3021
- * @return {Command}
3022
- */
3023
- nameFromFilename(filename) {
3024
- this._name = path.basename(filename, path.extname(filename));
3025
- return this;
3026
- }
3027
- /**
3028
- * Get or set the directory for searching for executable subcommands of this command.
3029
- *
3030
- * @example
3031
- * program.executableDir(__dirname);
3032
- * // or
3033
- * program.executableDir('subcommands');
3034
- *
3035
- * @param {string} [path]
3036
- * @return {(string|null|Command)}
3037
- */
3038
- executableDir(path2) {
3039
- if (path2 === void 0) return this._executableDir;
3040
- this._executableDir = path2;
3041
- return this;
3042
- }
3043
- /**
3044
- * Return program help documentation.
3045
- *
3046
- * @param {{ error: boolean }} [contextOptions] - pass {error:true} to wrap for stderr instead of stdout
3047
- * @return {string}
3048
- */
3049
- helpInformation(contextOptions) {
3050
- const helper = this.createHelp();
3051
- const context = this._getOutputContext(contextOptions);
3052
- helper.prepareContext({
3053
- error: context.error,
3054
- helpWidth: context.helpWidth,
3055
- outputHasColors: context.hasColors
3056
- });
3057
- const text = helper.formatHelp(this, helper);
3058
- if (context.hasColors) return text;
3059
- return this._outputConfiguration.stripColor(text);
3060
- }
3061
- /**
3062
- * @typedef HelpContext
3063
- * @type {object}
3064
- * @property {boolean} error
3065
- * @property {number} helpWidth
3066
- * @property {boolean} hasColors
3067
- * @property {function} write - includes stripColor if needed
3068
- *
3069
- * @returns {HelpContext}
3070
- * @private
3071
- */
3072
- _getOutputContext(contextOptions) {
3073
- contextOptions = contextOptions || {};
3074
- const error = !!contextOptions.error;
3075
- let baseWrite;
3076
- let hasColors;
3077
- let helpWidth;
3078
- if (error) {
3079
- baseWrite = (str) => this._outputConfiguration.writeErr(str);
3080
- hasColors = this._outputConfiguration.getErrHasColors();
3081
- helpWidth = this._outputConfiguration.getErrHelpWidth();
3082
- } else {
3083
- baseWrite = (str) => this._outputConfiguration.writeOut(str);
3084
- hasColors = this._outputConfiguration.getOutHasColors();
3085
- helpWidth = this._outputConfiguration.getOutHelpWidth();
3086
- }
3087
- const write = (str) => {
3088
- if (!hasColors) str = this._outputConfiguration.stripColor(str);
3089
- return baseWrite(str);
3090
- };
3091
- return { error, write, hasColors, helpWidth };
3092
- }
3093
- /**
3094
- * Output help information for this command.
3095
- *
3096
- * Outputs built-in help, and custom text added using `.addHelpText()`.
3097
- *
3098
- * @param {{ error: boolean } | Function} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3099
- */
3100
- outputHelp(contextOptions) {
3101
- let deprecatedCallback;
3102
- if (typeof contextOptions === "function") {
3103
- deprecatedCallback = contextOptions;
3104
- contextOptions = void 0;
3105
- }
3106
- const outputContext = this._getOutputContext(contextOptions);
3107
- const eventContext = {
3108
- error: outputContext.error,
3109
- write: outputContext.write,
3110
- command: this
3111
- };
3112
- this._getCommandAndAncestors().reverse().forEach((command) => command.emit("beforeAllHelp", eventContext));
3113
- this.emit("beforeHelp", eventContext);
3114
- let helpInformation = this.helpInformation({ error: outputContext.error });
3115
- if (deprecatedCallback) {
3116
- helpInformation = deprecatedCallback(helpInformation);
3117
- if (typeof helpInformation !== "string" && !Buffer.isBuffer(helpInformation)) {
3118
- throw new Error("outputHelp callback must return a string or a Buffer");
3119
- }
3120
- }
3121
- outputContext.write(helpInformation);
3122
- if (this._getHelpOption()?.long) {
3123
- this.emit(this._getHelpOption().long);
3124
- }
3125
- this.emit("afterHelp", eventContext);
3126
- this._getCommandAndAncestors().forEach(
3127
- (command) => command.emit("afterAllHelp", eventContext)
3128
- );
3129
- }
3130
- /**
3131
- * You can pass in flags and a description to customise the built-in help option.
3132
- * Pass in false to disable the built-in help option.
3133
- *
3134
- * @example
3135
- * program.helpOption('-?, --help' 'show help'); // customise
3136
- * program.helpOption(false); // disable
3137
- *
3138
- * @param {(string | boolean)} flags
3139
- * @param {string} [description]
3140
- * @return {Command} `this` command for chaining
3141
- */
3142
- helpOption(flags, description) {
3143
- if (typeof flags === "boolean") {
3144
- if (flags) {
3145
- this._helpOption = this._helpOption ?? void 0;
3146
- } else {
3147
- this._helpOption = null;
3148
- }
3149
- return this;
3150
- }
3151
- flags = flags ?? "-h, --help";
3152
- description = description ?? "display help for command";
3153
- this._helpOption = this.createOption(flags, description);
3154
- return this;
3155
- }
3156
- /**
3157
- * Lazy create help option.
3158
- * Returns null if has been disabled with .helpOption(false).
3159
- *
3160
- * @returns {(Option | null)} the help option
3161
- * @package
3162
- */
3163
- _getHelpOption() {
3164
- if (this._helpOption === void 0) {
3165
- this.helpOption(void 0, void 0);
3166
- }
3167
- return this._helpOption;
3168
- }
3169
- /**
3170
- * Supply your own option to use for the built-in help option.
3171
- * This is an alternative to using helpOption() to customise the flags and description etc.
3172
- *
3173
- * @param {Option} option
3174
- * @return {Command} `this` command for chaining
3175
- */
3176
- addHelpOption(option) {
3177
- this._helpOption = option;
3178
- return this;
3179
- }
3180
- /**
3181
- * Output help information and exit.
3182
- *
3183
- * Outputs built-in help, and custom text added using `.addHelpText()`.
3184
- *
3185
- * @param {{ error: boolean }} [contextOptions] - pass {error:true} to write to stderr instead of stdout
3186
- */
3187
- help(contextOptions) {
3188
- this.outputHelp(contextOptions);
3189
- let exitCode = Number(process2.exitCode ?? 0);
3190
- if (exitCode === 0 && contextOptions && typeof contextOptions !== "function" && contextOptions.error) {
3191
- exitCode = 1;
3192
- }
3193
- this._exit(exitCode, "commander.help", "(outputHelp)");
3194
- }
3195
- /**
3196
- * // Do a little typing to coordinate emit and listener for the help text events.
3197
- * @typedef HelpTextEventContext
3198
- * @type {object}
3199
- * @property {boolean} error
3200
- * @property {Command} command
3201
- * @property {function} write
3202
- */
3203
- /**
3204
- * Add additional text to be displayed with the built-in help.
3205
- *
3206
- * Position is 'before' or 'after' to affect just this command,
3207
- * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
3208
- *
3209
- * @param {string} position - before or after built-in help
3210
- * @param {(string | Function)} text - string to add, or a function returning a string
3211
- * @return {Command} `this` command for chaining
3212
- */
3213
- addHelpText(position, text) {
3214
- const allowedValues = ["beforeAll", "before", "after", "afterAll"];
3215
- if (!allowedValues.includes(position)) {
3216
- throw new Error(`Unexpected value for position to addHelpText.
3217
- Expecting one of '${allowedValues.join("', '")}'`);
3218
- }
3219
- const helpEvent = `${position}Help`;
3220
- this.on(helpEvent, (context) => {
3221
- let helpStr;
3222
- if (typeof text === "function") {
3223
- helpStr = text({ error: context.error, command: context.command });
3224
- } else {
3225
- helpStr = text;
3226
- }
3227
- if (helpStr) {
3228
- context.write(`${helpStr}
3229
- `);
3230
- }
3231
- });
3232
- return this;
3233
- }
3234
- /**
3235
- * Output help information if help flags specified
3236
- *
3237
- * @param {Array} args - array of options to search for help flags
3238
- * @private
3239
- */
3240
- _outputHelpIfRequested(args) {
3241
- const helpOption = this._getHelpOption();
3242
- const helpRequested = helpOption && args.find((arg) => helpOption.is(arg));
3243
- if (helpRequested) {
3244
- this.outputHelp();
3245
- this._exit(0, "commander.helpDisplayed", "(outputHelp)");
3246
- }
3247
- }
3248
- };
3249
- function incrementNodeInspectorPort(args) {
3250
- return args.map((arg) => {
3251
- if (!arg.startsWith("--inspect")) {
3252
- return arg;
3253
- }
3254
- let debugOption;
3255
- let debugHost = "127.0.0.1";
3256
- let debugPort = "9229";
3257
- let match;
3258
- if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) {
3259
- debugOption = match[1];
3260
- } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) {
3261
- debugOption = match[1];
3262
- if (/^\d+$/.test(match[3])) {
3263
- debugPort = match[3];
3264
- } else {
3265
- debugHost = match[3];
3266
- }
3267
- } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) {
3268
- debugOption = match[1];
3269
- debugHost = match[3];
3270
- debugPort = match[4];
3271
- }
3272
- if (debugOption && debugPort !== "0") {
3273
- return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`;
3274
- }
3275
- return arg;
3276
- });
3277
- }
3278
- function useColor() {
3279
- if (process2.env.NO_COLOR || process2.env.FORCE_COLOR === "0" || process2.env.FORCE_COLOR === "false")
3280
- return false;
3281
- if (process2.env.FORCE_COLOR || process2.env.CLICOLOR_FORCE !== void 0)
3282
- return true;
3283
- return void 0;
3284
- }
3285
- exports.Command = Command2;
3286
- exports.useColor = useColor;
3287
- }
3288
- });
3289
-
3290
- // ../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/index.js
3291
- var require_commander = __commonJS({
3292
- "../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/index.js"(exports) {
3293
- "use strict";
3294
- var { Argument: Argument2 } = require_argument();
3295
- var { Command: Command2 } = require_command();
3296
- var { CommanderError: CommanderError2, InvalidArgumentError: InvalidArgumentError2 } = require_error();
3297
- var { Help: Help2 } = require_help();
3298
- var { Option: Option2 } = require_option();
3299
- exports.program = new Command2();
3300
- exports.createCommand = (name) => new Command2(name);
3301
- exports.createOption = (flags, description) => new Option2(flags, description);
3302
- exports.createArgument = (name, description) => new Argument2(name, description);
3303
- exports.Command = Command2;
3304
- exports.Option = Option2;
3305
- exports.Argument = Argument2;
3306
- exports.Help = Help2;
3307
- exports.CommanderError = CommanderError2;
3308
- exports.InvalidArgumentError = InvalidArgumentError2;
3309
- exports.InvalidOptionArgumentError = InvalidArgumentError2;
3310
- }
3311
- });
5
+ resetMemo
6
+ } from "./chunk-YDM4HHQ4.js";
3312
7
 
3313
8
  // src/index.ts
3314
- import { readFileSync, existsSync, watch, readdirSync, statSync, writeFileSync } from "fs";
9
+ import { readFileSync, existsSync, watch, readdirSync, statSync, writeFileSync, mkdirSync } from "fs";
3315
10
  import { resolve, dirname, relative, join, basename } from "path";
3316
-
3317
- // ../../node_modules/.pnpm/commander@13.1.0/node_modules/commander/esm.mjs
3318
- var import_index = __toESM(require_commander(), 1);
3319
- var {
3320
- program,
3321
- createCommand,
3322
- createArgument,
3323
- createOption,
3324
- CommanderError,
3325
- InvalidArgumentError,
3326
- InvalidOptionArgumentError,
3327
- // deprecated old name
3328
- Command,
3329
- Argument,
3330
- Option,
3331
- Help
3332
- } = import_index.default;
3333
-
3334
- // src/index.ts
3335
- import {
3336
- T,
3337
- typeValueToString,
3338
- createEnvironment,
3339
- mockHelperToTypeValue
3340
- } from "@nudojs/core";
3341
- import { parse, extractDirectives, parseTypeValueExpr } from "@nudojs/parser";
11
+ import { fileURLToPath } from "url";
12
+ import { Command } from "commander";
13
+ import { typeValueToString as typeValueToString2 } from "@nudojs/core";
3342
14
  import {
3343
15
  typeValueToZodSchema,
3344
16
  generateGuardFunction,
17
+ generateGuardFunctionFromAbs,
3345
18
  generateFunctionDtsLines,
3346
19
  analyzeFileAsync,
3347
20
  buildModuleGraph,
@@ -3350,75 +23,88 @@ import {
3350
23
  collectCallRecords,
3351
24
  stripGeneratedCaseDirectives,
3352
25
  insertGeneratedCaseDirectives,
3353
- unifiedDiff
26
+ unifiedDiff,
27
+ isNudoTargetPath,
28
+ collectDtsFromEntry,
29
+ evictAnalysisCachesForFiles
3354
30
  } from "@nudojs/service";
3355
31
  import { harvestDts, emitEnvModule } from "@nudojs/harvester";
3356
- var program2 = new Command();
3357
- program2.name("nudo").description("Nudo type inference engine").version("0.0.1");
3358
- function applyMocks(directives, env, filePath) {
3359
- for (const d of directives) {
3360
- if (d.kind !== "mock") continue;
3361
- if (d.arrowFn) {
3362
- const fnType = T.fn(d.arrowFn.params, d.arrowFn.body, env);
3363
- fnType._paramPatterns = d.arrowFn.paramPatterns;
3364
- env.bind(d.name, fnType);
3365
- } else if (d.nudoMock) {
3366
- const typeVal = mockHelperToTypeValue(d.nudoMock, env);
3367
- env.bind(d.name, typeVal);
3368
- } else if (d.sinonExpr) {
3369
- const sinonType = createSinonTypeValue(d.sinonExpr);
3370
- env.bind(d.name, sinonType);
3371
- } else if (d.expression) {
3372
- env.bind(d.name, parseTypeValueExpr(d.expression));
3373
- } else if (d.fromPath) {
3374
- const mockPath = resolve(dirname(filePath), d.fromPath);
3375
- const mockSource = readFileSync(mockPath, "utf-8");
3376
- const mockAst = parse(mockSource);
3377
- const mockEnv = createEnvironment();
3378
- evaluateProgram(mockAst, mockEnv);
3379
- const mockVal = mockEnv.lookup(d.name);
3380
- env.bind(d.name, mockVal);
32
+
33
+ // src/run-test.ts
34
+ import { isSubtypeOf, typeValueToString } from "@nudojs/core";
35
+ function buildTestReport(file, result) {
36
+ const outcomes = [];
37
+ for (const fn of result.functions) {
38
+ for (const c of fn.cases) {
39
+ if (c.source !== "directive") continue;
40
+ const actual = typeValueToString(c.result);
41
+ if (!c.expected) {
42
+ outcomes.push({
43
+ fn: fn.name,
44
+ caseName: c.name,
45
+ ok: true,
46
+ unchecked: true,
47
+ actual
48
+ });
49
+ continue;
50
+ }
51
+ const expected = typeValueToString(c.expected);
52
+ let ok = false;
53
+ try {
54
+ ok = isSubtypeOf(c.result, c.expected);
55
+ } catch {
56
+ ok = false;
57
+ }
58
+ outcomes.push({
59
+ fn: fn.name,
60
+ caseName: c.name,
61
+ ok,
62
+ unchecked: false,
63
+ expected,
64
+ actual
65
+ });
3381
66
  }
3382
67
  }
68
+ return {
69
+ file,
70
+ passed: outcomes.filter((o) => o.ok && !o.unchecked).length,
71
+ failed: outcomes.filter((o) => !o.ok).length,
72
+ unchecked: outcomes.filter((o) => o.unchecked).length,
73
+ outcomes
74
+ };
3383
75
  }
3384
- function createSinonTypeValue(sinonExpr) {
3385
- const body = { type: "BlockStatement", body: [] };
3386
- const fn = T.fn(["...args"], body, createEnvironment());
3387
- if (sinonExpr.returnValue) {
3388
- fn._directReturn = sinonExpr.returnValue;
3389
- } else if (sinonExpr.resolvedValue) {
3390
- fn._directReturn = T.promise(sinonExpr.resolvedValue);
3391
- } else if (sinonExpr.rejectedValue) {
3392
- fn._directReturn = T.never;
3393
- } else {
3394
- fn._directReturn = T.unknown;
3395
- }
3396
- return fn;
3397
- }
3398
- function resolveModule(source, fromDir) {
3399
- const extensions = [".js", ".ts", ".mjs"];
3400
- const nudoPath = resolveNpmNudo(source, fromDir);
3401
- if (nudoPath) {
3402
- const src = readFileSync(nudoPath, "utf-8");
3403
- return { ast: parse(src), filePath: nudoPath };
3404
- }
3405
- const basePath = resolve(fromDir, source);
3406
- for (const ext of ["", ...extensions]) {
3407
- const candidate = basePath + ext;
3408
- if (existsSync(candidate)) {
3409
- if (candidate.endsWith(".json")) {
3410
- try {
3411
- return { ast: parse("module.exports = undefined;"), filePath: candidate, json: JSON.parse(readFileSync(candidate, "utf-8")) };
3412
- } catch {
3413
- return null;
3414
- }
3415
- }
3416
- const src = readFileSync(candidate, "utf-8");
3417
- return { ast: parse(src), filePath: candidate };
76
+ function formatTestReport(r) {
77
+ const lines = [];
78
+ lines.push(`nudo test ${r.file}`);
79
+ if (r.passed + r.failed + r.unchecked === 0) {
80
+ lines.push("No @nudo:case directives found.");
81
+ return lines.join("\n");
82
+ }
83
+ lines.push(r.failed === 0 ? "PASS" : "FAILED");
84
+ lines.push(` ${r.passed} passed \xB7 ${r.failed} failed \xB7 ${r.unchecked} unchecked`);
85
+ lines.push("");
86
+ for (const o of r.outcomes) {
87
+ if (o.unchecked) {
88
+ lines.push(` [unchecked] ${o.fn} case "${o.caseName}" \u2192 ${o.actual}`);
89
+ } else if (o.ok) {
90
+ lines.push(` [ok] ${o.fn} case "${o.caseName}" \u2192 ${o.actual}`);
91
+ } else {
92
+ lines.push(` [FAIL] ${o.fn} case "${o.caseName}"`);
93
+ lines.push(` expected: ${o.expected}`);
94
+ lines.push(` actual: ${o.actual}`);
3418
95
  }
3419
96
  }
3420
- return null;
97
+ return lines.join("\n");
3421
98
  }
99
+
100
+ // src/index.ts
101
+ var program = new Command();
102
+ function readPackageVersion() {
103
+ const pkgPath = join(dirname(fileURLToPath(import.meta.url)), "..", "package.json");
104
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
105
+ return pkg.version ?? "0.0.0";
106
+ }
107
+ program.name("nudo").description("Nudo type inference engine").version(readPackageVersion());
3422
108
  async function reemitUpdate(filePath, source, callsites) {
3423
109
  const stripped = stripGeneratedCaseDirectives(source);
3424
110
  const result = await analyzeFileAsync(filePath, stripped.source, void 0, callsites);
@@ -3471,7 +157,7 @@ async function runInfer(file, options = {}) {
3471
157
  }
3472
158
  if (fn.skipped) {
3473
159
  if (fn.combined) {
3474
- console.log(`Skipped (declared): ${typeValueToString(fn.combined)}`);
160
+ console.log(`Skipped (declared): ${typeValueToString2(fn.combined)}`);
3475
161
  } else {
3476
162
  console.log("Skipped (no return type declared)");
3477
163
  }
@@ -3479,23 +165,29 @@ async function runInfer(file, options = {}) {
3479
165
  continue;
3480
166
  }
3481
167
  for (const c of fn.cases) {
3482
- const argsStr = c.args.map(typeValueToString).join(", ");
3483
- let line = `Case "${c.name}": (${argsStr}) => ${typeValueToString(c.result)}`;
3484
- if (c.throws.kind !== "never") line += ` throws ${typeValueToString(c.throws)}`;
168
+ const argsStr = c.args.map(typeValueToString2).join(", ");
169
+ let line = `Case "${c.name}": (${argsStr}) => ${typeValueToString2(c.result)}`;
170
+ if (c.throws.kind !== "never") line += ` throws ${typeValueToString2(c.throws)}`;
3485
171
  console.log(line);
172
+ if (c.intension?.display) {
173
+ console.log(` intension: ${c.intension.display}`);
174
+ } else if (c.intension?.term || c.intension?.pred) {
175
+ const parts = [];
176
+ if (c.intension.term) parts.push(`term=${c.intension.term}`);
177
+ if (c.intension.pred) parts.push(`pred: ${c.intension.pred}`);
178
+ if (c.intension.conf) parts.push(`#${c.intension.conf}`);
179
+ console.log(` ${parts.join(" ")}`);
180
+ }
181
+ if (c.intension?.abs) {
182
+ console.log(` abs: ${c.intension.abs}`);
183
+ }
3486
184
  }
3487
185
  if (fn.entryOnly) {
3488
186
  console.log("# no call sites found; parameters default to unknown");
3489
187
  }
3490
188
  if (fn.cases.length > 1 && fn.combined) {
3491
189
  console.log(`
3492
- Combined: ${typeValueToString(fn.combined)}`);
3493
- }
3494
- if (fn.assertionErrors && fn.assertionErrors.length > 0) {
3495
- for (const err of fn.assertionErrors) {
3496
- console.log(`
3497
- \u26A0 ${err}`);
3498
- }
190
+ Combined: ${typeValueToString2(fn.combined)}`);
3499
191
  }
3500
192
  console.log();
3501
193
  }
@@ -3515,21 +207,21 @@ Combined: ${typeValueToString(fn.combined)}`);
3515
207
  console.log(`=== ${fn.name} ===
3516
208
  `);
3517
209
  for (const c of fn.cases) {
3518
- const argsStr = c.args.map(typeValueToString).join(", ");
3519
- let line = `Case "${c.name}": (${argsStr}) => ${typeValueToString(c.result)}`;
3520
- if (c.throws.kind !== "never") line += ` throws ${typeValueToString(c.throws)}`;
210
+ const argsStr = c.args.map(typeValueToString2).join(", ");
211
+ let line = `Case "${c.name}": (${argsStr}) => ${typeValueToString2(c.result)}`;
212
+ if (c.throws.kind !== "never") line += ` throws ${typeValueToString2(c.throws)}`;
3521
213
  console.log(line);
3522
214
  }
3523
215
  if (fn.cases.length > 1 && fn.combined) {
3524
216
  console.log(`
3525
- Combined: ${typeValueToString(fn.combined)}`);
217
+ Combined: ${typeValueToString2(fn.combined)}`);
3526
218
  }
3527
219
  console.log();
3528
220
  }
3529
221
  }
3530
222
  }
3531
223
  if (options.dts && dtsLines.length > 0) {
3532
- const dtsPath = filePath.replace(/\.js$/, ".d.ts");
224
+ const dtsPath = filePath.replace(/\.[cm]?js$|\.ts$/, ".d.ts");
3533
225
  const dtsContent = dtsLines.join("\n") + "\n";
3534
226
  writeFileSync(dtsPath, dtsContent, "utf-8");
3535
227
  console.log(`Generated: ${relative(process.cwd(), dtsPath)}`);
@@ -3575,44 +267,10 @@ async function runInferJson(file, externalRecords) {
3575
267
  const filePath = resolve(file);
3576
268
  const source = readFileSync(filePath, "utf-8");
3577
269
  const result = await analyzeFileAsync(filePath, source, void 0, externalRecords);
3578
- const jsonOutput = {
3579
- functions: result.functions.map((f) => ({
3580
- name: f.name,
3581
- loc: f.loc,
3582
- cases: f.cases.map((c) => ({
3583
- name: c.name,
3584
- args: c.args.map(typeValueToString),
3585
- result: typeValueToString(c.result),
3586
- throws: c.throws.kind !== "never" ? typeValueToString(c.throws) : null,
3587
- source: c.source ?? null
3588
- })),
3589
- entryOnly: f.entryOnly ?? false,
3590
- assertionErrors: f.assertionErrors
3591
- })),
3592
- externalFunctions: result.externalFunctions?.map((f) => ({
3593
- name: f.name,
3594
- fromModule: f.fromModule,
3595
- cases: f.cases.map((c) => ({
3596
- name: c.name,
3597
- args: c.args.map(typeValueToString),
3598
- result: typeValueToString(c.result),
3599
- throws: c.throws.kind !== "never" ? typeValueToString(c.throws) : null,
3600
- source: c.source ?? null
3601
- }))
3602
- })),
3603
- diagnostics: result.diagnostics.map((d) => ({
3604
- range: d.range,
3605
- severity: d.severity,
3606
- message: d.message,
3607
- code: d.code,
3608
- suggestions: d.suggestions,
3609
- tags: d.tags,
3610
- origin: d.origin
3611
- }))
3612
- };
3613
- console.log(JSON.stringify(jsonOutput, null, 2));
270
+ const { serializeInferJson } = await import("@nudojs/service");
271
+ console.log(JSON.stringify(serializeInferJson(result, filePath), null, 2));
3614
272
  }
3615
- program2.command("infer").description("Infer types from a JS file \u2014 functions with @nudo:case directives use them; all other functions are inferred from call sites (whole-program analysis)").argument("<file>", "Path to the JS file").option("--dts", "Generate .d.ts file").option("--loc", "Show source locations in output").option("--json", "Output as JSON").option("--callsites <paths...>", "Usage-site files (tests/apps) to harvest real call shapes from; their calls to this file's exports become synthesized cases").option("--emit-cases [mode]", "Write synthesized call-site cases back into the source as @nudo:case directives (call@ prefix); mode: update (default: add)").option("--dry-run", "With --emit-cases: print a unified diff instead of writing to disk").option("--exit-on-diff", "With --dry-run: exit with code 1 when the diff is non-empty").action(
273
+ program.command("infer").description("Infer types from a JS/TS file (or a directory of them) \u2014 functions with @nudo:case directives use them; all other functions are inferred from call sites (whole-program analysis)").argument("<file>", "Path to the JS/TS file (or directory)").option("--dts", "Generate .d.ts file").option("--loc", "Show source locations in output").option("--json", "Output as JSON").option("--callsites <paths...>", "Usage-site files (tests/apps) to harvest real call shapes from; their calls to this file's exports become synthesized cases").option("--emit-cases [mode]", "Write synthesized call-site cases back into the source as @nudo:case directives (call@ prefix); mode: update (default: add)").option("--dry-run", "With --emit-cases: print a unified diff instead of writing to disk").option("--exit-on-diff", "With --dry-run: exit with code 1 when the diff is non-empty").action(
3616
274
  async (file, opts) => {
3617
275
  let emit;
3618
276
  if (opts.emitCases !== void 0) {
@@ -3640,6 +298,27 @@ program2.command("infer").description("Infer types from a JS file \u2014 functio
3640
298
  if (opts.callsites?.length) {
3641
299
  externalRecords = collectExternalRecords(opts.callsites);
3642
300
  }
301
+ const target = resolve(file);
302
+ if (existsSync(target) && statSync(target).isDirectory()) {
303
+ const files = collectNudoFiles(target);
304
+ if (files.length === 0) {
305
+ console.log("No nudo files found in directory.");
306
+ return;
307
+ }
308
+ if (opts.json) {
309
+ console.error("--json requires a single file, not a directory");
310
+ process.exitCode = 1;
311
+ return;
312
+ }
313
+ for (const f of files) {
314
+ try {
315
+ await runInfer(f, { dts: opts.dts, showLoc: opts.loc, callsites: externalRecords, emit });
316
+ } catch (err) {
317
+ console.error(`Error analyzing ${relative(process.cwd(), f)}:`, err.message);
318
+ }
319
+ }
320
+ return;
321
+ }
3643
322
  if (opts.json) {
3644
323
  await runInferJson(file, externalRecords);
3645
324
  } else {
@@ -3647,27 +326,132 @@ program2.command("infer").description("Infer types from a JS file \u2014 functio
3647
326
  }
3648
327
  }
3649
328
  );
3650
- async function runCheck(file) {
329
+ async function runCheck(file, opts = {}) {
3651
330
  const filePath = resolve(file);
3652
331
  const source = readFileSync(filePath, "utf-8");
3653
- const result = await analyzeFileAsync(filePath, source);
3654
- if (result.diagnostics.length === 0) {
3655
- console.log("No issues found.");
3656
- return;
332
+ const { checkSource, formatCheckReport, serializeCheckJson, pTrue } = await import("@nudojs/core");
333
+ const { defaultLoadModule: loadModule } = await import("@nudojs/service");
334
+ const algebraReport = checkSource(filePath, source, pTrue, {
335
+ loadModule,
336
+ fromFile: filePath
337
+ });
338
+ if (opts.json) {
339
+ console.log(JSON.stringify(serializeCheckJson(algebraReport), null, 2));
340
+ } else {
341
+ console.log(formatCheckReport(algebraReport, { verbose: true }));
342
+ }
343
+ if (!algebraReport.ok) {
344
+ process.exitCode = 1;
3657
345
  }
3658
- for (const d of result.diagnostics) {
3659
- const loc = `${relative(process.cwd(), filePath)}:${d.range.start.line}:${d.range.start.column}`;
3660
- console.log(`[${d.severity}] ${loc} ${d.message}${d.code ? ` (${d.code})` : ""}`);
3661
- if (d.origin) {
3662
- console.log(` \u2192 value originates at ${d.origin.line}:${d.origin.column}`);
346
+ }
347
+ function resolveTargets(path) {
348
+ const resolved = resolve(path);
349
+ if (!existsSync(resolved)) {
350
+ console.error(`Not found: ${resolved}`);
351
+ process.exitCode = 1;
352
+ return [];
353
+ }
354
+ if (statSync(resolved).isDirectory()) {
355
+ const files = collectNudoFiles(resolved);
356
+ if (files.length === 0) {
357
+ console.error(`No nudo files found in directory: ${resolved}`);
358
+ process.exitCode = 1;
359
+ }
360
+ return files;
361
+ }
362
+ return [resolved];
363
+ }
364
+ program.command("types").description("Type-as-computation view: show term + constraints from the algebra (not just extensional shape)").argument("<file>", "Path to the JS/TS file or a directory of them").option("--fn <name>", "Only analyze this function").option("--assume <pred...>", "Assume constraints, e.g. x>0 y>=1").option("--generalize", "Show polymorphic signatures via symbolic execution").action(
365
+ async (file, opts) => {
366
+ const targets = resolveTargets(file);
367
+ if (targets.length === 0) return;
368
+ for (const t of targets) {
369
+ await runTypes(t, opts);
370
+ if (targets.length > 1) console.log("");
3663
371
  }
3664
372
  }
3665
- if (result.diagnostics.some((d) => d.severity === "error")) {
373
+ );
374
+ async function runTypes(filePath, opts) {
375
+ const { readFileSync: readFileSync2 } = await import("fs");
376
+ const { basename: basename2 } = await import("path");
377
+ const algebra = await import("@nudojs/core");
378
+ const source = readFileSync2(filePath, "utf8");
379
+ let phi = algebra.pTrue;
380
+ const assumeIds = /* @__PURE__ */ new Set();
381
+ for (const a of opts.assume ?? []) {
382
+ const m = /^([A-Za-z_$][\w$]*)\s*(>=|>)\s*(-?\d+(?:\.\d+)?)$/.exec(a.trim());
383
+ if (!m) {
384
+ console.error(`\u65E0\u6CD5\u89E3\u6790 --assume: ${a}\uFF08\u652F\u6301 x>0 / x>=1\uFF09`);
385
+ continue;
386
+ }
387
+ const id = m[1];
388
+ const n = Number(m[3]);
389
+ phi = algebra.gtNum(algebra.v(id), n);
390
+ assumeIds.add(id);
391
+ }
392
+ const list = opts.fn ? [opts.fn] : algebra.listFunctionNames(source);
393
+ if (list.length === 0) {
394
+ console.error(`\u672A\u627E\u5230\u51FD\u6570: ${basename2(filePath)}`);
3666
395
  process.exitCode = 1;
396
+ return;
397
+ }
398
+ const { defaultLoadModule: loadModule } = await import("@nudojs/service");
399
+ console.log(`nudo types ${basename2(filePath)}`);
400
+ if (assumeIds.size > 0) {
401
+ console.log(`assume: ${[...assumeIds].map((id) => `${id} > 0`).join(", ")}`);
402
+ }
403
+ if (opts.generalize) {
404
+ console.log("mode: generalize (symbolic \u03B1)\n");
405
+ } else {
406
+ console.log("");
407
+ }
408
+ for (const name of list) {
409
+ if (opts.generalize) {
410
+ const g = algebra.generalizeFromAst(name, source, {
411
+ refine: { loadModule, fromFile: filePath }
412
+ });
413
+ if (!g) continue;
414
+ console.log(g.display);
415
+ console.log("");
416
+ continue;
417
+ }
418
+ const args = algebra.buildArgsFromAssume(source, name, assumeIds);
419
+ const result = algebra.analyzeFn(source, name, args, phi);
420
+ const label = `${name}(${args.map((a) => algebra.formatShape(a)).join(", ")})`;
421
+ console.log(algebra.formatAbsMultiline(result, label));
422
+ console.log("");
3667
423
  }
3668
424
  }
3669
- program2.command("check").description("Check a JS file for type errors \u2014 exits with code 1 when errors are found").argument("<file>", "Path to the JS file").action(async (file) => {
3670
- await runCheck(file);
425
+ program.command("check").description("Check JS/TS file(s) or directory(s) for type errors \u2014 exits with code 1 when errors are found").argument("<paths...>", "File(s) or directory(s) to check").option("--json", "Emit stable CheckJson (CI / Agent contract; single file only)").action(async (paths, opts) => {
426
+ const targets = [];
427
+ for (const p of paths) {
428
+ targets.push(...resolveTargets(p));
429
+ }
430
+ if (targets.length === 0) return;
431
+ if (opts.json && targets.length > 1) {
432
+ console.error("--json requires a single file, not multiple targets");
433
+ process.exitCode = 1;
434
+ return;
435
+ }
436
+ for (const t of targets) {
437
+ await runCheck(t, opts);
438
+ }
439
+ });
440
+ program.command("test").description("Run @nudo:case directives as assertions (case-as-test); exit 1 on failure").argument("<file>", "Path to the JS/TS file or a directory of them").action(async (file) => {
441
+ const targets = resolveTargets(file);
442
+ if (targets.length === 0) return;
443
+ for (const filePath of targets) {
444
+ const source = readFileSync(filePath, "utf-8");
445
+ try {
446
+ const result = await analyzeFileAsync(filePath, source);
447
+ const report = buildTestReport(filePath, result);
448
+ console.log(formatTestReport(report));
449
+ if (report.failed > 0) process.exitCode = 1;
450
+ } catch (err) {
451
+ console.error(`nudo test failed to analyze ${filePath}: ${err.message}`);
452
+ process.exitCode = 1;
453
+ }
454
+ }
3671
455
  });
3672
456
  var displayPath = (p) => {
3673
457
  const rel = relative(process.cwd(), p);
@@ -3772,10 +556,10 @@ Summary: ${reports.length} file(s) \xB7 ${driftCount} drift \xB7 ${errorCount} e
3772
556
  }
3773
557
  if (failed) process.exitCode = 1;
3774
558
  }
3775
- program2.command("doctor").description("Health-check JS files: functions without cases, call-site solidification drift (--callsites), analysis errors \u2014 exits 1 on drift/errors").argument("[paths...]", "File(s) or directory(s) to check (default: current directory)").option("--callsites <paths...>", "Usage-site files (tests/apps): re-solidify per current call shapes and report drift when directives would change").option("--json", "Output as JSON").action(async (paths, opts) => {
559
+ program.command("doctor").description("Health-check JS files: functions without cases, call-site solidification drift (--callsites), analysis errors \u2014 exits 1 on drift/errors").argument("[paths...]", "File(s) or directory(s) to check (default: current directory)").option("--callsites <paths...>", "Usage-site files (tests/apps): re-solidify per current call shapes and report drift when directives would change").option("--json", "Output as JSON").action(async (paths, opts) => {
3776
560
  await runDoctor(paths, opts);
3777
561
  });
3778
- program2.command("watch").description("Watch file(s) for changes and re-run inference").argument("<path>", "File or directory to watch").option("--dts", "Generate .d.ts files on each change").action((watchPath, opts) => {
562
+ program.command("watch").description("Watch file(s) for changes and re-run inference").argument("<path>", "File or directory to watch").option("--dts", "Generate .d.ts files on each change").action((watchPath, opts) => {
3779
563
  const resolved = resolve(watchPath);
3780
564
  const isDir = existsSync(resolved) && statSync(resolved).isDirectory();
3781
565
  const getFiles = () => {
@@ -3812,6 +596,7 @@ program2.command("watch").description("Watch file(s) for changes and re-run infe
3812
596
  `);
3813
597
  const t0 = performance.now();
3814
598
  resetMemo();
599
+ evictAnalysisCachesForFiles(ordered);
3815
600
  for (const f of ordered) {
3816
601
  try {
3817
602
  await runInfer(f, { dts: opts.dts, showLoc: true });
@@ -3832,7 +617,7 @@ program2.command("watch").description("Watch file(s) for changes and re-run infe
3832
617
  watch(watchTarget, { recursive: isDir }, (_event, filename) => {
3833
618
  if (!filename) return;
3834
619
  const fullPath = isDir ? join(watchTarget, filename) : resolved;
3835
- if (!fullPath.endsWith(".js")) return;
620
+ if (!isNudoTargetPath(fullPath)) return;
3836
621
  if (!existsSync(fullPath)) return;
3837
622
  pendingChanged.add(fullPath);
3838
623
  if (debounceTimer) clearTimeout(debounceTimer);
@@ -3850,136 +635,103 @@ function collectNudoFiles(dir) {
3850
635
  const fullPath = join(dir, entry.name);
3851
636
  if (entry.isDirectory() && entry.name !== "node_modules") {
3852
637
  results.push(...collectNudoFiles(fullPath));
3853
- } else if (entry.isFile() && entry.name.endsWith(".js")) {
638
+ } else if (entry.isFile() && isNudoTargetPath(fullPath)) {
3854
639
  results.push(fullPath);
3855
640
  }
3856
641
  }
3857
642
  return results;
3858
643
  }
3859
- function nodeLoc(node) {
3860
- return {
3861
- start: { line: node.loc?.start.line ?? 1, column: node.loc?.start.column ?? 0 },
3862
- end: { line: node.loc?.end.line ?? 1, column: node.loc?.end.column ?? 0 }
3863
- };
3864
- }
3865
- function fnParamNames(node) {
3866
- const fn = node.type === "ExportDefaultDeclaration" ? node.declaration : node;
3867
- const paramListOf = (params) => params.map((p) => {
3868
- if (p.type === "Identifier") return p.name;
3869
- if (p.type === "AssignmentPattern" && p.left.type === "Identifier") return p.left.name;
3870
- if (p.type === "RestElement" && p.argument.type === "Identifier") return `...${p.argument.name}`;
3871
- return "_";
3872
- });
3873
- if (fn.type === "FunctionDeclaration" || fn.type === "FunctionExpression" || fn.type === "ArrowFunctionExpression") {
3874
- return paramListOf(fn.params);
3875
- }
3876
- if (fn.type === "VariableDeclaration") {
3877
- const init = fn.declarations[0].init;
3878
- if (init?.type === "FunctionExpression" || init?.type === "ArrowFunctionExpression") {
3879
- return paramListOf(init.params);
3880
- }
3881
- }
3882
- return [];
3883
- }
3884
- program2.command("generate").description("Generate runtime validators from inferred types").argument("<file>", "JavaScript file to analyze").option("--format <format>", "Output format: zod, guard, dts, all", "all").option("--output <dir>", "Output directory", ".").action((file, options) => {
644
+ async function runGenerate(file, format, output) {
3885
645
  const filePath = resolve(file);
3886
646
  const source = readFileSync(filePath, "utf-8");
3887
- const ast = parse(source);
3888
- const functions = extractDirectives(ast);
647
+ const result = await analyzeFileAsync(filePath, source);
648
+ const functions = result.functions.filter(
649
+ (f) => f.cases.some((c) => c.source === "directive")
650
+ );
3889
651
  if (functions.length === 0) {
3890
652
  console.log("No functions with @nudo:case directives found.");
3891
653
  return;
3892
654
  }
3893
- resetMemo();
3894
- setModuleResolver(resolveModule);
3895
- setCurrentFileDir(dirname(filePath));
3896
- const globalEnv = createEnvironment();
3897
- evaluateProgram(ast, globalEnv);
655
+ const zodChunks = [];
656
+ const guardChunks = [];
657
+ const dtsChunks = [];
3898
658
  for (const fn of functions) {
3899
- applyMocks(fn.directives, globalEnv, filePath);
3900
- const caseDirectives = fn.directives.filter((d) => d.kind === "case");
3901
- if (caseDirectives.length === 0) continue;
3902
- const caseResults = caseDirectives.map((directive) => {
3903
- const fullResult = evaluateFunctionFull(fn.node, directive.args, globalEnv);
3904
- return {
3905
- name: directive.name,
3906
- args: directive.args,
3907
- result: fullResult.value,
3908
- throws: fullResult.throws,
3909
- source: "directive"
3910
- };
3911
- });
659
+ const caseResults = fn.cases.filter((c) => c.source === "directive");
3912
660
  const baseName = fn.name;
3913
- if (options.format === "zod" || options.format === "all") {
3914
- console.log(`
3915
- // === ${baseName} Zod Schemas ===`);
661
+ if (format === "zod" || format === "all") {
662
+ const lines = [`
663
+ // === ${baseName} Zod Schemas ===`];
3916
664
  for (const c of caseResults) {
3917
665
  const inputSchemas = c.args.map((a, i) => `arg${i}: ${typeValueToZodSchema(a)}`).join(", ");
3918
666
  const outputSchema = typeValueToZodSchema(c.result);
3919
- console.log(`// Case "${c.name}":`);
3920
- console.log(`// Input: { ${inputSchemas} }`);
3921
- console.log(`// Output: ${outputSchema}`);
667
+ lines.push(`// Case "${c.name}":`);
668
+ lines.push(`// Input: { ${inputSchemas} }`);
669
+ lines.push(`// Output: ${outputSchema}`);
3922
670
  }
671
+ zodChunks.push(lines.join("\n"));
3923
672
  }
3924
- if (options.format === "guard" || options.format === "all") {
3925
- console.log(`
3926
- // === ${baseName} Type Guards ===`);
673
+ if (format === "guard" || format === "all") {
674
+ const lines = [`
675
+ // === ${baseName} Type Guards ===`];
3927
676
  for (const c of caseResults) {
3928
- const guard = generateGuardFunction(`is${baseName}${c.name.charAt(0).toUpperCase() + c.name.slice(1)}Output`, c.result);
3929
- console.log(guard);
677
+ const guardName = `is${baseName}${c.name.charAt(0).toUpperCase() + c.name.slice(1)}Output`;
678
+ if (c.abs) {
679
+ lines.push(generateGuardFunctionFromAbs(guardName, c.abs));
680
+ } else {
681
+ lines.push(generateGuardFunction(guardName, c.result));
682
+ }
3930
683
  }
684
+ guardChunks.push(lines.join("\n"));
3931
685
  }
3932
- if (options.format === "dts" || options.format === "all") {
3933
- console.log(`
3934
- // === ${baseName} TypeScript Declarations ===`);
3935
- const analysis = {
3936
- name: baseName,
3937
- loc: nodeLoc(fn.node),
3938
- paramNames: fnParamNames(fn.node),
3939
- cases: caseResults
3940
- };
3941
- for (const line of generateFunctionDtsLines(analysis)) {
3942
- console.log(line);
3943
- }
686
+ if (format === "dts" || format === "all") {
687
+ dtsChunks.push(generateFunctionDtsLines(fn).join("\n"));
3944
688
  }
3945
689
  }
3946
- setModuleResolver(null);
3947
- });
3948
- var HARVEST_MAX_FILES = 200;
3949
- var REFERENCE_PATH_REGEX = /<reference\s+path=["']([^"']+)["']\s*\/>/g;
3950
- var RELATIVE_FROM_REGEX = /\bfrom\s+["'](\.[^"']+)["']/g;
3951
- function collectDtsFiles(entry) {
3952
- const files = [];
3953
- const seen = /* @__PURE__ */ new Set();
3954
- const queue = [entry];
3955
- while (queue.length > 0 && files.length < HARVEST_MAX_FILES) {
3956
- const current = queue.shift();
3957
- if (seen.has(current) || !existsSync(current)) continue;
3958
- seen.add(current);
3959
- if (!current.endsWith(".d.ts")) continue;
3960
- files.push(current);
3961
- let text;
3962
- try {
3963
- text = readFileSync(current, "utf-8");
3964
- } catch {
3965
- continue;
690
+ const stem = basename(filePath).replace(/\.[cm]?[jt]s$/, "");
691
+ if (output) {
692
+ const outDir = resolve(output);
693
+ mkdirSync(outDir, { recursive: true });
694
+ const written = [];
695
+ if (zodChunks.length > 0) {
696
+ const p = join(outDir, `${stem}.nudo.zod.ts`);
697
+ writeFileSync(p, zodChunks.join("\n") + "\n", "utf-8");
698
+ written.push(p);
3966
699
  }
3967
- const dir = dirname(current);
3968
- for (const match of text.matchAll(REFERENCE_PATH_REGEX)) {
3969
- queue.push(resolve(dir, match[1]));
700
+ if (guardChunks.length > 0) {
701
+ const p = join(outDir, `${stem}.nudo.guard.ts`);
702
+ writeFileSync(p, guardChunks.join("\n") + "\n", "utf-8");
703
+ written.push(p);
3970
704
  }
3971
- for (const match of text.matchAll(RELATIVE_FROM_REGEX)) {
3972
- const base = resolve(dir, match[1]);
3973
- for (const candidate of [`${base}.d.ts`, join(base, "index.d.ts")]) {
3974
- if (existsSync(candidate)) {
3975
- queue.push(candidate);
3976
- break;
3977
- }
3978
- }
705
+ if (dtsChunks.length > 0) {
706
+ const p = join(outDir, `${stem}.d.ts`);
707
+ writeFileSync(p, dtsChunks.join("\n") + "\n", "utf-8");
708
+ written.push(p);
709
+ }
710
+ for (const p of written) {
711
+ console.log(`wrote ${relative(process.cwd(), p)}`);
3979
712
  }
713
+ return;
714
+ }
715
+ for (const chunk of [...zodChunks, ...guardChunks, ...dtsChunks]) {
716
+ console.log(chunk);
3980
717
  }
3981
- return files;
3982
718
  }
719
+ program.command("generate").description("Generate runtime validators from inferred types").argument("<file>", "JavaScript file to analyze").option("--format <format>", "Output format: zod, guard, dts, all", "all").option("--output <dir>", "Write validator files to this directory (omit for stdout)").action(async (file, options) => {
720
+ const format = options.format;
721
+ if (!["zod", "guard", "dts", "all"].includes(format)) {
722
+ console.error(`Unknown --format ${format}; expected zod | guard | dts | all`);
723
+ process.exitCode = 1;
724
+ return;
725
+ }
726
+ await runGenerate(file, format, options.output);
727
+ });
728
+ program.command("emit").description("Emit TypeScript .d.ts declarations from inferred types (npm compatibility exit)").argument("<file>", "JavaScript file to analyze").option("--output <dir>", "Write <stem>.d.ts to this directory (omit for stdout)").action(async (file, options) => {
729
+ await runGenerate(file, "dts", options.output);
730
+ });
731
+ program.command("guard").description("Generate runtime type-guard functions from inferred result types").argument("<file>", "JavaScript file to analyze").option("--output <dir>", "Write <stem>.nudo.guard.ts to this directory (omit for stdout)").action(async (file, options) => {
732
+ await runGenerate(file, "guard", options.output);
733
+ });
734
+ var HARVEST_MAX_FILES = 200;
3983
735
  function runHarvest(pkg, outOpt) {
3984
736
  const typesDir = resolve(process.cwd(), "node_modules", "@types", pkg);
3985
737
  if (!existsSync(typesDir)) {
@@ -4006,7 +758,7 @@ function runHarvest(pkg, outOpt) {
4006
758
  process.exitCode = 1;
4007
759
  return;
4008
760
  }
4009
- const files = collectDtsFiles(entry);
761
+ const files = collectDtsFromEntry(entry, HARVEST_MAX_FILES);
4010
762
  if (files.length === 0) {
4011
763
  console.error(`Error: no .d.ts files collected from ${relative(process.cwd(), entry)}.`);
4012
764
  process.exitCode = 1;
@@ -4026,10 +778,52 @@ Usage \u2014 add this directive at the top of your JS file:`);
4026
778
  const hintPath = resolve(process.cwd()) === outDir ? basename(out) : out;
4027
779
  console.log(` /// @nudo:env ${hintPath}`);
4028
780
  }
4029
- program2.command("harvest").description("Convert @types/<pkg> .d.ts declarations into a Nudo env file (TS source using T.* constructors)").argument("<pkg>", "Package name under @types (e.g. node)").option("--out <file>", "Output .ts env file (default: ./nudo-harvest-<pkg>.ts)").action((pkg, opts) => {
781
+ program.command("harvest").description("Convert @types/<pkg> .d.ts declarations into a Nudo env file (TS source using T.* constructors)").argument("[pkg]", "Package name under @types (e.g. node)").option("--out <file>", "Output .ts env file (default: ./nudo-harvest-<pkg>.ts)").option("--auto [dir]", "Scan directory (default .) for bare imports and report auto-harvestable @types packages").action(async (pkg, opts) => {
782
+ if (opts.auto !== void 0) {
783
+ const dir = resolve(typeof opts.auto === "string" ? opts.auto : ".");
784
+ const files = existsSync(dir) && statSync(dir).isDirectory() ? collectNudoFiles(dir) : existsSync(dir) ? [dir] : [];
785
+ if (files.length === 0) {
786
+ console.error(`No inference targets under ${dir}`);
787
+ process.exitCode = 1;
788
+ return;
789
+ }
790
+ const { collectBarePackages, harvestPackageCached, formatHarvestSummary } = await import("@nudojs/service");
791
+ const seen = /* @__PURE__ */ new Set();
792
+ const report = [];
793
+ for (const f of files) {
794
+ let src;
795
+ try {
796
+ src = readFileSync(f, "utf-8");
797
+ } catch {
798
+ continue;
799
+ }
800
+ for (const p of collectBarePackages(src)) {
801
+ if (seen.has(p)) continue;
802
+ seen.add(p);
803
+ const h = harvestPackageCached(p, dirname(f));
804
+ if (h) report.push(formatHarvestSummary(h));
805
+ else report.push(`${p}: no .d.ts / @types (skipped)`);
806
+ }
807
+ }
808
+ if (report.length === 0) {
809
+ console.log("No bare imports found (or nothing to harvest).");
810
+ return;
811
+ }
812
+ console.log(`auto harvest candidates under ${relative(process.cwd(), dir) || "."}:
813
+ `);
814
+ for (const line of report) console.log(line);
815
+ console.log(`
816
+ Analysis injects these automatically; use \`nudo harvest <pkg>\` to write a persistent env file.`);
817
+ return;
818
+ }
819
+ if (!pkg) {
820
+ console.error("Error: <pkg> is required (or use --auto).");
821
+ process.exitCode = 1;
822
+ return;
823
+ }
4030
824
  runHarvest(pkg, opts.out);
4031
825
  });
4032
- program2.parseAsync(process.argv).catch((err) => {
826
+ program.parseAsync(process.argv).catch((err) => {
4033
827
  console.error(err instanceof Error ? process.env.NUDO_DEBUG ? err.stack : err.message : err);
4034
828
  process.exitCode = 1;
4035
829
  });