dummie-tools
Version:
This is a set of my idea tools
27 lines • 50.3 kB
JavaScript
#!/usr/bin/env node
'use strict';var $=require('fs'),w=require('path'),ft=require('readline'),googleTranslateApi=require('@vitalets/google-translate-api'),puppeteerCore=require('puppeteer-core'),child_process=require('child_process');function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var $__namespace=/*#__PURE__*/_interopNamespace($);var w__namespace=/*#__PURE__*/_interopNamespace(w);var ft__namespace=/*#__PURE__*/_interopNamespace(ft);var vt=Object.create;var Z=Object.defineProperty;var $t=Object.getOwnPropertyDescriptor;var St=Object.getOwnPropertyNames;var Ht=Object.getPrototypeOf,Tt=Object.prototype.hasOwnProperty;var x=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(t,e)=>(typeof require<"u"?require:t)[e]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var E=(o,t)=>()=>(o&&(t=o(o=0)),t);var A=(o,t)=>()=>(t||o((t={exports:{}}).exports,t),t.exports);var kt=(o,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of St(t))!Tt.call(o,n)&&n!==e&&Z(o,n,{get:()=>t[n],enumerable:!(i=$t(t,n))||i.enumerable});return o};var Pt=(o,t,e)=>(e=o!=null?vt(Ht(o)):{},kt(Z(e,"default",{value:o,enumerable:true}),o));var d=E(()=>{});var v=A(V=>{d();var H=class 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=void 0;}},P=class extends H{constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name;}};V.CommanderError=H;V.InvalidArgumentError=P;});var T=A(I=>{d();var{InvalidArgumentError:Vt}=v(),D=class{constructor(t,e){switch(this.description=e||"",this.variadic=false,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,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}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){return e===this.defaultValue||!Array.isArray(e)?[t]:e.concat(t)}default(t,e){return this.defaultValue=t,this.defaultValueDescription=e,this}argParser(t){return this.parseArg=t,this}choices(t){return this.argChoices=t.slice(),this.parseArg=(e,i)=>{if(!this.argChoices.includes(e))throw new Vt(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(e,i):e},this}argRequired(){return this.required=true,this}argOptional(){return this.required=false,this}};function Dt(o){let t=o.name()+(o.variadic===true?"...":"");return o.required?"<"+t+">":"["+t+"]"}I.Argument=D;I.humanReadableArgName=Dt;});var W=A(F=>{d();var{humanReadableArgName:It}=T(),G=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=false,this.sortOptions=false,this.showGlobalOptions=false;}prepareContext(t){this.helpWidth=this.helpWidth??t.helpWidth??80;}visibleCommands(t){let e=t.commands.filter(n=>!n._hidden),i=t._getHelpCommand();return i&&!i._hidden&&e.push(i),this.sortSubcommands&&e.sort((n,s)=>n.name().localeCompare(s.name())),e}compareOptions(t,e){let i=n=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return i(t).localeCompare(i(e))}visibleOptions(t){let e=t.options.filter(n=>!n.hidden),i=t._getHelpOption();if(i&&!i.hidden){let n=i.short&&t._findOption(i.short),s=i.long&&t._findOption(i.long);!n&&!s?e.push(i):i.long&&!s?e.push(t.createOption(i.long,i.description)):i.short&&!n&&e.push(t.createOption(i.short,i.description));}return this.sortOptions&&e.sort(this.compareOptions),e}visibleGlobalOptions(t){if(!this.showGlobalOptions)return [];let e=[];for(let i=t.parent;i;i=i.parent){let n=i.options.filter(s=>!s.hidden);e.push(...n);}return this.sortOptions&&e.sort(this.compareOptions),e}visibleArguments(t){return t._argsDescription&&t.registeredArguments.forEach(e=>{e.description=e.description||t._argsDescription[e.name()]||"";}),t.registeredArguments.find(e=>e.description)?t.registeredArguments:[]}subcommandTerm(t){let e=t.registeredArguments.map(i=>It(i)).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((i,n)=>Math.max(i,this.displayWidth(e.styleSubcommandTerm(e.subcommandTerm(n)))),0)}longestOptionTermLength(t,e){return e.visibleOptions(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleOptionTerm(e.optionTerm(n)))),0)}longestGlobalOptionTermLength(t,e){return e.visibleGlobalOptions(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleOptionTerm(e.optionTerm(n)))),0)}longestArgumentTermLength(t,e){return e.visibleArguments(t).reduce((i,n)=>Math.max(i,this.displayWidth(e.styleArgumentTerm(e.argumentTerm(n)))),0)}commandUsage(t){let e=t._name;t._aliases[0]&&(e=e+"|"+t._aliases[0]);let i="";for(let n=t.parent;n;n=n.parent)i=n.name()+" "+i;return i+e+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){let e=[];if(t.argChoices&&e.push(`choices: ${t.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),t.defaultValue!==void 0&&(t.required||t.optional||t.isBoolean()&&typeof t.defaultValue=="boolean")&&e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),t.presetArg!==void 0&&t.optional&&e.push(`preset: ${JSON.stringify(t.presetArg)}`),t.envVar!==void 0&&e.push(`env: ${t.envVar}`),e.length>0){let i=`(${e.join(", ")})`;return t.description?`${t.description} ${i}`:i}return t.description}argumentDescription(t){let e=[];if(t.argChoices&&e.push(`choices: ${t.argChoices.map(i=>JSON.stringify(i)).join(", ")}`),t.defaultValue!==void 0&&e.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),e.length>0){let i=`(${e.join(", ")})`;return t.description?`${t.description} ${i}`:i}return t.description}formatItemList(t,e,i){return e.length===0?[]:[i.styleTitle(t),...e,""]}groupItems(t,e,i){let n=new Map;return t.forEach(s=>{let r=i(s);n.has(r)||n.set(r,[]);}),e.forEach(s=>{let r=i(s);n.has(r)||n.set(r,[]),n.get(r).push(s);}),n}formatHelp(t,e){let i=e.padWidth(t,e),n=e.helpWidth??80;function s(l,m){return e.formatItem(l,i,m,e)}let r=[`${e.styleTitle("Usage:")} ${e.styleUsage(e.commandUsage(t))}`,""],a=e.commandDescription(t);a.length>0&&(r=r.concat([e.boxWrap(e.styleCommandDescription(a),n),""]));let c=e.visibleArguments(t).map(l=>s(e.styleArgumentTerm(e.argumentTerm(l)),e.styleArgumentDescription(e.argumentDescription(l))));if(r=r.concat(this.formatItemList("Arguments:",c,e)),this.groupItems(t.options,e.visibleOptions(t),l=>l.helpGroupHeading??"Options:").forEach((l,m)=>{let g=l.map(b=>s(e.styleOptionTerm(e.optionTerm(b)),e.styleOptionDescription(e.optionDescription(b))));r=r.concat(this.formatItemList(m,g,e));}),e.showGlobalOptions){let l=e.visibleGlobalOptions(t).map(m=>s(e.styleOptionTerm(e.optionTerm(m)),e.styleOptionDescription(e.optionDescription(m))));r=r.concat(this.formatItemList("Global Options:",l,e));}return this.groupItems(t.commands,e.visibleCommands(t),l=>l.helpGroup()||"Commands:").forEach((l,m)=>{let g=l.map(b=>s(e.styleSubcommandTerm(e.subcommandTerm(b)),e.styleSubcommandDescription(e.subcommandDescription(b))));r=r.concat(this.formatItemList(m,g,e));}),r.join(`
`)}displayWidth(t){return tt(t).length}styleTitle(t){return t}styleUsage(t){return t.split(" ").map(e=>e==="[options]"?this.styleOptionText(e):e==="[command]"?this.styleSubcommandText(e):e[0]==="["||e[0]==="<"?this.styleArgumentText(e):this.styleCommandText(e)).join(" ")}styleCommandDescription(t){return this.styleDescriptionText(t)}styleOptionDescription(t){return this.styleDescriptionText(t)}styleSubcommandDescription(t){return this.styleDescriptionText(t)}styleArgumentDescription(t){return this.styleDescriptionText(t)}styleDescriptionText(t){return t}styleOptionTerm(t){return this.styleOptionText(t)}styleSubcommandTerm(t){return t.split(" ").map(e=>e==="[options]"?this.styleOptionText(e):e[0]==="["||e[0]==="<"?this.styleArgumentText(e):this.styleSubcommandText(e)).join(" ")}styleArgumentTerm(t){return this.styleArgumentText(t)}styleOptionText(t){return t}styleArgumentText(t){return t}styleSubcommandText(t){return t}styleCommandText(t){return t}padWidth(t,e){return Math.max(e.longestOptionTermLength(t,e),e.longestGlobalOptionTermLength(t,e),e.longestSubcommandTermLength(t,e),e.longestArgumentTermLength(t,e))}preformatted(t){return /\n[^\S\r\n]/.test(t)}formatItem(t,e,i,n){let r=" ".repeat(2);if(!i)return r+t;let a=t.padEnd(e+t.length-n.displayWidth(t)),c=2,h=(this.helpWidth??80)-e-c-2,l;return h<this.minWidthToWrap||n.preformatted(i)?l=i:l=n.boxWrap(i,h).replace(/\n/g,`
`+" ".repeat(e+c)),r+a+" ".repeat(c)+l.replace(/\n/g,`
${r}`)}boxWrap(t,e){if(e<this.minWidthToWrap)return t;let i=t.split(/\r\n|\n/),n=/[\s]*[^\s]+/g,s=[];return i.forEach(r=>{let a=r.match(n);if(a===null){s.push("");return}let c=[a.shift()],u=this.displayWidth(c[0]);a.forEach(h=>{let l=this.displayWidth(h);if(u+l<=e){c.push(h),u+=l;return}s.push(c.join(""));let m=h.trimStart();c=[m],u=this.displayWidth(m);}),s.push(c.join(""));}),s.join(`
`)}};function tt(o){let t=/\x1b\[\d*(;\d*)*m/g;return o.replace(t,"")}F.Help=G;F.stripColor=tt;});var j=A(q=>{d();var{InvalidArgumentError:Gt}=v(),N=class{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;let i=Ft(t);this.short=i.shortFlag,this.long=i.longFlag,this.negate=false,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=false,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0;}default(t,e){return this.defaultValue=t,this.defaultValueDescription=e,this}preset(t){return this.presetArg=t,this}conflicts(t){return this.conflictsWith=this.conflictsWith.concat(t),this}implies(t){let e=t;return typeof t=="string"&&(e={[t]:true}),this.implied=Object.assign(this.implied||{},e),this}env(t){return this.envVar=t,this}argParser(t){return this.parseArg=t,this}makeOptionMandatory(t=true){return this.mandatory=!!t,this}hideHelp(t=true){return this.hidden=!!t,this}_concatValue(t,e){return e===this.defaultValue||!Array.isArray(e)?[t]:e.concat(t)}choices(t){return this.argChoices=t.slice(),this.parseArg=(e,i)=>{if(!this.argChoices.includes(e))throw new Gt(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(e,i):e},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?et(this.name().replace(/^no-/,"")):et(this.name())}helpGroup(t){return this.helpGroupHeading=t,this}is(t){return this.short===t||this.long===t}isBoolean(){return !this.required&&!this.optional&&!this.negate}},M=class{constructor(t){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,t.forEach(e=>{e.negate?this.negativeOptions.set(e.attributeName(),e):this.positiveOptions.set(e.attributeName(),e);}),this.negativeOptions.forEach((e,i)=>{this.positiveOptions.has(i)&&this.dualOptions.add(i);});}valueFromOption(t,e){let i=e.attributeName();if(!this.dualOptions.has(i))return true;let n=this.negativeOptions.get(i).presetArg,s=n!==void 0?n:false;return e.negate===(s===t)}};function et(o){return o.split("-").reduce((t,e)=>t+e[0].toUpperCase()+e.slice(1))}function Ft(o){let t,e,i=/^-[^-]$/,n=/^--[^-]/,s=o.split(/[ |,]+/).concat("guard");if(i.test(s[0])&&(t=s.shift()),n.test(s[0])&&(e=s.shift()),!t&&i.test(s[0])&&(t=s.shift()),!t&&n.test(s[0])&&(t=e,e=s.shift()),s[0].startsWith("-")){let r=s[0],a=`option creation failed due to '${r}' in option flags '${o}'`;throw /^-[^-][^-]/.test(r)?new Error(`${a}
- a short flag is a single dash and a single character
- either use a single dash and a single character (for a short flag)
- or use a double dash for a long option (and can have two, like '--ws, --workspace')`):i.test(r)?new Error(`${a}
- too many short flags`):n.test(r)?new Error(`${a}
- too many long flags`):new Error(`${a}
- unrecognised flag format`)}if(t===void 0&&e===void 0)throw new Error(`option creation failed due to no flags found in '${o}'.`);return {shortFlag:t,longFlag:e}}q.Option=N;q.DualOptions=M;});var nt=A(it=>{d();function Wt(o,t){if(Math.abs(o.length-t.length)>3)return Math.max(o.length,t.length);let e=[];for(let i=0;i<=o.length;i++)e[i]=[i];for(let i=0;i<=t.length;i++)e[0][i]=i;for(let i=1;i<=t.length;i++)for(let n=1;n<=o.length;n++){let s=1;o[n-1]===t[i-1]?s=0:s=1,e[n][i]=Math.min(e[n-1][i]+1,e[n][i-1]+1,e[n-1][i-1]+s),n>1&&i>1&&o[n-1]===t[i-2]&&o[n-2]===t[i-1]&&(e[n][i]=Math.min(e[n][i],e[n-2][i-2]+1));}return e[o.length][t.length]}function Nt(o,t){if(!t||t.length===0)return "";t=Array.from(new Set(t));let e=o.startsWith("--");e&&(o=o.slice(2),t=t.map(r=>r.slice(2)));let i=[],n=3,s=.4;return t.forEach(r=>{if(r.length<=1)return;let a=Wt(o,r),c=Math.max(o.length,r.length);(c-a)/c>s&&(a<n?(n=a,i=[r]):a===n&&i.push(r));}),i.sort((r,a)=>r.localeCompare(a)),e&&(i=i.map(r=>`--${r}`)),i.length>1?`
(Did you mean one of ${i.join(", ")}?)`:i.length===1?`
(Did you mean ${i[0]}?)`:""}it.suggestSimilar=Nt;});var at=A(J=>{d();var Mt=x("events").EventEmitter,L=x("child_process"),y=x("path"),k=x("fs"),p=x("process"),{Argument:qt,humanReadableArgName:jt}=T(),{CommanderError:R}=v(),{Help:Lt,stripColor:Rt}=W(),{Option:st,DualOptions:Ut}=j(),{suggestSimilar:rt}=nt(),U=class o extends Mt{constructor(t){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=false,this._allowExcessArguments=false,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=void 0,this._enablePositionalOptions=false,this._passThroughOptions=false,this._lifeCycleHooks={},this._showHelpAfterError=false,this._showSuggestionAfterError=true,this._savedState=null,this._outputConfiguration={writeOut:e=>p.stdout.write(e),writeErr:e=>p.stderr.write(e),outputError:(e,i)=>i(e),getOutHelpWidth:()=>p.stdout.isTTY?p.stdout.columns:void 0,getErrHelpWidth:()=>p.stderr.isTTY?p.stderr.columns:void 0,getOutHasColors:()=>B()??(p.stdout.isTTY&&p.stdout.hasColors?.()),getErrHasColors:()=>B()??(p.stderr.isTTY&&p.stderr.hasColors?.()),stripColor:e=>Rt(e)},this._hidden=false,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={},this._helpGroupHeading=void 0,this._defaultCommandGroup=void 0,this._defaultOptionGroup=void 0;}copyInheritedSettings(t){return 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,this}_getCommandAndAncestors(){let t=[];for(let e=this;e;e=e.parent)t.push(e);return t}command(t,e,i){let n=e,s=i;typeof n=="object"&&n!==null&&(s=n,n=null),s=s||{};let[,r,a]=t.match(/([^ ]+) *(.*)/),c=this.createCommand(r);return n&&(c.description(n),c._executableHandler=true),s.isDefault&&(this._defaultCommandName=c._name),c._hidden=!!(s.noHelp||s.hidden),c._executableFile=s.executableFile||null,a&&c.arguments(a),this._registerCommand(c),c.parent=this,c.copyInheritedSettings(this),n?this:c}createCommand(t){return new o(t)}createHelp(){return Object.assign(new Lt,this.configureHelp())}configureHelp(t){return t===void 0?this._helpConfiguration:(this._helpConfiguration=t,this)}configureOutput(t){return t===void 0?this._outputConfiguration:(this._outputConfiguration=Object.assign({},this._outputConfiguration,t),this)}showHelpAfterError(t=true){return typeof t!="string"&&(t=!!t),this._showHelpAfterError=t,this}showSuggestionAfterError(t=true){return this._showSuggestionAfterError=!!t,this}addCommand(t,e){if(!t._name)throw new Error(`Command passed to .addCommand() must have a name
- specify the name in Command constructor or using .name()`);return e=e||{},e.isDefault&&(this._defaultCommandName=t._name),(e.noHelp||e.hidden)&&(t._hidden=true),this._registerCommand(t),t.parent=this,t._checkForBrokenPassThrough(),this}createArgument(t,e){return new qt(t,e)}argument(t,e,i,n){let s=this.createArgument(t,e);return typeof i=="function"?s.default(n).argParser(i):s.default(i),this.addArgument(s),this}arguments(t){return t.trim().split(/ +/).forEach(e=>{this.argument(e);}),this}addArgument(t){let 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!==void 0&&t.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${t.name()}'`);return this.registeredArguments.push(t),this}helpCommand(t,e){if(typeof t=="boolean")return this._addImplicitHelpCommand=t,t&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let i=t??"help [command]",[,n,s]=i.match(/([^ ]+) *(.*)/),r=e??"display help for command",a=this.createCommand(n);return a.helpOption(false),s&&a.arguments(s),r&&a.description(r),this._addImplicitHelpCommand=true,this._helpCommand=a,(t||e)&&this._initCommandGroup(a),this}addHelpCommand(t,e){return typeof t!="object"?(this.helpCommand(t,e),this):(this._addImplicitHelpCommand=true,this._helpCommand=t,this._initCommandGroup(t),this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(t,e){let i=["preSubcommand","preAction","postAction"];if(!i.includes(t))throw new Error(`Unexpected value for event passed to hook : '${t}'.
Expecting one of '${i.join("', '")}'`);return this._lifeCycleHooks[t]?this._lifeCycleHooks[t].push(e):this._lifeCycleHooks[t]=[e],this}exitOverride(t){return t?this._exitCallback=t:this._exitCallback=e=>{if(e.code!=="commander.executeSubCommandAsync")throw e},this}_exit(t,e,i){this._exitCallback&&this._exitCallback(new R(t,e,i)),p.exit(t);}action(t){let e=i=>{let n=this.registeredArguments.length,s=i.slice(0,n);return this._storeOptionsAsProperties?s[n]=this:s[n]=this.opts(),s.push(this),t.apply(this,s)};return this._actionHandler=e,this}createOption(t,e){return new st(t,e)}_callParseArg(t,e,i,n){try{return t.parseArg(e,i)}catch(s){if(s.code==="commander.invalidArgument"){let r=`${n} ${s.message}`;this.error(r,{exitCode:s.exitCode,code:s.code});}throw s}}_registerOption(t){let e=t.short&&this._findOption(t.short)||t.long&&this._findOption(t.long);if(e){let 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}'
- already used by option '${e.flags}'`)}this._initOptionGroup(t),this.options.push(t);}_registerCommand(t){let e=n=>[n.name()].concat(n.aliases()),i=e(t).find(n=>this._findCommand(n));if(i){let n=e(this._findCommand(i)).join("|"),s=e(t).join("|");throw new Error(`cannot add command '${s}' as already have command '${n}'`)}this._initCommandGroup(t),this.commands.push(t);}addOption(t){this._registerOption(t);let e=t.name(),i=t.attributeName();if(t.negate){let s=t.long.replace(/^--no-/,"--");this._findOption(s)||this.setOptionValueWithSource(i,t.defaultValue===void 0?true:t.defaultValue,"default");}else t.defaultValue!==void 0&&this.setOptionValueWithSource(i,t.defaultValue,"default");let n=(s,r,a)=>{s==null&&t.presetArg!==void 0&&(s=t.presetArg);let c=this.getOptionValue(i);s!==null&&t.parseArg?s=this._callParseArg(t,s,c,r):s!==null&&t.variadic&&(s=t._concatValue(s,c)),s==null&&(t.negate?s=false:t.isBoolean()||t.optional?s=true:s=""),this.setOptionValueWithSource(i,s,a);};return this.on("option:"+e,s=>{let r=`error: option '${t.flags}' argument '${s}' is invalid.`;n(s,r,"cli");}),t.envVar&&this.on("optionEnv:"+e,s=>{let r=`error: option '${t.flags}' value '${s}' from env '${t.envVar}' is invalid.`;n(s,r,"env");}),this}_optionEx(t,e,i,n,s){if(typeof e=="object"&&e instanceof st)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let r=this.createOption(e,i);if(r.makeOptionMandatory(!!t.mandatory),typeof n=="function")r.default(s).argParser(n);else if(n instanceof RegExp){let a=n;n=(c,u)=>{let h=a.exec(c);return h?h[0]:u},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){return this._combineFlagAndOptionalValue=!!t,this}allowUnknownOption(t=true){return this._allowUnknownOption=!!t,this}allowExcessArguments(t=true){return this._allowExcessArguments=!!t,this}enablePositionalOptions(t=true){return this._enablePositionalOptions=!!t,this}passThroughOptions(t=true){return this._passThroughOptions=!!t,this._checkForBrokenPassThrough(),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");return this._storeOptionsAsProperties=!!t,this}getOptionValue(t){return this._storeOptionsAsProperties?this[t]:this._optionValues[t]}setOptionValue(t,e){return this.setOptionValueWithSource(t,e,void 0)}setOptionValueWithSource(t,e,i){return this._storeOptionsAsProperties?this[t]=e:this._optionValues[t]=e,this._optionValueSources[t]=i,this}getOptionValueSource(t){return this._optionValueSources[t]}getOptionValueSourceWithGlobals(t){let e;return this._getCommandAndAncestors().forEach(i=>{i.getOptionValueSource(t)!==void 0&&(e=i.getOptionValueSource(t));}),e}_prepareUserArgs(t,e){if(t!==void 0&&!Array.isArray(t))throw new Error("first parameter to parse must be array or undefined");if(e=e||{},t===void 0&&e.from===void 0){p.versions?.electron&&(e.from="electron");let n=p.execArgv??[];(n.includes("-e")||n.includes("--eval")||n.includes("-p")||n.includes("--print"))&&(e.from="eval");}t===void 0&&(t=p.argv),this.rawArgs=t.slice();let i;switch(e.from){case void 0:case "node":this._scriptPath=t[1],i=t.slice(2);break;case "electron":p.defaultApp?(this._scriptPath=t[1],i=t.slice(2)):i=t.slice(1);break;case "user":i=t.slice(0);break;case "eval":i=t.slice(1);break;default:throw new Error(`unexpected parse option { from: '${e.from}' }`)}return !this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",i}parse(t,e){this._prepareForParse();let i=this._prepareUserArgs(t,e);return this._parseCommand([],i),this}async parseAsync(t,e){this._prepareForParse();let i=this._prepareUserArgs(t,e);return await this._parseCommand([],i),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse();}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}};}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
- either make a new Command for each call to parse, or stop storing options as properties`);this._name=this._savedState._name,this._scriptPath=null,this.rawArgs=[],this._optionValues={...this._savedState._optionValues},this._optionValueSources={...this._savedState._optionValueSources},this.args=[],this.processedArgs=[];}_checkForMissingExecutable(t,e,i){if(k.existsSync(t))return;let n=e?`searched for local subcommand relative to directory '${e}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",s=`'${t}' does not exist
- if '${i}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
- if the default executable name is not suitable, use the executableFile option to supply a custom name or path
- ${n}`;throw new Error(s)}_executeSubCommand(t,e){e=e.slice();let i=false,n=[".js",".ts",".tsx",".mjs",".cjs"];function s(h,l){let m=y.resolve(h,l);if(k.existsSync(m))return m;if(n.includes(y.extname(l)))return;let g=n.find(b=>k.existsSync(`${m}${b}`));if(g)return `${m}${g}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let r=t._executableFile||`${this._name}-${t._name}`,a=this._executableDir||"";if(this._scriptPath){let h;try{h=k.realpathSync(this._scriptPath);}catch{h=this._scriptPath;}a=y.resolve(y.dirname(h),a);}if(a){let h=s(a,r);if(!h&&!t._executableFile&&this._scriptPath){let l=y.basename(this._scriptPath,y.extname(this._scriptPath));l!==this._name&&(h=s(a,`${l}-${t._name}`));}r=h||r;}i=n.includes(y.extname(r));let c;p.platform!=="win32"?i?(e.unshift(r),e=ot(p.execArgv).concat(e),c=L.spawn(p.argv[0],e,{stdio:"inherit"})):c=L.spawn(r,e,{stdio:"inherit"}):(this._checkForMissingExecutable(r,a,t._name),e.unshift(r),e=ot(p.execArgv).concat(e),c=L.spawn(p.execPath,e,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(l=>{p.on(l,()=>{c.killed===false&&c.exitCode===null&&c.kill(l);});});let u=this._exitCallback;c.on("close",h=>{h=h??1,u?u(new R(h,"commander.executeSubCommandAsync","(close)")):p.exit(h);}),c.on("error",h=>{if(h.code==="ENOENT")this._checkForMissingExecutable(r,a,t._name);else if(h.code==="EACCES")throw new Error(`'${r}' not executable`);if(!u)p.exit(1);else {let l=new R(1,"commander.executeSubCommandAsync","(error)");l.nestedError=h,u(l);}}),this.runningCommand=c;}_dispatchSubcommand(t,e,i){let n=this._findCommand(t);n||this.help({error:true}),n._prepareForParse();let s;return 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)}),s}_dispatchHelpCommand(t){t||this.help();let e=this._findCommand(t);return e&&!e._executableHandler&&e.help(),this._dispatchSubcommand(t,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((t,e)=>{t.required&&this.args[e]==null&&this.missingArgument(t.name());}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args);}_processArguments(){let t=(i,n,s)=>{let r=n;if(n!==null&&i.parseArg){let a=`error: command-argument value '${n}' is invalid for argument '${i.name()}'.`;r=this._callParseArg(i,n,s,a);}return r};this._checkNumberOfArguments();let e=[];this.registeredArguments.forEach((i,n)=>{let s=i.defaultValue;i.variadic?n<this.args.length?(s=this.args.slice(n),i.parseArg&&(s=s.reduce((r,a)=>t(i,a,r),i.defaultValue))):s===void 0&&(s=[]):n<this.args.length&&(s=this.args[n],i.parseArg&&(s=t(i,s,i.defaultValue))),e[n]=s;}),this.processedArgs=e;}_chainOrCall(t,e){return t&&t.then&&typeof t.then=="function"?t.then(()=>e()):e()}_chainOrCallHooks(t,e){let i=t,n=[];return this._getCommandAndAncestors().reverse().filter(s=>s._lifeCycleHooks[e]!==void 0).forEach(s=>{s._lifeCycleHooks[e].forEach(r=>{n.push({hookedCommand:s,callback:r});});}),e==="postAction"&&n.reverse(),n.forEach(s=>{i=this._chainOrCall(i,()=>s.callback(s.hookedCommand,this));}),i}_chainOrCallSubCommandHook(t,e,i){let n=t;return this._lifeCycleHooks[i]!==void 0&&this._lifeCycleHooks[i].forEach(s=>{n=this._chainOrCall(n,()=>s(this,e));}),n}_parseCommand(t,e){let i=this.parseOptions(e);if(this._parseOptionsEnv(),this._parseOptionsImplied(),t=t.concat(i.operands),e=i.unknown,this.args=t.concat(e),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)return this._outputHelpIfRequested(e),this._dispatchSubcommand(this._defaultCommandName,t,e);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:true}),this._outputHelpIfRequested(i.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let n=()=>{i.unknown.length>0&&this.unknownOption(i.unknown[0]);},s=`command:${this.name()}`;if(this._actionHandler){n(),this._processArguments();let r;return r=this._chainOrCallHooks(r,"preAction"),r=this._chainOrCall(r,()=>this._actionHandler(this.processedArgs)),this.parent&&(r=this._chainOrCall(r,()=>{this.parent.emit(s,t,e);})),r=this._chainOrCallHooks(r,"postAction"),r}if(this.parent&&this.parent.listenerCount(s))n(),this._processArguments(),this.parent.emit(s,t,e);else if(t.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",t,e);this.listenerCount("command:*")?this.emit("command:*",t,e):this.commands.length?this.unknownCommand():(n(),this._processArguments());}else this.commands.length?(n(),this.help({error:true})):(n(),this._processArguments());}_findCommand(t){if(t)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=>{e.mandatory&&t.getOptionValue(e.attributeName())===void 0&&t.missingMandatoryOptionValue(e);});});}_checkForConflictingLocalOptions(){let t=this.options.filter(i=>{let n=i.attributeName();return this.getOptionValue(n)===void 0?false:this.getOptionValueSource(n)!=="default"});t.filter(i=>i.conflictsWith.length>0).forEach(i=>{let n=t.find(s=>i.conflictsWith.includes(s.attributeName()));n&&this._conflictingOption(i,n);});}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(t=>{t._checkForConflictingLocalOptions();});}parseOptions(t){let e=[],i=[],n=e,s=t.slice();function r(u){return u.length>1&&u[0]==="-"}let a=u=>/^-\d*\.?\d+(e[+-]?\d+)?$/.test(u)?!this._getCommandAndAncestors().some(h=>h.options.map(l=>l.short).some(l=>/^-\d$/.test(l))):false,c=null;for(;s.length;){let u=s.shift();if(u==="--"){n===i&&n.push(u),n.push(...s);break}if(c&&(!r(u)||a(u))){this.emit(`option:${c.name()}`,u);continue}if(c=null,r(u)){let h=this._findOption(u);if(h){if(h.required){let l=s.shift();l===void 0&&this.optionMissingArgument(h),this.emit(`option:${h.name()}`,l);}else if(h.optional){let l=null;s.length>0&&(!r(s[0])||a(s[0]))&&(l=s.shift()),this.emit(`option:${h.name()}`,l);}else this.emit(`option:${h.name()}`);c=h.variadic?h:null;continue}}if(u.length>2&&u[0]==="-"&&u[1]!=="-"){let h=this._findOption(`-${u[1]}`);if(h){h.required||h.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${h.name()}`,u.slice(2)):(this.emit(`option:${h.name()}`),s.unshift(`-${u.slice(2)}`));continue}}if(/^--[^=]+=/.test(u)){let h=u.indexOf("="),l=this._findOption(u.slice(0,h));if(l&&(l.required||l.optional)){this.emit(`option:${l.name()}`,u.slice(h+1));continue}}if(n===e&&r(u)&&!(this.commands.length===0&&a(u))&&(n=i),(this._enablePositionalOptions||this._passThroughOptions)&&e.length===0&&i.length===0){if(this._findCommand(u)){e.push(u),s.length>0&&i.push(...s);break}else if(this._getHelpCommand()&&u===this._getHelpCommand().name()){e.push(u),s.length>0&&e.push(...s);break}else if(this._defaultCommandName){i.push(u),s.length>0&&i.push(...s);break}}if(this._passThroughOptions){n.push(u),s.length>0&&n.push(...s);break}n.push(u);}return {operands:e,unknown:i}}opts(){if(this._storeOptionsAsProperties){let t={},e=this.options.length;for(let i=0;i<e;i++){let n=this.options[i].attributeName();t[n]=n===this._versionOptionName?this._version:this[n];}return t}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((t,e)=>Object.assign(t,e.opts()),{})}error(t,e){this._outputConfiguration.outputError(`${t}
`,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
`):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
`),this.outputHelp({error:true}));let i=e||{},n=i.exitCode||1,s=i.code||"commander.error";this._exit(n,s,t);}_parseOptionsEnv(){this.options.forEach(t=>{if(t.envVar&&t.envVar in p.env){let e=t.attributeName();(this.getOptionValue(e)===void 0||["default","config","env"].includes(this.getOptionValueSource(e)))&&(t.required||t.optional?this.emit(`optionEnv:${t.name()}`,p.env[t.envVar]):this.emit(`optionEnv:${t.name()}`));}});}_parseOptionsImplied(){let t=new Ut(this.options),e=i=>this.getOptionValue(i)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(i));this.options.filter(i=>i.implied!==void 0&&e(i.attributeName())&&t.valueFromOption(this.getOptionValue(i.attributeName()),i)).forEach(i=>{Object.keys(i.implied).filter(n=>!e(n)).forEach(n=>{this.setOptionValueWithSource(n,i.implied[n],"implied");});});}missingArgument(t){let e=`error: missing required argument '${t}'`;this.error(e,{code:"commander.missingArgument"});}optionMissingArgument(t){let e=`error: option '${t.flags}' argument missing`;this.error(e,{code:"commander.optionMissingArgument"});}missingMandatoryOptionValue(t){let e=`error: required option '${t.flags}' not specified`;this.error(e,{code:"commander.missingMandatoryOptionValue"});}_conflictingOption(t,e){let i=r=>{let a=r.attributeName(),c=this.getOptionValue(a),u=this.options.find(l=>l.negate&&a===l.attributeName()),h=this.options.find(l=>!l.negate&&a===l.attributeName());return u&&(u.presetArg===void 0&&c===false||u.presetArg!==void 0&&c===u.presetArg)?u:h||r},n=r=>{let a=i(r),c=a.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},s=`error: ${n(t)} cannot be used with ${n(e)}`;this.error(s,{code:"commander.conflictingOption"});}unknownOption(t){if(this._allowUnknownOption)return;let e="";if(t.startsWith("--")&&this._showSuggestionAfterError){let n=[],s=this;do{let r=s.createHelp().visibleOptions(s).filter(a=>a.long).map(a=>a.long);n=n.concat(r),s=s.parent;}while(s&&!s._enablePositionalOptions);e=rt(t,n);}let i=`error: unknown option '${t}'${e}`;this.error(i,{code:"commander.unknownOption"});}_excessArguments(t){if(this._allowExcessArguments)return;let e=this.registeredArguments.length,i=e===1?"":"s",s=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${e} argument${i} but got ${t.length}.`;this.error(s,{code:"commander.excessArguments"});}unknownCommand(){let t=this.args[0],e="";if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(s=>{n.push(s.name()),s.alias()&&n.push(s.alias());}),e=rt(t,n);}let i=`error: unknown command '${t}'${e}`;this.error(i,{code:"commander.unknownCommand"});}version(t,e,i){if(t===void 0)return this._version;this._version=t,e=e||"-V, --version",i=i||"output the version number";let n=this.createOption(e,i);return this._versionOptionName=n.attributeName(),this._registerOption(n),this.on("option:"+n.name(),()=>{this._outputConfiguration.writeOut(`${t}
`),this._exit(0,"commander.version",t);}),this}description(t,e){return t===void 0&&e===void 0?this._description:(this._description=t,e&&(this._argsDescription=e),this)}summary(t){return t===void 0?this._summary:(this._summary=t,this)}alias(t){if(t===void 0)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]),t===e._name)throw new Error("Command alias can't be the same as its name");let i=this.parent?._findCommand(t);if(i){let n=[i.name()].concat(i.aliases()).join("|");throw new Error(`cannot add alias '${t}' to command '${this.name()}' as already have command '${n}'`)}return e._aliases.push(t),this}aliases(t){return t===void 0?this._aliases:(t.forEach(e=>this.alias(e)),this)}usage(t){if(t===void 0){if(this._usage)return this._usage;let e=this.registeredArguments.map(i=>jt(i));return [].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?e:[]).join(" ")}return this._usage=t,this}name(t){return t===void 0?this._name:(this._name=t,this)}helpGroup(t){return t===void 0?this._helpGroupHeading??"":(this._helpGroupHeading=t,this)}commandsGroup(t){return t===void 0?this._defaultCommandGroup??"":(this._defaultCommandGroup=t,this)}optionsGroup(t){return t===void 0?this._defaultOptionGroup??"":(this._defaultOptionGroup=t,this)}_initOptionGroup(t){this._defaultOptionGroup&&!t.helpGroupHeading&&t.helpGroup(this._defaultOptionGroup);}_initCommandGroup(t){this._defaultCommandGroup&&!t.helpGroup()&&t.helpGroup(this._defaultCommandGroup);}nameFromFilename(t){return this._name=y.basename(t,y.extname(t)),this}executableDir(t){return t===void 0?this._executableDir:(this._executableDir=t,this)}helpInformation(t){let e=this.createHelp(),i=this._getOutputContext(t);e.prepareContext({error:i.error,helpWidth:i.helpWidth,outputHasColors:i.hasColors});let n=e.formatHelp(this,e);return i.hasColors?n:this._outputConfiguration.stripColor(n)}_getOutputContext(t){t=t||{};let e=!!t.error,i,n,s;return e?(i=a=>this._outputConfiguration.writeErr(a),n=this._outputConfiguration.getErrHasColors(),s=this._outputConfiguration.getErrHelpWidth()):(i=a=>this._outputConfiguration.writeOut(a),n=this._outputConfiguration.getOutHasColors(),s=this._outputConfiguration.getOutHelpWidth()),{error:e,write:a=>(n||(a=this._outputConfiguration.stripColor(a)),i(a)),hasColors:n,helpWidth:s}}outputHelp(t){let e;typeof t=="function"&&(e=t,t=void 0);let i=this._getOutputContext(t),n={error:i.error,write:i.write,command:this};this._getCommandAndAncestors().reverse().forEach(r=>r.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let s=this.helpInformation({error:i.error});if(e&&(s=e(s),typeof s!="string"&&!Buffer.isBuffer(s)))throw new Error("outputHelp callback must return a string or a Buffer");i.write(s),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(r=>r.emit("afterAllHelp",n));}helpOption(t,e){return typeof t=="boolean"?(t?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(t??"-h, --help",e??"display help for command"),(t||e)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(t){return this._helpOption=t,this._initOptionGroup(t),this}help(t){this.outputHelp(t);let e=Number(p.exitCode??0);e===0&&t&&typeof t!="function"&&t.error&&(e=1),this._exit(e,"commander.help","(outputHelp)");}addHelpText(t,e){let i=["beforeAll","before","after","afterAll"];if(!i.includes(t))throw new Error(`Unexpected value for position to addHelpText.
Expecting one of '${i.join("', '")}'`);let n=`${t}Help`;return this.on(n,s=>{let r;typeof e=="function"?r=e({error:s.error,command:s.command}):r=e,r&&s.write(`${r}
`);}),this}_outputHelpIfRequested(t){let e=this._getHelpOption();e&&t.find(n=>e.is(n))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"));}};function ot(o){return o.map(t=>{if(!t.startsWith("--inspect"))return t;let e,i="127.0.0.1",n="9229",s;return (s=t.match(/^(--inspect(-brk)?)$/))!==null?e=s[1]:(s=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(e=s[1],/^\d+$/.test(s[3])?n=s[3]:i=s[3]):(s=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(e=s[1],i=s[3],n=s[4]),e&&n!=="0"?`${e}=${i}:${parseInt(n)+1}`:t})}function B(){if(p.env.NO_COLOR||p.env.FORCE_COLOR==="0"||p.env.FORCE_COLOR==="false")return false;if(p.env.FORCE_COLOR||p.env.CLICOLOR_FORCE!==void 0)return true}J.Command=U;J.useColor=B;});var ct=A(_=>{d();var{Argument:lt}=T(),{Command:Y}=at(),{CommanderError:Bt,InvalidArgumentError:ut}=v(),{Help:Jt}=W(),{Option:ht}=j();_.program=new Y;_.createCommand=o=>new Y(o);_.createOption=(o,t)=>new ht(o,t);_.createArgument=(o,t)=>new lt(o,t);_.Command=Y;_.Option=ht;_.Argument=lt;_.Help=Jt;_.CommanderError=Bt;_.InvalidArgumentError=ut;_.InvalidOptionArgumentError=ut;});var pt,Ae,xe,Ee,ve,$e,Se,He,mt,Te,ke,Pe,dt=E(()=>{d();pt=Pt(ct()),{program:Ae,createCommand:xe,createArgument:Ee,createOption:ve,CommanderError:$e,InvalidArgumentError:Se,InvalidOptionArgumentError:He,Command:mt,Argument:Te,Option:ke,Help:Pe}=pt.default;});async function Kt(o){if(K.has(o))return K.get(o);let t=ft__namespace.createInterface({input:process.stdin,output:process.stdout});return new Promise(e=>{t.question(`Skip directory "${o}"? (y/n): `,i=>{let n=i.toLowerCase().startsWith("y");K.set(o,n),t.close(),e(n);});})}async function Qt(o,t,e,i){let n=new Set(e);if(!i)return n;async function s(r,a=0){if(a>=t)return;let c;try{c=await $__namespace.promises.readdir(r);}catch{return}for(let u of c){let h=w__namespace.join(r,u);try{if((await $__namespace.promises.stat(h)).isDirectory()){let m=w__namespace.relative(o,h);Yt.has(u)&&!n.has(m)?await Kt(u)?n.add(m):await s(h,a+1):await s(h,a+1);}}catch{}}}return await s(o),n}async function gt(o,t,e,i="",n=0){let s=w__namespace.basename(w__namespace.resolve(o));if(n===0&&console.log(s),n>=t)return;let r;try{r=await $__namespace.promises.readdir(o);}catch{return}let u=(await Promise.all(r.map(async l=>{let m=w__namespace.join(o,l);try{let g=await $__namespace.promises.stat(m);return {entry:l,fullPath:m,stats:g,isDirectory:g.isDirectory()}}catch{return null}}))).filter(l=>l!==null).sort((l,m)=>l.isDirectory&&!m.isDirectory?-1:!l.isDirectory&&m.isDirectory?1:l.entry.localeCompare(m.entry)).filter(({entry:l})=>!e.has(l)),h=u.length-1;for(let l=0;l<u.length;l++){let{entry:m,fullPath:g,isDirectory:b}=u[l],Q=l===h,Et=Q?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 ",z=i+(Q?" ":"\u2502 "),X=i+Et;b?(console.log(`${X}${m}`),n+1===t?console.log(`${z}\u2514\u2500\u2500 [...]`):await gt(g,t,e,z,n+1)):console.log(`${X}${m}`);}}async function _t({dirPath:o,maxDepth:t,skipDirs:e=new Set,interactive:i=true}){let n=await Qt(o,t,e,i);await gt(o,t,n);}var Yt,K,Ot=E(()=>{d();Yt=new Set(["node_modules","next","dist","build",".git",".github"]),K=new Map;});function Ct(o){return typeof o=="number"&&!isNaN(o)}var bt=E(()=>{d();});function f(...o){Zt&&console.log("[DEBUG]",...o);}async function wt(o,t="en",e="vi"){try{f(`Attempting translation via HTTP API: "${o}" from ${t} to ${e}`);let i=await googleTranslateApi.translate(o,{from:t,to:e});return f(`Received translation: "${i.text}"`),f("HTTP translation successful"),i.text}catch(i){f("HTTP translate failed, falling back to Puppeteer:",i),!process.env.QUIET&&!process.argv.includes("--quiet")&&console.warn("API translation failed, falling back to browser-based translation. This may take longer...");try{f(`Looking for Chrome at: ${yt}`);let n=await puppeteerCore.launch({executablePath:yt,headless:!0,args:["--no-sandbox","--disable-setuid-sandbox","--disable-dev-shm-usage"]});try{f("Browser launched successfully");let s=await n.newPage();await s.setDefaultNavigationTimeout(3e4);let r=`https://translate.google.com/?sl=${t}&tl=${e}&text=${encodeURIComponent(o)}&op=translate`;f(`Navigating to: ${r}`),await s.goto(r,{waitUntil:"networkidle2"}),f("Page loaded, waiting for translation element"),await s.waitForSelector('span[jsname="W297wb"]',{timeout:1e4}),f("Translation element found, extracting result");let a=await s.evaluate(()=>document.querySelector('span[jsname="W297wb"]')?.textContent||"");if(!a)throw f("Empty translation result received"),new Error("Translation failed: Empty result received from Google Translate");return f(`Translation successful: "${a}"`),a}finally{f("Closing browser"),await n.close();}}catch(n){throw f("Browser translation failed:",n),new Error(`Translation failed: ${n instanceof Error?n.message:String(n)}`)}}}var yt,Zt,At=E(()=>{d();yt=process.env.CHROME_PATH||(process.platform==="win32"?"C:/Program Files/Google/Chrome/Application/chrome.exe":process.platform==="darwin"?"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome":"/usr/bin/google-chrome"),Zt=process.env.DEBUG==="true"||process.argv.includes("--debug");});var oe=A(()=>{d();dt();Ot();bt();At();if(process.env.NODE_ENV!=="development"){let o=process.emit;process.emit=function(t,e,...i){return t==="warning"&&e&&typeof e=="object"&&"name"in e&&e.name==="DeprecationWarning"&&"message"in e&&typeof e.message=="string"&&e.message.includes("punycode")?false:o.apply(process,[t,e,...i])};}var ne=w.join(__dirname,"..","package.json"),se=JSON.parse($.readFileSync(ne,"utf-8")),S=se.version;function re(o,t){return t.concat([o])}var O=new mt;O.configureOutput({writeErr:o=>process.stderr.write(o),writeOut:o=>process.stdout.write(o)});O.enablePositionalOptions(true);O.passThroughOptions(false);O.name("dummie").description("dummie-tools CLI").version(S);O.option("-d, --debug","enable debug mode").option("-q, --quiet","suppress output");O.hook("preAction",o=>{let t=o.opts();t.debug&&(process.env.DEBUG="true"),t.quiet&&(process.env.QUIET="true");});O.command("strucview").description("print directory tree view").option("-l, --level <n>",'max depth level (or use "la" for all)',"3").option("-d, --dir <path>","directory to scan",".").option("-s, --skip <name>","directory name to skip (can be used multiple times)",re,[]).option("-n, --no-interactive","disable interactive prompts for directories").action(async o=>{let t=o,e;if(t.level==="la")e=1/0;else {let s=parseInt(t.level,10);(!Ct(s)||s<0)&&(console.error("Error: Level must be a non-negative number or 'la'"),process.exit(1)),e=s;}let i=t.dir;typeof i!="string"&&(console.error("Error: Directory must be a string"),process.exit(1));let n=new Set(t.skip);try{await _t({dirPath:i,maxDepth:e,skipDirs:n,interactive:t.interactive});}catch(s){console.error(`Error processing directory: ${s instanceof Error?s.message:String(s)}`),process.exit(1);}});O.command("translate <text>").description("translate text using HTTP API with Puppeteer fallback").option("-f, --from <lang>","source language code (default: en)","en").option("-t, --to <lang>","target language code (default: vi)","vi").action(async(o,t)=>{try{let e=await wt(o,t.from,t.to);console.log(e);}catch(e){console.error(`Translation error: ${e instanceof Error?e.message:String(e)}`),process.exit(1);}});O.command("info").description("display system and environment information").action(()=>{console.log("dummie-tools Information:"),console.log(`Version: ${S}`),console.log(`Node Version: ${process.version}`),console.log(`OS: ${process.platform} (${process.arch})`);try{let o=child_process.execSync("npm --version",{encoding:"utf8"}).trim();console.log(`NPM Version: ${o}`);}catch{console.log("NPM Version: Not available");}console.log(`Package Location: ${__dirname}`);});O.command("version-check").description("check for new version of dummie-tools").action(async()=>{try{console.log("Checking for updates...");let o=child_process.execSync("npm view dummie-tools version",{encoding:"utf8"}).trim();o===S?console.log(`You are using the latest version (${S}).`):(console.log(`Current version: ${S}`),console.log(`Latest version: ${o}`),console.log("You can update using: npm install -g dummie-tools@latest"));}catch(o){console.error("Failed to check for updates:",o instanceof Error?o.message:String(o));}});O.command("browser-detect").description("detect browser installations for translation feature").action(()=>{console.log("Detecting browsers for translation feature...");let t={win32:["C:/Program Files/Google/Chrome/Application/chrome.exe","C:/Program Files (x86)/Google/Chrome/Application/chrome.exe",process.env.LOCALAPPDATA+"/Google/Chrome/Application/chrome.exe"],darwin:["/Applications/Google Chrome.app/Contents/MacOS/Google Chrome","/Applications/Chromium.app/Contents/MacOS/Chromium"],linux:["/usr/bin/google-chrome","/usr/bin/chromium-browser","/usr/bin/chromium"]}[process.platform]||[],e=false;for(let i of t)try{if($.existsSync(i)){console.log(`\u2705 Found Chrome at: ${i}`),console.log(""),console.log("To use this browser for translations, set the CHROME_PATH environment variable:"),console.log(""),process.platform==="win32"?console.log(`setx CHROME_PATH "${i}"`):console.log(`export CHROME_PATH="${i}"`),e=!0;break}}catch{}e||(console.log("\u274C No Chrome installation found in common locations."),console.log(""),console.log("Manual configuration needed:"),console.log("1. Install Google Chrome"),console.log("2. Set the CHROME_PATH environment variable to your chrome.exe location"),console.log(""),process.platform==="win32"?c