UNPKG

@runtime-env/cli

Version:

Build once, deploy anywhere. Startup/runtime environment variable solution for JavaScript.

27 lines 429 kB
#!/usr/bin/env node var cN=Object.create;var au=Object.defineProperty;var dN=Object.getOwnPropertyDescriptor;var hN=Object.getOwnPropertyNames;var pN=Object.getPrototypeOf,mN=Object.prototype.hasOwnProperty;var $c=(e,r)=>()=>(e&&(r=e(e=0)),r);var $=(e,r)=>()=>(r||e((r={exports:{}}).exports,r),r.exports),gN=(e,r)=>{for(var t in r)au(e,t,{get:r[t],enumerable:!0})},R_=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let o of hN(r))!mN.call(e,o)&&o!==t&&au(e,o,{get:()=>r[o],enumerable:!(n=dN(r,o))||n.enumerable});return e};var vn=(e,r,t)=>(t=e!=null?cN(pN(e)):{},R_(r||!e||!e.__esModule?au(t,"default",{value:e,enumerable:!0}):t,e)),Pc=e=>R_(au({},"__esModule",{value:!0}),e);var os=$(Tc=>{var uu=class extends Error{constructor(r,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=r,this.nestedError=void 0}},Cc=class extends uu{constructor(r){super(1,"commander.invalidArgument",r),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Tc.CommanderError=uu;Tc.InvalidArgumentError=Cc});var lu=$(Nc=>{var{InvalidArgumentError:_N}=os(),Ic=class{constructor(r,t){switch(this.description=t||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,r[0]){case"<":this.required=!0,this._name=r.slice(1,-1);break;case"[":this.required=!1,this._name=r.slice(1,-1);break;default:this.required=!0,this._name=r;break}this._name.endsWith("...")&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_collectValue(r,t){return t===this.defaultValue||!Array.isArray(t)?[r]:(t.push(r),t)}default(r,t){return this.defaultValue=r,this.defaultValueDescription=t,this}argParser(r){return this.parseArg=r,this}choices(r){return this.argChoices=r.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new _N(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(t,n):t},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function yN(e){let r=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+r+">":"["+r+"]"}Nc.Argument=Ic;Nc.humanReadableArgName=yN});var Mc=$(Dc=>{var{humanReadableArgName:vN}=lu(),Rc=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(r){this.helpWidth=this.helpWidth??r.helpWidth??80}visibleCommands(r){let t=r.commands.filter(o=>!o._hidden),n=r._getHelpCommand();return n&&!n._hidden&&t.push(n),this.sortSubcommands&&t.sort((o,a)=>o.name().localeCompare(a.name())),t}compareOptions(r,t){let n=o=>o.short?o.short.replace(/^-/,""):o.long.replace(/^--/,"");return n(r).localeCompare(n(t))}visibleOptions(r){let t=r.options.filter(o=>!o.hidden),n=r._getHelpOption();if(n&&!n.hidden){let o=n.short&&r._findOption(n.short),a=n.long&&r._findOption(n.long);!o&&!a?t.push(n):n.long&&!a?t.push(r.createOption(n.long,n.description)):n.short&&!o&&t.push(r.createOption(n.short,n.description))}return this.sortOptions&&t.sort(this.compareOptions),t}visibleGlobalOptions(r){if(!this.showGlobalOptions)return[];let t=[];for(let n=r.parent;n;n=n.parent){let o=n.options.filter(a=>!a.hidden);t.push(...o)}return this.sortOptions&&t.sort(this.compareOptions),t}visibleArguments(r){return r._argsDescription&&r.registeredArguments.forEach(t=>{t.description=t.description||r._argsDescription[t.name()]||""}),r.registeredArguments.find(t=>t.description)?r.registeredArguments:[]}subcommandTerm(r){let t=r.registeredArguments.map(n=>vN(n)).join(" ");return r._name+(r._aliases[0]?"|"+r._aliases[0]:"")+(r.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(r){return r.flags}argumentTerm(r){return r.name()}longestSubcommandTermLength(r,t){return t.visibleCommands(r).reduce((n,o)=>Math.max(n,this.displayWidth(t.styleSubcommandTerm(t.subcommandTerm(o)))),0)}longestOptionTermLength(r,t){return t.visibleOptions(r).reduce((n,o)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(o)))),0)}longestGlobalOptionTermLength(r,t){return t.visibleGlobalOptions(r).reduce((n,o)=>Math.max(n,this.displayWidth(t.styleOptionTerm(t.optionTerm(o)))),0)}longestArgumentTermLength(r,t){return t.visibleArguments(r).reduce((n,o)=>Math.max(n,this.displayWidth(t.styleArgumentTerm(t.argumentTerm(o)))),0)}commandUsage(r){let t=r._name;r._aliases[0]&&(t=t+"|"+r._aliases[0]);let n="";for(let o=r.parent;o;o=o.parent)n=o.name()+" "+n;return n+t+" "+r.usage()}commandDescription(r){return r.description()}subcommandDescription(r){return r.summary()||r.description()}optionDescription(r){let t=[];if(r.argChoices&&t.push(`choices: ${r.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),r.defaultValue!==void 0&&(r.required||r.optional||r.isBoolean()&&typeof r.defaultValue=="boolean")&&t.push(`default: ${r.defaultValueDescription||JSON.stringify(r.defaultValue)}`),r.presetArg!==void 0&&r.optional&&t.push(`preset: ${JSON.stringify(r.presetArg)}`),r.envVar!==void 0&&t.push(`env: ${r.envVar}`),t.length>0){let n=`(${t.join(", ")})`;return r.description?`${r.description} ${n}`:n}return r.description}argumentDescription(r){let t=[];if(r.argChoices&&t.push(`choices: ${r.argChoices.map(n=>JSON.stringify(n)).join(", ")}`),r.defaultValue!==void 0&&t.push(`default: ${r.defaultValueDescription||JSON.stringify(r.defaultValue)}`),t.length>0){let n=`(${t.join(", ")})`;return r.description?`${r.description} ${n}`:n}return r.description}formatItemList(r,t,n){return t.length===0?[]:[n.styleTitle(r),...t,""]}groupItems(r,t,n){let o=new Map;return r.forEach(a=>{let u=n(a);o.has(u)||o.set(u,[])}),t.forEach(a=>{let u=n(a);o.has(u)||o.set(u,[]),o.get(u).push(a)}),o}formatHelp(r,t){let n=t.padWidth(r,t),o=t.helpWidth??80;function a(m,v){return t.formatItem(m,n,v,t)}let u=[`${t.styleTitle("Usage:")} ${t.styleUsage(t.commandUsage(r))}`,""],f=t.commandDescription(r);f.length>0&&(u=u.concat([t.boxWrap(t.styleCommandDescription(f),o),""]));let c=t.visibleArguments(r).map(m=>a(t.styleArgumentTerm(t.argumentTerm(m)),t.styleArgumentDescription(t.argumentDescription(m))));if(u=u.concat(this.formatItemList("Arguments:",c,t)),this.groupItems(r.options,t.visibleOptions(r),m=>m.helpGroupHeading??"Options:").forEach((m,v)=>{let w=m.map(O=>a(t.styleOptionTerm(t.optionTerm(O)),t.styleOptionDescription(t.optionDescription(O))));u=u.concat(this.formatItemList(v,w,t))}),t.showGlobalOptions){let m=t.visibleGlobalOptions(r).map(v=>a(t.styleOptionTerm(t.optionTerm(v)),t.styleOptionDescription(t.optionDescription(v))));u=u.concat(this.formatItemList("Global Options:",m,t))}return this.groupItems(r.commands,t.visibleCommands(r),m=>m.helpGroup()||"Commands:").forEach((m,v)=>{let w=m.map(O=>a(t.styleSubcommandTerm(t.subcommandTerm(O)),t.styleSubcommandDescription(t.subcommandDescription(O))));u=u.concat(this.formatItemList(v,w,t))}),u.join(` `)}displayWidth(r){return D_(r).length}styleTitle(r){return r}styleUsage(r){return r.split(" ").map(t=>t==="[options]"?this.styleOptionText(t):t==="[command]"?this.styleSubcommandText(t):t[0]==="["||t[0]==="<"?this.styleArgumentText(t):this.styleCommandText(t)).join(" ")}styleCommandDescription(r){return this.styleDescriptionText(r)}styleOptionDescription(r){return this.styleDescriptionText(r)}styleSubcommandDescription(r){return this.styleDescriptionText(r)}styleArgumentDescription(r){return this.styleDescriptionText(r)}styleDescriptionText(r){return r}styleOptionTerm(r){return this.styleOptionText(r)}styleSubcommandTerm(r){return r.split(" ").map(t=>t==="[options]"?this.styleOptionText(t):t[0]==="["||t[0]==="<"?this.styleArgumentText(t):this.styleSubcommandText(t)).join(" ")}styleArgumentTerm(r){return this.styleArgumentText(r)}styleOptionText(r){return r}styleArgumentText(r){return r}styleSubcommandText(r){return r}styleCommandText(r){return r}padWidth(r,t){return Math.max(t.longestOptionTermLength(r,t),t.longestGlobalOptionTermLength(r,t),t.longestSubcommandTermLength(r,t),t.longestArgumentTermLength(r,t))}preformatted(r){return/\n[^\S\r\n]/.test(r)}formatItem(r,t,n,o){let u=" ".repeat(2);if(!n)return u+r;let f=r.padEnd(t+r.length-o.displayWidth(r)),c=2,p=(this.helpWidth??80)-t-c-2,m;return p<this.minWidthToWrap||o.preformatted(n)?m=n:m=o.boxWrap(n,p).replace(/\n/g,` `+" ".repeat(t+c)),u+f+" ".repeat(c)+m.replace(/\n/g,` ${u}`)}boxWrap(r,t){if(t<this.minWidthToWrap)return r;let n=r.split(/\r\n|\n/),o=/[\s]*[^\s]+/g,a=[];return n.forEach(u=>{let f=u.match(o);if(f===null){a.push("");return}let c=[f.shift()],h=this.displayWidth(c[0]);f.forEach(p=>{let m=this.displayWidth(p);if(h+m<=t){c.push(p),h+=m;return}a.push(c.join(""));let v=p.trimStart();c=[v],h=this.displayWidth(v)}),a.push(c.join(""))}),a.join(` `)}};function D_(e){let r=/\x1b\[\d*(;\d*)*m/g;return e.replace(r,"")}Dc.Help=Rc;Dc.stripColor=D_});var Lc=$(jc=>{var{InvalidArgumentError:wN}=os(),qc=class{constructor(r,t){this.flags=r,this.description=t||"",this.required=r.includes("<"),this.optional=r.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(r),this.mandatory=!1;let n=bN(r);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,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=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0,this.helpGroupHeading=void 0}default(r,t){return this.defaultValue=r,this.defaultValueDescription=t,this}preset(r){return this.presetArg=r,this}conflicts(r){return this.conflictsWith=this.conflictsWith.concat(r),this}implies(r){let t=r;return typeof r=="string"&&(t={[r]:!0}),this.implied=Object.assign(this.implied||{},t),this}env(r){return this.envVar=r,this}argParser(r){return this.parseArg=r,this}makeOptionMandatory(r=!0){return this.mandatory=!!r,this}hideHelp(r=!0){return this.hidden=!!r,this}_collectValue(r,t){return t===this.defaultValue||!Array.isArray(t)?[r]:(t.push(r),t)}choices(r){return this.argChoices=r.slice(),this.parseArg=(t,n)=>{if(!this.argChoices.includes(t))throw new wN(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._collectValue(t,n):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?M_(this.name().replace(/^no-/,"")):M_(this.name())}helpGroup(r){return this.helpGroupHeading=r,this}is(r){return this.short===r||this.long===r}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Fc=class{constructor(r){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,r.forEach(t=>{t.negate?this.negativeOptions.set(t.attributeName(),t):this.positiveOptions.set(t.attributeName(),t)}),this.negativeOptions.forEach((t,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(r,t){let n=t.attributeName();if(!this.dualOptions.has(n))return!0;let o=this.negativeOptions.get(n).presetArg,a=o!==void 0?o:!1;return t.negate===(a===r)}};function M_(e){return e.split("-").reduce((r,t)=>r+t[0].toUpperCase()+t.slice(1))}function bN(e){let r,t,n=/^-[^-]$/,o=/^--[^-]/,a=e.split(/[ |,]+/).concat("guard");if(n.test(a[0])&&(r=a.shift()),o.test(a[0])&&(t=a.shift()),!r&&n.test(a[0])&&(r=a.shift()),!r&&o.test(a[0])&&(r=t,t=a.shift()),a[0].startsWith("-")){let u=a[0],f=`option creation failed due to '${u}' in option flags '${e}'`;throw/^-[^-][^-]/.test(u)?new Error(`${f} - 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')`):n.test(u)?new Error(`${f} - too many short flags`):o.test(u)?new Error(`${f} - too many long flags`):new Error(`${f} - unrecognised flag format`)}if(r===void 0&&t===void 0)throw new Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:r,longFlag:t}}jc.Option=qc;jc.DualOptions=Fc});var F_=$(q_=>{function EN(e,r){if(Math.abs(e.length-r.length)>3)return Math.max(e.length,r.length);let t=[];for(let n=0;n<=e.length;n++)t[n]=[n];for(let n=0;n<=r.length;n++)t[0][n]=n;for(let n=1;n<=r.length;n++)for(let o=1;o<=e.length;o++){let a=1;e[o-1]===r[n-1]?a=0:a=1,t[o][n]=Math.min(t[o-1][n]+1,t[o][n-1]+1,t[o-1][n-1]+a),o>1&&n>1&&e[o-1]===r[n-2]&&e[o-2]===r[n-1]&&(t[o][n]=Math.min(t[o][n],t[o-2][n-2]+1))}return t[e.length][r.length]}function ON(e,r){if(!r||r.length===0)return"";r=Array.from(new Set(r));let t=e.startsWith("--");t&&(e=e.slice(2),r=r.map(u=>u.slice(2)));let n=[],o=3,a=.4;return r.forEach(u=>{if(u.length<=1)return;let f=EN(e,u),c=Math.max(e.length,u.length);(c-f)/c>a&&(f<o?(o=f,n=[u]):f===o&&n.push(u))}),n.sort((u,f)=>u.localeCompare(f)),t&&(n=n.map(u=>`--${u}`)),n.length>1?` (Did you mean one of ${n.join(", ")}?)`:n.length===1?` (Did you mean ${n[0]}?)`:""}q_.suggestSimilar=ON});var U_=$(Wc=>{var xN=require("node:events").EventEmitter,kc=require("node:child_process"),zt=require("node:path"),fu=require("node:fs"),me=require("node:process"),{Argument:AN,humanReadableArgName:SN}=lu(),{CommanderError:Uc}=os(),{Help:$N,stripColor:PN}=Mc(),{Option:j_,DualOptions:CN}=Lc(),{suggestSimilar:L_}=F_(),Hc=class e extends xN{constructor(r){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=r||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:t=>me.stdout.write(t),writeErr:t=>me.stderr.write(t),outputError:(t,n)=>n(t),getOutHelpWidth:()=>me.stdout.isTTY?me.stdout.columns:void 0,getErrHelpWidth:()=>me.stderr.isTTY?me.stderr.columns:void 0,getOutHasColors:()=>Bc()??(me.stdout.isTTY&&me.stdout.hasColors?.()),getErrHasColors:()=>Bc()??(me.stderr.isTTY&&me.stderr.hasColors?.()),stripColor:t=>PN(t)},this._hidden=!1,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(r){return this._outputConfiguration=r._outputConfiguration,this._helpOption=r._helpOption,this._helpCommand=r._helpCommand,this._helpConfiguration=r._helpConfiguration,this._exitCallback=r._exitCallback,this._storeOptionsAsProperties=r._storeOptionsAsProperties,this._combineFlagAndOptionalValue=r._combineFlagAndOptionalValue,this._allowExcessArguments=r._allowExcessArguments,this._enablePositionalOptions=r._enablePositionalOptions,this._showHelpAfterError=r._showHelpAfterError,this._showSuggestionAfterError=r._showSuggestionAfterError,this}_getCommandAndAncestors(){let r=[];for(let t=this;t;t=t.parent)r.push(t);return r}command(r,t,n){let o=t,a=n;typeof o=="object"&&o!==null&&(a=o,o=null),a=a||{};let[,u,f]=r.match(/([^ ]+) *(.*)/),c=this.createCommand(u);return o&&(c.description(o),c._executableHandler=!0),a.isDefault&&(this._defaultCommandName=c._name),c._hidden=!!(a.noHelp||a.hidden),c._executableFile=a.executableFile||null,f&&c.arguments(f),this._registerCommand(c),c.parent=this,c.copyInheritedSettings(this),o?this:c}createCommand(r){return new e(r)}createHelp(){return Object.assign(new $N,this.configureHelp())}configureHelp(r){return r===void 0?this._helpConfiguration:(this._helpConfiguration=r,this)}configureOutput(r){return r===void 0?this._outputConfiguration:(this._outputConfiguration={...this._outputConfiguration,...r},this)}showHelpAfterError(r=!0){return typeof r!="string"&&(r=!!r),this._showHelpAfterError=r,this}showSuggestionAfterError(r=!0){return this._showSuggestionAfterError=!!r,this}addCommand(r,t){if(!r._name)throw new Error(`Command passed to .addCommand() must have a name - specify the name in Command constructor or using .name()`);return t=t||{},t.isDefault&&(this._defaultCommandName=r._name),(t.noHelp||t.hidden)&&(r._hidden=!0),this._registerCommand(r),r.parent=this,r._checkForBrokenPassThrough(),this}createArgument(r,t){return new AN(r,t)}argument(r,t,n,o){let a=this.createArgument(r,t);return typeof n=="function"?a.default(o).argParser(n):a.default(n),this.addArgument(a),this}arguments(r){return r.trim().split(/ +/).forEach(t=>{this.argument(t)}),this}addArgument(r){let t=this.registeredArguments.slice(-1)[0];if(t?.variadic)throw new Error(`only the last argument can be variadic '${t.name()}'`);if(r.required&&r.defaultValue!==void 0&&r.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${r.name()}'`);return this.registeredArguments.push(r),this}helpCommand(r,t){if(typeof r=="boolean")return this._addImplicitHelpCommand=r,r&&this._defaultCommandGroup&&this._initCommandGroup(this._getHelpCommand()),this;let n=r??"help [command]",[,o,a]=n.match(/([^ ]+) *(.*)/),u=t??"display help for command",f=this.createCommand(o);return f.helpOption(!1),a&&f.arguments(a),u&&f.description(u),this._addImplicitHelpCommand=!0,this._helpCommand=f,(r||t)&&this._initCommandGroup(f),this}addHelpCommand(r,t){return typeof r!="object"?(this.helpCommand(r,t),this):(this._addImplicitHelpCommand=!0,this._helpCommand=r,this._initCommandGroup(r),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(r,t){let n=["preSubcommand","preAction","postAction"];if(!n.includes(r))throw new Error(`Unexpected value for event passed to hook : '${r}'. Expecting one of '${n.join("', '")}'`);return this._lifeCycleHooks[r]?this._lifeCycleHooks[r].push(t):this._lifeCycleHooks[r]=[t],this}exitOverride(r){return r?this._exitCallback=r:this._exitCallback=t=>{if(t.code!=="commander.executeSubCommandAsync")throw t},this}_exit(r,t,n){this._exitCallback&&this._exitCallback(new Uc(r,t,n)),me.exit(r)}action(r){let t=n=>{let o=this.registeredArguments.length,a=n.slice(0,o);return this._storeOptionsAsProperties?a[o]=this:a[o]=this.opts(),a.push(this),r.apply(this,a)};return this._actionHandler=t,this}createOption(r,t){return new j_(r,t)}_callParseArg(r,t,n,o){try{return r.parseArg(t,n)}catch(a){if(a.code==="commander.invalidArgument"){let u=`${o} ${a.message}`;this.error(u,{exitCode:a.exitCode,code:a.code})}throw a}}_registerOption(r){let t=r.short&&this._findOption(r.short)||r.long&&this._findOption(r.long);if(t){let n=r.long&&this._findOption(r.long)?r.long:r.short;throw new Error(`Cannot add option '${r.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${n}' - already used by option '${t.flags}'`)}this._initOptionGroup(r),this.options.push(r)}_registerCommand(r){let t=o=>[o.name()].concat(o.aliases()),n=t(r).find(o=>this._findCommand(o));if(n){let o=t(this._findCommand(n)).join("|"),a=t(r).join("|");throw new Error(`cannot add command '${a}' as already have command '${o}'`)}this._initCommandGroup(r),this.commands.push(r)}addOption(r){this._registerOption(r);let t=r.name(),n=r.attributeName();if(r.negate){let a=r.long.replace(/^--no-/,"--");this._findOption(a)||this.setOptionValueWithSource(n,r.defaultValue===void 0?!0:r.defaultValue,"default")}else r.defaultValue!==void 0&&this.setOptionValueWithSource(n,r.defaultValue,"default");let o=(a,u,f)=>{a==null&&r.presetArg!==void 0&&(a=r.presetArg);let c=this.getOptionValue(n);a!==null&&r.parseArg?a=this._callParseArg(r,a,c,u):a!==null&&r.variadic&&(a=r._collectValue(a,c)),a==null&&(r.negate?a=!1:r.isBoolean()||r.optional?a=!0:a=""),this.setOptionValueWithSource(n,a,f)};return this.on("option:"+t,a=>{let u=`error: option '${r.flags}' argument '${a}' is invalid.`;o(a,u,"cli")}),r.envVar&&this.on("optionEnv:"+t,a=>{let u=`error: option '${r.flags}' value '${a}' from env '${r.envVar}' is invalid.`;o(a,u,"env")}),this}_optionEx(r,t,n,o,a){if(typeof t=="object"&&t instanceof j_)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let u=this.createOption(t,n);if(u.makeOptionMandatory(!!r.mandatory),typeof o=="function")u.default(a).argParser(o);else if(o instanceof RegExp){let f=o;o=(c,h)=>{let p=f.exec(c);return p?p[0]:h},u.default(a).argParser(o)}else u.default(o);return this.addOption(u)}option(r,t,n,o){return this._optionEx({},r,t,n,o)}requiredOption(r,t,n,o){return this._optionEx({mandatory:!0},r,t,n,o)}combineFlagAndOptionalValue(r=!0){return this._combineFlagAndOptionalValue=!!r,this}allowUnknownOption(r=!0){return this._allowUnknownOption=!!r,this}allowExcessArguments(r=!0){return this._allowExcessArguments=!!r,this}enablePositionalOptions(r=!0){return this._enablePositionalOptions=!!r,this}passThroughOptions(r=!0){return this._passThroughOptions=!!r,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(r=!0){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=!!r,this}getOptionValue(r){return this._storeOptionsAsProperties?this[r]:this._optionValues[r]}setOptionValue(r,t){return this.setOptionValueWithSource(r,t,void 0)}setOptionValueWithSource(r,t,n){return this._storeOptionsAsProperties?this[r]=t:this._optionValues[r]=t,this._optionValueSources[r]=n,this}getOptionValueSource(r){return this._optionValueSources[r]}getOptionValueSourceWithGlobals(r){let t;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(r)!==void 0&&(t=n.getOptionValueSource(r))}),t}_prepareUserArgs(r,t){if(r!==void 0&&!Array.isArray(r))throw new Error("first parameter to parse must be array or undefined");if(t=t||{},r===void 0&&t.from===void 0){me.versions?.electron&&(t.from="electron");let o=me.execArgv??[];(o.includes("-e")||o.includes("--eval")||o.includes("-p")||o.includes("--print"))&&(t.from="eval")}r===void 0&&(r=me.argv),this.rawArgs=r.slice();let n;switch(t.from){case void 0:case"node":this._scriptPath=r[1],n=r.slice(2);break;case"electron":me.defaultApp?(this._scriptPath=r[1],n=r.slice(2)):n=r.slice(1);break;case"user":n=r.slice(0);break;case"eval":n=r.slice(1);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",n}parse(r,t){this._prepareForParse();let n=this._prepareUserArgs(r,t);return this._parseCommand([],n),this}async parseAsync(r,t){this._prepareForParse();let n=this._prepareUserArgs(r,t);return await this._parseCommand([],n),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(r,t,n){if(fu.existsSync(r))return;let o=t?`searched for local subcommand relative to directory '${t}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",a=`'${r}' does not exist - if '${n}' 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 - ${o}`;throw new Error(a)}_executeSubCommand(r,t){t=t.slice();let n=!1,o=[".js",".ts",".tsx",".mjs",".cjs"];function a(p,m){let v=zt.resolve(p,m);if(fu.existsSync(v))return v;if(o.includes(zt.extname(m)))return;let w=o.find(O=>fu.existsSync(`${v}${O}`));if(w)return`${v}${w}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let u=r._executableFile||`${this._name}-${r._name}`,f=this._executableDir||"";if(this._scriptPath){let p;try{p=fu.realpathSync(this._scriptPath)}catch{p=this._scriptPath}f=zt.resolve(zt.dirname(p),f)}if(f){let p=a(f,u);if(!p&&!r._executableFile&&this._scriptPath){let m=zt.basename(this._scriptPath,zt.extname(this._scriptPath));m!==this._name&&(p=a(f,`${m}-${r._name}`))}u=p||u}n=o.includes(zt.extname(u));let c;me.platform!=="win32"?n?(t.unshift(u),t=k_(me.execArgv).concat(t),c=kc.spawn(me.argv[0],t,{stdio:"inherit"})):c=kc.spawn(u,t,{stdio:"inherit"}):(this._checkForMissingExecutable(u,f,r._name),t.unshift(u),t=k_(me.execArgv).concat(t),c=kc.spawn(me.execPath,t,{stdio:"inherit"})),c.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(m=>{me.on(m,()=>{c.killed===!1&&c.exitCode===null&&c.kill(m)})});let h=this._exitCallback;c.on("close",p=>{p=p??1,h?h(new Uc(p,"commander.executeSubCommandAsync","(close)")):me.exit(p)}),c.on("error",p=>{if(p.code==="ENOENT")this._checkForMissingExecutable(u,f,r._name);else if(p.code==="EACCES")throw new Error(`'${u}' not executable`);if(!h)me.exit(1);else{let m=new Uc(1,"commander.executeSubCommandAsync","(error)");m.nestedError=p,h(m)}}),this.runningCommand=c}_dispatchSubcommand(r,t,n){let o=this._findCommand(r);o||this.help({error:!0}),o._prepareForParse();let a;return a=this._chainOrCallSubCommandHook(a,o,"preSubcommand"),a=this._chainOrCall(a,()=>{if(o._executableHandler)this._executeSubCommand(o,t.concat(n));else return o._parseCommand(t,n)}),a}_dispatchHelpCommand(r){r||this.help();let t=this._findCommand(r);return t&&!t._executableHandler&&t.help(),this._dispatchSubcommand(r,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((r,t)=>{r.required&&this.args[t]==null&&this.missingArgument(r.name())}),!(this.registeredArguments.length>0&&this.registeredArguments[this.registeredArguments.length-1].variadic)&&this.args.length>this.registeredArguments.length&&this._excessArguments(this.args)}_processArguments(){let r=(n,o,a)=>{let u=o;if(o!==null&&n.parseArg){let f=`error: command-argument value '${o}' is invalid for argument '${n.name()}'.`;u=this._callParseArg(n,o,a,f)}return u};this._checkNumberOfArguments();let t=[];this.registeredArguments.forEach((n,o)=>{let a=n.defaultValue;n.variadic?o<this.args.length?(a=this.args.slice(o),n.parseArg&&(a=a.reduce((u,f)=>r(n,f,u),n.defaultValue))):a===void 0&&(a=[]):o<this.args.length&&(a=this.args[o],n.parseArg&&(a=r(n,a,n.defaultValue))),t[o]=a}),this.processedArgs=t}_chainOrCall(r,t){return r?.then&&typeof r.then=="function"?r.then(()=>t()):t()}_chainOrCallHooks(r,t){let n=r,o=[];return this._getCommandAndAncestors().reverse().filter(a=>a._lifeCycleHooks[t]!==void 0).forEach(a=>{a._lifeCycleHooks[t].forEach(u=>{o.push({hookedCommand:a,callback:u})})}),t==="postAction"&&o.reverse(),o.forEach(a=>{n=this._chainOrCall(n,()=>a.callback(a.hookedCommand,this))}),n}_chainOrCallSubCommandHook(r,t,n){let o=r;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(a=>{o=this._chainOrCall(o,()=>a(this,t))}),o}_parseCommand(r,t){let n=this.parseOptions(t);if(this._parseOptionsEnv(),this._parseOptionsImplied(),r=r.concat(n.operands),t=n.unknown,this.args=r.concat(t),r&&this._findCommand(r[0]))return this._dispatchSubcommand(r[0],r.slice(1),t);if(this._getHelpCommand()&&r[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(r[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(t),this._dispatchSubcommand(this._defaultCommandName,r,t);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},a=`command:${this.name()}`;if(this._actionHandler){o(),this._processArguments();let u;return u=this._chainOrCallHooks(u,"preAction"),u=this._chainOrCall(u,()=>this._actionHandler(this.processedArgs)),this.parent&&(u=this._chainOrCall(u,()=>{this.parent.emit(a,r,t)})),u=this._chainOrCallHooks(u,"postAction"),u}if(this.parent?.listenerCount(a))o(),this._processArguments(),this.parent.emit(a,r,t);else if(r.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",r,t);this.listenerCount("command:*")?this.emit("command:*",r,t):this.commands.length?this.unknownCommand():(o(),this._processArguments())}else this.commands.length?(o(),this.help({error:!0})):(o(),this._processArguments())}_findCommand(r){if(r)return this.commands.find(t=>t._name===r||t._aliases.includes(r))}_findOption(r){return this.options.find(t=>t.is(r))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(r=>{r.options.forEach(t=>{t.mandatory&&r.getOptionValue(t.attributeName())===void 0&&r.missingMandatoryOptionValue(t)})})}_checkForConflictingLocalOptions(){let r=this.options.filter(n=>{let o=n.attributeName();return this.getOptionValue(o)===void 0?!1:this.getOptionValueSource(o)!=="default"});r.filter(n=>n.conflictsWith.length>0).forEach(n=>{let o=r.find(a=>n.conflictsWith.includes(a.attributeName()));o&&this._conflictingOption(n,o)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(r=>{r._checkForConflictingLocalOptions()})}parseOptions(r){let t=[],n=[],o=t;function a(p){return p.length>1&&p[0]==="-"}let u=p=>/^-(\d+|\d*\.\d+)(e[+-]?\d+)?$/.test(p)?!this._getCommandAndAncestors().some(m=>m.options.map(v=>v.short).some(v=>/^-\d$/.test(v))):!1,f=null,c=null,h=0;for(;h<r.length||c;){let p=c??r[h++];if(c=null,p==="--"){o===n&&o.push(p),o.push(...r.slice(h));break}if(f&&(!a(p)||u(p))){this.emit(`option:${f.name()}`,p);continue}if(f=null,a(p)){let m=this._findOption(p);if(m){if(m.required){let v=r[h++];v===void 0&&this.optionMissingArgument(m),this.emit(`option:${m.name()}`,v)}else if(m.optional){let v=null;h<r.length&&(!a(r[h])||u(r[h]))&&(v=r[h++]),this.emit(`option:${m.name()}`,v)}else this.emit(`option:${m.name()}`);f=m.variadic?m:null;continue}}if(p.length>2&&p[0]==="-"&&p[1]!=="-"){let m=this._findOption(`-${p[1]}`);if(m){m.required||m.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${m.name()}`,p.slice(2)):(this.emit(`option:${m.name()}`),c=`-${p.slice(2)}`);continue}}if(/^--[^=]+=/.test(p)){let m=p.indexOf("="),v=this._findOption(p.slice(0,m));if(v&&(v.required||v.optional)){this.emit(`option:${v.name()}`,p.slice(m+1));continue}}if(o===t&&a(p)&&!(this.commands.length===0&&u(p))&&(o=n),(this._enablePositionalOptions||this._passThroughOptions)&&t.length===0&&n.length===0){if(this._findCommand(p)){t.push(p),n.push(...r.slice(h));break}else if(this._getHelpCommand()&&p===this._getHelpCommand().name()){t.push(p,...r.slice(h));break}else if(this._defaultCommandName){n.push(p,...r.slice(h));break}}if(this._passThroughOptions){o.push(p,...r.slice(h));break}o.push(p)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){let r={},t=this.options.length;for(let n=0;n<t;n++){let o=this.options[n].attributeName();r[o]=o===this._versionOptionName?this._version:this[o]}return r}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((r,t)=>Object.assign(r,t.opts()),{})}error(r,t){this._outputConfiguration.outputError(`${r} `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError} `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(` `),this.outputHelp({error:!0}));let n=t||{},o=n.exitCode||1,a=n.code||"commander.error";this._exit(o,a,r)}_parseOptionsEnv(){this.options.forEach(r=>{if(r.envVar&&r.envVar in me.env){let t=r.attributeName();(this.getOptionValue(t)===void 0||["default","config","env"].includes(this.getOptionValueSource(t)))&&(r.required||r.optional?this.emit(`optionEnv:${r.name()}`,me.env[r.envVar]):this.emit(`optionEnv:${r.name()}`))}})}_parseOptionsImplied(){let r=new CN(this.options),t=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&t(n.attributeName())&&r.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(o=>!t(o)).forEach(o=>{this.setOptionValueWithSource(o,n.implied[o],"implied")})})}missingArgument(r){let t=`error: missing required argument '${r}'`;this.error(t,{code:"commander.missingArgument"})}optionMissingArgument(r){let t=`error: option '${r.flags}' argument missing`;this.error(t,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(r){let t=`error: required option '${r.flags}' not specified`;this.error(t,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(r,t){let n=u=>{let f=u.attributeName(),c=this.getOptionValue(f),h=this.options.find(m=>m.negate&&f===m.attributeName()),p=this.options.find(m=>!m.negate&&f===m.attributeName());return h&&(h.presetArg===void 0&&c===!1||h.presetArg!==void 0&&c===h.presetArg)?h:p||u},o=u=>{let f=n(u),c=f.attributeName();return this.getOptionValueSource(c)==="env"?`environment variable '${f.envVar}'`:`option '${f.flags}'`},a=`error: ${o(r)} cannot be used with ${o(t)}`;this.error(a,{code:"commander.conflictingOption"})}unknownOption(r){if(this._allowUnknownOption)return;let t="";if(r.startsWith("--")&&this._showSuggestionAfterError){let o=[],a=this;do{let u=a.createHelp().visibleOptions(a).filter(f=>f.long).map(f=>f.long);o=o.concat(u),a=a.parent}while(a&&!a._enablePositionalOptions);t=L_(r,o)}let n=`error: unknown option '${r}'${t}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(r){if(this._allowExcessArguments)return;let t=this.registeredArguments.length,n=t===1?"":"s",a=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${t} argument${n} but got ${r.length}.`;this.error(a,{code:"commander.excessArguments"})}unknownCommand(){let r=this.args[0],t="";if(this._showSuggestionAfterError){let o=[];this.createHelp().visibleCommands(this).forEach(a=>{o.push(a.name()),a.alias()&&o.push(a.alias())}),t=L_(r,o)}let n=`error: unknown command '${r}'${t}`;this.error(n,{code:"commander.unknownCommand"})}version(r,t,n){if(r===void 0)return this._version;this._version=r,t=t||"-V, --version",n=n||"output the version number";let o=this.createOption(t,n);return this._versionOptionName=o.attributeName(),this._registerOption(o),this.on("option:"+o.name(),()=>{this._outputConfiguration.writeOut(`${r} `),this._exit(0,"commander.version",r)}),this}description(r,t){return r===void 0&&t===void 0?this._description:(this._description=r,t&&(this._argsDescription=t),this)}summary(r){return r===void 0?this._summary:(this._summary=r,this)}alias(r){if(r===void 0)return this._aliases[0];let t=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),r===t._name)throw new Error("Command alias can't be the same as its name");let n=this.parent?._findCommand(r);if(n){let o=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${r}' to command '${this.name()}' as already have command '${o}'`)}return t._aliases.push(r),this}aliases(r){return r===void 0?this._aliases:(r.forEach(t=>this.alias(t)),this)}usage(r){if(r===void 0){if(this._usage)return this._usage;let t=this.registeredArguments.map(n=>SN(n));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?t:[]).join(" ")}return this._usage=r,this}name(r){return r===void 0?this._name:(this._name=r,this)}helpGroup(r){return r===void 0?this._helpGroupHeading??"":(this._helpGroupHeading=r,this)}commandsGroup(r){return r===void 0?this._defaultCommandGroup??"":(this._defaultCommandGroup=r,this)}optionsGroup(r){return r===void 0?this._defaultOptionGroup??"":(this._defaultOptionGroup=r,this)}_initOptionGroup(r){this._defaultOptionGroup&&!r.helpGroupHeading&&r.helpGroup(this._defaultOptionGroup)}_initCommandGroup(r){this._defaultCommandGroup&&!r.helpGroup()&&r.helpGroup(this._defaultCommandGroup)}nameFromFilename(r){return this._name=zt.basename(r,zt.extname(r)),this}executableDir(r){return r===void 0?this._executableDir:(this._executableDir=r,this)}helpInformation(r){let t=this.createHelp(),n=this._getOutputContext(r);t.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let o=t.formatHelp(this,t);return n.hasColors?o:this._outputConfiguration.stripColor(o)}_getOutputContext(r){r=r||{};let t=!!r.error,n,o,a;return t?(n=f=>this._outputConfiguration.writeErr(f),o=this._outputConfiguration.getErrHasColors(),a=this._outputConfiguration.getErrHelpWidth()):(n=f=>this._outputConfiguration.writeOut(f),o=this._outputConfiguration.getOutHasColors(),a=this._outputConfiguration.getOutHelpWidth()),{error:t,write:f=>(o||(f=this._outputConfiguration.stripColor(f)),n(f)),hasColors:o,helpWidth:a}}outputHelp(r){let t;typeof r=="function"&&(t=r,r=void 0);let n=this._getOutputContext(r),o={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(u=>u.emit("beforeAllHelp",o)),this.emit("beforeHelp",o);let a=this.helpInformation({error:n.error});if(t&&(a=t(a),typeof a!="string"&&!Buffer.isBuffer(a)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(a),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",o),this._getCommandAndAncestors().forEach(u=>u.emit("afterAllHelp",o))}helpOption(r,t){return typeof r=="boolean"?(r?(this._helpOption===null&&(this._helpOption=void 0),this._defaultOptionGroup&&this._initOptionGroup(this._getHelpOption())):this._helpOption=null,this):(this._helpOption=this.createOption(r??"-h, --help",t??"display help for command"),(r||t)&&this._initOptionGroup(this._helpOption),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(r){return this._helpOption=r,this._initOptionGroup(r),this}help(r){this.outputHelp(r);let t=Number(me.exitCode??0);t===0&&r&&typeof r!="function"&&r.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(r,t){let n=["beforeAll","before","after","afterAll"];if(!n.includes(r))throw new Error(`Unexpected value for position to addHelpText. Expecting one of '${n.join("', '")}'`);let o=`${r}Help`;return this.on(o,a=>{let u;typeof t=="function"?u=t({error:a.error,command:a.command}):u=t,u&&a.write(`${u} `)}),this}_outputHelpIfRequested(r){let t=this._getHelpOption();t&&r.find(o=>t.is(o))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function k_(e){return e.map(r=>{if(!r.startsWith("--inspect"))return r;let t,n="127.0.0.1",o="9229",a;return(a=r.match(/^(--inspect(-brk)?)$/))!==null?t=a[1]:(a=r.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(t=a[1],/^\d+$/.test(a[3])?o=a[3]:n=a[3]):(a=r.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(t=a[1],n=a[3],o=a[4]),t&&o!=="0"?`${t}=${n}:${parseInt(o)+1}`:r})}function Bc(){if(me.env.NO_COLOR||me.env.FORCE_COLOR==="0"||me.env.FORCE_COLOR==="false")return!1;if(me.env.FORCE_COLOR||me.env.CLICOLOR_FORCE!==void 0)return!0}Wc.Command=Hc;Wc.useColor=Bc});var z_=$(Wr=>{var{Argument:H_}=lu(),{Command:zc}=U_(),{CommanderError:TN,InvalidArgumentError:B_}=os(),{Help:IN}=Mc(),{Option:W_}=Lc();Wr.program=new zc;Wr.createCommand=e=>new zc(e);Wr.createOption=(e,r)=>new W_(e,r);Wr.createArgument=(e,r)=>new H_(e,r);Wr.Command=zc;Wr.Option=W_;Wr.Argument=H_;Wr.Help=IN;Wr.CommanderError=TN;Wr.InvalidArgumentError=B_;Wr.InvalidOptionArgumentError=B_});var us=$(de=>{"use strict";Object.defineProperty(de,"__esModule",{value:!0});de.regexpCode=de.getEsmExportName=de.getProperty=de.safeStringify=de.stringify=de.strConcat=de.addCodeArg=de.str=de._=de.nil=de._Code=de.Name=de.IDENTIFIER=de._CodeOrName=void 0;var ss=class{};de._CodeOrName=ss;de.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var Xn=class extends ss{constructor(r){if(super(),!de.IDENTIFIER.test(r))throw new Error("CodeGen: name must be a valid identifier");this.str=r}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};de.Name=Xn;var zr=class extends ss{constructor(r){super(),this._items=typeof r=="string"?[r]:r}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let r=this._items[0];return r===""||r==='""'}get str(){var r;return(r=this._str)!==null&&r!==void 0?r:this._str=this._items.reduce((t,n)=>`${t}${n}`,"")}get names(){var r;return(r=this._names)!==null&&r!==void 0?r:this._names=this._items.reduce((t,n)=>(n instanceof Xn&&(t[n.str]=(t[n.str]||0)+1),t),{})}};de._Code=zr;de.nil=new zr("");function Y_(e,...r){let t=[e[0]],n=0;for(;n<r.length;)Gc(t,r[n]),t.push(e[++n]);return new zr(t)}de._=Y_;var Vc=new zr("+");function K_(e,...r){let t=[as(e[0])],n=0;for(;n<r.length;)t.push(Vc),Gc(t,r[n]),t.push(Vc,as(e[++n]));return RN(t),new zr(t)}de.str=K_;function Gc(e,r){r instanceof zr?e.push(...r._items):r instanceof Xn?e.push(r):e.push(qN(r))}de.addCodeArg=Gc;function RN(e){let r=1;for(;r<e.length-1;){if(e[r]===Vc){let t=DN(e[r-1],e[r+1]);if(t!==void 0){e.splice(r-1,3,t);continue}e[r++]="+"}r++}}function DN(e,r){if(r==='""')return e;if(e==='""')return r;if(typeof e=="string")return r instanceof Xn||e[e.length-1]!=='"'?void 0:typeof r!="string"?`${e.slice(0,-1)}${r}"`:r[0]==='"'?e.slice(0,-1)+r.slice(1):void 0;if(typeof r=="string"&&r[0]==='"'&&!(e instanceof Xn))return`"${e}${r.slice(1)}`}function MN(e,r){return r.emptyStr()?e:e.emptyStr()?r:K_`${e}${r}`}de.strConcat=MN;function qN(e){return typeof e=="number"||typeof e=="boolean"||e===null?e:as(Array.isArray(e)?e.join(","):e)}function FN(e){return new zr(as(e))}de.stringify=FN;function as(e){return JSON.stringify(e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}de.safeStringify=as;function jN(e){return typeof e=="string"&&de.IDENTIFIER.test(e)?new zr(`.${e}`):Y_`[${e}]`}de.getProperty=jN;function LN(e){if(typeof e=="string"&&de.IDENTIFIER.test(e))return new zr(`${e}`);throw new Error(`CodeGen: invalid export name: ${e}, use explicit $id name mapping`)}de.getEsmExportName=LN;function kN(e){return new zr(e.toString())}de.regexpCode=kN});var Jc=$(gr=>{"use strict";Object.defineProperty(gr,"__esModule",{value:!0});gr.ValueScope=gr.ValueScopeName=gr.Scope=gr.varKinds=gr.UsedValueState=void 0;var mr=us(),Yc=class extends Error{constructor(r){super(`CodeGen: "code" for ${r} not defined`),this.value=r.value}},cu;(function(e){e[e.Started=0]="Started",e[e.Completed=1]="Completed"})(cu||(gr.UsedValueState=cu={}));gr.varKinds={const:new mr.Name("const"),let:new mr.Name("let"),var:new mr.Name("var")};var du=class{constructor({prefixes:r,parent:t}={}){this._names={},this._prefixes=r,this._parent=t}toName(r){return r instanceof mr.Name?r:this.name(r)}name(r){return new mr.Name(this._newName(r))}_newName(r){let t=this._names[r]||this._nameGroup(r);return`${r}${t.index++}`}_nameGroup(r){var t,n;if(!((n=(t=this._parent)===null||t===void 0?void 0:t._prefixes)===null||n===void 0)&&n.has(r)||this._prefixes&&!this._prefixes.has(r))throw new Error(`CodeGen: prefix "${r}" is not allowed in this scope`);return this._names[r]={prefix:r,index:0}}};gr.Scope=du;var hu=class extends mr.Name{constructor(r,t){super(t),this.prefix=r}setValue(r,{property:t,itemIndex:n}){this.value=r,this.scopePath=(0,mr._)`.${new mr.Name(t)}[${n}]`}};gr.ValueScopeName=hu;var UN=(0,mr._)`\n`,Kc=class extends du{constructor(r){super(r),this._values={},this._scope=r.scope,this.opts={...r,_n:r.lines?UN:mr.nil}}get(){return this._scope}name(r){return new hu(r,this._newName(r))}value(r,t){var n;if(t.ref===void 0)throw new Error("CodeGen: ref must be passed in value");let o=this.toName(r),{prefix:a}=o,u=(n=t.key)!==null&&n!==void 0?n:t.ref,f=this._values[a];if(f){let p=f.get(u);if(p)return p}else f=this._values[a]=new Map;f.set(u,o);let c=this._scope[a]||(this._scope[a]=[]),h=c.length;return c[h]=t.ref,o.setValue(t,{property:a,itemIndex:h}),o}getValue(r,t){let n=this._values[r];if(n)return n.get(t)}scopeRefs(r,t=this._values){return this._reduceValues(t,n=>{if(n.scopePath===void 0)throw new Error(`CodeGen: name "${n}" has no value`);return(0,mr._)`${r}${n.scopePath}`})}scopeCode(r=this._values,t,n){return this._reduceValues(r,o=>{if(o.value===void 0)throw new Error(`CodeGen: name "${o}" has no value`);return o.value.code},t,n)}_reduceValues(r,t,n={},o){let a=mr.nil;for(let u in r){let f=r[u];if(!f)continue;let c=n[u]=n[u]||new Map;f.forEach(h=>{if(c.has(h))return;c.set(h,cu.Started);let p=t(h);if(p){let m=this.opts.es5?gr.varKinds.var:gr.varKinds.const;a=(0,mr._)`${a}${m} ${h} = ${p};${this.opts._n}`}else if(p=o?.(h))a=(0,mr._)`${a}${p}${this.opts._n}`;else throw new Yc(h);c.set(h,cu.Completed)})}return a}};gr.ValueScope=Kc});var re=$(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.or=ne.and=ne.not=ne.CodeGen=ne.operators=ne.varKinds=ne.ValueScopeName=ne.ValueScope=ne.Scope=ne.Name=ne.regexpCode=ne.stringify=ne.getProperty=ne.nil=ne.strConcat=ne.str=ne._=void 0;var le=us(),ot=Jc(),bn=us();Object.defineProperty(ne,"_",{enumerable:!0,get:function(){return bn._}});Object.defineProperty(ne,"str",{enumerable:!0,get:function(){return bn.str}});Object.defineProperty(ne,"strConcat",{enumerable:!0,get:function(){return bn.strConcat}});Object.defineProperty(ne,"nil",{enumerable:!0,get:function(){return bn.nil}});Object.defineProperty(ne,"getProperty",{enumerable:!0,get:function(){return bn.getProperty}});Object.defineProperty(ne,"stringify",{enumerable:!0,get:function(){return bn.stringify}});Object.defineProperty(ne,"regexpCode",{enumerable:!0,get:function(){return bn.regexpCode}});Object.defineProperty(ne,"Name",{enumerable:!0,get:function(){return bn.Name}});var _u=Jc();Object.defineProperty(ne,"Scope",{enumerable:!0,get:function(){return _u.Scope}});Object.defineProperty(ne,"ValueScope",{enumerable:!0,get:function(){return _u.ValueScope}});Object.defineProperty(ne,"ValueScopeName",{enumerable:!0,get:function(){return _u.ValueScopeName}});Object.defineProperty(ne,"varKinds",{enumerable:!0,get:function(){return _u.varKinds}});ne.operators={GT:new le._Code(">"),GTE:new le._Code(">="),LT:new le._Code("<"),LTE:new le._Code("<="),EQ:new le._Code("==="),NEQ:new le._Code("!=="),NOT:new le._Code("!"),OR:new le._Code("||"),AND:new le._Code("&&"),ADD:new le._Code("+")};var Vt=class{optimizeNodes(){return this}optimizeNames(r,t){return this}},Zc=class extends Vt{constructor(r,t,n){super(),this.varKind=r,this.name=t,this.rhs=n}render({es5:r,_n:t}){let n=r?ot.varKinds.var:this.varKind,o=this.rhs===void 0?"":` = ${this.rhs}`;return`${n} ${this.name}${o};`+t}optimizeNames(r,t){if(r[this.name.str])return this.rhs&&(this.rhs=Hi(this.rhs,r,t)),this}get names(){return this.rhs instanceof le._CodeOrName?this.rhs.names:{}}},pu=class extends Vt{constructor(r,t,n){super(),this.lhs=r,this.rhs=t,this.sideEffects=n}render({_n:r}){return`${this.lhs} = ${this.rhs};`+r}optimizeNames(r,t){if(!(this.lhs instanceof le.Name&&!r[this.lhs.str]&&!this.sideEffects))return this.rhs=Hi(this.rhs,r,t),this}get names(){let r=this.lhs instanceof le.Name?{}:{...this.lhs.names};return gu(r,this.rhs)}},Xc=class extends pu{constructor(r,t,n,o){super(r,n,o),this.op=t}render({_n:r}){return`${this.lhs} ${this.op}= ${this.rhs};`+r}},Qc=class extends Vt{constructor(r){super(),this.label=r,this.names={}}render({_n:r}){return`${this.label}:`+r}},ed=class extends Vt{constructor(r){super(),this.label=r,this.names={}}render({_n:r}){return`break${this.label?` ${this.label}`:""};`+r}},rd=class extends Vt{constructor(r){super(),this.error=r}render({_n:r}){return`throw ${this.error};`+r}get names(){return this.error.names}},td=class extends Vt{constructor(r){super(),this.code=r}render({_n:r}){return`${this.code};`+r}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(r,t){return this.code=Hi(this.code,r,t),this}get names(){return this.code instanceof le._CodeOrName?this.code.names:{}}},ls=class extends Vt{constructor(r=[]){super(),this.nodes=r}render(r){return this.nodes.reduce((t,n)=>t+n.render(r),"")}optimizeNodes(){let{nodes:r}=this,t=r.length;for(;t--;){let n=r[t].optimizeNodes();Array.isArray(n)?r.splice(t,1,...n):n?r[t]=n:r.splice(t,1)}return r.length>0?this:void 0}optimizeNames(r,t){let{nodes:n}=this,o=n.length;for(;o--;){let a=n[o];a.optimizeNames(r,t)||(HN(r,a.names),n.splice(o,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((r,t)=>ri(r,t.names),{})}},Gt=class extends ls{render(r){return"{"+r._n+super.render(r)+"}"+r._n}},nd=class extends ls{},Ui=class extends Gt{};Ui.kind="else";var Qn=class e extends Gt{constructor(r,t){super(t),this.condition=r}render(r){let t=`if(${this.condition})`+super.render(r);return this.else&&(t+="else "+this.else.render(r)),t}optimizeNodes(){super.optimizeNodes();let r=this.condition;if(r===!0)return this.nodes;let t=this.else;if(t){let n=t.optimizeNodes();t=this.else=Array.isArray(n)?new Ui(n):n}if(t)return r===!1?t instanceof e?t:t.nodes:thi