UNPKG

@mojito-inc/loyalty-cli

Version:

CLI tool for managing Mojito's Loyalty operations

3 lines (2 loc) 39.1 kB
#!/usr/bin/env node var e=require("events"),t=require("child_process"),n=require("path"),i=require("fs");function r(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var o,s,a=/*#__PURE__*/r(e),h=/*#__PURE__*/r(t),c=/*#__PURE__*/r(n),l=/*#__PURE__*/r(i),u=(o=function(e,t){const n=a.default.EventEmitter;class i{constructor(){this.helpWidth=void 0,this.sortSubcommands=!1,this.sortOptions=!1}visibleCommands(e){const t=e.commands.filter(e=>!e._hidden);if(e._hasImplicitHelpCommand()){const n=e._helpCommandnameAndArgs.split(/ +/),i=e.createCommand(n.shift()).helpOption(!1);i.description(e._helpCommandDescription),i._parseExpectedArgs(n),t.push(i)}return this.sortSubcommands&&t.sort((e,t)=>e.name().localeCompare(t.name())),t}visibleOptions(e){const t=e.options.filter(e=>!e.hidden),n=e._hasHelpOption&&e._helpShortFlag&&!e._findOption(e._helpShortFlag),i=e._hasHelpOption&&!e._findOption(e._helpLongFlag);if(n||i){let r;r=e.createOption(n?i?e._helpFlags:e._helpShortFlag:e._helpLongFlag,e._helpDescription),t.push(r)}if(this.sortOptions){const e=e=>e.short?e.short.replace(/^-/,""):e.long.replace(/^--/,"");t.sort((t,n)=>e(t).localeCompare(e(n)))}return t}visibleArguments(e){return e._argsDescription&&e._args.length?e._args.map(t=>({term:t.name,description:e._argsDescription[t.name]||""}),0):[]}subcommandTerm(e){const t=e._args.map(e=>m(e)).join(" ");return e._name+(e._aliases[0]?"|"+e._aliases[0]:"")+(e.options.length?" [options]":"")+(t?" "+t:"")}optionTerm(e){return e.flags}longestSubcommandTermLength(e,t){return t.visibleCommands(e).reduce((e,n)=>Math.max(e,t.subcommandTerm(n).length),0)}longestOptionTermLength(e,t){return t.visibleOptions(e).reduce((e,n)=>Math.max(e,t.optionTerm(n).length),0)}longestArgumentTermLength(e,t){return t.visibleArguments(e).reduce((e,t)=>Math.max(e,t.term.length),0)}commandUsage(e){let t=e._name;e._aliases[0]&&(t=t+"|"+e._aliases[0]);let n="";for(let t=e.parent;t;t=t.parent)n=t.name()+" "+n;return n+t+" "+e.usage()}commandDescription(e){return e.description()}subcommandDescription(e){return e.description()}optionDescription(e){if(e.negate)return e.description;const t=[];return e.argChoices&&t.push(`choices: ${e.argChoices.map(e=>JSON.stringify(e)).join(", ")}`),void 0!==e.defaultValue&&t.push(`default: ${e.defaultValueDescription||JSON.stringify(e.defaultValue)}`),t.length>0?`${e.description} (${t.join(", ")})`:e.description}formatHelp(e,t){const n=t.padWidth(e,t),i=t.helpWidth||80;function r(e,r){if(r){const o=`${e.padEnd(n+2)}${r}`;return t.wrap(o,i-2,n+2)}return e}function o(e){return e.join("\n").replace(/^/gm," ".repeat(2))}let s=[`Usage: ${t.commandUsage(e)}`,""];const a=t.commandDescription(e);a.length>0&&(s=s.concat([a,""]));const h=t.visibleArguments(e).map(e=>r(e.term,e.description));h.length>0&&(s=s.concat(["Arguments:",o(h),""]));const c=t.visibleOptions(e).map(e=>r(t.optionTerm(e),t.optionDescription(e)));c.length>0&&(s=s.concat(["Options:",o(c),""]));const l=t.visibleCommands(e).map(e=>r(t.subcommandTerm(e),t.subcommandDescription(e)));return l.length>0&&(s=s.concat(["Commands:",o(l),""])),s.join("\n")}padWidth(e,t){return Math.max(t.longestOptionTermLength(e,t),t.longestSubcommandTermLength(e,t),t.longestArgumentTermLength(e,t))}wrap(e,t,n,i=40){if(e.match(/[\n]\s+/))return e;const r=t-n;if(r<i)return e;const o=e.substr(0,n),s=e.substr(n),a=" ".repeat(n),h=new RegExp(".{1,"+(r-1)+"}([\\s​]|$)|[^\\s​]+?([\\s​]|$)","g");return o+(s.match(h)||[]).map((e,t)=>("\n"===e.slice(-1)&&(e=e.slice(0,e.length-1)),(t>0?a:"")+e.trimRight())).join("\n")}}class r{constructor(e,t){this.flags=e,this.description=t||"",this.required=e.includes("<"),this.optional=e.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(e),this.mandatory=!1;const n=d(e);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.parseArg=void 0,this.hidden=!1,this.argChoices=void 0}default(e,t){return this.defaultValue=e,this.defaultValueDescription=t,this}argParser(e){return this.parseArg=e,this}makeOptionMandatory(e=!0){return this.mandatory=!!e,this}hideHelp(e=!0){return this.hidden=!!e,this}_concatValue(e,t){return t!==this.defaultValue&&Array.isArray(t)?t.concat(e):[e]}choices(e){return this.argChoices=e,this.parseArg=(t,n)=>{if(!e.includes(t))throw new s(`Allowed choices are ${e.join(", ")}.`);return this.variadic?this._concatValue(t,n):t},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.name().replace(/^no-/,"").split("-").reduce((e,t)=>e+t[0].toUpperCase()+t.slice(1))}is(e){return this.short===e||this.long===e}}class o extends Error{constructor(e,t,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=t,this.exitCode=e,this.nestedError=void 0}}class s extends o{constructor(e){super(1,"commander.invalidOptionArgument",e),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}}class u extends n{constructor(e){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!0,this._args=[],this.rawArgs=null,this._scriptPath=null,this._name=e||"",this._optionValues={},this._storeOptionsAsProperties=!1,this._actionResults=[],this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._outputConfiguration={writeOut:e=>process.stdout.write(e),writeErr:e=>process.stderr.write(e),getOutHelpWidth:()=>process.stdout.isTTY?process.stdout.columns:void 0,getErrHelpWidth:()=>process.stderr.isTTY?process.stderr.columns:void 0,outputError:(e,t)=>t(e)},this._hidden=!1,this._hasHelpOption=!0,this._helpFlags="-h, --help",this._helpDescription="display help for command",this._helpShortFlag="-h",this._helpLongFlag="--help",this._addImplicitHelpCommand=void 0,this._helpCommandName="help",this._helpCommandnameAndArgs="help [command]",this._helpCommandDescription="display help for command",this._helpConfiguration={}}command(e,t,n){let i=t,r=n;"object"==typeof i&&null!==i&&(r=i,i=null),r=r||{};const o=e.split(/ +/),s=this.createCommand(o.shift());return i&&(s.description(i),s._executableHandler=!0),r.isDefault&&(this._defaultCommandName=s._name),s._outputConfiguration=this._outputConfiguration,s._hidden=!(!r.noHelp&&!r.hidden),s._hasHelpOption=this._hasHelpOption,s._helpFlags=this._helpFlags,s._helpDescription=this._helpDescription,s._helpShortFlag=this._helpShortFlag,s._helpLongFlag=this._helpLongFlag,s._helpCommandName=this._helpCommandName,s._helpCommandnameAndArgs=this._helpCommandnameAndArgs,s._helpCommandDescription=this._helpCommandDescription,s._helpConfiguration=this._helpConfiguration,s._exitCallback=this._exitCallback,s._storeOptionsAsProperties=this._storeOptionsAsProperties,s._combineFlagAndOptionalValue=this._combineFlagAndOptionalValue,s._allowExcessArguments=this._allowExcessArguments,s._enablePositionalOptions=this._enablePositionalOptions,s._executableFile=r.executableFile||null,this.commands.push(s),s._parseExpectedArgs(o),s.parent=this,i?this:s}createCommand(e){return new u(e)}createHelp(){return Object.assign(new i,this.configureHelp())}configureHelp(e){return void 0===e?this._helpConfiguration:(this._helpConfiguration=e,this)}configureOutput(e){return void 0===e?this._outputConfiguration:(Object.assign(this._outputConfiguration,e),this)}addCommand(e,t){if(!e._name)throw new Error("Command passed to .addCommand() must have a name");return function e(t){t.forEach(t=>{if(t._executableHandler&&!t._executableFile)throw new Error(`Must specify executableFile for deeply nested executable: ${t.name()}`);e(t.commands)})}(e.commands),(t=t||{}).isDefault&&(this._defaultCommandName=e._name),(t.noHelp||t.hidden)&&(e._hidden=!0),this.commands.push(e),e.parent=this,this}arguments(e){return this._parseExpectedArgs(e.split(/ +/))}addHelpCommand(e,t){return!1===e?this._addImplicitHelpCommand=!1:(this._addImplicitHelpCommand=!0,"string"==typeof e&&(this._helpCommandName=e.split(" ")[0],this._helpCommandnameAndArgs=e),this._helpCommandDescription=t||this._helpCommandDescription),this}_hasImplicitHelpCommand(){return void 0===this._addImplicitHelpCommand?this.commands.length&&!this._actionHandler&&!this._findCommand("help"):this._addImplicitHelpCommand}_parseExpectedArgs(e){if(e.length)return e.forEach(e=>{const t={required:!1,name:"",variadic:!1};switch(e[0]){case"<":t.required=!0,t.name=e.slice(1,-1);break;case"[":t.name=e.slice(1,-1)}t.name.length>3&&"..."===t.name.slice(-3)&&(t.variadic=!0,t.name=t.name.slice(0,-3)),t.name&&this._args.push(t)}),this._args.forEach((e,t)=>{if(e.variadic&&t<this._args.length-1)throw new Error(`only the last argument can be variadic '${e.name}'`)}),this}exitOverride(e){return this._exitCallback=e||(e=>{if("commander.executeSubCommandAsync"!==e.code)throw e}),this}_exit(e,t,n){this._exitCallback&&this._exitCallback(new o(e,t,n)),process.exit(e)}action(e){return this._actionHandler=t=>{const n=this._args.length,i=t.slice(0,n);i[n]=this._storeOptionsAsProperties?this:this.opts(),i.push(this);const r=e.apply(this,i);let o=this;for(;o.parent;)o=o.parent;o._actionResults.push(r)},this}createOption(e,t){return new r(e,t)}addOption(e){const t=e.name(),n=e.attributeName();let i=e.defaultValue;if(e.negate||e.optional||e.required||"boolean"==typeof i){if(e.negate){const t=e.long.replace(/^--no-/,"--");i=!this._findOption(t)||this._getOptionValue(n)}void 0!==i&&this._setOptionValue(n,i)}return this.options.push(e),this.on("option:"+t,t=>{const r=this._getOptionValue(n);if(null!==t&&e.parseArg)try{t=e.parseArg(t,void 0===r?i:r)}catch(n){throw"commander.invalidOptionArgument"===n.code&&this._displayError(n.exitCode,n.code,`error: option '${e.flags}' argument '${t}' is invalid. ${n.message}`),n}else null!==t&&e.variadic&&(t=e._concatValue(t,r));"boolean"==typeof r||void 0===r?this._setOptionValue(n,null==t?!e.negate&&(i||!0):t):null!==t&&this._setOptionValue(n,!e.negate&&t)}),this}_optionEx(e,t,n,i,r){const o=this.createOption(t,n);if(o.makeOptionMandatory(!!e.mandatory),"function"==typeof i)o.default(r).argParser(i);else if(i instanceof RegExp){const e=i;i=(t,n)=>{const i=e.exec(t);return i?i[0]:n},o.default(r).argParser(i)}else o.default(i);return this.addOption(o)}option(e,t,n,i){return this._optionEx({},e,t,n,i)}requiredOption(e,t,n,i){return this._optionEx({mandatory:!0},e,t,n,i)}combineFlagAndOptionalValue(e=!0){return this._combineFlagAndOptionalValue=!!e,this}allowUnknownOption(e=!0){return this._allowUnknownOption=!!e,this}allowExcessArguments(e=!0){return this._allowExcessArguments=!!e,this}enablePositionalOptions(e=!0){return this._enablePositionalOptions=!!e,this}passThroughOptions(e=!0){if(this._passThroughOptions=!!e,this.parent&&e&&!this.parent._enablePositionalOptions)throw new Error("passThroughOptions can not be used without turning on enablePositionalOptions for parent command(s)");return this}storeOptionsAsProperties(e=!0){if(this._storeOptionsAsProperties=!!e,this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");return this}_setOptionValue(e,t){this._storeOptionsAsProperties?this[e]=t:this._optionValues[e]=t}_getOptionValue(e){return this._storeOptionsAsProperties?this[e]:this._optionValues[e]}parse(e,t){if(void 0!==e&&!Array.isArray(e))throw new Error("first parameter to parse must be array or undefined");let n;switch(t=t||{},void 0===e&&(e=process.argv,process.versions&&process.versions.electron&&(t.from="electron")),this.rawArgs=e.slice(),t.from){case void 0:case"node":this._scriptPath=e[1],n=e.slice(2);break;case"electron":process.defaultApp?(this._scriptPath=e[1],n=e.slice(2)):n=e.slice(1);break;case"user":n=e.slice(0);break;default:throw new Error(`unexpected parse option { from: '${t.from}' }`)}return!this._scriptPath&&require.main&&(this._scriptPath=require.main.filename),this._name=this._name||this._scriptPath&&c.default.basename(this._scriptPath,c.default.extname(this._scriptPath)),this._parseCommand([],n),this}parseAsync(e,t){return this.parse(e,t),Promise.all(this._actionResults).then(()=>this)}_executeSubCommand(e,t){t=t.slice();let n=!1;const i=[".js",".ts",".tsx",".mjs",".cjs"];this._checkForMissingMandatoryOptions();let r,s=this._scriptPath;!s&&require.main&&(s=require.main.filename);try{const e=l.default.realpathSync(s);r=c.default.dirname(e)}catch(e){r="."}let a=c.default.basename(s,c.default.extname(s))+"-"+e._name;e._executableFile&&(a=e._executableFile);const u=c.default.join(r,a);let p;l.default.existsSync(u)?a=u:i.forEach(e=>{l.default.existsSync(`${u}${e}`)&&(a=`${u}${e}`)}),n=i.includes(c.default.extname(a)),"win32"!==process.platform?n?(t.unshift(a),t=f(process.execArgv).concat(t),p=h.default.spawn(process.argv[0],t,{stdio:"inherit"})):p=h.default.spawn(a,t,{stdio:"inherit"}):(t.unshift(a),t=f(process.execArgv).concat(t),p=h.default.spawn(process.execPath,t,{stdio:"inherit"})),["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(e=>{process.on(e,()=>{!1===p.killed&&null===p.exitCode&&p.kill(e)})});const m=this._exitCallback;p.on("close",m?()=>{m(new o(process.exitCode||0,"commander.executeSubCommandAsync","(close)"))}:process.exit.bind(process)),p.on("error",t=>{if("ENOENT"===t.code)throw new Error(`'${a}' does not exist\n - if '${e._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead\n - if the default executable name is not suitable, use the executableFile option to supply a custom name`);if("EACCES"===t.code)throw new Error(`'${a}' not executable`);if(m){const e=new o(1,"commander.executeSubCommandAsync","(error)");e.nestedError=t,m(e)}else process.exit(1)}),this.runningCommand=p}_dispatchSubcommand(e,t,n){const i=this._findCommand(e);i||this.help({error:!0}),i._executableHandler?this._executeSubCommand(i,t.concat(n)):i._parseCommand(t,n)}_parseCommand(e,t){const n=this.parseOptions(t);if(e=e.concat(n.operands),this.args=e.concat(t=n.unknown),e&&this._findCommand(e[0]))this._dispatchSubcommand(e[0],e.slice(1),t);else if(this._hasImplicitHelpCommand()&&e[0]===this._helpCommandName)1===e.length?this.help():this._dispatchSubcommand(e[1],[],[this._helpLongFlag]);else if(this._defaultCommandName)p(this,t),this._dispatchSubcommand(this._defaultCommandName,e,t);else{!this.commands.length||0!==this.args.length||this._actionHandler||this._defaultCommandName||this.help({error:!0}),p(this,n.unknown),this._checkForMissingMandatoryOptions();const i=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},r=`command:${this.name()}`;if(this._actionHandler){i();const n=this.args.slice();this._args.forEach((e,t)=>{e.required&&null==n[t]?this.missingArgument(e.name):e.variadic&&(n[t]=n.splice(t),n.length=Math.min(t+1,n.length))}),n.length>this._args.length&&this._excessArguments(n),this._actionHandler(n),this.parent&&this.parent.emit(r,e,t)}else this.parent&&this.parent.listenerCount(r)?(i(),this.parent.emit(r,e,t)):e.length?this._findCommand("*")?this._dispatchSubcommand("*",e,t):this.listenerCount("command:*")?this.emit("command:*",e,t):this.commands.length?this.unknownCommand():i():this.commands.length?this.help({error:!0}):i()}}_findCommand(e){if(e)return this.commands.find(t=>t._name===e||t._aliases.includes(e))}_findOption(e){return this.options.find(t=>t.is(e))}_checkForMissingMandatoryOptions(){for(let e=this;e;e=e.parent)e.options.forEach(t=>{t.mandatory&&void 0===e._getOptionValue(t.attributeName())&&e.missingMandatoryOptionValue(t)})}parseOptions(e){const t=[],n=[];let i=t;const r=e.slice();function o(e){return e.length>1&&"-"===e[0]}let s=null;for(;r.length;){const e=r.shift();if("--"===e){i===n&&i.push(e),i.push(...r);break}if(!s||o(e)){if(s=null,o(e)){const t=this._findOption(e);if(t){if(t.required){const e=r.shift();void 0===e&&this.optionMissingArgument(t),this.emit(`option:${t.name()}`,e)}else if(t.optional){let e=null;r.length>0&&!o(r[0])&&(e=r.shift()),this.emit(`option:${t.name()}`,e)}else this.emit(`option:${t.name()}`);s=t.variadic?t:null;continue}}if(e.length>2&&"-"===e[0]&&"-"!==e[1]){const t=this._findOption(`-${e[1]}`);if(t){t.required||t.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${t.name()}`,e.slice(2)):(this.emit(`option:${t.name()}`),r.unshift(`-${e.slice(2)}`));continue}}if(/^--[^=]+=/.test(e)){const t=e.indexOf("="),n=this._findOption(e.slice(0,t));if(n&&(n.required||n.optional)){this.emit(`option:${n.name()}`,e.slice(t+1));continue}}if(o(e)&&(i=n),(this._enablePositionalOptions||this._passThroughOptions)&&0===t.length&&0===n.length){if(this._findCommand(e)){t.push(e),r.length>0&&n.push(...r);break}if(e===this._helpCommandName&&this._hasImplicitHelpCommand()){t.push(e),r.length>0&&t.push(...r);break}if(this._defaultCommandName){n.push(e),r.length>0&&n.push(...r);break}}if(this._passThroughOptions){i.push(e),r.length>0&&i.push(...r);break}i.push(e)}else this.emit(`option:${s.name()}`,e)}return{operands:t,unknown:n}}opts(){if(this._storeOptionsAsProperties){const e={},t=this.options.length;for(let n=0;n<t;n++){const t=this.options[n].attributeName();e[t]=t===this._versionOptionName?this._version:this[t]}return e}return this._optionValues}_displayError(e,t,n){this._outputConfiguration.outputError(`${n}\n`,this._outputConfiguration.writeErr),this._exit(e,t,n)}missingArgument(e){this._displayError(1,"commander.missingArgument",`error: missing required argument '${e}'`)}optionMissingArgument(e){this._displayError(1,"commander.optionMissingArgument",`error: option '${e.flags}' argument missing`)}missingMandatoryOptionValue(e){this._displayError(1,"commander.missingMandatoryOptionValue",`error: required option '${e.flags}' not specified`)}unknownOption(e){this._allowUnknownOption||this._displayError(1,"commander.unknownOption",`error: unknown option '${e}'`)}_excessArguments(e){if(this._allowExcessArguments)return;const t=this._args.length,n=1===t?"":"s",i=this.parent?` for '${this.name()}'`:"";this._displayError(1,"commander.excessArguments",`error: too many arguments${i}. Expected ${t} argument${n} but got ${e.length}.`)}unknownCommand(){const e=[this.name()];for(let t=this.parent;t;t=t.parent)e.unshift(t.name());const t=e.join(" ");this._displayError(1,"commander.unknownCommand",`error: unknown command '${this.args[0]}'.`+(this._hasHelpOption?` See '${t} ${this._helpLongFlag}'.`:""))}version(e,t,n){if(void 0===e)return this._version;this._version=e;const i=this.createOption(t=t||"-V, --version",n=n||"output the version number");return this._versionOptionName=i.attributeName(),this.options.push(i),this.on("option:"+i.name(),()=>{this._outputConfiguration.writeOut(`${e}\n`),this._exit(0,"commander.version",e)}),this}description(e,t){return void 0===e&&void 0===t?this._description:(this._description=e,this._argsDescription=t,this)}alias(e){if(void 0===e)return this._aliases[0];let t=this;if(0!==this.commands.length&&this.commands[this.commands.length-1]._executableHandler&&(t=this.commands[this.commands.length-1]),e===t._name)throw new Error("Command alias can't be the same as its name");return t._aliases.push(e),this}aliases(e){return void 0===e?this._aliases:(e.forEach(e=>this.alias(e)),this)}usage(e){if(void 0===e){if(this._usage)return this._usage;const e=this._args.map(e=>m(e));return[].concat(this.options.length||this._hasHelpOption?"[options]":[],this.commands.length?"[command]":[],this._args.length?e:[]).join(" ")}return this._usage=e,this}name(e){return void 0===e?this._name:(this._name=e,this)}helpInformation(e){const t=this.createHelp();return void 0===t.helpWidth&&(t.helpWidth=e&&e.error?this._outputConfiguration.getErrHelpWidth():this._outputConfiguration.getOutHelpWidth()),t.formatHelp(this,t)}_getHelpContext(e){const t={error:!!(e=e||{}).error};let n;return n=t.error?e=>this._outputConfiguration.writeErr(e):e=>this._outputConfiguration.writeOut(e),t.write=e.write||n,t.command=this,t}outputHelp(e){let t;"function"==typeof e&&(t=e,e=void 0);const n=this._getHelpContext(e),i=[];let r=this;for(;r;)i.push(r),r=r.parent;i.slice().reverse().forEach(e=>e.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let o=this.helpInformation(n);if(t&&(o=t(o),"string"!=typeof o&&!Buffer.isBuffer(o)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(o),this.emit(this._helpLongFlag),this.emit("afterHelp",n),i.forEach(e=>e.emit("afterAllHelp",n))}helpOption(e,t){if("boolean"==typeof e)return this._hasHelpOption=e,this;this._helpFlags=e||this._helpFlags,this._helpDescription=t||this._helpDescription;const n=d(this._helpFlags);return this._helpShortFlag=n.shortFlag,this._helpLongFlag=n.longFlag,this}help(e){this.outputHelp(e);let t=process.exitCode||0;0===t&&e&&"function"!=typeof e&&e.error&&(t=1),this._exit(t,"commander.help","(outputHelp)")}addHelpText(e,t){const n=["beforeAll","before","after","afterAll"];if(!n.includes(e))throw new Error(`Unexpected value for position to addHelpText.\nExpecting one of '${n.join("', '")}'`);return this.on(`${e}Help`,e=>{let n;n="function"==typeof t?t({error:e.error,command:e.command}):t,n&&e.write(`${n}\n`)}),this}}function p(e,t){e._hasHelpOption&&t.find(t=>t===e._helpLongFlag||t===e._helpShortFlag)&&(e.outputHelp(),e._exit(0,"commander.helpDisplayed","(outputHelp)"))}function m(e){const t=e.name+(!0===e.variadic?"...":"");return e.required?"<"+t+">":"["+t+"]"}function d(e){let t,n;const i=e.split(/[ |,]+/);return i.length>1&&!/^[[<]/.test(i[1])&&(t=i.shift()),n=i.shift(),!t&&/^-[^-]$/.test(n)&&(t=n,n=void 0),{shortFlag:t,longFlag:n}}function f(e){return e.map(e=>{if(!e.startsWith("--inspect"))return e;let t,n,i="127.0.0.1",r="9229";return null!==(n=e.match(/^(--inspect(-brk)?)$/))?t=n[1]:null!==(n=e.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))?(t=n[1],/^\d+$/.test(n[3])?r=n[3]:i=n[3]):null!==(n=e.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))&&(t=n[1],i=n[3],r=n[4]),t&&"0"!==r?`${t}=${i}:${parseInt(r)+1}`:e})}(t=e.exports=new u).program=t,t.Command=u,t.Option=r,t.CommanderError=o,t.InvalidOptionArgumentError=s,t.Help=i},o(s={exports:{}},s.exports),s.exports);function p(e,t){console.error(e+":",t)}function m(e){return""!==e&&/^[A-Za-z0-9-_]+$/.test(e)}function d(e){return/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}var f={ENV_URLS:{prod:"https://loyalty-api.mojito.xyz",sandbox:"https://loyalty-api-sandbox.mojito.xyz",staging:"https://loyalty-api-stg.mojito.xyz",dev:"https://loyalty-api-dev.mojito.xyz"},Referer:"https://loyaltydocs.getmojito.com/"};function g(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var _,v,y,w,A,E,b,I=function(e,t,n){try{var i=n.getApiKey();if(!i)throw new Error("API Key is not set. Authorization required.");var r=f.ENV_URLS[n.getEnv()]||f.ENV_URLS.dev;return Promise.resolve(g(function(){return Promise.resolve(fetch(r+"/"+e,{method:"POST",headers:{Accept:"application/json","Content-Type":"application/json",Referer:f.Referer,"x-api-key":i},body:JSON.stringify(t)})).then(function(e){if(!e.ok)throw new Error(""+e.statusText);return e.json()})},function(e){throw new Error(""+e)}))}catch(e){return Promise.reject(e)}},P=function(e,t){try{var n=t.getApiKey();if(!n)throw new Error("API Key is not set. Authorization required.");var i=f.ENV_URLS[t.getEnv()]||f.ENV_URLS.dev;return Promise.resolve(g(function(){return Promise.resolve(fetch(i+"/"+e,{method:"GET",headers:{Accept:"application/json","Content-Type":"application/json",Referer:f.Referer,"x-api-key":n}})).then(function(e){if(!e.ok)throw new Error(""+e.statusText);return e.json()})},function(e){throw new Error(""+e)}))}catch(e){return Promise.reject(e)}},C=/*#__PURE__*/function(){function e(e){this.jwtToken=void 0,this.apiKey=void 0,this.env=void 0,this.jwtToken=null,this.apiKey=null,this.env=e}var t=e.prototype;return t.setJWT=function(e){if(function(e){return/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+$/.test(e)}(e))try{this.jwtToken=e,console.log("JWT Token is valid and set.")}catch(e){p("JWT Authorization Failed",e)}else console.error("Invalid JWT Token format.")},t.getJWT=function(){return this.jwtToken},t.attachJWT=function(e){if(void 0===e&&(e={}),!this.jwtToken)throw new Error("JWT Token is not set.");return e.Authorization="Bearer "+this.jwtToken,e},t.setApiKey=function(e){if(function(e){return/^.{40}$/.test(e)}(e))try{this.apiKey=e,console.log("API Key is valid and set.")}catch(e){p("API Key Authorization Failed",e)}else console.error("Invalid API Key format.")},t.getApiKey=function(){return this.apiKey},t.getEnv=function(){return this.env},t.attachApiKey=function(e){if(void 0===e&&(e={}),!this.apiKey)throw new Error("API Key is not set.");return e["x-api-key"]=this.apiKey,e},t.fetchSignMessage=function(e,t){try{if(!m(e))throw new Error("Invalid User Reference. It must be a non-empty alphanumeric string.");return Promise.resolve(P("wallet/signature?wallet_address="+e,t))}catch(e){return Promise.reject(e)}},t.generateJWT=function(e,t,n,i){try{if(!m(e))throw new Error("Invalid User Reference. It must be a non-empty alphanumeric string.");var r=i.getEnv(),o="sui-mainnet";return r in["dev","staging","sandbox"]&&(o="sui-testnet"),Promise.resolve(I("user/login",{wallet_address:e,signature:t,chain:o,message:n},i))}catch(e){return Promise.reject(e)}},e}(),O=/*#__PURE__*/function(){function e(){}return e.prototype.initiateClaim=function(e,t,n){try{if(!d(e))throw new Error("Invalid Mission ID format. It should be a valid UUID.");if(!m(t))throw new Error("Invalid User Reference. It must be a non-empty alphanumeric string.");return Promise.resolve(I("mission/claim",{mission_id:e,user_reference:t},n))}catch(e){return Promise.reject(e)}},e}(),x=/*#__PURE__*/function(){function e(){}return e.prototype.initiateReward=function(e,t,n,i){try{if(!d(e))throw new Error("Invalid Reward ID format. It should be a valid UUID.");if(!m(t))throw new Error("Invalid User Reference. It must be a non-empty alphanumeric string.");if(!n||"string"!=typeof n)throw new Error("Invalid Wallet Address. It must be a non-empty string.");return Promise.resolve(I("partners/reward-redeem",{reward_id:e,user_reference:t,wallet_address:n},i))}catch(e){return Promise.reject(e)}},e}();!function(e){e.AVAILABLE="AVAILABLE",e.COMPLETED="COMPLETED"}(_||(_={})),function(e){e.CREATED_AT="created_at",e.NAME="name",e.AWARD_POINTS="award_points"}(v||(v={})),function(e){e.ASC="asc",e.DESC="desc"}(y||(y={})),function(e){e.CURRENT="CURRENT",e.COMPLETED="COMPLETED"}(w||(w={})),function(e){e.CREATED_AT="created_at",e.NAME="name",e.REWARD_COST_POINTS="reward_cost_points",e.REWARD_TOKENS_AWARDED="reward_tokens_awarded",e.REWARD_TOKEN_ID="reward_token_id",e.TYPE="type",e.REWARD_COST_TYPE="reward_cost_type"}(A||(A={})),function(e){e.ONE_DAY="1D",e.SEVEN_DAYS="7D",e.THIRTY_DAYS="30D",e.ALL_TIME="ALLTIME"}(E||(E={})),function(e){e.POINTS="Points",e.MISSIONS="Missions"}(b||(b={}));var T=/*#__PURE__*/function(){function e(){}var t=e.prototype;return t.getMissions=function(e,t,n,i,r,o,s,a,h){void 0===i&&(i=""),void 0===s&&(s=10),void 0===a&&(a=0);try{if(void 0===n&&(n=_.AVAILABLE),void 0===r&&(r=v.CREATED_AT),void 0===o&&(o=y.DESC),!m(t))throw new Error("Invalid User Reference. It must be a non-empty alphanumeric string.");if(i&&!d(i))throw new Error("Invalid Mission ID format. It should be a valid UUID.");return Promise.resolve(P(e+"/user/missions?status="+n+"&user_reference="+t+"&mission_id="+i+"&sort_by="+r+"&order="+o+"&limit="+s+"&offset="+a,h))}catch(e){return Promise.reject(e)}},t.getUserCredits=function(e,t,n){try{if(!m(t))throw new Error("Invalid User Reference. It must be a non-empty alphanumeric string.");return Promise.resolve(P(e+"/user/balance?user_reference="+t,n))}catch(e){return Promise.reject(e)}},t.getClaimStatus=function(e,t,n,i,r){try{if(!d(t))throw new Error("Invalid Mission ID format. It should be a valid UUID.");if(!d(i))throw new Error("Invalid Claim ID format. It should be a valid UUID.");if(!m(n))throw new Error("Invalid User Reference. It must be a non-empty alphanumeric string.");return Promise.resolve(P(e+"/user/mission/"+t+"/status?user_reference="+n+"&claim_id="+i,r))}catch(e){return Promise.reject(e)}},t.getRewards=function(e,t,n,i,r,o,s,a){void 0===o&&(o=10),void 0===s&&(s=0);try{if(void 0===n&&(n=w.CURRENT),void 0===i&&(i=A.CREATED_AT),void 0===r&&(r=y.DESC),!m(t))throw new Error("Invalid User Reference. It must be a non-empty alphanumeric string.");return Promise.resolve(P(e+"/user/reward?status="+n+"&user_reference="+t+"&sort_by="+i+"&order="+r+"&limit="+o+"&offset="+s,a))}catch(e){return Promise.reject(e)}},t.getRedeemStatus=function(e,t,n,i,r){try{if(!d(t))throw new Error("Invalid Reward ID format. It should be a valid UUID.");if(!d(i))throw new Error("Invalid Redeem ID format. It should be a valid UUID.");if(!m(n))throw new Error("Invalid User Reference. It must be a non-empty alphanumeric string.");return Promise.resolve(P(e+"/user/redeem/"+t+"/status?user_reference="+n+"&redeem_id="+i,r))}catch(e){return Promise.reject(e)}},t.fetchReward=function(e,t){try{if(!d(e))throw new Error("Invalid Reward ID format. It should be a valid UUID.");return Promise.resolve(P("reward/"+e,t))}catch(e){return Promise.reject(e)}},t.fetchMission=function(e,t){try{if(!d(e))throw new Error("Invalid Mission ID format. It should be a valid UUID.");return Promise.resolve(P("mission/"+e,t))}catch(e){return Promise.reject(e)}},e}(),K=/*#__PURE__*/function(){function e(){}var t=e.prototype;return t.getLeaderboard=function(e,t,n,i,r,o){void 0===i&&(i=10),void 0===r&&(r=0);try{return void 0===t&&(t=b.POINTS),void 0===n&&(n=E.ALL_TIME),Promise.resolve(P(e+"/leaderboard?sort="+t+"&date-range="+n+"&limit="+i+"&offset="+r,o))}catch(e){return Promise.reject(e)}},t.getTransactions=function(e,t,n,i,r,o){void 0===i&&(i=10),void 0===r&&(r=0);try{if(void 0===n&&(n=E.ALL_TIME),!m(t))throw new Error("Invalid User Reference. It must be a non-empty alphanumeric string.");return Promise.resolve(P(e+"/user/transaction-history?user_reference="+t+"&date_range="+n+"&limit="+i+"&offset="+r,o))}catch(e){return Promise.reject(e)}},e}();function D(e,t){try{var n=e()}catch(e){return t(e)}return n&&n.then?n.then(void 0,t):n}var R=new u.Command,S=new function(e){this.auth=void 0,this.claim=void 0,this.redemption=void 0,this.admin=void 0,this.wallet=void 0,this.auth=new C(e),this.claim=new O,this.redemption=new x,this.admin=new T,this.wallet=new K}(R.opts().env);R.name("moj-loyalty-cli").description("A CLI tool for Moj Loyalty authentication").version("1.0.0"),R.option("-e, --env <env>","Specify environment: dev, staging,sandbox or prod","prod"),R.command("fetchSignMessage").description("Fetch the sign message for authentication").arguments("<walletAddress>").option("-k, --apiKey <apiKey>","API Key").action(function(e,t){try{var n=D(function(){return Promise.resolve(S.auth.setApiKey(t.apiKey)).then(function(){return Promise.resolve(S.auth.fetchSignMessage(e,S.auth)).then(function(e){console.log("Fetched Signature Message:",e)})})},function(e){console.error("Error fetching sign message:",e)});return Promise.resolve(n&&n.then?n.then(function(){}):void 0)}catch(e){return Promise.reject(e)}}),R.command("generateJWT").description("Generate a JWT token using a signature").arguments("<walletAddress> <signature> <message>").option("-k, --apiKey <apiKey>","API Key").action(function(e,t,n,i){try{var r=D(function(){return Promise.resolve(S.auth.setApiKey(i.apiKey)).then(function(){return Promise.resolve(S.auth.generateJWT(e,t,n,S.auth)).then(function(e){console.log("Generated JWT:",e)})})},function(e){console.error("Error generating JWT:",e)});return Promise.resolve(r&&r.then?r.then(function(){}):void 0)}catch(e){return Promise.reject(e)}}),R.command("getMissions").description("Fetch missions for a user").arguments("<tenantId> <user_reference>").option("-k, --apiKey <apiKey>","API Key").option("-s, --status <status>","Mission status","AVAILABLE").option("-m, --missionId <missionId>","Mission ID","").option("-sb, --sortBy <sortBy>","Sort by field","created_at").option("-o, --order <order>","Sort order","desc").option("-l, --limit <limit>","Number of results","10").option("-of, --offset <offset>","Offset for pagination","0").action(function(e,t,n){try{var i=D(function(){return Promise.resolve(S.auth.setApiKey(n.apiKey)).then(function(){return Promise.resolve(S.admin.getMissions(e,t,n.status,n.missionId,n.sortBy,n.order,parseInt(n.limit),parseInt(n.offset),S.auth)).then(function(e){console.log("Missions:",e)})})},function(e){console.error("Error fetching missions:",e)});return Promise.resolve(i&&i.then?i.then(function(){}):void 0)}catch(e){return Promise.reject(e)}}),R.command("getUserCredits").description("User credit points").option("-k, --apiKey <apiKey>","API Key").arguments("<tenantId> <user_reference>").action(function(e,t,n){try{return Promise.resolve(S.auth.setApiKey(n.apiKey)).then(function(){var n=D(function(){return Promise.resolve(S.admin.getUserCredits(e,t,S.auth)).then(function(e){console.log("User Credit Points:",e)})},function(e){console.error("Error fetching Credit Points:",e)});if(n&&n.then)return n.then(function(){})})}catch(e){return Promise.reject(e)}}),R.command("getClaimStatus").description("Fetching the status of the claim").arguments("<tenantId> <missionId> <userId> <claimId>").option("-k, --apiKey <apiKey>","API Key").action(function(e,t,n,i,r){try{return Promise.resolve(S.auth.setApiKey(r.apiKey)).then(function(){var r=D(function(){return Promise.resolve(S.admin.getClaimStatus(e,t,n,i,S.auth)).then(function(e){console.log("Claim status:",e)})},function(e){console.error("Error fetching status:",e)});if(r&&r.then)return r.then(function(){})})}catch(e){return Promise.reject(e)}}),R.command("getRewards").description("Fetch rewards for a user").arguments("<tenantId> <user_reference>").option("-k, --apiKey <apiKey>","API Key").option("-s, --status <status>","Mission status","AVAILABLE").option("-sb, --sortBy <sortBy>","Sort by field","created_at").option("-o, --order <order>","Sort order","desc").option("-l, --limit <limit>","Number of results","10").option("-of, --offset <offset>","Offset for pagination","0").action(function(e,t,n){try{var i=D(function(){return Promise.resolve(S.auth.setApiKey(n.apiKey)).then(function(){return Promise.resolve(S.admin.getRewards(e,t,n.status,n.sortBy,n.order,parseInt(n.limit),parseInt(n.offset),S.auth)).then(function(e){console.log("Rewards:",e)})})},function(e){console.error("Error fetching rewards:",e)});return Promise.resolve(i&&i.then?i.then(function(){}):void 0)}catch(e){return Promise.reject(e)}}),R.command("getRedeemStatus").description("Fetching the status of the redeem").arguments("<tenantId> <rewardId> <userId> <redeemId>").option("-k, --apiKey <apiKey>","API Key").action(function(e,t,n,i,r){try{return Promise.resolve(S.auth.setApiKey(r.apiKey)).then(function(){var o=D(function(){return Promise.resolve(S.auth.setApiKey(r.apiKey)).then(function(){return Promise.resolve(S.admin.getRedeemStatus(e,t,n,i,S.auth)).then(function(e){console.log("Redeem status:",e)})})},function(e){console.error("Error fetching status:",e)});if(o&&o.then)return o.then(function(){})})}catch(e){return Promise.reject(e)}}),R.command("fetchReward").description("Fetching the reward details").arguments("<rewardId>").option("-k, --apiKey <apiKey>","API Key").action(function(e,t){try{var n=D(function(){return Promise.resolve(S.auth.setApiKey(t.apiKey)).then(function(){return Promise.resolve(S.admin.fetchReward(e,S.auth)).then(function(e){console.log("Reward Details:",e)})})},function(e){console.error("Error fetching details:",e)});return Promise.resolve(n&&n.then?n.then(function(){}):void 0)}catch(e){return Promise.reject(e)}}),R.command("fetchMission").description("Fetching the mission details").arguments("<missionId>").option("-k, --apiKey <apiKey>","API Key").action(function(e,t){try{var n=D(function(){return Promise.resolve(S.auth.setApiKey(t.apiKey)).then(function(){return Promise.resolve(S.admin.fetchMission(e,S.auth)).then(function(e){console.log("Mission Details:",e)})})},function(e){console.error("Error fetching details:",e)});return Promise.resolve(n&&n.then?n.then(function(){}):void 0)}catch(e){return Promise.reject(e)}}),R.command("initiateClaim").description("Initiating the claim process").arguments("<missionId> <userReference>").option("-k, --apiKey <apiKey>","API Key").action(function(e,t,n){try{var i=D(function(){return Promise.resolve(S.auth.setApiKey(n.apiKey)).then(function(){return Promise.resolve(S.claim.initiateClaim(e,t,S.auth)).then(function(e){console.log("Claim Initiated Details:",e)})})},function(e){console.error("Error fetching details:",e)});return Promise.resolve(i&&i.then?i.then(function(){}):void 0)}catch(e){return Promise.reject(e)}}),R.command("initiateReward").description("Initiating the reward redeem process").arguments("<reward_id> <userReference> <wallet_address>").option("-k, --apiKey <apiKey>","API Key").action(function(e,t,n,i){try{var r=D(function(){return Promise.resolve(S.auth.setApiKey(i.apiKey)).then(function(){return Promise.resolve(S.redemption.initiateReward(e,t,n,S.auth)).then(function(e){console.log("Redeem Initiated Details:",e)})})},function(e){console.error("Error fetching details:",e)});return Promise.resolve(r&&r.then?r.then(function(){}):void 0)}catch(e){return Promise.reject(e)}}),R.command("getLeaderboard").description("Fetch the Leaderboard").arguments("<tenantId>").option("-k, --apiKey <apiKey>","API Key").option("-s, --sort <sort>","Sort by field","Points").option("-d, --date-range <dateRange>","Date Range","ALLTIME").option("-l, --limit <limit>","Number of results","10").option("-of, --offset <offset>","Offset for pagination","0").action(function(e,t){try{var n=D(function(){return Promise.resolve(S.auth.setApiKey(t.apiKey)).then(function(){return Promise.resolve(S.wallet.getLeaderboard(e,t.sort,t.dateRange,parseInt(t.limit),parseInt(t.offset),S.auth)).then(function(e){console.log("LeaderBoard Details:",e)})})},function(e){console.error("Error fetching details:",e)});return Promise.resolve(n&&n.then?n.then(function(){}):void 0)}catch(e){return Promise.reject(e)}}),R.command("getTransactions").description("Fetch the user Transactions").arguments("<tenantId> <userReference>").option("-k, --apiKey <apiKey>","API Key").option("-d, --date-range <dateRange>","Date Range","ALLTIME").option("-l, --limit <limit>","Number of results","10").option("-of, --offset <offset>","Offset for pagination","0").action(function(e,t,n){try{var i=D(function(){return Promise.resolve(S.auth.setApiKey(n.apiKey)).then(function(){return Promise.resolve(S.wallet.getTransactions(e,t,n.dateRange,parseInt(n.limit),parseInt(n.offset),S.auth)).then(function(e){console.log("Transaction Details:",e)})})},function(e){console.error("Error fetching Transactions:",e)});return Promise.resolve(i&&i.then?i.then(function(){}):void 0)}catch(e){return Promise.reject(e)}}),R.parse(process.argv);