@rsbuild/core 0.4.13 → 0.4.15

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.
@@ -0,0 +1 @@
1
+ (()=>{var t={81:t=>{"use strict";t.exports=require("child_process")},361:t=>{"use strict";t.exports=require("events")},147:t=>{"use strict";t.exports=require("fs")},17:t=>{"use strict";t.exports=require("path")},282:t=>{"use strict";t.exports=require("process")},975:(t,e,i)=>{const{InvalidArgumentError:n}=i(422);class Argument{constructor(t,e){this.description=e||"";this.variadic=false;this.parseArg=undefined;this.defaultValue=undefined;this.defaultValueDescription=undefined;this.argChoices=undefined;switch(t[0]){case"<":this.required=true;this._name=t.slice(1,-1);break;case"[":this.required=false;this._name=t.slice(1,-1);break;default:this.required=true;this._name=t;break}if(this._name.length>3&&this._name.slice(-3)==="..."){this.variadic=true;this._name=this._name.slice(0,-3)}}name(){return this._name}_concatValue(t,e){if(e===this.defaultValue||!Array.isArray(e)){return[t]}return e.concat(t)}default(t,e){this.defaultValue=t;this.defaultValueDescription=e;return this}argParser(t){this.parseArg=t;return this}choices(t){this.argChoices=t.slice();this.parseArg=(t,e)=>{if(!this.argChoices.includes(t)){throw new n(`Allowed choices are ${this.argChoices.join(", ")}.`)}if(this.variadic){return this._concatValue(t,e)}return t};return this}argRequired(){this.required=true;return this}argOptional(){this.required=false;return this}}function humanReadableArgName(t){const e=t.name()+(t.variadic===true?"...":"");return t.required?"<"+e+">":"["+e+"]"}e.Argument=Argument;e.humanReadableArgName=humanReadableArgName},965:(t,e,i)=>{const n=i(361).EventEmitter;const s=i(81);const r=i(17);const o=i(147);const a=i(282);const{Argument:h,humanReadableArgName:l}=i(975);const{CommanderError:u}=i(422);const{Help:c}=i(455);const{Option:p,DualOptions:d}=i(985);const{suggestSimilar:m}=i(745);class Command extends n{constructor(t){super();this.commands=[];this.options=[];this.parent=null;this._allowUnknownOption=false;this._allowExcessArguments=true;this.registeredArguments=[];this._args=this.registeredArguments;this.args=[];this.rawArgs=[];this.processedArgs=[];this._scriptPath=null;this._name=t||"";this._optionValues={};this._optionValueSources={};this._storeOptionsAsProperties=false;this._actionHandler=null;this._executableHandler=false;this._executableFile=null;this._executableDir=null;this._defaultCommandName=null;this._exitCallback=null;this._aliases=[];this._combineFlagAndOptionalValue=true;this._description="";this._summary="";this._argsDescription=undefined;this._enablePositionalOptions=false;this._passThroughOptions=false;this._lifeCycleHooks={};this._showHelpAfterError=false;this._showSuggestionAfterError=true;this._outputConfiguration={writeOut:t=>a.stdout.write(t),writeErr:t=>a.stderr.write(t),getOutHelpWidth:()=>a.stdout.isTTY?a.stdout.columns:undefined,getErrHelpWidth:()=>a.stderr.isTTY?a.stderr.columns:undefined,outputError:(t,e)=>e(t)};this._hidden=false;this._helpOption=undefined;this._addImplicitHelpCommand=undefined;this._helpCommand=undefined;this._helpConfiguration={}}copyInheritedSettings(t){this._outputConfiguration=t._outputConfiguration;this._helpOption=t._helpOption;this._helpCommand=t._helpCommand;this._helpConfiguration=t._helpConfiguration;this._exitCallback=t._exitCallback;this._storeOptionsAsProperties=t._storeOptionsAsProperties;this._combineFlagAndOptionalValue=t._combineFlagAndOptionalValue;this._allowExcessArguments=t._allowExcessArguments;this._enablePositionalOptions=t._enablePositionalOptions;this._showHelpAfterError=t._showHelpAfterError;this._showSuggestionAfterError=t._showSuggestionAfterError;return this}_getCommandAndAncestors(){const t=[];for(let e=this;e;e=e.parent){t.push(e)}return t}command(t,e,i){let n=e;let s=i;if(typeof n==="object"&&n!==null){s=n;n=null}s=s||{};const[,r,o]=t.match(/([^ ]+) *(.*)/);const a=this.createCommand(r);if(n){a.description(n);a._executableHandler=true}if(s.isDefault)this._defaultCommandName=a._name;a._hidden=!!(s.noHelp||s.hidden);a._executableFile=s.executableFile||null;if(o)a.arguments(o);this._registerCommand(a);a.parent=this;a.copyInheritedSettings(this);if(n)return this;return a}createCommand(t){return new Command(t)}createHelp(){return Object.assign(new c,this.configureHelp())}configureHelp(t){if(t===undefined)return this._helpConfiguration;this._helpConfiguration=t;return this}configureOutput(t){if(t===undefined)return this._outputConfiguration;Object.assign(this._outputConfiguration,t);return this}showHelpAfterError(t=true){if(typeof t!=="string")t=!!t;this._showHelpAfterError=t;return this}showSuggestionAfterError(t=true){this._showSuggestionAfterError=!!t;return this}addCommand(t,e){if(!t._name){throw new Error(`Command passed to .addCommand() must have a name\n- specify the name in Command constructor or using .name()`)}e=e||{};if(e.isDefault)this._defaultCommandName=t._name;if(e.noHelp||e.hidden)t._hidden=true;this._registerCommand(t);t.parent=this;t._checkForBrokenPassThrough();return this}createArgument(t,e){return new h(t,e)}argument(t,e,i,n){const s=this.createArgument(t,e);if(typeof i==="function"){s.default(n).argParser(i)}else{s.default(i)}this.addArgument(s);return this}arguments(t){t.trim().split(/ +/).forEach((t=>{this.argument(t)}));return this}addArgument(t){const e=this.registeredArguments.slice(-1)[0];if(e&&e.variadic){throw new Error(`only the last argument can be variadic '${e.name()}'`)}if(t.required&&t.defaultValue!==undefined&&t.parseArg===undefined){throw new Error(`a default value for a required argument is never used: '${t.name()}'`)}this.registeredArguments.push(t);return this}helpCommand(t,e){if(typeof t==="boolean"){this._addImplicitHelpCommand=t;return this}t=t??"help [command]";const[,i,n]=t.match(/([^ ]+) *(.*)/);const s=e??"display help for command";const r=this.createCommand(i);r.helpOption(false);if(n)r.arguments(n);if(s)r.description(s);this._addImplicitHelpCommand=true;this._helpCommand=r;return this}addHelpCommand(t,e){if(typeof t!=="object"){this.helpCommand(t,e);return this}this._addImplicitHelpCommand=true;this._helpCommand=t;return this}_getHelpCommand(){const t=this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"));if(t){if(this._helpCommand===undefined){this.helpCommand(undefined,undefined)}return this._helpCommand}return null}hook(t,e){const i=["preSubcommand","preAction","postAction"];if(!i.includes(t)){throw new Error(`Unexpected value for event passed to hook : '${t}'.\nExpecting one of '${i.join("', '")}'`)}if(this._lifeCycleHooks[t]){this._lifeCycleHooks[t].push(e)}else{this._lifeCycleHooks[t]=[e]}return this}exitOverride(t){if(t){this._exitCallback=t}else{this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync"){throw t}else{}}}return this}_exit(t,e,i){if(this._exitCallback){this._exitCallback(new u(t,e,i))}a.exit(t)}action(t){const listener=e=>{const i=this.registeredArguments.length;const n=e.slice(0,i);if(this._storeOptionsAsProperties){n[i]=this}else{n[i]=this.opts()}n.push(this);return t.apply(this,n)};this._actionHandler=listener;return this}createOption(t,e){return new p(t,e)}_callParseArg(t,e,i,n){try{return t.parseArg(e,i)}catch(t){if(t.code==="commander.invalidArgument"){const e=`${n} ${t.message}`;this.error(e,{exitCode:t.exitCode,code:t.code})}throw t}}_registerOption(t){const e=t.short&&this._findOption(t.short)||t.long&&this._findOption(t.long);if(e){const i=t.long&&this._findOption(t.long)?t.long:t.short;throw new Error(`Cannot add option '${t.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${i}'\n- already used by option '${e.flags}'`)}this.options.push(t)}_registerCommand(t){const knownBy=t=>[t.name()].concat(t.aliases());const e=knownBy(t).find((t=>this._findCommand(t)));if(e){const i=knownBy(this._findCommand(e)).join("|");const n=knownBy(t).join("|");throw new Error(`cannot add command '${n}' as already have command '${i}'`)}this.commands.push(t)}addOption(t){this._registerOption(t);const e=t.name();const i=t.attributeName();if(t.negate){const e=t.long.replace(/^--no-/,"--");if(!this._findOption(e)){this.setOptionValueWithSource(i,t.defaultValue===undefined?true:t.defaultValue,"default")}}else if(t.defaultValue!==undefined){this.setOptionValueWithSource(i,t.defaultValue,"default")}const handleOptionValue=(e,n,s)=>{if(e==null&&t.presetArg!==undefined){e=t.presetArg}const r=this.getOptionValue(i);if(e!==null&&t.parseArg){e=this._callParseArg(t,e,r,n)}else if(e!==null&&t.variadic){e=t._concatValue(e,r)}if(e==null){if(t.negate){e=false}else if(t.isBoolean()||t.optional){e=true}else{e=""}}this.setOptionValueWithSource(i,e,s)};this.on("option:"+e,(e=>{const i=`error: option '${t.flags}' argument '${e}' is invalid.`;handleOptionValue(e,i,"cli")}));if(t.envVar){this.on("optionEnv:"+e,(e=>{const i=`error: option '${t.flags}' value '${e}' from env '${t.envVar}' is invalid.`;handleOptionValue(e,i,"env")}))}return this}_optionEx(t,e,i,n,s){if(typeof e==="object"&&e instanceof p){throw new Error("To add an Option object use addOption() instead of option() or requiredOption()")}const r=this.createOption(e,i);r.makeOptionMandatory(!!t.mandatory);if(typeof n==="function"){r.default(s).argParser(n)}else if(n instanceof RegExp){const t=n;n=(e,i)=>{const n=t.exec(e);return n?n[0]:i};r.default(s).argParser(n)}else{r.default(n)}return this.addOption(r)}option(t,e,i,n){return this._optionEx({},t,e,i,n)}requiredOption(t,e,i,n){return this._optionEx({mandatory:true},t,e,i,n)}combineFlagAndOptionalValue(t=true){this._combineFlagAndOptionalValue=!!t;return this}allowUnknownOption(t=true){this._allowUnknownOption=!!t;return this}allowExcessArguments(t=true){this._allowExcessArguments=!!t;return this}enablePositionalOptions(t=true){this._enablePositionalOptions=!!t;return this}passThroughOptions(t=true){this._passThroughOptions=!!t;this._checkForBrokenPassThrough();return this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions){throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}}storeOptionsAsProperties(t=true){if(this.options.length){throw new Error("call .storeOptionsAsProperties() before adding options")}if(Object.keys(this._optionValues).length){throw new Error("call .storeOptionsAsProperties() before setting option values")}this._storeOptionsAsProperties=!!t;return this}getOptionValue(t){if(this._storeOptionsAsProperties){return this[t]}return this._optionValues[t]}setOptionValue(t,e){return this.setOptionValueWithSource(t,e,undefined)}setOptionValueWithSource(t,e,i){if(this._storeOptionsAsProperties){this[t]=e}else{this._optionValues[t]=e}this._optionValueSources[t]=i;return this}getOptionValueSource(t){return this._optionValueSources[t]}getOptionValueSourceWithGlobals(t){let e;this._getCommandAndAncestors().forEach((i=>{if(i.getOptionValueSource(t)!==undefined){e=i.getOptionValueSource(t)}}));return e}_prepareUserArgs(t,e){if(t!==undefined&&!Array.isArray(t)){throw new Error("first parameter to parse must be array or undefined")}e=e||{};if(t===undefined){t=a.argv;if(a.versions&&a.versions.electron){e.from="electron"}}this.rawArgs=t.slice();let i;switch(e.from){case undefined:case"node":this._scriptPath=t[1];i=t.slice(2);break;case"electron":if(a.defaultApp){this._scriptPath=t[1];i=t.slice(2)}else{i=t.slice(1)}break;case"user":i=t.slice(0);break;default:throw new Error(`unexpected parse option { from: '${e.from}' }`)}if(!this._name&&this._scriptPath)this.nameFromFilename(this._scriptPath);this._name=this._name||"program";return i}parse(t,e){const i=this._prepareUserArgs(t,e);this._parseCommand([],i);return this}async parseAsync(t,e){const i=this._prepareUserArgs(t,e);await this._parseCommand([],i);return this}_executeSubCommand(t,e){e=e.slice();let i=false;const n=[".js",".ts",".tsx",".mjs",".cjs"];function findFile(t,e){const i=r.resolve(t,e);if(o.existsSync(i))return i;if(n.includes(r.extname(e)))return undefined;const s=n.find((t=>o.existsSync(`${i}${t}`)));if(s)return`${i}${s}`;return undefined}this._checkForMissingMandatoryOptions();this._checkForConflictingOptions();let h=t._executableFile||`${this._name}-${t._name}`;let l=this._executableDir||"";if(this._scriptPath){let t;try{t=o.realpathSync(this._scriptPath)}catch(e){t=this._scriptPath}l=r.resolve(r.dirname(t),l)}if(l){let e=findFile(l,h);if(!e&&!t._executableFile&&this._scriptPath){const i=r.basename(this._scriptPath,r.extname(this._scriptPath));if(i!==this._name){e=findFile(l,`${i}-${t._name}`)}}h=e||h}i=n.includes(r.extname(h));let c;if(a.platform!=="win32"){if(i){e.unshift(h);e=incrementNodeInspectorPort(a.execArgv).concat(e);c=s.spawn(a.argv[0],e,{stdio:"inherit"})}else{c=s.spawn(h,e,{stdio:"inherit"})}}else{e.unshift(h);e=incrementNodeInspectorPort(a.execArgv).concat(e);c=s.spawn(a.execPath,e,{stdio:"inherit"})}if(!c.killed){const t=["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"];t.forEach((t=>{a.on(t,(()=>{if(c.killed===false&&c.exitCode===null){c.kill(t)}}))}))}const p=this._exitCallback;c.on("close",((t,e)=>{t=t??1;if(!p){a.exit(t)}else{p(new u(t,"commander.executeSubCommandAsync","(close)"))}}));c.on("error",(e=>{if(e.code==="ENOENT"){const e=l?`searched for local subcommand relative to directory '${l}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory";const i=`'${h}' does not exist\n - if '${t._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead\n - if the default executable name is not suitable, use the executableFile option to supply a custom name or path\n - ${e}`;throw new Error(i)}else if(e.code==="EACCES"){throw new Error(`'${h}' not executable`)}if(!p){a.exit(1)}else{const t=new u(1,"commander.executeSubCommandAsync","(error)");t.nestedError=e;p(t)}}));this.runningCommand=c}_dispatchSubcommand(t,e,i){const n=this._findCommand(t);if(!n)this.help({error:true});let s;s=this._chainOrCallSubCommandHook(s,n,"preSubcommand");s=this._chainOrCall(s,(()=>{if(n._executableHandler){this._executeSubCommand(n,e.concat(i))}else{return n._parseCommand(e,i)}}));return s}_dispatchHelpCommand(t){if(!t){this.help()}const e=this._findCommand(t);if(e&&!e._executableHandler){e.help()}return this._dispatchSubcommand(t,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach(((t,e)=>{if(t.required&&this.args[e]==null){this.missingArgument(t.name())}}));if(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic){return}if(this.args.length>this.registeredArguments.length){this._excessArguments(this.args)}}_processArguments(){const myParseArg=(t,e,i)=>{let n=e;if(e!==null&&t.parseArg){const s=`error: command-argument value '${e}' is invalid for argument '${t.name()}'.`;n=this._callParseArg(t,e,i,s)}return n};this._checkNumberOfArguments();const t=[];this.registeredArguments.forEach(((e,i)=>{let n=e.defaultValue;if(e.variadic){if(i<this.args.length){n=this.args.slice(i);if(e.parseArg){n=n.reduce(((t,i)=>myParseArg(e,i,t)),e.defaultValue)}}else if(n===undefined){n=[]}}else if(i<this.args.length){n=this.args[i];if(e.parseArg){n=myParseArg(e,n,e.defaultValue)}}t[i]=n}));this.processedArgs=t}_chainOrCall(t,e){if(t&&t.then&&typeof t.then==="function"){return t.then((()=>e()))}return e()}_chainOrCallHooks(t,e){let i=t;const n=[];this._getCommandAndAncestors().reverse().filter((t=>t._lifeCycleHooks[e]!==undefined)).forEach((t=>{t._lifeCycleHooks[e].forEach((e=>{n.push({hookedCommand:t,callback:e})}))}));if(e==="postAction"){n.reverse()}n.forEach((t=>{i=this._chainOrCall(i,(()=>t.callback(t.hookedCommand,this)))}));return i}_chainOrCallSubCommandHook(t,e,i){let n=t;if(this._lifeCycleHooks[i]!==undefined){this._lifeCycleHooks[i].forEach((t=>{n=this._chainOrCall(n,(()=>t(this,e)))}))}return n}_parseCommand(t,e){const i=this.parseOptions(e);this._parseOptionsEnv();this._parseOptionsImplied();t=t.concat(i.operands);e=i.unknown;this.args=t.concat(e);if(t&&this._findCommand(t[0])){return this._dispatchSubcommand(t[0],t.slice(1),e)}if(this._getHelpCommand()&&t[0]===this._getHelpCommand().name()){return this._dispatchHelpCommand(t[1])}if(this._defaultCommandName){this._outputHelpIfRequested(e);return this._dispatchSubcommand(this._defaultCommandName,t,e)}if(this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName){this.help({error:true})}this._outputHelpIfRequested(i.unknown);this._checkForMissingMandatoryOptions();this._checkForConflictingOptions();const checkForUnknownOptions=()=>{if(i.unknown.length>0){this.unknownOption(i.unknown[0])}};const n=`command:${this.name()}`;if(this._actionHandler){checkForUnknownOptions();this._processArguments();let i;i=this._chainOrCallHooks(i,"preAction");i=this._chainOrCall(i,(()=>this._actionHandler(this.processedArgs)));if(this.parent){i=this._chainOrCall(i,(()=>{this.parent.emit(n,t,e)}))}i=this._chainOrCallHooks(i,"postAction");return i}if(this.parent&&this.parent.listenerCount(n)){checkForUnknownOptions();this._processArguments();this.parent.emit(n,t,e)}else if(t.length){if(this._findCommand("*")){return this._dispatchSubcommand("*",t,e)}if(this.listenerCount("command:*")){this.emit("command:*",t,e)}else if(this.commands.length){this.unknownCommand()}else{checkForUnknownOptions();this._processArguments()}}else if(this.commands.length){checkForUnknownOptions();this.help({error:true})}else{checkForUnknownOptions();this._processArguments()}}_findCommand(t){if(!t)return undefined;return this.commands.find((e=>e._name===t||e._aliases.includes(t)))}_findOption(t){return this.options.find((e=>e.is(t)))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach((t=>{t.options.forEach((e=>{if(e.mandatory&&t.getOptionValue(e.attributeName())===undefined){t.missingMandatoryOptionValue(e)}}))}))}_checkForConflictingLocalOptions(){const t=this.options.filter((t=>{const e=t.attributeName();if(this.getOptionValue(e)===undefined){return false}return this.getOptionValueSource(e)!=="default"}));const e=t.filter((t=>t.conflictsWith.length>0));e.forEach((e=>{const i=t.find((t=>e.conflictsWith.includes(t.attributeName())));if(i){this._conflictingOption(e,i)}}))}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach((t=>{t._checkForConflictingLocalOptions()}))}parseOptions(t){const e=[];const i=[];let n=e;const s=t.slice();function maybeOption(t){return t.length>1&&t[0]==="-"}let r=null;while(s.length){const t=s.shift();if(t==="--"){if(n===i)n.push(t);n.push(...s);break}if(r&&!maybeOption(t)){this.emit(`option:${r.name()}`,t);continue}r=null;if(maybeOption(t)){const e=this._findOption(t);if(e){if(e.required){const t=s.shift();if(t===undefined)this.optionMissingArgument(e);this.emit(`option:${e.name()}`,t)}else if(e.optional){let t=null;if(s.length>0&&!maybeOption(s[0])){t=s.shift()}this.emit(`option:${e.name()}`,t)}else{this.emit(`option:${e.name()}`)}r=e.variadic?e:null;continue}}if(t.length>2&&t[0]==="-"&&t[1]!=="-"){const e=this._findOption(`-${t[1]}`);if(e){if(e.required||e.optional&&this._combineFlagAndOptionalValue){this.emit(`option:${e.name()}`,t.slice(2))}else{this.emit(`option:${e.name()}`);s.unshift(`-${t.slice(2)}`)}continue}}if(/^--[^=]+=/.test(t)){const e=t.indexOf("=");const i=this._findOption(t.slice(0,e));if(i&&(i.required||i.optional)){this.emit(`option:${i.name()}`,t.slice(e+1));continue}}if(maybeOption(t)){n=i}if((this._enablePositionalOptions||this._passThroughOptions)&&e.length===0&&i.length===0){if(this._findCommand(t)){e.push(t);if(s.length>0)i.push(...s);break}else if(this._getHelpCommand()&&t===this._getHelpCommand().name()){e.push(t);if(s.length>0)e.push(...s);break}else if(this._defaultCommandName){i.push(t);if(s.length>0)i.push(...s);break}}if(this._passThroughOptions){n.push(t);if(s.length>0)n.push(...s);break}n.push(t)}return{operands:e,unknown:i}}opts(){if(this._storeOptionsAsProperties){const t={};const e=this.options.length;for(let i=0;i<e;i++){const e=this.options[i].attributeName();t[e]=e===this._versionOptionName?this._version:this[e]}return t}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce(((t,e)=>Object.assign(t,e.opts())),{})}error(t,e){this._outputConfiguration.outputError(`${t}\n`,this._outputConfiguration.writeErr);if(typeof this._showHelpAfterError==="string"){this._outputConfiguration.writeErr(`${this._showHelpAfterError}\n`)}else if(this._showHelpAfterError){this._outputConfiguration.writeErr("\n");this.outputHelp({error:true})}const i=e||{};const n=i.exitCode||1;const s=i.code||"commander.error";this._exit(n,s,t)}_parseOptionsEnv(){this.options.forEach((t=>{if(t.envVar&&t.envVar in a.env){const e=t.attributeName();if(this.getOptionValue(e)===undefined||["default","config","env"].includes(this.getOptionValueSource(e))){if(t.required||t.optional){this.emit(`optionEnv:${t.name()}`,a.env[t.envVar])}else{this.emit(`optionEnv:${t.name()}`)}}}}))}_parseOptionsImplied(){const t=new d(this.options);const hasCustomOptionValue=t=>this.getOptionValue(t)!==undefined&&!["default","implied"].includes(this.getOptionValueSource(t));this.options.filter((e=>e.implied!==undefined&&hasCustomOptionValue(e.attributeName())&&t.valueFromOption(this.getOptionValue(e.attributeName()),e))).forEach((t=>{Object.keys(t.implied).filter((t=>!hasCustomOptionValue(t))).forEach((e=>{this.setOptionValueWithSource(e,t.implied[e],"implied")}))}))}missingArgument(t){const e=`error: missing required argument '${t}'`;this.error(e,{code:"commander.missingArgument"})}optionMissingArgument(t){const e=`error: option '${t.flags}' argument missing`;this.error(e,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(t){const e=`error: required option '${t.flags}' not specified`;this.error(e,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(t,e){const findBestOptionFromValue=t=>{const e=t.attributeName();const i=this.getOptionValue(e);const n=this.options.find((t=>t.negate&&e===t.attributeName()));const s=this.options.find((t=>!t.negate&&e===t.attributeName()));if(n&&(n.presetArg===undefined&&i===false||n.presetArg!==undefined&&i===n.presetArg)){return n}return s||t};const getErrorMessage=t=>{const e=findBestOptionFromValue(t);const i=e.attributeName();const n=this.getOptionValueSource(i);if(n==="env"){return`environment variable '${e.envVar}'`}return`option '${e.flags}'`};const i=`error: ${getErrorMessage(t)} cannot be used with ${getErrorMessage(e)}`;this.error(i,{code:"commander.conflictingOption"})}unknownOption(t){if(this._allowUnknownOption)return;let e="";if(t.startsWith("--")&&this._showSuggestionAfterError){let i=[];let n=this;do{const t=n.createHelp().visibleOptions(n).filter((t=>t.long)).map((t=>t.long));i=i.concat(t);n=n.parent}while(n&&!n._enablePositionalOptions);e=m(t,i)}const i=`error: unknown option '${t}'${e}`;this.error(i,{code:"commander.unknownOption"})}_excessArguments(t){if(this._allowExcessArguments)return;const e=this.registeredArguments.length;const i=e===1?"":"s";const n=this.parent?` for '${this.name()}'`:"";const s=`error: too many arguments${n}. Expected ${e} argument${i} but got ${t.length}.`;this.error(s,{code:"commander.excessArguments"})}unknownCommand(){const t=this.args[0];let e="";if(this._showSuggestionAfterError){const i=[];this.createHelp().visibleCommands(this).forEach((t=>{i.push(t.name());if(t.alias())i.push(t.alias())}));e=m(t,i)}const i=`error: unknown command '${t}'${e}`;this.error(i,{code:"commander.unknownCommand"})}version(t,e,i){if(t===undefined)return this._version;this._version=t;e=e||"-V, --version";i=i||"output the version number";const n=this.createOption(e,i);this._versionOptionName=n.attributeName();this._registerOption(n);this.on("option:"+n.name(),(()=>{this._outputConfiguration.writeOut(`${t}\n`);this._exit(0,"commander.version",t)}));return this}description(t,e){if(t===undefined&&e===undefined)return this._description;this._description=t;if(e){this._argsDescription=e}return this}summary(t){if(t===undefined)return this._summary;this._summary=t;return this}alias(t){if(t===undefined)return this._aliases[0];let e=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler){e=this.commands[this.commands.length-1]}if(t===e._name)throw new Error("Command alias can't be the same as its name");const i=this.parent?._findCommand(t);if(i){const e=[i.name()].concat(i.aliases()).join("|");throw new Error(`cannot add alias '${t}' to command '${this.name()}' as already have command '${e}'`)}e._aliases.push(t);return this}aliases(t){if(t===undefined)return this._aliases;t.forEach((t=>this.alias(t)));return this}usage(t){if(t===undefined){if(this._usage)return this._usage;const t=this.registeredArguments.map((t=>l(t)));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}this._usage=t;return this}name(t){if(t===undefined)return this._name;this._name=t;return this}nameFromFilename(t){this._name=r.basename(t,r.extname(t));return this}executableDir(t){if(t===undefined)return this._executableDir;this._executableDir=t;return this}helpInformation(t){const e=this.createHelp();if(e.helpWidth===undefined){e.helpWidth=t&&t.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()}return e.formatHelp(this,e)}_getHelpContext(t){t=t||{};const e={error:!!t.error};let i;if(e.error){i=t=>this._outputConfiguration.writeErr(t)}else{i=t=>this._outputConfiguration.writeOut(t)}e.write=t.write||i;e.command=this;return e}outputHelp(t){let e;if(typeof t==="function"){e=t;t=undefined}const i=this._getHelpContext(t);this._getCommandAndAncestors().reverse().forEach((t=>t.emit("beforeAllHelp",i)));this.emit("beforeHelp",i);let n=this.helpInformation(i);if(e){n=e(n);if(typeof n!=="string"&&!Buffer.isBuffer(n)){throw new Error("outputHelp callback must return a string or a Buffer")}}i.write(n);if(this._getHelpOption()?.long){this.emit(this._getHelpOption().long)}this.emit("afterHelp",i);this._getCommandAndAncestors().forEach((t=>t.emit("afterAllHelp",i)))}helpOption(t,e){if(typeof t==="boolean"){if(t){this._helpOption=this._helpOption??undefined}else{this._helpOption=null}return this}t=t??"-h, --help";e=e??"display help for command";this._helpOption=this.createOption(t,e);return this}_getHelpOption(){if(this._helpOption===undefined){this.helpOption(undefined,undefined)}return this._helpOption}addHelpOption(t){this._helpOption=t;return this}help(t){this.outputHelp(t);let e=a.exitCode||0;if(e===0&&t&&typeof t!=="function"&&t.error){e=1}this._exit(e,"commander.help","(outputHelp)")}addHelpText(t,e){const i=["beforeAll","before","after","afterAll"];if(!i.includes(t)){throw new Error(`Unexpected value for position to addHelpText.\nExpecting one of '${i.join("', '")}'`)}const n=`${t}Help`;this.on(n,(t=>{let i;if(typeof e==="function"){i=e({error:t.error,command:t.command})}else{i=e}if(i){t.write(`${i}\n`)}}));return this}_outputHelpIfRequested(t){const e=this._getHelpOption();const i=e&&t.find((t=>e.is(t)));if(i){this.outputHelp();this._exit(0,"commander.helpDisplayed","(outputHelp)")}}}function incrementNodeInspectorPort(t){return t.map((t=>{if(!t.startsWith("--inspect")){return t}let e;let i="127.0.0.1";let n="9229";let s;if((s=t.match(/^(--inspect(-brk)?)$/))!==null){e=s[1]}else if((s=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null){e=s[1];if(/^\d+$/.test(s[3])){n=s[3]}else{i=s[3]}}else if((s=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null){e=s[1];i=s[3];n=s[4]}if(e&&n!=="0"){return`${e}=${i}:${parseInt(n)+1}`}return t}))}e.Command=Command},422:(t,e)=>{class CommanderError extends Error{constructor(t,e,i){super(i);Error.captureStackTrace(this,this.constructor);this.name=this.constructor.name;this.code=e;this.exitCode=t;this.nestedError=undefined}}class InvalidArgumentError extends CommanderError{constructor(t){super(1,"commander.invalidArgument",t);Error.captureStackTrace(this,this.constructor);this.name=this.constructor.name}}e.CommanderError=CommanderError;e.InvalidArgumentError=InvalidArgumentError},455:(t,e,i)=>{const{humanReadableArgName:n}=i(975);class Help{constructor(){this.helpWidth=undefined;this.sortSubcommands=false;this.sortOptions=false;this.showGlobalOptions=false}visibleCommands(t){const e=t.commands.filter((t=>!t._hidden));const i=t._getHelpCommand();if(i&&!i._hidden){e.push(i)}if(this.sortSubcommands){e.sort(((t,e)=>t.name().localeCompare(e.name())))}return e}compareOptions(t,e){const getSortKey=t=>t.short?t.short.replace(/^-/,""):t.long.replace(/^--/,"");return getSortKey(t).localeCompare(getSortKey(e))}visibleOptions(t){const e=t.options.filter((t=>!t.hidden));const i=t._getHelpOption();if(i&&!i.hidden){const n=i.short&&t._findOption(i.short);const s=i.long&&t._findOption(i.long);if(!n&&!s){e.push(i)}else if(i.long&&!s){e.push(t.createOption(i.long,i.description))}else if(i.short&&!n){e.push(t.createOption(i.short,i.description))}}if(this.sortOptions){e.sort(this.compareOptions)}return e}visibleGlobalOptions(t){if(!this.showGlobalOptions)return[];const e=[];for(let i=t.parent;i;i=i.parent){const t=i.options.filter((t=>!t.hidden));e.push(...t)}if(this.sortOptions){e.sort(this.compareOptions)}return e}visibleArguments(t){if(t._argsDescription){t.registeredArguments.forEach((e=>{e.description=e.description||t._argsDescription[e.name()]||""}))}if(t.registeredArguments.find((t=>t.description))){return t.registeredArguments}return[]}subcommandTerm(t){const e=t.registeredArguments.map((t=>n(t))).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(e?" "+e:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,e){return e.visibleCommands(t).reduce(((t,i)=>Math.max(t,e.subcommandTerm(i).length)),0)}longestOptionTermLength(t,e){return e.visibleOptions(t).reduce(((t,i)=>Math.max(t,e.optionTerm(i).length)),0)}longestGlobalOptionTermLength(t,e){return e.visibleGlobalOptions(t).reduce(((t,i)=>Math.max(t,e.optionTerm(i).length)),0)}longestArgumentTermLength(t,e){return e.visibleArguments(t).reduce(((t,i)=>Math.max(t,e.argumentTerm(i).length)),0)}commandUsage(t){let e=t._name;if(t._aliases[0]){e=e+"|"+t._aliases[0]}let i="";for(let e=t.parent;e;e=e.parent){i=e.name()+" "+i}return i+e+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){const e=[];if(t.argChoices){e.push(`choices: ${t.argChoices.map((t=>JSON.stringify(t))).join(", ")}`)}if(t.defaultValue!==undefined){const i=t.required||t.optional||t.isBoolean()&&typeof t.defaultValue==="boolean";if(i){e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`)}}if(t.presetArg!==undefined&&t.optional){e.push(`preset: ${JSON.stringify(t.presetArg)}`)}if(t.envVar!==undefined){e.push(`env: ${t.envVar}`)}if(e.length>0){return`${t.description} (${e.join(", ")})`}return t.description}argumentDescription(t){const e=[];if(t.argChoices){e.push(`choices: ${t.argChoices.map((t=>JSON.stringify(t))).join(", ")}`)}if(t.defaultValue!==undefined){e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`)}if(e.length>0){const i=`(${e.join(", ")})`;if(t.description){return`${t.description} ${i}`}return i}return t.description}formatHelp(t,e){const i=e.padWidth(t,e);const n=e.helpWidth||80;const s=2;const r=2;function formatItem(t,o){if(o){const a=`${t.padEnd(i+r)}${o}`;return e.wrap(a,n-s,i+r)}return t}function formatList(t){return t.join("\n").replace(/^/gm," ".repeat(s))}let o=[`Usage: ${e.commandUsage(t)}`,""];const a=e.commandDescription(t);if(a.length>0){o=o.concat([e.wrap(a,n,0),""])}const h=e.visibleArguments(t).map((t=>formatItem(e.argumentTerm(t),e.argumentDescription(t))));if(h.length>0){o=o.concat(["Arguments:",formatList(h),""])}const l=e.visibleOptions(t).map((t=>formatItem(e.optionTerm(t),e.optionDescription(t))));if(l.length>0){o=o.concat(["Options:",formatList(l),""])}if(this.showGlobalOptions){const i=e.visibleGlobalOptions(t).map((t=>formatItem(e.optionTerm(t),e.optionDescription(t))));if(i.length>0){o=o.concat(["Global Options:",formatList(i),""])}}const u=e.visibleCommands(t).map((t=>formatItem(e.subcommandTerm(t),e.subcommandDescription(t))));if(u.length>0){o=o.concat(["Commands:",formatList(u),""])}return o.join("\n")}padWidth(t,e){return Math.max(e.longestOptionTermLength(t,e),e.longestGlobalOptionTermLength(t,e),e.longestSubcommandTermLength(t,e),e.longestArgumentTermLength(t,e))}wrap(t,e,i,n=40){const s=" \\f\\t\\v   -    \ufeff";const r=new RegExp(`[\\n][${s}]+`);if(t.match(r))return t;const o=e-i;if(o<n)return t;const a=t.slice(0,i);const h=t.slice(i).replace("\r\n","\n");const l=" ".repeat(i);const u="​";const c=`\\s${u}`;const p=new RegExp(`\n|.{1,${o-1}}([${c}]|$)|[^${c}]+?([${c}]|$)`,"g");const d=h.match(p)||[];return a+d.map(((t,e)=>{if(t==="\n")return"";return(e>0?l:"")+t.trimEnd()})).join("\n")}}e.Help=Help},985:(t,e,i)=>{const{InvalidArgumentError:n}=i(422);class Option{constructor(t,e){this.flags=t;this.description=e||"";this.required=t.includes("<");this.optional=t.includes("[");this.variadic=/\w\.\.\.[>\]]$/.test(t);this.mandatory=false;const i=splitOptionFlags(t);this.short=i.shortFlag;this.long=i.longFlag;this.negate=false;if(this.long){this.negate=this.long.startsWith("--no-")}this.defaultValue=undefined;this.defaultValueDescription=undefined;this.presetArg=undefined;this.envVar=undefined;this.parseArg=undefined;this.hidden=false;this.argChoices=undefined;this.conflictsWith=[];this.implied=undefined}default(t,e){this.defaultValue=t;this.defaultValueDescription=e;return this}preset(t){this.presetArg=t;return this}conflicts(t){this.conflictsWith=this.conflictsWith.concat(t);return this}implies(t){let e=t;if(typeof t==="string"){e={[t]:true}}this.implied=Object.assign(this.implied||{},e);return this}env(t){this.envVar=t;return this}argParser(t){this.parseArg=t;return this}makeOptionMandatory(t=true){this.mandatory=!!t;return this}hideHelp(t=true){this.hidden=!!t;return this}_concatValue(t,e){if(e===this.defaultValue||!Array.isArray(e)){return[t]}return e.concat(t)}choices(t){this.argChoices=t.slice();this.parseArg=(t,e)=>{if(!this.argChoices.includes(t)){throw new n(`Allowed choices are ${this.argChoices.join(", ")}.`)}if(this.variadic){return this._concatValue(t,e)}return t};return this}name(){if(this.long){return this.long.replace(/^--/,"")}return this.short.replace(/^-/,"")}attributeName(){return camelcase(this.name().replace(/^no-/,""))}is(t){return this.short===t||this.long===t}isBoolean(){return!this.required&&!this.optional&&!this.negate}}class DualOptions{constructor(t){this.positiveOptions=new Map;this.negativeOptions=new Map;this.dualOptions=new Set;t.forEach((t=>{if(t.negate){this.negativeOptions.set(t.attributeName(),t)}else{this.positiveOptions.set(t.attributeName(),t)}}));this.negativeOptions.forEach(((t,e)=>{if(this.positiveOptions.has(e)){this.dualOptions.add(e)}}))}valueFromOption(t,e){const i=e.attributeName();if(!this.dualOptions.has(i))return true;const n=this.negativeOptions.get(i).presetArg;const s=n!==undefined?n:false;return e.negate===(s===t)}}function camelcase(t){return t.split("-").reduce(((t,e)=>t+e[0].toUpperCase()+e.slice(1)))}function splitOptionFlags(t){let e;let i;const n=t.split(/[ |,]+/);if(n.length>1&&!/^[[<]/.test(n[1]))e=n.shift();i=n.shift();if(!e&&/^-[^-]$/.test(i)){e=i;i=undefined}return{shortFlag:e,longFlag:i}}e.Option=Option;e.DualOptions=DualOptions},745:(t,e)=>{const i=3;function editDistance(t,e){if(Math.abs(t.length-e.length)>i)return Math.max(t.length,e.length);const n=[];for(let e=0;e<=t.length;e++){n[e]=[e]}for(let t=0;t<=e.length;t++){n[0][t]=t}for(let i=1;i<=e.length;i++){for(let s=1;s<=t.length;s++){let r=1;if(t[s-1]===e[i-1]){r=0}else{r=1}n[s][i]=Math.min(n[s-1][i]+1,n[s][i-1]+1,n[s-1][i-1]+r);if(s>1&&i>1&&t[s-1]===e[i-2]&&t[s-2]===e[i-1]){n[s][i]=Math.min(n[s][i],n[s-2][i-2]+1)}}}return n[t.length][e.length]}function suggestSimilar(t,e){if(!e||e.length===0)return"";e=Array.from(new Set(e));const n=t.startsWith("--");if(n){t=t.slice(2);e=e.map((t=>t.slice(2)))}let s=[];let r=i;const o=.4;e.forEach((e=>{if(e.length<=1)return;const i=editDistance(t,e);const n=Math.max(t.length,e.length);const a=(n-i)/n;if(a>o){if(i<r){r=i;s=[e]}else if(i===r){s.push(e)}}}));s.sort(((t,e)=>t.localeCompare(e)));if(n){s=s.map((t=>`--${t}`))}if(s.length>1){return`\n(Did you mean one of ${s.join(", ")}?)`}if(s.length===1){return`\n(Did you mean ${s[0]}?)`}return""}e.suggestSimilar=suggestSimilar}};var e={};function __nccwpck_require__(i){var n=e[i];if(n!==undefined){return n.exports}var s=e[i]={exports:{}};var r=true;try{t[i](s,s.exports,__nccwpck_require__);r=false}finally{if(r)delete e[i]}return s.exports}if(typeof __nccwpck_require__!=="undefined")__nccwpck_require__.ab=__dirname+"/";var i={};(()=>{var t=i;const{Argument:e}=__nccwpck_require__(975);const{Command:n}=__nccwpck_require__(965);const{CommanderError:s,InvalidArgumentError:r}=__nccwpck_require__(422);const{Help:o}=__nccwpck_require__(455);const{Option:a}=__nccwpck_require__(985);t.program=new n;t.createCommand=t=>new n(t);t.createOption=(t,e)=>new a(t,e);t.createArgument=(t,i)=>new e(t,i);t.Command=n;t.Option=a;t.Argument=e;t.Help=o;t.CommanderError=s;t.InvalidArgumentError=r;t.InvalidOptionArgumentError=r})();module.exports=i})();
@@ -0,0 +1,22 @@
1
+ (The MIT License)
2
+
3
+ Copyright (c) 2011 TJ Holowaychuk <tj@vision-media.ca>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ 'Software'), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
19
+ IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
20
+ CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
21
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
22
+ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1 @@
1
+ {"name":"commander","author":"TJ Holowaychuk <tj@vision-media.ca>","version":"12.0.0","license":"MIT","types":"typings/index.d.ts","type":"commonjs"}
@@ -0,0 +1,899 @@
1
+ // Type definitions for commander
2
+ // Original definitions by: Alan Agius <https://github.com/alan-agius4>, Marcelo Dezem <https://github.com/mdezem>, vvakame <https://github.com/vvakame>, Jules Randolph <https://github.com/sveinburne>
3
+
4
+ // Using method rather than property for method-signature-style, to document method overloads separately. Allow either.
5
+ /* eslint-disable @typescript-eslint/method-signature-style */
6
+ /* eslint-disable @typescript-eslint/no-explicit-any */
7
+
8
+ // This is a trick to encourage editor to suggest the known literals while still
9
+ // allowing any BaseType value.
10
+ // References:
11
+ // - https://github.com/microsoft/TypeScript/issues/29729
12
+ // - https://github.com/sindresorhus/type-fest/blob/main/source/literal-union.d.ts
13
+ // - https://github.com/sindresorhus/type-fest/blob/main/source/primitive.d.ts
14
+ type LiteralUnion<LiteralType, BaseType extends string | number> = LiteralType | (BaseType & Record<never, never>);
15
+
16
+ export class CommanderError extends Error {
17
+ code: string;
18
+ exitCode: number;
19
+ message: string;
20
+ nestedError?: string;
21
+
22
+ /**
23
+ * Constructs the CommanderError class
24
+ * @param exitCode - suggested exit code which could be used with process.exit
25
+ * @param code - an id string representing the error
26
+ * @param message - human-readable description of the error
27
+ * @constructor
28
+ */
29
+ constructor(exitCode: number, code: string, message: string);
30
+ }
31
+
32
+ export class InvalidArgumentError extends CommanderError {
33
+ /**
34
+ * Constructs the InvalidArgumentError class
35
+ * @param message - explanation of why argument is invalid
36
+ * @constructor
37
+ */
38
+ constructor(message: string);
39
+ }
40
+ export { InvalidArgumentError as InvalidOptionArgumentError }; // deprecated old name
41
+
42
+ export interface ErrorOptions { // optional parameter for error()
43
+ /** an id string representing the error */
44
+ code?: string;
45
+ /** suggested exit code which could be used with process.exit */
46
+ exitCode?: number;
47
+ }
48
+
49
+ export class Argument {
50
+ description: string;
51
+ required: boolean;
52
+ variadic: boolean;
53
+ defaultValue?: any;
54
+ defaultValueDescription?: string;
55
+ argChoices?: string[];
56
+
57
+ /**
58
+ * Initialize a new command argument with the given name and description.
59
+ * The default is that the argument is required, and you can explicitly
60
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
61
+ */
62
+ constructor(arg: string, description?: string);
63
+
64
+ /**
65
+ * Return argument name.
66
+ */
67
+ name(): string;
68
+
69
+ /**
70
+ * Set the default value, and optionally supply the description to be displayed in the help.
71
+ */
72
+ default(value: unknown, description?: string): this;
73
+
74
+ /**
75
+ * Set the custom handler for processing CLI command arguments into argument values.
76
+ */
77
+ argParser<T>(fn: (value: string, previous: T) => T): this;
78
+
79
+ /**
80
+ * Only allow argument value to be one of choices.
81
+ */
82
+ choices(values: readonly string[]): this;
83
+
84
+ /**
85
+ * Make argument required.
86
+ */
87
+ argRequired(): this;
88
+
89
+ /**
90
+ * Make argument optional.
91
+ */
92
+ argOptional(): this;
93
+ }
94
+
95
+ export class Option {
96
+ flags: string;
97
+ description: string;
98
+
99
+ required: boolean; // A value must be supplied when the option is specified.
100
+ optional: boolean; // A value is optional when the option is specified.
101
+ variadic: boolean;
102
+ mandatory: boolean; // The option must have a value after parsing, which usually means it must be specified on command line.
103
+ short?: string;
104
+ long?: string;
105
+ negate: boolean;
106
+ defaultValue?: any;
107
+ defaultValueDescription?: string;
108
+ presetArg?: unknown;
109
+ envVar?: string;
110
+ parseArg?: <T>(value: string, previous: T) => T;
111
+ hidden: boolean;
112
+ argChoices?: string[];
113
+
114
+ constructor(flags: string, description?: string);
115
+
116
+ /**
117
+ * Set the default value, and optionally supply the description to be displayed in the help.
118
+ */
119
+ default(value: unknown, description?: string): this;
120
+
121
+ /**
122
+ * Preset to use when option used without option-argument, especially optional but also boolean and negated.
123
+ * The custom processing (parseArg) is called.
124
+ *
125
+ * @example
126
+ * ```ts
127
+ * new Option('--color').default('GREYSCALE').preset('RGB');
128
+ * new Option('--donate [amount]').preset('20').argParser(parseFloat);
129
+ * ```
130
+ */
131
+ preset(arg: unknown): this;
132
+
133
+ /**
134
+ * Add option name(s) that conflict with this option.
135
+ * An error will be displayed if conflicting options are found during parsing.
136
+ *
137
+ * @example
138
+ * ```ts
139
+ * new Option('--rgb').conflicts('cmyk');
140
+ * new Option('--js').conflicts(['ts', 'jsx']);
141
+ * ```
142
+ */
143
+ conflicts(names: string | string[]): this;
144
+
145
+ /**
146
+ * Specify implied option values for when this option is set and the implied options are not.
147
+ *
148
+ * The custom processing (parseArg) is not called on the implied values.
149
+ *
150
+ * @example
151
+ * program
152
+ * .addOption(new Option('--log', 'write logging information to file'))
153
+ * .addOption(new Option('--trace', 'log extra details').implies({ log: 'trace.txt' }));
154
+ */
155
+ implies(optionValues: OptionValues): this;
156
+
157
+ /**
158
+ * Set environment variable to check for option value.
159
+ *
160
+ * An environment variables is only used if when processed the current option value is
161
+ * undefined, or the source of the current value is 'default' or 'config' or 'env'.
162
+ */
163
+ env(name: string): this;
164
+
165
+ /**
166
+ * Calculate the full description, including defaultValue etc.
167
+ */
168
+ fullDescription(): string;
169
+
170
+ /**
171
+ * Set the custom handler for processing CLI option arguments into option values.
172
+ */
173
+ argParser<T>(fn: (value: string, previous: T) => T): this;
174
+
175
+ /**
176
+ * Whether the option is mandatory and must have a value after parsing.
177
+ */
178
+ makeOptionMandatory(mandatory?: boolean): this;
179
+
180
+ /**
181
+ * Hide option in help.
182
+ */
183
+ hideHelp(hide?: boolean): this;
184
+
185
+ /**
186
+ * Only allow option value to be one of choices.
187
+ */
188
+ choices(values: readonly string[]): this;
189
+
190
+ /**
191
+ * Return option name.
192
+ */
193
+ name(): string;
194
+
195
+ /**
196
+ * Return option name, in a camelcase format that can be used
197
+ * as a object attribute key.
198
+ */
199
+ attributeName(): string;
200
+
201
+ /**
202
+ * Return whether a boolean option.
203
+ *
204
+ * Options are one of boolean, negated, required argument, or optional argument.
205
+ */
206
+ isBoolean(): boolean;
207
+ }
208
+
209
+ export class Help {
210
+ /** output helpWidth, long lines are wrapped to fit */
211
+ helpWidth?: number;
212
+ sortSubcommands: boolean;
213
+ sortOptions: boolean;
214
+ showGlobalOptions: boolean;
215
+
216
+ constructor();
217
+
218
+ /** Get the command term to show in the list of subcommands. */
219
+ subcommandTerm(cmd: Command): string;
220
+ /** Get the command summary to show in the list of subcommands. */
221
+ subcommandDescription(cmd: Command): string;
222
+ /** Get the option term to show in the list of options. */
223
+ optionTerm(option: Option): string;
224
+ /** Get the option description to show in the list of options. */
225
+ optionDescription(option: Option): string;
226
+ /** Get the argument term to show in the list of arguments. */
227
+ argumentTerm(argument: Argument): string;
228
+ /** Get the argument description to show in the list of arguments. */
229
+ argumentDescription(argument: Argument): string;
230
+
231
+ /** Get the command usage to be displayed at the top of the built-in help. */
232
+ commandUsage(cmd: Command): string;
233
+ /** Get the description for the command. */
234
+ commandDescription(cmd: Command): string;
235
+
236
+ /** Get an array of the visible subcommands. Includes a placeholder for the implicit help command, if there is one. */
237
+ visibleCommands(cmd: Command): Command[];
238
+ /** Get an array of the visible options. Includes a placeholder for the implicit help option, if there is one. */
239
+ visibleOptions(cmd: Command): Option[];
240
+ /** Get an array of the visible global options. (Not including help.) */
241
+ visibleGlobalOptions(cmd: Command): Option[];
242
+ /** Get an array of the arguments which have descriptions. */
243
+ visibleArguments(cmd: Command): Argument[];
244
+
245
+ /** Get the longest command term length. */
246
+ longestSubcommandTermLength(cmd: Command, helper: Help): number;
247
+ /** Get the longest option term length. */
248
+ longestOptionTermLength(cmd: Command, helper: Help): number;
249
+ /** Get the longest global option term length. */
250
+ longestGlobalOptionTermLength(cmd: Command, helper: Help): number;
251
+ /** Get the longest argument term length. */
252
+ longestArgumentTermLength(cmd: Command, helper: Help): number;
253
+ /** Calculate the pad width from the maximum term length. */
254
+ padWidth(cmd: Command, helper: Help): number;
255
+
256
+ /**
257
+ * Wrap the given string to width characters per line, with lines after the first indented.
258
+ * Do not wrap if insufficient room for wrapping (minColumnWidth), or string is manually formatted.
259
+ */
260
+ wrap(str: string, width: number, indent: number, minColumnWidth?: number): string;
261
+
262
+ /** Generate the built-in help text. */
263
+ formatHelp(cmd: Command, helper: Help): string;
264
+ }
265
+ export type HelpConfiguration = Partial<Help>;
266
+
267
+ export interface ParseOptions {
268
+ from: 'node' | 'electron' | 'user';
269
+ }
270
+ export interface HelpContext { // optional parameter for .help() and .outputHelp()
271
+ error: boolean;
272
+ }
273
+ export interface AddHelpTextContext { // passed to text function used with .addHelpText()
274
+ error: boolean;
275
+ command: Command;
276
+ }
277
+ export interface OutputConfiguration {
278
+ writeOut?(str: string): void;
279
+ writeErr?(str: string): void;
280
+ getOutHelpWidth?(): number;
281
+ getErrHelpWidth?(): number;
282
+ outputError?(str: string, write: (str: string) => void): void;
283
+
284
+ }
285
+
286
+ export type AddHelpTextPosition = 'beforeAll' | 'before' | 'after' | 'afterAll';
287
+ export type HookEvent = 'preSubcommand' | 'preAction' | 'postAction';
288
+ // The source is a string so author can define their own too.
289
+ export type OptionValueSource = LiteralUnion<'default' | 'config' | 'env' | 'cli' | 'implied', string> | undefined;
290
+
291
+ export type OptionValues = Record<string, any>;
292
+
293
+ export class Command {
294
+ args: string[];
295
+ processedArgs: any[];
296
+ readonly commands: readonly Command[];
297
+ readonly options: readonly Option[];
298
+ readonly registeredArguments: readonly Argument[];
299
+ parent: Command | null;
300
+
301
+ constructor(name?: string);
302
+
303
+ /**
304
+ * Set the program version to `str`.
305
+ *
306
+ * This method auto-registers the "-V, --version" flag
307
+ * which will print the version number when passed.
308
+ *
309
+ * You can optionally supply the flags and description to override the defaults.
310
+ */
311
+ version(str: string, flags?: string, description?: string): this;
312
+ /**
313
+ * Get the program version.
314
+ */
315
+ version(): string | undefined;
316
+
317
+ /**
318
+ * Define a command, implemented using an action handler.
319
+ *
320
+ * @remarks
321
+ * The command description is supplied using `.description`, not as a parameter to `.command`.
322
+ *
323
+ * @example
324
+ * ```ts
325
+ * program
326
+ * .command('clone <source> [destination]')
327
+ * .description('clone a repository into a newly created directory')
328
+ * .action((source, destination) => {
329
+ * console.log('clone command called');
330
+ * });
331
+ * ```
332
+ *
333
+ * @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
334
+ * @param opts - configuration options
335
+ * @returns new command
336
+ */
337
+ command(nameAndArgs: string, opts?: CommandOptions): ReturnType<this['createCommand']>;
338
+ /**
339
+ * Define a command, implemented in a separate executable file.
340
+ *
341
+ * @remarks
342
+ * The command description is supplied as the second parameter to `.command`.
343
+ *
344
+ * @example
345
+ * ```ts
346
+ * program
347
+ * .command('start <service>', 'start named service')
348
+ * .command('stop [service]', 'stop named service, or all if no name supplied');
349
+ * ```
350
+ *
351
+ * @param nameAndArgs - command name and arguments, args are `<required>` or `[optional]` and last may also be `variadic...`
352
+ * @param description - description of executable command
353
+ * @param opts - configuration options
354
+ * @returns `this` command for chaining
355
+ */
356
+ command(nameAndArgs: string, description: string, opts?: ExecutableCommandOptions): this;
357
+
358
+ /**
359
+ * Factory routine to create a new unattached command.
360
+ *
361
+ * See .command() for creating an attached subcommand, which uses this routine to
362
+ * create the command. You can override createCommand to customise subcommands.
363
+ */
364
+ createCommand(name?: string): Command;
365
+
366
+ /**
367
+ * Add a prepared subcommand.
368
+ *
369
+ * See .command() for creating an attached subcommand which inherits settings from its parent.
370
+ *
371
+ * @returns `this` command for chaining
372
+ */
373
+ addCommand(cmd: Command, opts?: CommandOptions): this;
374
+
375
+ /**
376
+ * Factory routine to create a new unattached argument.
377
+ *
378
+ * See .argument() for creating an attached argument, which uses this routine to
379
+ * create the argument. You can override createArgument to return a custom argument.
380
+ */
381
+ createArgument(name: string, description?: string): Argument;
382
+
383
+ /**
384
+ * Define argument syntax for command.
385
+ *
386
+ * The default is that the argument is required, and you can explicitly
387
+ * indicate this with <> around the name. Put [] around the name for an optional argument.
388
+ *
389
+ * @example
390
+ * ```
391
+ * program.argument('<input-file>');
392
+ * program.argument('[output-file]');
393
+ * ```
394
+ *
395
+ * @returns `this` command for chaining
396
+ */
397
+ argument<T>(flags: string, description: string, fn: (value: string, previous: T) => T, defaultValue?: T): this;
398
+ argument(name: string, description?: string, defaultValue?: unknown): this;
399
+
400
+ /**
401
+ * Define argument syntax for command, adding a prepared argument.
402
+ *
403
+ * @returns `this` command for chaining
404
+ */
405
+ addArgument(arg: Argument): this;
406
+
407
+ /**
408
+ * Define argument syntax for command, adding multiple at once (without descriptions).
409
+ *
410
+ * See also .argument().
411
+ *
412
+ * @example
413
+ * ```
414
+ * program.arguments('<cmd> [env]');
415
+ * ```
416
+ *
417
+ * @returns `this` command for chaining
418
+ */
419
+ arguments(names: string): this;
420
+
421
+ /**
422
+ * Customise or override default help command. By default a help command is automatically added if your command has subcommands.
423
+ *
424
+ * @example
425
+ * ```ts
426
+ * program.helpCommand('help [cmd]');
427
+ * program.helpCommand('help [cmd]', 'show help');
428
+ * program.helpCommand(false); // suppress default help command
429
+ * program.helpCommand(true); // add help command even if no subcommands
430
+ * ```
431
+ */
432
+ helpCommand(nameAndArgs: string, description?: string): this;
433
+ helpCommand(enable: boolean): this;
434
+
435
+ /**
436
+ * Add prepared custom help command.
437
+ */
438
+ addHelpCommand(cmd: Command): this;
439
+ /** @deprecated since v12, instead use helpCommand */
440
+ addHelpCommand(nameAndArgs: string, description?: string): this;
441
+ /** @deprecated since v12, instead use helpCommand */
442
+ addHelpCommand(enable?: boolean): this;
443
+
444
+ /**
445
+ * Add hook for life cycle event.
446
+ */
447
+ hook(event: HookEvent, listener: (thisCommand: Command, actionCommand: Command) => void | Promise<void>): this;
448
+
449
+ /**
450
+ * Register callback to use as replacement for calling process.exit.
451
+ */
452
+ exitOverride(callback?: (err: CommanderError) => never | void): this;
453
+
454
+ /**
455
+ * Display error message and exit (or call exitOverride).
456
+ */
457
+ error(message: string, errorOptions?: ErrorOptions): never;
458
+
459
+ /**
460
+ * You can customise the help with a subclass of Help by overriding createHelp,
461
+ * or by overriding Help properties using configureHelp().
462
+ */
463
+ createHelp(): Help;
464
+
465
+ /**
466
+ * You can customise the help by overriding Help properties using configureHelp(),
467
+ * or with a subclass of Help by overriding createHelp().
468
+ */
469
+ configureHelp(configuration: HelpConfiguration): this;
470
+ /** Get configuration */
471
+ configureHelp(): HelpConfiguration;
472
+
473
+ /**
474
+ * The default output goes to stdout and stderr. You can customise this for special
475
+ * applications. You can also customise the display of errors by overriding outputError.
476
+ *
477
+ * The configuration properties are all functions:
478
+ * ```
479
+ * // functions to change where being written, stdout and stderr
480
+ * writeOut(str)
481
+ * writeErr(str)
482
+ * // matching functions to specify width for wrapping help
483
+ * getOutHelpWidth()
484
+ * getErrHelpWidth()
485
+ * // functions based on what is being written out
486
+ * outputError(str, write) // used for displaying errors, and not used for displaying help
487
+ * ```
488
+ */
489
+ configureOutput(configuration: OutputConfiguration): this;
490
+ /** Get configuration */
491
+ configureOutput(): OutputConfiguration;
492
+
493
+ /**
494
+ * Copy settings that are useful to have in common across root command and subcommands.
495
+ *
496
+ * (Used internally when adding a command using `.command()` so subcommands inherit parent settings.)
497
+ */
498
+ copyInheritedSettings(sourceCommand: Command): this;
499
+
500
+ /**
501
+ * Display the help or a custom message after an error occurs.
502
+ */
503
+ showHelpAfterError(displayHelp?: boolean | string): this;
504
+
505
+ /**
506
+ * Display suggestion of similar commands for unknown commands, or options for unknown options.
507
+ */
508
+ showSuggestionAfterError(displaySuggestion?: boolean): this;
509
+
510
+ /**
511
+ * Register callback `fn` for the command.
512
+ *
513
+ * @example
514
+ * ```
515
+ * program
516
+ * .command('serve')
517
+ * .description('start service')
518
+ * .action(function() {
519
+ * // do work here
520
+ * });
521
+ * ```
522
+ *
523
+ * @returns `this` command for chaining
524
+ */
525
+ action(fn: (...args: any[]) => void | Promise<void>): this;
526
+
527
+ /**
528
+ * Define option with `flags`, `description`, and optional argument parsing function or `defaultValue` or both.
529
+ *
530
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space. A required
531
+ * option-argument is indicated by `<>` and an optional option-argument by `[]`.
532
+ *
533
+ * See the README for more details, and see also addOption() and requiredOption().
534
+ *
535
+ * @example
536
+ *
537
+ * ```js
538
+ * program
539
+ * .option('-p, --pepper', 'add pepper')
540
+ * .option('-p, --pizza-type <TYPE>', 'type of pizza') // required option-argument
541
+ * .option('-c, --cheese [CHEESE]', 'add extra cheese', 'mozzarella') // optional option-argument with default
542
+ * .option('-t, --tip <VALUE>', 'add tip to purchase cost', parseFloat) // custom parse function
543
+ * ```
544
+ *
545
+ * @returns `this` command for chaining
546
+ */
547
+ option(flags: string, description?: string, defaultValue?: string | boolean | string[]): this;
548
+ option<T>(flags: string, description: string, parseArg: (value: string, previous: T) => T, defaultValue?: T): this;
549
+ /** @deprecated since v7, instead use choices or a custom function */
550
+ option(flags: string, description: string, regexp: RegExp, defaultValue?: string | boolean | string[]): this;
551
+
552
+ /**
553
+ * Define a required option, which must have a value after parsing. This usually means
554
+ * the option must be specified on the command line. (Otherwise the same as .option().)
555
+ *
556
+ * The `flags` string contains the short and/or long flags, separated by comma, a pipe or space.
557
+ */
558
+ requiredOption(flags: string, description?: string, defaultValue?: string | boolean | string[]): this;
559
+ requiredOption<T>(flags: string, description: string, parseArg: (value: string, previous: T) => T, defaultValue?: T): this;
560
+ /** @deprecated since v7, instead use choices or a custom function */
561
+ requiredOption(flags: string, description: string, regexp: RegExp, defaultValue?: string | boolean | string[]): this;
562
+
563
+ /**
564
+ * Factory routine to create a new unattached option.
565
+ *
566
+ * See .option() for creating an attached option, which uses this routine to
567
+ * create the option. You can override createOption to return a custom option.
568
+ */
569
+
570
+ createOption(flags: string, description?: string): Option;
571
+
572
+ /**
573
+ * Add a prepared Option.
574
+ *
575
+ * See .option() and .requiredOption() for creating and attaching an option in a single call.
576
+ */
577
+ addOption(option: Option): this;
578
+
579
+ /**
580
+ * Whether to store option values as properties on command object,
581
+ * or store separately (specify false). In both cases the option values can be accessed using .opts().
582
+ *
583
+ * @returns `this` command for chaining
584
+ */
585
+ storeOptionsAsProperties<T extends OptionValues>(): this & T;
586
+ storeOptionsAsProperties<T extends OptionValues>(storeAsProperties: true): this & T;
587
+ storeOptionsAsProperties(storeAsProperties?: boolean): this;
588
+
589
+ /**
590
+ * Retrieve option value.
591
+ */
592
+ getOptionValue(key: string): any;
593
+
594
+ /**
595
+ * Store option value.
596
+ */
597
+ setOptionValue(key: string, value: unknown): this;
598
+
599
+ /**
600
+ * Store option value and where the value came from.
601
+ */
602
+ setOptionValueWithSource(key: string, value: unknown, source: OptionValueSource): this;
603
+
604
+ /**
605
+ * Get source of option value.
606
+ */
607
+ getOptionValueSource(key: string): OptionValueSource | undefined;
608
+
609
+ /**
610
+ * Get source of option value. See also .optsWithGlobals().
611
+ */
612
+ getOptionValueSourceWithGlobals(key: string): OptionValueSource | undefined;
613
+
614
+ /**
615
+ * Alter parsing of short flags with optional values.
616
+ *
617
+ * @example
618
+ * ```
619
+ * // for `.option('-f,--flag [value]'):
620
+ * .combineFlagAndOptionalValue(true) // `-f80` is treated like `--flag=80`, this is the default behaviour
621
+ * .combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b`
622
+ * ```
623
+ *
624
+ * @returns `this` command for chaining
625
+ */
626
+ combineFlagAndOptionalValue(combine?: boolean): this;
627
+
628
+ /**
629
+ * Allow unknown options on the command line.
630
+ *
631
+ * @returns `this` command for chaining
632
+ */
633
+ allowUnknownOption(allowUnknown?: boolean): this;
634
+
635
+ /**
636
+ * Allow excess command-arguments on the command line. Pass false to make excess arguments an error.
637
+ *
638
+ * @returns `this` command for chaining
639
+ */
640
+ allowExcessArguments(allowExcess?: boolean): this;
641
+
642
+ /**
643
+ * Enable positional options. Positional means global options are specified before subcommands which lets
644
+ * subcommands reuse the same option names, and also enables subcommands to turn on passThroughOptions.
645
+ *
646
+ * The default behaviour is non-positional and global options may appear anywhere on the command line.
647
+ *
648
+ * @returns `this` command for chaining
649
+ */
650
+ enablePositionalOptions(positional?: boolean): this;
651
+
652
+ /**
653
+ * Pass through options that come after command-arguments rather than treat them as command-options,
654
+ * so actual command-options come before command-arguments. Turning this on for a subcommand requires
655
+ * positional options to have been enabled on the program (parent commands).
656
+ *
657
+ * The default behaviour is non-positional and options may appear before or after command-arguments.
658
+ *
659
+ * @returns `this` command for chaining
660
+ */
661
+ passThroughOptions(passThrough?: boolean): this;
662
+
663
+ /**
664
+ * Parse `argv`, setting options and invoking commands when defined.
665
+ *
666
+ * The default expectation is that the arguments are from node and have the application as argv[0]
667
+ * and the script being run in argv[1], with user parameters after that.
668
+ *
669
+ * @example
670
+ * ```
671
+ * program.parse(process.argv);
672
+ * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions
673
+ * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
674
+ * ```
675
+ *
676
+ * @returns `this` command for chaining
677
+ */
678
+ parse(argv?: readonly string[], options?: ParseOptions): this;
679
+
680
+ /**
681
+ * Parse `argv`, setting options and invoking commands when defined.
682
+ *
683
+ * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise.
684
+ *
685
+ * The default expectation is that the arguments are from node and have the application as argv[0]
686
+ * and the script being run in argv[1], with user parameters after that.
687
+ *
688
+ * @example
689
+ * ```
690
+ * program.parseAsync(process.argv);
691
+ * program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions
692
+ * program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0]
693
+ * ```
694
+ *
695
+ * @returns Promise
696
+ */
697
+ parseAsync(argv?: readonly string[], options?: ParseOptions): Promise<this>;
698
+
699
+ /**
700
+ * Parse options from `argv` removing known options,
701
+ * and return argv split into operands and unknown arguments.
702
+ *
703
+ * argv => operands, unknown
704
+ * --known kkk op => [op], []
705
+ * op --known kkk => [op], []
706
+ * sub --unknown uuu op => [sub], [--unknown uuu op]
707
+ * sub -- --unknown uuu op => [sub --unknown uuu op], []
708
+ */
709
+ parseOptions(argv: string[]): ParseOptionsResult;
710
+
711
+ /**
712
+ * Return an object containing local option values as key-value pairs
713
+ */
714
+ opts<T extends OptionValues>(): T;
715
+
716
+ /**
717
+ * Return an object containing merged local and global option values as key-value pairs.
718
+ */
719
+ optsWithGlobals<T extends OptionValues>(): T;
720
+
721
+ /**
722
+ * Set the description.
723
+ *
724
+ * @returns `this` command for chaining
725
+ */
726
+
727
+ description(str: string): this;
728
+ /** @deprecated since v8, instead use .argument to add command argument with description */
729
+ description(str: string, argsDescription: Record<string, string>): this;
730
+ /**
731
+ * Get the description.
732
+ */
733
+ description(): string;
734
+
735
+ /**
736
+ * Set the summary. Used when listed as subcommand of parent.
737
+ *
738
+ * @returns `this` command for chaining
739
+ */
740
+
741
+ summary(str: string): this;
742
+ /**
743
+ * Get the summary.
744
+ */
745
+ summary(): string;
746
+
747
+ /**
748
+ * Set an alias for the command.
749
+ *
750
+ * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help.
751
+ *
752
+ * @returns `this` command for chaining
753
+ */
754
+ alias(alias: string): this;
755
+ /**
756
+ * Get alias for the command.
757
+ */
758
+ alias(): string;
759
+
760
+ /**
761
+ * Set aliases for the command.
762
+ *
763
+ * Only the first alias is shown in the auto-generated help.
764
+ *
765
+ * @returns `this` command for chaining
766
+ */
767
+ aliases(aliases: readonly string[]): this;
768
+ /**
769
+ * Get aliases for the command.
770
+ */
771
+ aliases(): string[];
772
+
773
+ /**
774
+ * Set the command usage.
775
+ *
776
+ * @returns `this` command for chaining
777
+ */
778
+ usage(str: string): this;
779
+ /**
780
+ * Get the command usage.
781
+ */
782
+ usage(): string;
783
+
784
+ /**
785
+ * Set the name of the command.
786
+ *
787
+ * @returns `this` command for chaining
788
+ */
789
+ name(str: string): this;
790
+ /**
791
+ * Get the name of the command.
792
+ */
793
+ name(): string;
794
+
795
+ /**
796
+ * Set the name of the command from script filename, such as process.argv[1],
797
+ * or require.main.filename, or __filename.
798
+ *
799
+ * (Used internally and public although not documented in README.)
800
+ *
801
+ * @example
802
+ * ```ts
803
+ * program.nameFromFilename(require.main.filename);
804
+ * ```
805
+ *
806
+ * @returns `this` command for chaining
807
+ */
808
+ nameFromFilename(filename: string): this;
809
+
810
+ /**
811
+ * Set the directory for searching for executable subcommands of this command.
812
+ *
813
+ * @example
814
+ * ```ts
815
+ * program.executableDir(__dirname);
816
+ * // or
817
+ * program.executableDir('subcommands');
818
+ * ```
819
+ *
820
+ * @returns `this` command for chaining
821
+ */
822
+ executableDir(path: string): this;
823
+ /**
824
+ * Get the executable search directory.
825
+ */
826
+ executableDir(): string | null;
827
+
828
+ /**
829
+ * Output help information for this command.
830
+ *
831
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
832
+ *
833
+ */
834
+ outputHelp(context?: HelpContext): void;
835
+ /** @deprecated since v7 */
836
+ outputHelp(cb?: (str: string) => string): void;
837
+
838
+ /**
839
+ * Return command help documentation.
840
+ */
841
+ helpInformation(context?: HelpContext): string;
842
+
843
+ /**
844
+ * You can pass in flags and a description to override the help
845
+ * flags and help description for your command. Pass in false
846
+ * to disable the built-in help option.
847
+ */
848
+ helpOption(flags?: string | boolean, description?: string): this;
849
+
850
+ /**
851
+ * Supply your own option to use for the built-in help option.
852
+ * This is an alternative to using helpOption() to customise the flags and description etc.
853
+ */
854
+ addHelpOption(option: Option): this;
855
+
856
+ /**
857
+ * Output help information and exit.
858
+ *
859
+ * Outputs built-in help, and custom text added using `.addHelpText()`.
860
+ */
861
+ help(context?: HelpContext): never;
862
+ /** @deprecated since v7 */
863
+ help(cb?: (str: string) => string): never;
864
+
865
+ /**
866
+ * Add additional text to be displayed with the built-in help.
867
+ *
868
+ * Position is 'before' or 'after' to affect just this command,
869
+ * and 'beforeAll' or 'afterAll' to affect this command and all its subcommands.
870
+ */
871
+ addHelpText(position: AddHelpTextPosition, text: string): this;
872
+ addHelpText(position: AddHelpTextPosition, text: (context: AddHelpTextContext) => string): this;
873
+
874
+ /**
875
+ * Add a listener (callback) for when events occur. (Implemented using EventEmitter.)
876
+ */
877
+ on(event: string | symbol, listener: (...args: any[]) => void): this;
878
+ }
879
+
880
+ export interface CommandOptions {
881
+ hidden?: boolean;
882
+ isDefault?: boolean;
883
+ /** @deprecated since v7, replaced by hidden */
884
+ noHelp?: boolean;
885
+ }
886
+ export interface ExecutableCommandOptions extends CommandOptions {
887
+ executableFile?: string;
888
+ }
889
+
890
+ export interface ParseOptionsResult {
891
+ operands: string[];
892
+ unknown: string[];
893
+ }
894
+
895
+ export function createCommand(name?: string): Command;
896
+ export function createOption(flags: string, description?: string): Option;
897
+ export function createArgument(name: string, description?: string): Argument;
898
+
899
+ export const program: Command;
@@ -24,7 +24,7 @@ module.exports = __toCommonJS(commands_exports);
24
24
  var import_node_path = require("node:path");
25
25
  var import_node_fs = require("node:fs");
26
26
  var import_shared = require("@rsbuild/shared");
27
- var import_commander = require("@rsbuild/shared/commander");
27
+ var import_commander = require("../../compiled/commander");
28
28
  var import_init = require("./init");
29
29
  const applyCommonOptions = (command) => {
30
30
  command.option(
@@ -39,7 +39,7 @@ const applyServerOptions = (command) => {
39
39
  command.option("-o --open [url]", "open the page in browser on startup").option("--port <port>", "specify a port number for server to listen").option("--host <host>", "specify the host that the server listens to");
40
40
  };
41
41
  function runCli() {
42
- import_commander.program.name("rsbuild").usage("<command> [options]").version("0.4.13");
42
+ import_commander.program.name("rsbuild").usage("<command> [options]").version("0.4.15");
43
43
  const devCommand = import_commander.program.command("dev");
44
44
  const buildCommand = import_commander.program.command("build");
45
45
  const previewCommand = import_commander.program.command("preview");
@@ -34,7 +34,7 @@ function prepareCli() {
34
34
  if (!npm_execpath || npm_execpath.includes("npx-cli.js")) {
35
35
  console.log();
36
36
  }
37
- import_rslog.logger.greet(` ${`Rsbuild v${"0.4.13"}`}
37
+ import_rslog.logger.greet(` ${`Rsbuild v${"0.4.15"}`}
38
38
  `);
39
39
  }
40
40
  // Annotate the CommonJS export names for ESM import in node:
package/dist/index.js CHANGED
@@ -38,7 +38,7 @@ var import_config = require("./config");
38
38
  var import_shared = require("@rsbuild/shared");
39
39
  var import_mergeConfig = require("./mergeConfig");
40
40
  var import_constants = require("./constants");
41
- const version = "0.4.13";
41
+ const version = "0.4.15";
42
42
  // Annotate the CommonJS export names for ESM import in node:
43
43
  0 && (module.exports = {
44
44
  PLUGIN_CSS_NAME,
@@ -34,6 +34,24 @@ __export(asset_exports, {
34
34
  module.exports = __toCommonJS(asset_exports);
35
35
  var import_node_path = __toESM(require("node:path"));
36
36
  var import_shared = require("@rsbuild/shared");
37
+ const chainStaticAssetRule = ({
38
+ rule,
39
+ maxSize,
40
+ filename,
41
+ assetType
42
+ }) => {
43
+ rule.oneOf(`${assetType}-asset-url`).type("asset/resource").resourceQuery(/(__inline=false|url)/).set("generator", {
44
+ filename
45
+ });
46
+ rule.oneOf(`${assetType}-asset-inline`).type("asset/inline").resourceQuery(/inline/);
47
+ rule.oneOf(`${assetType}-asset`).type("asset").parser({
48
+ dataUrlCondition: {
49
+ maxSize
50
+ }
51
+ }).set("generator", {
52
+ filename
53
+ });
54
+ };
37
55
  function getRegExpForExts(exts) {
38
56
  const matcher = exts.map((ext) => ext.trim()).map((ext) => ext.startsWith(".") ? ext.slice(1) : ext).join("|");
39
57
  return new RegExp(
@@ -53,7 +71,7 @@ const pluginAsset = () => ({
53
71
  const { dataUriLimit } = config.output;
54
72
  const maxSize = typeof dataUriLimit === "number" ? dataUriLimit : dataUriLimit[assetType];
55
73
  const rule = chain.module.rule(assetType).test(regExp);
56
- (0, import_shared.chainStaticAssetRule)({
74
+ chainStaticAssetRule({
57
75
  rule,
58
76
  maxSize,
59
77
  filename: import_node_path.default.posix.join(distDir, filename),
@@ -50,10 +50,10 @@ const build = async (initOptions, { mode = "production", watch, compiler: custom
50
50
  isFirstCompile = false;
51
51
  await p;
52
52
  };
53
- try {
54
- compiler.hooks.done.tapPromise("rsbuild:done", onDone);
55
- } catch {
53
+ if ((0, import_shared.isMultiCompiler)(compiler)) {
56
54
  compiler.hooks.done.tap("rsbuild:done", onDone);
55
+ } else {
56
+ compiler.hooks.done.tapPromise("rsbuild:done", onDone);
57
57
  }
58
58
  if (watch) {
59
59
  compiler.watch({}, (err) => {
@@ -71,7 +71,7 @@ async function createCompiler({
71
71
  if ((0, import_shared.isProd)()) {
72
72
  compiler.hooks.run.tap("rsbuild:run", logRspackVersion);
73
73
  }
74
- compiler.hooks.done.tap("rsbuild:done", async (stats) => {
74
+ const done = async (stats) => {
75
75
  const obj = stats.toJson({
76
76
  all: false,
77
77
  timings: true
@@ -108,7 +108,12 @@ async function createCompiler({
108
108
  }
109
109
  isCompiling = false;
110
110
  isFirstCompile = false;
111
- });
111
+ };
112
+ if ((0, import_shared.isMultiCompiler)(compiler)) {
113
+ compiler.hooks.done.tap("rsbuild:done", done);
114
+ } else {
115
+ compiler.hooks.done.tapPromise("rsbuild:done", done);
116
+ }
112
117
  await context.hooks.onAfterCreateCompiler.call({ compiler });
113
118
  (0, import_shared.debug)("create compiler done");
114
119
  return compiler;
@@ -44,7 +44,7 @@ async function createContextByConfig(options, bundlerType, config = {}) {
44
44
  const context = {
45
45
  entry: (0, import_entry.getEntryObject)(config, "web"),
46
46
  targets: config.output?.targets || [],
47
- version: "0.4.13",
47
+ version: "0.4.15",
48
48
  rootPath,
49
49
  distPath,
50
50
  cachePath,
@@ -49,7 +49,7 @@ const getDevMiddleware = (multiCompiler) => (options) => {
49
49
  }
50
50
  (0, import_shared.setupServerHooks)(compiler, callbacks);
51
51
  };
52
- if (multiCompiler.compilers) {
52
+ if ((0, import_shared.isMultiCompiler)(multiCompiler)) {
53
53
  multiCompiler.compilers.forEach(setupCompiler);
54
54
  } else {
55
55
  setupCompiler(multiCompiler);
@@ -26,16 +26,13 @@ const pluginResolve = () => ({
26
26
  name: "rsbuild:resolve",
27
27
  setup(api) {
28
28
  (0, import_shared.applyResolvePlugin)(api);
29
- api.modifyRspackConfig(async (rspackConfig, { isServer }) => {
29
+ api.modifyRspackConfig(async (rspackConfig) => {
30
30
  const isTsProject = Boolean(api.context.tsconfigPath);
31
31
  const config = api.getNormalizedConfig();
32
32
  rspackConfig.resolve || (rspackConfig.resolve = {});
33
33
  if (isTsProject && config.source.aliasStrategy === "prefer-tsconfig") {
34
34
  rspackConfig.resolve.tsConfigPath = api.context.tsconfigPath;
35
35
  }
36
- if (isServer) {
37
- rspackConfig.resolve.conditionNames = ["require", "node"];
38
- }
39
36
  });
40
37
  }
41
38
  });
@@ -78,9 +78,7 @@ async function getServerAPIs(options, createDevMiddleware, {
78
78
  customCompiler
79
79
  );
80
80
  const { CompilerDevMiddleware } = await Promise.resolve().then(() => __toESM(require("./compilerDevMiddleware")));
81
- const publicPaths = compiler.compilers ? compiler.compilers.map(
82
- import_shared.getPublicPathFromCompiler
83
- ) : [(0, import_shared.getPublicPathFromCompiler)(compiler)];
81
+ const publicPaths = (0, import_shared.isMultiCompiler)(compiler) ? compiler.compilers.map(import_shared.getPublicPathFromCompiler) : [(0, import_shared.getPublicPathFromCompiler)(compiler)];
84
82
  const compilerDevMiddleware = new CompilerDevMiddleware({
85
83
  dev: devServerConfig,
86
84
  publicPaths,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rsbuild/core",
3
- "version": "0.4.13",
3
+ "version": "0.4.15",
4
4
  "description": "The Rspack-based build tool.",
5
5
  "homepage": "https://rsbuild.dev",
6
6
  "bugs": {
@@ -52,12 +52,12 @@
52
52
  "types.d.ts"
53
53
  ],
54
54
  "dependencies": {
55
- "@rspack/core": "0.5.6",
55
+ "@rspack/core": "0.5.7",
56
56
  "@swc/helpers": "0.5.3",
57
- "core-js": "~3.32.2",
57
+ "core-js": "~3.36.0",
58
58
  "html-webpack-plugin": "npm:html-rspack-plugin@5.6.2",
59
59
  "postcss": "^8.4.33",
60
- "@rsbuild/shared": "0.4.13"
60
+ "@rsbuild/shared": "0.4.15"
61
61
  },
62
62
  "devDependencies": {
63
63
  "@types/node": "16.x",
File without changes
@@ -1 +0,0 @@
1
- "use strict";
File without changes
@@ -1 +0,0 @@
1
- "use strict";