domani-cli 0.4.50 → 0.4.52

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/domani.cjs +75 -74
  2. package/package.json +1 -1
package/dist/domani.cjs CHANGED
@@ -18,81 +18,81 @@ Expecting one of '${s.join("', '")}'`);return this._lifeCycleHooks[t]?this._life
18
18
  - 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,i,s){if(bi.existsSync(t))return;let n=i?`searched for local subcommand relative to directory '${i}'`:"no directory for search for local subcommand, use .executableDir() to supply a custom directory",r=`'${t}' does not exist
19
19
  - if '${s}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
20
20
  - if the default executable name is not suitable, use the executableFile option to supply a custom name or path
21
- - ${n}`;throw new Error(r)}_executeSubCommand(t,i){i=i.slice();let s=!1,n=[".js",".ts",".tsx",".mjs",".cjs"];function r(f,g){let b=ct.resolve(f,g);if(bi.existsSync(b))return b;if(n.includes(ct.extname(g)))return;let v=n.find(w=>bi.existsSync(`${b}${w}`));if(v)return`${b}${v}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=t._executableFile||`${this._name}-${t._name}`,a=this._executableDir||"";if(this._scriptPath){let f;try{f=bi.realpathSync(this._scriptPath)}catch{f=this._scriptPath}a=ct.resolve(ct.dirname(f),a)}if(a){let f=r(a,o);if(!f&&!t._executableFile&&this._scriptPath){let g=ct.basename(this._scriptPath,ct.extname(this._scriptPath));g!==this._name&&(f=r(a,`${g}-${t._name}`))}o=f||o}s=n.includes(ct.extname(o));let l;ne.platform!=="win32"?s?(i.unshift(o),i=En(ne.execArgv).concat(i),l=ps.spawn(ne.argv[0],i,{stdio:"inherit"})):l=ps.spawn(o,i,{stdio:"inherit"}):(this._checkForMissingExecutable(o,a,t._name),i.unshift(o),i=En(ne.execArgv).concat(i),l=ps.spawn(ne.execPath,i,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(g=>{ne.on(g,()=>{l.killed===!1&&l.exitCode===null&&l.kill(g)})});let m=this._exitCallback;l.on("close",f=>{f=f??1,m?m(new hs(f,"commander.executeSubCommandAsync","(close)")):ne.exit(f)}),l.on("error",f=>{if(f.code==="ENOENT")this._checkForMissingExecutable(o,a,t._name);else if(f.code==="EACCES")throw new Error(`'${o}' not executable`);if(!m)ne.exit(1);else{let g=new hs(1,"commander.executeSubCommandAsync","(error)");g.nestedError=f,m(g)}}),this.runningCommand=l}_dispatchSubcommand(t,i,s){let n=this._findCommand(t);n||this.help({error:!0}),n._prepareForParse();let r;return r=this._chainOrCallSubCommandHook(r,n,"preSubcommand"),r=this._chainOrCall(r,()=>{if(n._executableHandler)this._executeSubCommand(n,i.concat(s));else return n._parseCommand(i,s)}),r}_dispatchHelpCommand(t){t||this.help();let i=this._findCommand(t);return i&&!i._executableHandler&&i.help(),this._dispatchSubcommand(t,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((t,i)=>{t.required&&this.args[i]==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=(s,n,r)=>{let o=n;if(n!==null&&s.parseArg){let a=`error: command-argument value '${n}' is invalid for argument '${s.name()}'.`;o=this._callParseArg(s,n,r,a)}return o};this._checkNumberOfArguments();let i=[];this.registeredArguments.forEach((s,n)=>{let r=s.defaultValue;s.variadic?n<this.args.length?(r=this.args.slice(n),s.parseArg&&(r=r.reduce((o,a)=>t(s,a,o),s.defaultValue))):r===void 0&&(r=[]):n<this.args.length&&(r=this.args[n],s.parseArg&&(r=t(s,r,s.defaultValue))),i[n]=r}),this.processedArgs=i}_chainOrCall(t,i){return t&&t.then&&typeof t.then=="function"?t.then(()=>i()):i()}_chainOrCallHooks(t,i){let s=t,n=[];return this._getCommandAndAncestors().reverse().filter(r=>r._lifeCycleHooks[i]!==void 0).forEach(r=>{r._lifeCycleHooks[i].forEach(o=>{n.push({hookedCommand:r,callback:o})})}),i==="postAction"&&n.reverse(),n.forEach(r=>{s=this._chainOrCall(s,()=>r.callback(r.hookedCommand,this))}),s}_chainOrCallSubCommandHook(t,i,s){let n=t;return this._lifeCycleHooks[s]!==void 0&&this._lifeCycleHooks[s].forEach(r=>{n=this._chainOrCall(n,()=>r(this,i))}),n}_parseCommand(t,i){let s=this.parseOptions(i);if(this._parseOptionsEnv(),this._parseOptionsImplied(),t=t.concat(s.operands),i=s.unknown,this.args=t.concat(i),t&&this._findCommand(t[0]))return this._dispatchSubcommand(t[0],t.slice(1),i);if(this._getHelpCommand()&&t[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(t[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(i),this._dispatchSubcommand(this._defaultCommandName,t,i);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(s.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let n=()=>{s.unknown.length>0&&this.unknownOption(s.unknown[0])},r=`command:${this.name()}`;if(this._actionHandler){n(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(r,t,i)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(r))n(),this._processArguments(),this.parent.emit(r,t,i);else if(t.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",t,i);this.listenerCount("command:*")?this.emit("command:*",t,i):this.commands.length?this.unknownCommand():(n(),this._processArguments())}else this.commands.length?(n(),this.help({error:!0})):(n(),this._processArguments())}_findCommand(t){if(t)return this.commands.find(i=>i._name===t||i._aliases.includes(t))}_findOption(t){return this.options.find(i=>i.is(t))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(t=>{t.options.forEach(i=>{i.mandatory&&t.getOptionValue(i.attributeName())===void 0&&t.missingMandatoryOptionValue(i)})})}_checkForConflictingLocalOptions(){let t=this.options.filter(s=>{let n=s.attributeName();return this.getOptionValue(n)===void 0?!1:this.getOptionValueSource(n)!=="default"});t.filter(s=>s.conflictsWith.length>0).forEach(s=>{let n=t.find(r=>s.conflictsWith.includes(r.attributeName()));n&&this._conflictingOption(s,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(t=>{t._checkForConflictingLocalOptions()})}parseOptions(t){let i=[],s=[],n=i,r=t.slice();function o(l){return l.length>1&&l[0]==="-"}let a=null;for(;r.length;){let l=r.shift();if(l==="--"){n===s&&n.push(l),n.push(...r);break}if(a&&!o(l)){this.emit(`option:${a.name()}`,l);continue}if(a=null,o(l)){let m=this._findOption(l);if(m){if(m.required){let f=r.shift();f===void 0&&this.optionMissingArgument(m),this.emit(`option:${m.name()}`,f)}else if(m.optional){let f=null;r.length>0&&!o(r[0])&&(f=r.shift()),this.emit(`option:${m.name()}`,f)}else this.emit(`option:${m.name()}`);a=m.variadic?m:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let m=this._findOption(`-${l[1]}`);if(m){m.required||m.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${m.name()}`,l.slice(2)):(this.emit(`option:${m.name()}`),r.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let m=l.indexOf("="),f=this._findOption(l.slice(0,m));if(f&&(f.required||f.optional)){this.emit(`option:${f.name()}`,l.slice(m+1));continue}}if(o(l)&&(n=s),(this._enablePositionalOptions||this._passThroughOptions)&&i.length===0&&s.length===0){if(this._findCommand(l)){i.push(l),r.length>0&&s.push(...r);break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){i.push(l),r.length>0&&i.push(...r);break}else if(this._defaultCommandName){s.push(l),r.length>0&&s.push(...r);break}}if(this._passThroughOptions){n.push(l),r.length>0&&n.push(...r);break}n.push(l)}return{operands:i,unknown:s}}opts(){if(this._storeOptionsAsProperties){let t={},i=this.options.length;for(let s=0;s<i;s++){let n=this.options[s].attributeName();t[n]=n===this._versionOptionName?this._version:this[n]}return t}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((t,i)=>Object.assign(t,i.opts()),{})}error(t,i){this._outputConfiguration.outputError(`${t}
21
+ - ${n}`;throw new Error(r)}_executeSubCommand(t,i){i=i.slice();let s=!1,n=[".js",".ts",".tsx",".mjs",".cjs"];function r(f,g){let b=ct.resolve(f,g);if(bi.existsSync(b))return b;if(n.includes(ct.extname(g)))return;let w=n.find(v=>bi.existsSync(`${b}${v}`));if(w)return`${b}${w}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=t._executableFile||`${this._name}-${t._name}`,a=this._executableDir||"";if(this._scriptPath){let f;try{f=bi.realpathSync(this._scriptPath)}catch{f=this._scriptPath}a=ct.resolve(ct.dirname(f),a)}if(a){let f=r(a,o);if(!f&&!t._executableFile&&this._scriptPath){let g=ct.basename(this._scriptPath,ct.extname(this._scriptPath));g!==this._name&&(f=r(a,`${g}-${t._name}`))}o=f||o}s=n.includes(ct.extname(o));let l;ne.platform!=="win32"?s?(i.unshift(o),i=En(ne.execArgv).concat(i),l=ps.spawn(ne.argv[0],i,{stdio:"inherit"})):l=ps.spawn(o,i,{stdio:"inherit"}):(this._checkForMissingExecutable(o,a,t._name),i.unshift(o),i=En(ne.execArgv).concat(i),l=ps.spawn(ne.execPath,i,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(g=>{ne.on(g,()=>{l.killed===!1&&l.exitCode===null&&l.kill(g)})});let m=this._exitCallback;l.on("close",f=>{f=f??1,m?m(new hs(f,"commander.executeSubCommandAsync","(close)")):ne.exit(f)}),l.on("error",f=>{if(f.code==="ENOENT")this._checkForMissingExecutable(o,a,t._name);else if(f.code==="EACCES")throw new Error(`'${o}' not executable`);if(!m)ne.exit(1);else{let g=new hs(1,"commander.executeSubCommandAsync","(error)");g.nestedError=f,m(g)}}),this.runningCommand=l}_dispatchSubcommand(t,i,s){let n=this._findCommand(t);n||this.help({error:!0}),n._prepareForParse();let r;return r=this._chainOrCallSubCommandHook(r,n,"preSubcommand"),r=this._chainOrCall(r,()=>{if(n._executableHandler)this._executeSubCommand(n,i.concat(s));else return n._parseCommand(i,s)}),r}_dispatchHelpCommand(t){t||this.help();let i=this._findCommand(t);return i&&!i._executableHandler&&i.help(),this._dispatchSubcommand(t,[],[this._getHelpOption()?.long??this._getHelpOption()?.short??"--help"])}_checkNumberOfArguments(){this.registeredArguments.forEach((t,i)=>{t.required&&this.args[i]==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=(s,n,r)=>{let o=n;if(n!==null&&s.parseArg){let a=`error: command-argument value '${n}' is invalid for argument '${s.name()}'.`;o=this._callParseArg(s,n,r,a)}return o};this._checkNumberOfArguments();let i=[];this.registeredArguments.forEach((s,n)=>{let r=s.defaultValue;s.variadic?n<this.args.length?(r=this.args.slice(n),s.parseArg&&(r=r.reduce((o,a)=>t(s,a,o),s.defaultValue))):r===void 0&&(r=[]):n<this.args.length&&(r=this.args[n],s.parseArg&&(r=t(s,r,s.defaultValue))),i[n]=r}),this.processedArgs=i}_chainOrCall(t,i){return t&&t.then&&typeof t.then=="function"?t.then(()=>i()):i()}_chainOrCallHooks(t,i){let s=t,n=[];return this._getCommandAndAncestors().reverse().filter(r=>r._lifeCycleHooks[i]!==void 0).forEach(r=>{r._lifeCycleHooks[i].forEach(o=>{n.push({hookedCommand:r,callback:o})})}),i==="postAction"&&n.reverse(),n.forEach(r=>{s=this._chainOrCall(s,()=>r.callback(r.hookedCommand,this))}),s}_chainOrCallSubCommandHook(t,i,s){let n=t;return this._lifeCycleHooks[s]!==void 0&&this._lifeCycleHooks[s].forEach(r=>{n=this._chainOrCall(n,()=>r(this,i))}),n}_parseCommand(t,i){let s=this.parseOptions(i);if(this._parseOptionsEnv(),this._parseOptionsImplied(),t=t.concat(s.operands),i=s.unknown,this.args=t.concat(i),t&&this._findCommand(t[0]))return this._dispatchSubcommand(t[0],t.slice(1),i);if(this._getHelpCommand()&&t[0]===this._getHelpCommand().name())return this._dispatchHelpCommand(t[1]);if(this._defaultCommandName)return this._outputHelpIfRequested(i),this._dispatchSubcommand(this._defaultCommandName,t,i);this.commands.length&&this.args.length===0&&!this._actionHandler&&!this._defaultCommandName&&this.help({error:!0}),this._outputHelpIfRequested(s.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let n=()=>{s.unknown.length>0&&this.unknownOption(s.unknown[0])},r=`command:${this.name()}`;if(this._actionHandler){n(),this._processArguments();let o;return o=this._chainOrCallHooks(o,"preAction"),o=this._chainOrCall(o,()=>this._actionHandler(this.processedArgs)),this.parent&&(o=this._chainOrCall(o,()=>{this.parent.emit(r,t,i)})),o=this._chainOrCallHooks(o,"postAction"),o}if(this.parent&&this.parent.listenerCount(r))n(),this._processArguments(),this.parent.emit(r,t,i);else if(t.length){if(this._findCommand("*"))return this._dispatchSubcommand("*",t,i);this.listenerCount("command:*")?this.emit("command:*",t,i):this.commands.length?this.unknownCommand():(n(),this._processArguments())}else this.commands.length?(n(),this.help({error:!0})):(n(),this._processArguments())}_findCommand(t){if(t)return this.commands.find(i=>i._name===t||i._aliases.includes(t))}_findOption(t){return this.options.find(i=>i.is(t))}_checkForMissingMandatoryOptions(){this._getCommandAndAncestors().forEach(t=>{t.options.forEach(i=>{i.mandatory&&t.getOptionValue(i.attributeName())===void 0&&t.missingMandatoryOptionValue(i)})})}_checkForConflictingLocalOptions(){let t=this.options.filter(s=>{let n=s.attributeName();return this.getOptionValue(n)===void 0?!1:this.getOptionValueSource(n)!=="default"});t.filter(s=>s.conflictsWith.length>0).forEach(s=>{let n=t.find(r=>s.conflictsWith.includes(r.attributeName()));n&&this._conflictingOption(s,n)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(t=>{t._checkForConflictingLocalOptions()})}parseOptions(t){let i=[],s=[],n=i,r=t.slice();function o(l){return l.length>1&&l[0]==="-"}let a=null;for(;r.length;){let l=r.shift();if(l==="--"){n===s&&n.push(l),n.push(...r);break}if(a&&!o(l)){this.emit(`option:${a.name()}`,l);continue}if(a=null,o(l)){let m=this._findOption(l);if(m){if(m.required){let f=r.shift();f===void 0&&this.optionMissingArgument(m),this.emit(`option:${m.name()}`,f)}else if(m.optional){let f=null;r.length>0&&!o(r[0])&&(f=r.shift()),this.emit(`option:${m.name()}`,f)}else this.emit(`option:${m.name()}`);a=m.variadic?m:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let m=this._findOption(`-${l[1]}`);if(m){m.required||m.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${m.name()}`,l.slice(2)):(this.emit(`option:${m.name()}`),r.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let m=l.indexOf("="),f=this._findOption(l.slice(0,m));if(f&&(f.required||f.optional)){this.emit(`option:${f.name()}`,l.slice(m+1));continue}}if(o(l)&&(n=s),(this._enablePositionalOptions||this._passThroughOptions)&&i.length===0&&s.length===0){if(this._findCommand(l)){i.push(l),r.length>0&&s.push(...r);break}else if(this._getHelpCommand()&&l===this._getHelpCommand().name()){i.push(l),r.length>0&&i.push(...r);break}else if(this._defaultCommandName){s.push(l),r.length>0&&s.push(...r);break}}if(this._passThroughOptions){n.push(l),r.length>0&&n.push(...r);break}n.push(l)}return{operands:i,unknown:s}}opts(){if(this._storeOptionsAsProperties){let t={},i=this.options.length;for(let s=0;s<i;s++){let n=this.options[s].attributeName();t[n]=n===this._versionOptionName?this._version:this[n]}return t}return this._optionValues}optsWithGlobals(){return this._getCommandAndAncestors().reduce((t,i)=>Object.assign(t,i.opts()),{})}error(t,i){this._outputConfiguration.outputError(`${t}
22
22
  `,this._outputConfiguration.writeErr),typeof this._showHelpAfterError=="string"?this._outputConfiguration.writeErr(`${this._showHelpAfterError}
23
23
  `):this._showHelpAfterError&&(this._outputConfiguration.writeErr(`
24
24
  `),this.outputHelp({error:!0}));let s=i||{},n=s.exitCode||1,r=s.code||"commander.error";this._exit(n,r,t)}_parseOptionsEnv(){this.options.forEach(t=>{if(t.envVar&&t.envVar in ne.env){let i=t.attributeName();(this.getOptionValue(i)===void 0||["default","config","env"].includes(this.getOptionValueSource(i)))&&(t.required||t.optional?this.emit(`optionEnv:${t.name()}`,ne.env[t.envVar]):this.emit(`optionEnv:${t.name()}`))}})}_parseOptionsImplied(){let t=new $a(this.options),i=s=>this.getOptionValue(s)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(s));this.options.filter(s=>s.implied!==void 0&&i(s.attributeName())&&t.valueFromOption(this.getOptionValue(s.attributeName()),s)).forEach(s=>{Object.keys(s.implied).filter(n=>!i(n)).forEach(n=>{this.setOptionValueWithSource(n,s.implied[n],"implied")})})}missingArgument(t){let i=`error: missing required argument '${t}'`;this.error(i,{code:"commander.missingArgument"})}optionMissingArgument(t){let i=`error: option '${t.flags}' argument missing`;this.error(i,{code:"commander.optionMissingArgument"})}missingMandatoryOptionValue(t){let i=`error: required option '${t.flags}' not specified`;this.error(i,{code:"commander.missingMandatoryOptionValue"})}_conflictingOption(t,i){let s=o=>{let a=o.attributeName(),l=this.getOptionValue(a),m=this.options.find(g=>g.negate&&a===g.attributeName()),f=this.options.find(g=>!g.negate&&a===g.attributeName());return m&&(m.presetArg===void 0&&l===!1||m.presetArg!==void 0&&l===m.presetArg)?m:f||o},n=o=>{let a=s(o),l=a.attributeName();return this.getOptionValueSource(l)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},r=`error: ${n(t)} cannot be used with ${n(i)}`;this.error(r,{code:"commander.conflictingOption"})}unknownOption(t){if(this._allowUnknownOption)return;let i="";if(t.startsWith("--")&&this._showSuggestionAfterError){let n=[],r=this;do{let o=r.createHelp().visibleOptions(r).filter(a=>a.long).map(a=>a.long);n=n.concat(o),r=r.parent}while(r&&!r._enablePositionalOptions);i=An(t,n)}let s=`error: unknown option '${t}'${i}`;this.error(s,{code:"commander.unknownOption"})}_excessArguments(t){if(this._allowExcessArguments)return;let i=this.registeredArguments.length,s=i===1?"":"s",r=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${i} argument${s} but got ${t.length}.`;this.error(r,{code:"commander.excessArguments"})}unknownCommand(){let t=this.args[0],i="";if(this._showSuggestionAfterError){let n=[];this.createHelp().visibleCommands(this).forEach(r=>{n.push(r.name()),r.alias()&&n.push(r.alias())}),i=An(t,n)}let s=`error: unknown command '${t}'${i}`;this.error(s,{code:"commander.unknownCommand"})}version(t,i,s){if(t===void 0)return this._version;this._version=t,i=i||"-V, --version",s=s||"output the version number";let n=this.createOption(i,s);return this._versionOptionName=n.attributeName(),this._registerOption(n),this.on("option:"+n.name(),()=>{this._outputConfiguration.writeOut(`${t}
25
25
  `),this._exit(0,"commander.version",t)}),this}description(t,i){return t===void 0&&i===void 0?this._description:(this._description=t,i&&(this._argsDescription=i),this)}summary(t){return t===void 0?this._summary:(this._summary=t,this)}alias(t){if(t===void 0)return this._aliases[0];let i=this;if(this.commands.length!==0&&this.commands[this.commands.length-1]._executableHandler&&(i=this.commands[this.commands.length-1]),t===i._name)throw new Error("Command alias can't be the same as its name");let s=this.parent?._findCommand(t);if(s){let n=[s.name()].concat(s.aliases()).join("|");throw new Error(`cannot add alias '${t}' to command '${this.name()}' as already have command '${n}'`)}return i._aliases.push(t),this}aliases(t){return t===void 0?this._aliases:(t.forEach(i=>this.alias(i)),this)}usage(t){if(t===void 0){if(this._usage)return this._usage;let i=this.registeredArguments.map(s=>ga(s));return[].concat(this.options.length||this._helpOption!==null?"[options]":[],this.commands.length?"[command]":[],this.registeredArguments.length?i:[]).join(" ")}return this._usage=t,this}name(t){return t===void 0?this._name:(this._name=t,this)}nameFromFilename(t){return this._name=ct.basename(t,ct.extname(t)),this}executableDir(t){return t===void 0?this._executableDir:(this._executableDir=t,this)}helpInformation(t){let i=this.createHelp(),s=this._getOutputContext(t);i.prepareContext({error:s.error,helpWidth:s.helpWidth,outputHasColors:s.hasColors});let n=i.formatHelp(this,i);return s.hasColors?n:this._outputConfiguration.stripColor(n)}_getOutputContext(t){t=t||{};let i=!!t.error,s,n,r;return i?(s=a=>this._outputConfiguration.writeErr(a),n=this._outputConfiguration.getErrHasColors(),r=this._outputConfiguration.getErrHelpWidth()):(s=a=>this._outputConfiguration.writeOut(a),n=this._outputConfiguration.getOutHasColors(),r=this._outputConfiguration.getOutHelpWidth()),{error:i,write:a=>(n||(a=this._outputConfiguration.stripColor(a)),s(a)),hasColors:n,helpWidth:r}}outputHelp(t){let i;typeof t=="function"&&(i=t,t=void 0);let s=this._getOutputContext(t),n={error:s.error,write:s.write,command:this};this._getCommandAndAncestors().reverse().forEach(o=>o.emit("beforeAllHelp",n)),this.emit("beforeHelp",n);let r=this.helpInformation({error:s.error});if(i&&(r=i(r),typeof r!="string"&&!Buffer.isBuffer(r)))throw new Error("outputHelp callback must return a string or a Buffer");s.write(r),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",n),this._getCommandAndAncestors().forEach(o=>o.emit("afterAllHelp",n))}helpOption(t,i){return typeof t=="boolean"?(t?this._helpOption=this._helpOption??void 0:this._helpOption=null,this):(t=t??"-h, --help",i=i??"display help for command",this._helpOption=this.createOption(t,i),this)}_getHelpOption(){return this._helpOption===void 0&&this.helpOption(void 0,void 0),this._helpOption}addHelpOption(t){return this._helpOption=t,this}help(t){this.outputHelp(t);let i=Number(ne.exitCode??0);i===0&&t&&typeof t!="function"&&t.error&&(i=1),this._exit(i,"commander.help","(outputHelp)")}addHelpText(t,i){let s=["beforeAll","before","after","afterAll"];if(!s.includes(t))throw new Error(`Unexpected value for position to addHelpText.
26
26
  Expecting one of '${s.join("', '")}'`);let n=`${t}Help`;return this.on(n,r=>{let o;typeof i=="function"?o=i({error:r.error,command:r.command}):o=i,o&&r.write(`${o}
27
- `)}),this}_outputHelpIfRequested(t){let i=this._getHelpOption();i&&t.find(n=>i.is(n))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function En(e){return e.map(t=>{if(!t.startsWith("--inspect"))return t;let i,s="127.0.0.1",n="9229",r;return(r=t.match(/^(--inspect(-brk)?)$/))!==null?i=r[1]:(r=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(i=r[1],/^\d+$/.test(r[3])?n=r[3]:s=r[3]):(r=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(i=r[1],s=r[3],n=r[4]),i&&n!=="0"?`${i}=${s}:${parseInt(n)+1}`:t})}function bs(){if(ne.env.NO_COLOR||ne.env.FORCE_COLOR==="0"||ne.env.FORCE_COLOR==="false")return!1;if(ne.env.FORCE_COLOR||ne.env.CLICOLOR_FORCE!==void 0)return!0}ys.Command=gs;ys.useColor=bs});var Un=dt(Ge=>{var{Argument:Dn}=gi(),{Command:$s}=Pn(),{CommanderError:va,InvalidArgumentError:Tn}=Zt(),{Help:wa}=ds(),{Option:Nn}=fs();Ge.program=new $s;Ge.createCommand=e=>new $s(e);Ge.createOption=(e,t)=>new Nn(e,t);Ge.createArgument=(e,t)=>new Dn(e,t);Ge.Command=$s;Ge.Option=Nn;Ge.Argument=Dn;Ge.Help=wa;Ge.CommanderError=va;Ge.InvalidArgumentError=Tn;Ge.InvalidOptionArgumentError=Tn});var L=dt((Rc,vs)=>{var $i=process||{},Mn=$i.argv||[],yi=$i.env||{},ka=!(yi.NO_COLOR||Mn.includes("--no-color"))&&(!!yi.FORCE_COLOR||Mn.includes("--color")||$i.platform==="win32"||($i.stdout||{}).isTTY&&yi.TERM!=="dumb"||!!yi.CI),_a=(e,t,i=e)=>s=>{let n=""+s,r=n.indexOf(t,e.length);return~r?e+ja(n,t,i,r)+t:e+n+t},ja=(e,t,i,s)=>{let n="",r=0;do n+=e.substring(r,s)+i,r=s+t.length,s=e.indexOf(t,r);while(~s);return n+e.substring(r)},Ln=(e=ka)=>{let t=e?_a:()=>String;return{isColorSupported:e,reset:t("\x1B[0m","\x1B[0m"),bold:t("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:t("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:t("\x1B[3m","\x1B[23m"),underline:t("\x1B[4m","\x1B[24m"),inverse:t("\x1B[7m","\x1B[27m"),hidden:t("\x1B[8m","\x1B[28m"),strikethrough:t("\x1B[9m","\x1B[29m"),black:t("\x1B[30m","\x1B[39m"),red:t("\x1B[31m","\x1B[39m"),green:t("\x1B[32m","\x1B[39m"),yellow:t("\x1B[33m","\x1B[39m"),blue:t("\x1B[34m","\x1B[39m"),magenta:t("\x1B[35m","\x1B[39m"),cyan:t("\x1B[36m","\x1B[39m"),white:t("\x1B[37m","\x1B[39m"),gray:t("\x1B[90m","\x1B[39m"),bgBlack:t("\x1B[40m","\x1B[49m"),bgRed:t("\x1B[41m","\x1B[49m"),bgGreen:t("\x1B[42m","\x1B[49m"),bgYellow:t("\x1B[43m","\x1B[49m"),bgBlue:t("\x1B[44m","\x1B[49m"),bgMagenta:t("\x1B[45m","\x1B[49m"),bgCyan:t("\x1B[46m","\x1B[49m"),bgWhite:t("\x1B[47m","\x1B[49m"),blackBright:t("\x1B[90m","\x1B[39m"),redBright:t("\x1B[91m","\x1B[39m"),greenBright:t("\x1B[92m","\x1B[39m"),yellowBright:t("\x1B[93m","\x1B[39m"),blueBright:t("\x1B[94m","\x1B[39m"),magentaBright:t("\x1B[95m","\x1B[39m"),cyanBright:t("\x1B[96m","\x1B[39m"),whiteBright:t("\x1B[97m","\x1B[39m"),bgBlackBright:t("\x1B[100m","\x1B[49m"),bgRedBright:t("\x1B[101m","\x1B[49m"),bgGreenBright:t("\x1B[102m","\x1B[49m"),bgYellowBright:t("\x1B[103m","\x1B[49m"),bgBlueBright:t("\x1B[104m","\x1B[49m"),bgMagentaBright:t("\x1B[105m","\x1B[49m"),bgCyanBright:t("\x1B[106m","\x1B[49m"),bgWhiteBright:t("\x1B[107m","\x1B[49m")}};vs.exports=Ln();vs.exports.createColors=Ln});var Lt,Qt,ei=Ie(()=>{"use strict";Lt="domani.run",Qt=`https://${Lt}`});function jt(e,t,i){try{let s=(0,Vn.spawnSync)(e,t,{encoding:"utf-8",input:i,timeout:3e3,stdio:["pipe","pipe","ignore"]});return{ok:s.status===0,stdout:(s.stdout||"").trim()}}catch{return{ok:!1,stdout:""}}}function Wn(){return process.platform==="darwin"?!0:process.platform==="linux"?jt("secret-tool",["--help"]).ok:!1}function Hn(e={}){if(e.refresh&&(Vt=void 0),Vt!==void 0)return Vt??void 0;let t;if(process.platform==="darwin"){let i=jt("security",["find-generic-password","-s",Wt,"-a",Ht,"-w"]);i.ok&&i.stdout&&(t=i.stdout)}else if(process.platform==="linux"){let i=jt("secret-tool",["lookup","service",Wt,"account",Ht]);i.ok&&i.stdout&&(t=i.stdout)}return Vt=t??null,t}function Jn(e){let t=!1;return process.platform==="darwin"?t=jt("security",["add-generic-password","-U","-s",Wt,"-a",Ht,"-w",e]).ok:process.platform==="linux"&&(t=jt("secret-tool",["store","--label=domani CLI token","service",Wt,"account",Ht],e+`
28
- `).ok),t&&(Vt=e),t}function Bn(){process.platform==="darwin"?jt("security",["delete-generic-password","-s",Wt,"-a",Ht]):process.platform==="linux"&&jt("secret-tool",["clear","service",Wt,"account",Ht]),Vt=null}var Vn,Wt,Ht,Vt,Gn=Ie(()=>{"use strict";Vn=require("child_process"),Wt="domani-cli",Ht="default"});function Yn(e){zn=e}function ut(){try{let e=$t.default.readFileSync(ws,"utf-8");return JSON.parse(e)}catch{return{}}}function Jt(e){e.token&&Wn()&&Jn(e.token)&&(e={...e,token:void 0,token_in_keychain:!0}),$t.default.mkdirSync(ki,{recursive:!0,mode:448}),$t.default.writeFileSync(ws,JSON.stringify(e,null,2),{mode:384})}function Zn(){Bn();try{$t.default.unlinkSync(ws)}catch{}}function qe(){return zn||ut().api_url||Qt}function Me(e={}){if(process.env.DOMANI_API_KEY)return process.env.DOMANI_API_KEY;let t=ut();if(t.token)return t.token;if(t.token_in_keychain)return Hn({refresh:e.refreshKeychain})}function Sa(){try{let e=$t.default.readFileSync(Xn,"utf-8");return JSON.parse(e)}catch{return null}}function Ca(e){try{$t.default.mkdirSync(ki,{recursive:!0,mode:448}),$t.default.writeFileSync(Xn,JSON.stringify(e),{mode:384})}catch{}}function vi(e,t){let i=e.split(".").map(Number),s=t.split(".").map(Number);for(let n=0;n<3;n++){if((i[n]||0)>(s[n]||0))return 1;if((i[n]||0)<(s[n]||0))return-1}return 0}async function Qn(){let e=Sa();if(e&&Date.now()-e.checkedAt<xa)return vi(e.version,_e)>0?{update:e.version,forced:vi(_e,e.min)<0}:null;try{let t=qe(),i=await fetch(`${t}/api/cli/version`,{signal:AbortSignal.timeout(3e3)});if(!i.ok)return null;let s=await i.json();if(Ca({version:s.version,min:s.min,checkedAt:Date.now()}),vi(s.version,_e)>0)return{update:s.version,forced:vi(_e,s.min)<0}}catch{}return null}var $t,wi,Kn,ki,ws,zn,Xn,xa,ks,_e,mt=Ie(()=>{"use strict";$t=U(require("fs"),1),wi=U(require("path"),1),Kn=U(require("os"),1);ei();Gn();ki=process.env.DOMANI_CONFIG_DIR||wi.default.join(Kn.default.homedir(),".domani"),ws=wi.default.join(ki,"config.json");Xn=wi.default.join(ki,"version-check.json"),xa=1440*60*1e3;ks=process.stdout.isTTY??!1,_e="0.4.50"});var js=dt((Nc,er)=>{"use strict";var _s={to(e,t){return t?`\x1B[${t+1};${e+1}H`:`\x1B[${e+1}G`},move(e,t){let i="";return e<0?i+=`\x1B[${-e}D`:e>0&&(i+=`\x1B[${e}C`),t<0?i+=`\x1B[${-t}A`:t>0&&(i+=`\x1B[${t}B`),i},up:(e=1)=>`\x1B[${e}A`,down:(e=1)=>`\x1B[${e}B`,forward:(e=1)=>`\x1B[${e}C`,backward:(e=1)=>`\x1B[${e}D`,nextLine:(e=1)=>"\x1B[E".repeat(e),prevLine:(e=1)=>"\x1B[F".repeat(e),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},Oa={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},Ia={screen:"\x1B[2J",up:(e=1)=>"\x1B[1J".repeat(e),down:(e=1)=>"\x1B[J".repeat(e),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(e){let t="";for(let i=0;i<e;i++)t+=this.line+(i<e-1?_s.up():"");return e&&(t+=_s.left),t}};er.exports={cursor:_s,scroll:Oa,erase:Ia,beep:"\x07"}});function ft(e,t,i){if(!i.some(o=>!o.disabled))return e;let s=e+t,n=Math.max(i.length-1,0),r=s<0?n:s>n?0:s;return i[r].disabled?ft(r,t<0?-1:1,i):r}function Is(e,t,i){return String(e).normalize().replaceAll(`\r
27
+ `)}),this}_outputHelpIfRequested(t){let i=this._getHelpOption();i&&t.find(n=>i.is(n))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function En(e){return e.map(t=>{if(!t.startsWith("--inspect"))return t;let i,s="127.0.0.1",n="9229",r;return(r=t.match(/^(--inspect(-brk)?)$/))!==null?i=r[1]:(r=t.match(/^(--inspect(-brk|-port)?)=([^:]+)$/))!==null?(i=r[1],/^\d+$/.test(r[3])?n=r[3]:s=r[3]):(r=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(i=r[1],s=r[3],n=r[4]),i&&n!=="0"?`${i}=${s}:${parseInt(n)+1}`:t})}function bs(){if(ne.env.NO_COLOR||ne.env.FORCE_COLOR==="0"||ne.env.FORCE_COLOR==="false")return!1;if(ne.env.FORCE_COLOR||ne.env.CLICOLOR_FORCE!==void 0)return!0}ys.Command=gs;ys.useColor=bs});var Un=dt(Ge=>{var{Argument:Dn}=gi(),{Command:$s}=Pn(),{CommanderError:va,InvalidArgumentError:Tn}=Zt(),{Help:wa}=ds(),{Option:Nn}=fs();Ge.program=new $s;Ge.createCommand=e=>new $s(e);Ge.createOption=(e,t)=>new Nn(e,t);Ge.createArgument=(e,t)=>new Dn(e,t);Ge.Command=$s;Ge.Option=Nn;Ge.Argument=Dn;Ge.Help=wa;Ge.CommanderError=va;Ge.InvalidArgumentError=Tn;Ge.InvalidOptionArgumentError=Tn});var L=dt((Rc,vs)=>{var $i=process||{},Mn=$i.argv||[],yi=$i.env||{},ka=!(yi.NO_COLOR||Mn.includes("--no-color"))&&(!!yi.FORCE_COLOR||Mn.includes("--color")||$i.platform==="win32"||($i.stdout||{}).isTTY&&yi.TERM!=="dumb"||!!yi.CI),_a=(e,t,i=e)=>s=>{let n=""+s,r=n.indexOf(t,e.length);return~r?e+xa(n,t,i,r)+t:e+n+t},xa=(e,t,i,s)=>{let n="",r=0;do n+=e.substring(r,s)+i,r=s+t.length,s=e.indexOf(t,r);while(~s);return n+e.substring(r)},Ln=(e=ka)=>{let t=e?_a:()=>String;return{isColorSupported:e,reset:t("\x1B[0m","\x1B[0m"),bold:t("\x1B[1m","\x1B[22m","\x1B[22m\x1B[1m"),dim:t("\x1B[2m","\x1B[22m","\x1B[22m\x1B[2m"),italic:t("\x1B[3m","\x1B[23m"),underline:t("\x1B[4m","\x1B[24m"),inverse:t("\x1B[7m","\x1B[27m"),hidden:t("\x1B[8m","\x1B[28m"),strikethrough:t("\x1B[9m","\x1B[29m"),black:t("\x1B[30m","\x1B[39m"),red:t("\x1B[31m","\x1B[39m"),green:t("\x1B[32m","\x1B[39m"),yellow:t("\x1B[33m","\x1B[39m"),blue:t("\x1B[34m","\x1B[39m"),magenta:t("\x1B[35m","\x1B[39m"),cyan:t("\x1B[36m","\x1B[39m"),white:t("\x1B[37m","\x1B[39m"),gray:t("\x1B[90m","\x1B[39m"),bgBlack:t("\x1B[40m","\x1B[49m"),bgRed:t("\x1B[41m","\x1B[49m"),bgGreen:t("\x1B[42m","\x1B[49m"),bgYellow:t("\x1B[43m","\x1B[49m"),bgBlue:t("\x1B[44m","\x1B[49m"),bgMagenta:t("\x1B[45m","\x1B[49m"),bgCyan:t("\x1B[46m","\x1B[49m"),bgWhite:t("\x1B[47m","\x1B[49m"),blackBright:t("\x1B[90m","\x1B[39m"),redBright:t("\x1B[91m","\x1B[39m"),greenBright:t("\x1B[92m","\x1B[39m"),yellowBright:t("\x1B[93m","\x1B[39m"),blueBright:t("\x1B[94m","\x1B[39m"),magentaBright:t("\x1B[95m","\x1B[39m"),cyanBright:t("\x1B[96m","\x1B[39m"),whiteBright:t("\x1B[97m","\x1B[39m"),bgBlackBright:t("\x1B[100m","\x1B[49m"),bgRedBright:t("\x1B[101m","\x1B[49m"),bgGreenBright:t("\x1B[102m","\x1B[49m"),bgYellowBright:t("\x1B[103m","\x1B[49m"),bgBlueBright:t("\x1B[104m","\x1B[49m"),bgMagentaBright:t("\x1B[105m","\x1B[49m"),bgCyanBright:t("\x1B[106m","\x1B[49m"),bgWhiteBright:t("\x1B[107m","\x1B[49m")}};vs.exports=Ln();vs.exports.createColors=Ln});var Lt,Qt,ei=Ie(()=>{"use strict";Lt="domani.run",Qt=`https://${Lt}`});function xt(e,t,i){try{let s=(0,Vn.spawnSync)(e,t,{encoding:"utf-8",input:i,timeout:3e3,stdio:["pipe","pipe","ignore"]});return{ok:s.status===0,stdout:(s.stdout||"").trim()}}catch{return{ok:!1,stdout:""}}}function Wn(){return process.platform==="darwin"?!0:process.platform==="linux"?xt("secret-tool",["--help"]).ok:!1}function Hn(e={}){if(e.refresh&&(Vt=void 0),Vt!==void 0)return Vt??void 0;let t;if(process.platform==="darwin"){let i=xt("security",["find-generic-password","-s",Wt,"-a",Ht,"-w"]);i.ok&&i.stdout&&(t=i.stdout)}else if(process.platform==="linux"){let i=xt("secret-tool",["lookup","service",Wt,"account",Ht]);i.ok&&i.stdout&&(t=i.stdout)}return Vt=t??null,t}function Jn(e){let t=!1;return process.platform==="darwin"?t=xt("security",["add-generic-password","-U","-s",Wt,"-a",Ht,"-w",e]).ok:process.platform==="linux"&&(t=xt("secret-tool",["store","--label=domani CLI token","service",Wt,"account",Ht],e+`
28
+ `).ok),t&&(Vt=e),t}function Bn(){process.platform==="darwin"?xt("security",["delete-generic-password","-s",Wt,"-a",Ht]):process.platform==="linux"&&xt("secret-tool",["clear","service",Wt,"account",Ht]),Vt=null}var Vn,Wt,Ht,Vt,Gn=Ie(()=>{"use strict";Vn=require("child_process"),Wt="domani-cli",Ht="default"});function Yn(e){zn=e}function ut(){try{let e=$t.default.readFileSync(ws,"utf-8");return JSON.parse(e)}catch{return{}}}function Jt(e){e.token&&Wn()&&Jn(e.token)&&(e={...e,token:void 0,token_in_keychain:!0}),$t.default.mkdirSync(ki,{recursive:!0,mode:448}),$t.default.writeFileSync(ws,JSON.stringify(e,null,2),{mode:384})}function Zn(){Bn();try{$t.default.unlinkSync(ws)}catch{}}function qe(){return zn||ut().api_url||Qt}function Me(e={}){if(process.env.DOMANI_API_KEY)return process.env.DOMANI_API_KEY;let t=ut();if(t.token)return t.token;if(t.token_in_keychain)return Hn({refresh:e.refreshKeychain})}function Sa(){try{let e=$t.default.readFileSync(Xn,"utf-8");return JSON.parse(e)}catch{return null}}function Ca(e){try{$t.default.mkdirSync(ki,{recursive:!0,mode:448}),$t.default.writeFileSync(Xn,JSON.stringify(e),{mode:384})}catch{}}function vi(e,t){let i=e.split(".").map(Number),s=t.split(".").map(Number);for(let n=0;n<3;n++){if((i[n]||0)>(s[n]||0))return 1;if((i[n]||0)<(s[n]||0))return-1}return 0}async function Qn(){let e=Sa();if(e&&Date.now()-e.checkedAt<ja)return vi(e.version,ke)>0?{update:e.version,forced:vi(ke,e.min)<0}:null;try{let t=qe(),i=await fetch(`${t}/api/cli/version`,{signal:AbortSignal.timeout(3e3)});if(!i.ok)return null;let s=await i.json();if(Ca({version:s.version,min:s.min,checkedAt:Date.now()}),vi(s.version,ke)>0)return{update:s.version,forced:vi(ke,s.min)<0}}catch{}return null}var $t,wi,Kn,ki,ws,zn,Xn,ja,ks,ke,mt=Ie(()=>{"use strict";$t=U(require("fs"),1),wi=U(require("path"),1),Kn=U(require("os"),1);ei();Gn();ki=process.env.DOMANI_CONFIG_DIR||wi.default.join(Kn.default.homedir(),".domani"),ws=wi.default.join(ki,"config.json");Xn=wi.default.join(ki,"version-check.json"),ja=1440*60*1e3;ks=process.stdout.isTTY??!1,ke="0.4.52"});var xs=dt((Nc,er)=>{"use strict";var _s={to(e,t){return t?`\x1B[${t+1};${e+1}H`:`\x1B[${e+1}G`},move(e,t){let i="";return e<0?i+=`\x1B[${-e}D`:e>0&&(i+=`\x1B[${e}C`),t<0?i+=`\x1B[${-t}A`:t>0&&(i+=`\x1B[${t}B`),i},up:(e=1)=>`\x1B[${e}A`,down:(e=1)=>`\x1B[${e}B`,forward:(e=1)=>`\x1B[${e}C`,backward:(e=1)=>`\x1B[${e}D`,nextLine:(e=1)=>"\x1B[E".repeat(e),prevLine:(e=1)=>"\x1B[F".repeat(e),left:"\x1B[G",hide:"\x1B[?25l",show:"\x1B[?25h",save:"\x1B7",restore:"\x1B8"},Oa={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},Ia={screen:"\x1B[2J",up:(e=1)=>"\x1B[1J".repeat(e),down:(e=1)=>"\x1B[J".repeat(e),line:"\x1B[2K",lineEnd:"\x1B[K",lineStart:"\x1B[1K",lines(e){let t="";for(let i=0;i<e;i++)t+=this.line+(i<e-1?_s.up():"");return e&&(t+=_s.left),t}};er.exports={cursor:_s,scroll:Oa,erase:Ia,beep:"\x07"}});function ft(e,t,i){if(!i.some(o=>!o.disabled))return e;let s=e+t,n=Math.max(i.length-1,0),r=s<0?n:s>n?0:s;return i[r].disabled?ft(r,t<0?-1:1,i):r}function Is(e,t,i){return String(e).normalize().replaceAll(`\r
29
29
  `,`
30
30
  `).split(`
31
31
  `).map(s=>La(s,t,i)).join(`
32
32
  `)}function dr(e){if(e.aliases!==void 0){let t=e.aliases;for(let i in t){if(!Object.hasOwn(t,i))continue;let s=t[i];ce.actions.has(s)&&(ce.aliases.has(i)||ce.aliases.set(i,s))}}if(e.messages!==void 0){let t=e.messages;t.cancel!==void 0&&(ce.messages.cancel=t.cancel),t.error!==void 0&&(ce.messages.error=t.error)}e.withGuide!==void 0&&(ce.withGuide=e.withGuide!==!1)}function Ps(e,t){if(typeof e=="string")return ce.aliases.get(e)===t;for(let i of e)if(i!==void 0&&Ps(i,t))return!0;return!1}function Wa(e,t){if(e===t)return;let i=e.split(`
33
33
  `),s=t.split(`
34
- `),n=Math.max(i.length,s.length),r=[];for(let o=0;o<n;o++)i[o]!==s[o]&&r.push(o);return{lines:r,numLinesBefore:i.length,numLinesAfter:s.length,numLines:n}}function le(e){return e===Rs}function Si(e,t){let i=e;i.isTTY&&i.setRawMode(t)}function cr({input:e=xt.stdin,output:t=xt.stdout,overwrite:i=!0,hideCursor:s=!0}={}){let n=wt.createInterface({input:e,output:t,prompt:"",tabSize:1});wt.emitKeypressEvents(e,n),e instanceof Os.ReadStream&&e.isTTY&&e.setRawMode(!0);let r=(o,{name:a,sequence:l})=>{let m=String(o);if(Ps([m,a,l],"cancel")){s&&t.write(Re.cursor.show),process.exit(0);return}if(!i)return;wt.moveCursor(t,a==="return"?0:-1,a==="return"?-1:0,()=>{wt.clearLine(t,1,()=>{e.once("keypress",r)})})};return s&&t.write(Re.cursor.hide),e.once("keypress",r),()=>{e.off("keypress",r),s&&t.write(Re.cursor.show),e instanceof Os.ReadStream&&e.isTTY&&!Ha&&e.setRawMode(!1),n.terminal=!1,n.close()}}function nt(e,t,i,s=i){let n=St(e??xt.stdout);return Is(t,n-i.length,{hard:!0,trim:!1}).split(`
34
+ `),n=Math.max(i.length,s.length),r=[];for(let o=0;o<n;o++)i[o]!==s[o]&&r.push(o);return{lines:r,numLinesBefore:i.length,numLinesAfter:s.length,numLines:n}}function le(e){return e===Rs}function Si(e,t){let i=e;i.isTTY&&i.setRawMode(t)}function cr({input:e=jt.stdin,output:t=jt.stdout,overwrite:i=!0,hideCursor:s=!0}={}){let n=wt.createInterface({input:e,output:t,prompt:"",tabSize:1});wt.emitKeypressEvents(e,n),e instanceof Os.ReadStream&&e.isTTY&&e.setRawMode(!0);let r=(o,{name:a,sequence:l})=>{let m=String(o);if(Ps([m,a,l],"cancel")){s&&t.write(Re.cursor.show),process.exit(0);return}if(!i)return;wt.moveCursor(t,a==="return"?0:-1,a==="return"?-1:0,()=>{wt.clearLine(t,1,()=>{e.once("keypress",r)})})};return s&&t.write(Re.cursor.hide),e.once("keypress",r),()=>{e.off("keypress",r),s&&t.write(Re.cursor.show),e instanceof Os.ReadStream&&e.isTTY&&!Ha&&e.setRawMode(!1),n.terminal=!1,n.close()}}function nt(e,t,i,s=i){let n=St(e??jt.stdout);return Is(t,n-i.length,{hard:!0,trim:!1}).split(`
35
35
  `).map((r,o)=>`${o===0?s:i}${r}`).join(`
36
- `)}function Ja(e,t){if(e===void 0||t.length===0)return 0;let i=t.findIndex(s=>s.value===e);return i!==-1?i:0}function Ba(e,t){return(t.label??String(t.value)).toLowerCase().includes(e.toLowerCase())}function Ga(e,t){if(t)return e?t:t[0]}var vt,xt,wt,nr,Re,Os,Ra,Aa,Ea,xs,_i,ji,Ss,xi,Pa,Da,rr,Ta,ti,Pi,or,Na,As,ar,Ua,lr,Es,tr,Fa,ir,sr,qa,Cs,Ma,La,Va,ce,Ha,Rs,St,Ds,st,ii,Ci,Oi,Ii,ur,Ri,Ai,Ei,Ts=Ie(()=>{vt=U(L(),1),xt=require("node:process"),wt=U(require("node:readline"),1),nr=U(require("node:readline"),1),Re=U(js(),1),Os=require("node:tty");Ra=e=>e===161||e===164||e===167||e===168||e===170||e===173||e===174||e>=176&&e<=180||e>=182&&e<=186||e>=188&&e<=191||e===198||e===208||e===215||e===216||e>=222&&e<=225||e===230||e>=232&&e<=234||e===236||e===237||e===240||e===242||e===243||e>=247&&e<=250||e===252||e===254||e===257||e===273||e===275||e===283||e===294||e===295||e===299||e>=305&&e<=307||e===312||e>=319&&e<=322||e===324||e>=328&&e<=331||e===333||e===338||e===339||e===358||e===359||e===363||e===462||e===464||e===466||e===468||e===470||e===472||e===474||e===476||e===593||e===609||e===708||e===711||e>=713&&e<=715||e===717||e===720||e>=728&&e<=731||e===733||e===735||e>=768&&e<=879||e>=913&&e<=929||e>=931&&e<=937||e>=945&&e<=961||e>=963&&e<=969||e===1025||e>=1040&&e<=1103||e===1105||e===8208||e>=8211&&e<=8214||e===8216||e===8217||e===8220||e===8221||e>=8224&&e<=8226||e>=8228&&e<=8231||e===8240||e===8242||e===8243||e===8245||e===8251||e===8254||e===8308||e===8319||e>=8321&&e<=8324||e===8364||e===8451||e===8453||e===8457||e===8467||e===8470||e===8481||e===8482||e===8486||e===8491||e===8531||e===8532||e>=8539&&e<=8542||e>=8544&&e<=8555||e>=8560&&e<=8569||e===8585||e>=8592&&e<=8601||e===8632||e===8633||e===8658||e===8660||e===8679||e===8704||e===8706||e===8707||e===8711||e===8712||e===8715||e===8719||e===8721||e===8725||e===8730||e>=8733&&e<=8736||e===8739||e===8741||e>=8743&&e<=8748||e===8750||e>=8756&&e<=8759||e===8764||e===8765||e===8776||e===8780||e===8786||e===8800||e===8801||e>=8804&&e<=8807||e===8810||e===8811||e===8814||e===8815||e===8834||e===8835||e===8838||e===8839||e===8853||e===8857||e===8869||e===8895||e===8978||e>=9312&&e<=9449||e>=9451&&e<=9547||e>=9552&&e<=9587||e>=9600&&e<=9615||e>=9618&&e<=9621||e===9632||e===9633||e>=9635&&e<=9641||e===9650||e===9651||e===9654||e===9655||e===9660||e===9661||e===9664||e===9665||e>=9670&&e<=9672||e===9675||e>=9678&&e<=9681||e>=9698&&e<=9701||e===9711||e===9733||e===9734||e===9737||e===9742||e===9743||e===9756||e===9758||e===9792||e===9794||e===9824||e===9825||e>=9827&&e<=9829||e>=9831&&e<=9834||e===9836||e===9837||e===9839||e===9886||e===9887||e===9919||e>=9926&&e<=9933||e>=9935&&e<=9939||e>=9941&&e<=9953||e===9955||e===9960||e===9961||e>=9963&&e<=9969||e===9972||e>=9974&&e<=9977||e===9979||e===9980||e===9982||e===9983||e===10045||e>=10102&&e<=10111||e>=11094&&e<=11097||e>=12872&&e<=12879||e>=57344&&e<=63743||e>=65024&&e<=65039||e===65533||e>=127232&&e<=127242||e>=127248&&e<=127277||e>=127280&&e<=127337||e>=127344&&e<=127373||e===127375||e===127376||e>=127387&&e<=127404||e>=917760&&e<=917999||e>=983040&&e<=1048573||e>=1048576&&e<=1114109,Aa=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Ea=e=>e>=4352&&e<=4447||e===8986||e===8987||e===9001||e===9002||e>=9193&&e<=9196||e===9200||e===9203||e===9725||e===9726||e===9748||e===9749||e>=9800&&e<=9811||e===9855||e===9875||e===9889||e===9898||e===9899||e===9917||e===9918||e===9924||e===9925||e===9934||e===9940||e===9962||e===9970||e===9971||e===9973||e===9978||e===9981||e===9989||e===9994||e===9995||e===10024||e===10060||e===10062||e>=10067&&e<=10069||e===10071||e>=10133&&e<=10135||e===10160||e===10175||e===11035||e===11036||e===11088||e===11093||e>=11904&&e<=11929||e>=11931&&e<=12019||e>=12032&&e<=12245||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12353&&e<=12438||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=19968&&e<=42124||e>=42128&&e<=42182||e>=43360&&e<=43388||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=94176&&e<=94180||e===94192||e===94193||e>=94208&&e<=100343||e>=100352&&e<=101589||e>=101632&&e<=101640||e>=110576&&e<=110579||e>=110581&&e<=110587||e===110589||e===110590||e>=110592&&e<=110882||e===110898||e>=110928&&e<=110930||e===110933||e>=110948&&e<=110951||e>=110960&&e<=111355||e===126980||e===127183||e===127374||e>=127377&&e<=127386||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e===127568||e===127569||e>=127584&&e<=127589||e>=127744&&e<=127776||e>=127789&&e<=127797||e>=127799&&e<=127868||e>=127870&&e<=127891||e>=127904&&e<=127946||e>=127951&&e<=127955||e>=127968&&e<=127984||e===127988||e>=127992&&e<=128062||e===128064||e>=128066&&e<=128252||e>=128255&&e<=128317||e>=128331&&e<=128334||e>=128336&&e<=128359||e===128378||e===128405||e===128406||e===128420||e>=128507&&e<=128591||e>=128640&&e<=128709||e===128716||e>=128720&&e<=128722||e>=128725&&e<=128727||e>=128732&&e<=128735||e===128747||e===128748||e>=128756&&e<=128764||e>=128992&&e<=129003||e===129008||e>=129292&&e<=129338||e>=129340&&e<=129349||e>=129351&&e<=129535||e>=129648&&e<=129660||e>=129664&&e<=129672||e>=129680&&e<=129725||e>=129727&&e<=129733||e>=129742&&e<=129755||e>=129760&&e<=129768||e>=129776&&e<=129784||e>=131072&&e<=196605||e>=196608&&e<=262141,xs=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,_i=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,ji=/\t{1,1000}/y,Ss=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),xi=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Pa=new RegExp("\\p{M}+","gu"),Da={limit:1/0,ellipsis:""},rr=(e,t={},i={})=>{let s=t.limit??1/0,n=t.ellipsis??"",r=t?.ellipsisWidth??(n?rr(n,Da,i).width:0),o=i.ansiWidth??0,a=i.controlWidth??0,l=i.tabWidth??8,m=i.ambiguousWidth??1,f=i.emojiWidth??2,g=i.fullWidthWidth??2,b=i.regularWidth??1,v=i.wideWidth??2,w=0,h=0,_=e.length,j=0,O=!1,R=_,M=Math.max(0,s-r),V=0,ee=0,P=0,E=0;e:for(;;){if(ee>V||h>=_&&h>w){let N=e.slice(V,ee)||e.slice(w,h);j=0;for(let Z of N.replaceAll(Pa,"")){let z=Z.codePointAt(0)||0;if(Aa(z)?E=g:Ea(z)?E=v:m!==b&&Ra(z)?E=m:E=b,P+E>M&&(R=Math.min(R,Math.max(V,w)+j)),P+E>s){O=!0;break e}j+=Z.length,P+=E}V=ee=0}if(h>=_)break;if(xi.lastIndex=h,xi.test(e)){if(j=xi.lastIndex-h,E=j*b,P+E>M&&(R=Math.min(R,h+Math.floor((M-P)/b))),P+E>s){O=!0;break}P+=E,V=w,ee=h,h=w=xi.lastIndex;continue}if(xs.lastIndex=h,xs.test(e)){if(P+o>M&&(R=Math.min(R,h)),P+o>s){O=!0;break}P+=o,V=w,ee=h,h=w=xs.lastIndex;continue}if(_i.lastIndex=h,_i.test(e)){if(j=_i.lastIndex-h,E=j*a,P+E>M&&(R=Math.min(R,h+Math.floor((M-P)/a))),P+E>s){O=!0;break}P+=E,V=w,ee=h,h=w=_i.lastIndex;continue}if(ji.lastIndex=h,ji.test(e)){if(j=ji.lastIndex-h,E=j*l,P+E>M&&(R=Math.min(R,h+Math.floor((M-P)/l))),P+E>s){O=!0;break}P+=E,V=w,ee=h,h=w=ji.lastIndex;continue}if(Ss.lastIndex=h,Ss.test(e)){if(P+f>M&&(R=Math.min(R,h)),P+f>s){O=!0;break}P+=f,V=w,ee=h,h=w=Ss.lastIndex;continue}h+=1}return{width:O?M:P,index:O?R:_,truncated:O,ellipsed:O&&s>=r}},Ta={limit:1/0,ellipsis:"",ellipsisWidth:0},ti=(e,t={})=>rr(e,Ta,t).width,Pi="\x1B",or="\x9B",Na=39,As="\x07",ar="[",Ua="]",lr="m",Es=`${Ua}8;;`,tr=new RegExp(`(?:\\${ar}(?<code>\\d+)m|\\${Es}(?<uri>.*)${As})`,"y"),Fa=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},ir=e=>`${Pi}${ar}${e}${lr}`,sr=e=>`${Pi}${Es}${e}${As}`,qa=e=>e.map(t=>ti(t)),Cs=(e,t,i)=>{let s=t[Symbol.iterator](),n=!1,r=!1,o=e.at(-1),a=o===void 0?0:ti(o),l=s.next(),m=s.next(),f=0;for(;!l.done;){let g=l.value,b=ti(g);a+b<=i?e[e.length-1]+=g:(e.push(g),a=0),(g===Pi||g===or)&&(n=!0,r=t.startsWith(Es,f+1)),n?r?g===As&&(n=!1,r=!1):g===lr&&(n=!1):(a+=b,a===i&&!m.done&&(e.push(""),a=0)),l=m,m=s.next(),f+=g.length}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop())},Ma=e=>{let t=e.split(" "),i=t.length;for(;i>0&&!(ti(t[i-1])>0);)i--;return i===t.length?e:t.slice(0,i).join(" ")+t.slice(i).join("")},La=(e,t,i={})=>{if(i.trim!==!1&&e.trim()==="")return"";let s="",n,r,o=e.split(" "),a=qa(o),l=[""];for(let[w,h]of o.entries()){i.trim!==!1&&(l[l.length-1]=(l.at(-1)??"").trimStart());let _=ti(l.at(-1)??"");if(w!==0&&(_>=t&&(i.wordWrap===!1||i.trim===!1)&&(l.push(""),_=0),(_>0||i.trim===!1)&&(l[l.length-1]+=" ",_++)),i.hard&&a[w]>t){let j=t-_,O=1+Math.floor((a[w]-j-1)/t);Math.floor((a[w]-1)/t)<O&&l.push(""),Cs(l,h,t);continue}if(_+a[w]>t&&_>0&&a[w]>0){if(i.wordWrap===!1&&_<t){Cs(l,h,t);continue}l.push("")}if(_+a[w]>t&&i.wordWrap===!1){Cs(l,h,t);continue}l[l.length-1]+=h}i.trim!==!1&&(l=l.map(w=>Ma(w)));let m=l.join(`
37
- `),f=m[Symbol.iterator](),g=f.next(),b=f.next(),v=0;for(;!g.done;){let w=g.value,h=b.value;if(s+=w,w===Pi||w===or){tr.lastIndex=v+1;let j=tr.exec(m)?.groups;if(j?.code!==void 0){let O=Number.parseFloat(j.code);n=O===Na?void 0:O}else j?.uri!==void 0&&(r=j.uri.length===0?void 0:j.uri)}let _=n?Fa(n):void 0;h===`
38
- `?(r&&(s+=sr("")),n&&_&&(s+=ir(_))):w===`
39
- `&&(n&&_&&(s+=ir(n)),r&&(s+=sr(r))),v+=w.length,g=b,b=f.next()}return s};Va=["up","down","left","right","space","enter","cancel"],ce={actions:new Set(Va),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0};Ha=globalThis.process.platform.startsWith("win"),Rs=Symbol("clack:cancel");St=e=>"columns"in e&&typeof e.columns=="number"?e.columns:80,Ds=e=>"rows"in e&&typeof e.rows=="number"?e.rows:20;st=class{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(t,i=!0){let{input:s=xt.stdin,output:n=xt.stdout,render:r,signal:o,...a}=t;this.opts=a,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=r.bind(this),this._track=i,this._abortSignal=o,this.input=s,this.output=n}unsubscribe(){this._subscribers.clear()}setSubscriber(t,i){let s=this._subscribers.get(t)??[];s.push(i),this._subscribers.set(t,s)}on(t,i){this.setSubscriber(t,{cb:i})}once(t,i){this.setSubscriber(t,{cb:i,once:!0})}emit(t,...i){let s=this._subscribers.get(t)??[],n=[];for(let r of s)r.cb(...i),r.once&&n.push(()=>s.splice(s.indexOf(r),1));for(let r of n)r()}prompt(){return new Promise(t=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),t(Rs);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=nr.default.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),Si(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(Re.cursor.show),this.output.off("resize",this.render),Si(this.input,!1),t(this.value)}),this.once("cancel",()=>{this.output.write(Re.cursor.show),this.output.off("resize",this.render),Si(this.input,!1),t(Rs)})})}_isActionKey(t,i){return t===" "}_setValue(t){this.value=t,this.emit("value",this.value)}_setUserInput(t,i){this.userInput=t??"",this.emit("userInput",this.userInput),i&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(t,i){if(this._track&&i.name!=="return"&&(i.name&&this._isActionKey(t,i)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),i?.name&&(!this._track&&ce.aliases.has(i.name)&&this.emit("cursor",ce.aliases.get(i.name)),ce.actions.has(i.name)&&this.emit("cursor",i.name)),t&&(t.toLowerCase()==="y"||t.toLowerCase()==="n")&&this.emit("confirm",t.toLowerCase()==="y"),this.emit("key",t?.toLowerCase(),i),i?.name==="return"){if(this.opts.validate){let s=this.opts.validate(this.value);s&&(this.error=s instanceof Error?s.message:s,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}Ps([t,i?.name,i?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
36
+ `)}function Ja(e,t){if(e===void 0||t.length===0)return 0;let i=t.findIndex(s=>s.value===e);return i!==-1?i:0}function Ba(e,t){return(t.label??String(t.value)).toLowerCase().includes(e.toLowerCase())}function Ga(e,t){if(t)return e?t:t[0]}var vt,jt,wt,nr,Re,Os,Ra,Aa,Ea,js,_i,xi,Ss,ji,Pa,Da,rr,Ta,ti,Pi,or,Na,As,ar,Ua,lr,Es,tr,Fa,ir,sr,qa,Cs,Ma,La,Va,ce,Ha,Rs,St,Ds,st,ii,Ci,Oi,Ii,ur,Ri,Ai,Ei,Ts=Ie(()=>{vt=U(L(),1),jt=require("node:process"),wt=U(require("node:readline"),1),nr=U(require("node:readline"),1),Re=U(xs(),1),Os=require("node:tty");Ra=e=>e===161||e===164||e===167||e===168||e===170||e===173||e===174||e>=176&&e<=180||e>=182&&e<=186||e>=188&&e<=191||e===198||e===208||e===215||e===216||e>=222&&e<=225||e===230||e>=232&&e<=234||e===236||e===237||e===240||e===242||e===243||e>=247&&e<=250||e===252||e===254||e===257||e===273||e===275||e===283||e===294||e===295||e===299||e>=305&&e<=307||e===312||e>=319&&e<=322||e===324||e>=328&&e<=331||e===333||e===338||e===339||e===358||e===359||e===363||e===462||e===464||e===466||e===468||e===470||e===472||e===474||e===476||e===593||e===609||e===708||e===711||e>=713&&e<=715||e===717||e===720||e>=728&&e<=731||e===733||e===735||e>=768&&e<=879||e>=913&&e<=929||e>=931&&e<=937||e>=945&&e<=961||e>=963&&e<=969||e===1025||e>=1040&&e<=1103||e===1105||e===8208||e>=8211&&e<=8214||e===8216||e===8217||e===8220||e===8221||e>=8224&&e<=8226||e>=8228&&e<=8231||e===8240||e===8242||e===8243||e===8245||e===8251||e===8254||e===8308||e===8319||e>=8321&&e<=8324||e===8364||e===8451||e===8453||e===8457||e===8467||e===8470||e===8481||e===8482||e===8486||e===8491||e===8531||e===8532||e>=8539&&e<=8542||e>=8544&&e<=8555||e>=8560&&e<=8569||e===8585||e>=8592&&e<=8601||e===8632||e===8633||e===8658||e===8660||e===8679||e===8704||e===8706||e===8707||e===8711||e===8712||e===8715||e===8719||e===8721||e===8725||e===8730||e>=8733&&e<=8736||e===8739||e===8741||e>=8743&&e<=8748||e===8750||e>=8756&&e<=8759||e===8764||e===8765||e===8776||e===8780||e===8786||e===8800||e===8801||e>=8804&&e<=8807||e===8810||e===8811||e===8814||e===8815||e===8834||e===8835||e===8838||e===8839||e===8853||e===8857||e===8869||e===8895||e===8978||e>=9312&&e<=9449||e>=9451&&e<=9547||e>=9552&&e<=9587||e>=9600&&e<=9615||e>=9618&&e<=9621||e===9632||e===9633||e>=9635&&e<=9641||e===9650||e===9651||e===9654||e===9655||e===9660||e===9661||e===9664||e===9665||e>=9670&&e<=9672||e===9675||e>=9678&&e<=9681||e>=9698&&e<=9701||e===9711||e===9733||e===9734||e===9737||e===9742||e===9743||e===9756||e===9758||e===9792||e===9794||e===9824||e===9825||e>=9827&&e<=9829||e>=9831&&e<=9834||e===9836||e===9837||e===9839||e===9886||e===9887||e===9919||e>=9926&&e<=9933||e>=9935&&e<=9939||e>=9941&&e<=9953||e===9955||e===9960||e===9961||e>=9963&&e<=9969||e===9972||e>=9974&&e<=9977||e===9979||e===9980||e===9982||e===9983||e===10045||e>=10102&&e<=10111||e>=11094&&e<=11097||e>=12872&&e<=12879||e>=57344&&e<=63743||e>=65024&&e<=65039||e===65533||e>=127232&&e<=127242||e>=127248&&e<=127277||e>=127280&&e<=127337||e>=127344&&e<=127373||e===127375||e===127376||e>=127387&&e<=127404||e>=917760&&e<=917999||e>=983040&&e<=1048573||e>=1048576&&e<=1114109,Aa=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Ea=e=>e>=4352&&e<=4447||e===8986||e===8987||e===9001||e===9002||e>=9193&&e<=9196||e===9200||e===9203||e===9725||e===9726||e===9748||e===9749||e>=9800&&e<=9811||e===9855||e===9875||e===9889||e===9898||e===9899||e===9917||e===9918||e===9924||e===9925||e===9934||e===9940||e===9962||e===9970||e===9971||e===9973||e===9978||e===9981||e===9989||e===9994||e===9995||e===10024||e===10060||e===10062||e>=10067&&e<=10069||e===10071||e>=10133&&e<=10135||e===10160||e===10175||e===11035||e===11036||e===11088||e===11093||e>=11904&&e<=11929||e>=11931&&e<=12019||e>=12032&&e<=12245||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12353&&e<=12438||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=19968&&e<=42124||e>=42128&&e<=42182||e>=43360&&e<=43388||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=94176&&e<=94180||e===94192||e===94193||e>=94208&&e<=100343||e>=100352&&e<=101589||e>=101632&&e<=101640||e>=110576&&e<=110579||e>=110581&&e<=110587||e===110589||e===110590||e>=110592&&e<=110882||e===110898||e>=110928&&e<=110930||e===110933||e>=110948&&e<=110951||e>=110960&&e<=111355||e===126980||e===127183||e===127374||e>=127377&&e<=127386||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e===127568||e===127569||e>=127584&&e<=127589||e>=127744&&e<=127776||e>=127789&&e<=127797||e>=127799&&e<=127868||e>=127870&&e<=127891||e>=127904&&e<=127946||e>=127951&&e<=127955||e>=127968&&e<=127984||e===127988||e>=127992&&e<=128062||e===128064||e>=128066&&e<=128252||e>=128255&&e<=128317||e>=128331&&e<=128334||e>=128336&&e<=128359||e===128378||e===128405||e===128406||e===128420||e>=128507&&e<=128591||e>=128640&&e<=128709||e===128716||e>=128720&&e<=128722||e>=128725&&e<=128727||e>=128732&&e<=128735||e===128747||e===128748||e>=128756&&e<=128764||e>=128992&&e<=129003||e===129008||e>=129292&&e<=129338||e>=129340&&e<=129349||e>=129351&&e<=129535||e>=129648&&e<=129660||e>=129664&&e<=129672||e>=129680&&e<=129725||e>=129727&&e<=129733||e>=129742&&e<=129755||e>=129760&&e<=129768||e>=129776&&e<=129784||e>=131072&&e<=196605||e>=196608&&e<=262141,js=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,_i=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,xi=/\t{1,1000}/y,Ss=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),ji=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Pa=new RegExp("\\p{M}+","gu"),Da={limit:1/0,ellipsis:""},rr=(e,t={},i={})=>{let s=t.limit??1/0,n=t.ellipsis??"",r=t?.ellipsisWidth??(n?rr(n,Da,i).width:0),o=i.ansiWidth??0,a=i.controlWidth??0,l=i.tabWidth??8,m=i.ambiguousWidth??1,f=i.emojiWidth??2,g=i.fullWidthWidth??2,b=i.regularWidth??1,w=i.wideWidth??2,v=0,h=0,_=e.length,x=0,O=!1,R=_,M=Math.max(0,s-r),V=0,ee=0,P=0,E=0;e:for(;;){if(ee>V||h>=_&&h>v){let N=e.slice(V,ee)||e.slice(v,h);x=0;for(let Z of N.replaceAll(Pa,"")){let z=Z.codePointAt(0)||0;if(Aa(z)?E=g:Ea(z)?E=w:m!==b&&Ra(z)?E=m:E=b,P+E>M&&(R=Math.min(R,Math.max(V,v)+x)),P+E>s){O=!0;break e}x+=Z.length,P+=E}V=ee=0}if(h>=_)break;if(ji.lastIndex=h,ji.test(e)){if(x=ji.lastIndex-h,E=x*b,P+E>M&&(R=Math.min(R,h+Math.floor((M-P)/b))),P+E>s){O=!0;break}P+=E,V=v,ee=h,h=v=ji.lastIndex;continue}if(js.lastIndex=h,js.test(e)){if(P+o>M&&(R=Math.min(R,h)),P+o>s){O=!0;break}P+=o,V=v,ee=h,h=v=js.lastIndex;continue}if(_i.lastIndex=h,_i.test(e)){if(x=_i.lastIndex-h,E=x*a,P+E>M&&(R=Math.min(R,h+Math.floor((M-P)/a))),P+E>s){O=!0;break}P+=E,V=v,ee=h,h=v=_i.lastIndex;continue}if(xi.lastIndex=h,xi.test(e)){if(x=xi.lastIndex-h,E=x*l,P+E>M&&(R=Math.min(R,h+Math.floor((M-P)/l))),P+E>s){O=!0;break}P+=E,V=v,ee=h,h=v=xi.lastIndex;continue}if(Ss.lastIndex=h,Ss.test(e)){if(P+f>M&&(R=Math.min(R,h)),P+f>s){O=!0;break}P+=f,V=v,ee=h,h=v=Ss.lastIndex;continue}h+=1}return{width:O?M:P,index:O?R:_,truncated:O,ellipsed:O&&s>=r}},Ta={limit:1/0,ellipsis:"",ellipsisWidth:0},ti=(e,t={})=>rr(e,Ta,t).width,Pi="\x1B",or="\x9B",Na=39,As="\x07",ar="[",Ua="]",lr="m",Es=`${Ua}8;;`,tr=new RegExp(`(?:\\${ar}(?<code>\\d+)m|\\${Es}(?<uri>.*)${As})`,"y"),Fa=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},ir=e=>`${Pi}${ar}${e}${lr}`,sr=e=>`${Pi}${Es}${e}${As}`,qa=e=>e.map(t=>ti(t)),Cs=(e,t,i)=>{let s=t[Symbol.iterator](),n=!1,r=!1,o=e.at(-1),a=o===void 0?0:ti(o),l=s.next(),m=s.next(),f=0;for(;!l.done;){let g=l.value,b=ti(g);a+b<=i?e[e.length-1]+=g:(e.push(g),a=0),(g===Pi||g===or)&&(n=!0,r=t.startsWith(Es,f+1)),n?r?g===As&&(n=!1,r=!1):g===lr&&(n=!1):(a+=b,a===i&&!m.done&&(e.push(""),a=0)),l=m,m=s.next(),f+=g.length}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop())},Ma=e=>{let t=e.split(" "),i=t.length;for(;i>0&&!(ti(t[i-1])>0);)i--;return i===t.length?e:t.slice(0,i).join(" ")+t.slice(i).join("")},La=(e,t,i={})=>{if(i.trim!==!1&&e.trim()==="")return"";let s="",n,r,o=e.split(" "),a=qa(o),l=[""];for(let[v,h]of o.entries()){i.trim!==!1&&(l[l.length-1]=(l.at(-1)??"").trimStart());let _=ti(l.at(-1)??"");if(v!==0&&(_>=t&&(i.wordWrap===!1||i.trim===!1)&&(l.push(""),_=0),(_>0||i.trim===!1)&&(l[l.length-1]+=" ",_++)),i.hard&&a[v]>t){let x=t-_,O=1+Math.floor((a[v]-x-1)/t);Math.floor((a[v]-1)/t)<O&&l.push(""),Cs(l,h,t);continue}if(_+a[v]>t&&_>0&&a[v]>0){if(i.wordWrap===!1&&_<t){Cs(l,h,t);continue}l.push("")}if(_+a[v]>t&&i.wordWrap===!1){Cs(l,h,t);continue}l[l.length-1]+=h}i.trim!==!1&&(l=l.map(v=>Ma(v)));let m=l.join(`
37
+ `),f=m[Symbol.iterator](),g=f.next(),b=f.next(),w=0;for(;!g.done;){let v=g.value,h=b.value;if(s+=v,v===Pi||v===or){tr.lastIndex=w+1;let x=tr.exec(m)?.groups;if(x?.code!==void 0){let O=Number.parseFloat(x.code);n=O===Na?void 0:O}else x?.uri!==void 0&&(r=x.uri.length===0?void 0:x.uri)}let _=n?Fa(n):void 0;h===`
38
+ `?(r&&(s+=sr("")),n&&_&&(s+=ir(_))):v===`
39
+ `&&(n&&_&&(s+=ir(n)),r&&(s+=sr(r))),w+=v.length,g=b,b=f.next()}return s};Va=["up","down","left","right","space","enter","cancel"],ce={actions:new Set(Va),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0};Ha=globalThis.process.platform.startsWith("win"),Rs=Symbol("clack:cancel");St=e=>"columns"in e&&typeof e.columns=="number"?e.columns:80,Ds=e=>"rows"in e&&typeof e.rows=="number"?e.rows:20;st=class{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame="";_subscribers=new Map;_cursor=0;state="initial";error="";value;userInput="";constructor(t,i=!0){let{input:s=jt.stdin,output:n=jt.stdout,render:r,signal:o,...a}=t;this.opts=a,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=r.bind(this),this._track=i,this._abortSignal=o,this.input=s,this.output=n}unsubscribe(){this._subscribers.clear()}setSubscriber(t,i){let s=this._subscribers.get(t)??[];s.push(i),this._subscribers.set(t,s)}on(t,i){this.setSubscriber(t,{cb:i})}once(t,i){this.setSubscriber(t,{cb:i,once:!0})}emit(t,...i){let s=this._subscribers.get(t)??[],n=[];for(let r of s)r.cb(...i),r.once&&n.push(()=>s.splice(s.indexOf(r),1));for(let r of n)r()}prompt(){return new Promise(t=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),t(Rs);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=nr.default.createInterface({input:this.input,tabSize:2,prompt:"",escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on("keypress",this.onKeypress),Si(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(Re.cursor.show),this.output.off("resize",this.render),Si(this.input,!1),t(this.value)}),this.once("cancel",()=>{this.output.write(Re.cursor.show),this.output.off("resize",this.render),Si(this.input,!1),t(Rs)})})}_isActionKey(t,i){return t===" "}_setValue(t){this.value=t,this.emit("value",this.value)}_setUserInput(t,i){this.userInput=t??"",this.emit("userInput",this.userInput),i&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:"u"}),this._setUserInput("")}onKeypress(t,i){if(this._track&&i.name!=="return"&&(i.name&&this._isActionKey(t,i)&&this.rl?.write(null,{ctrl:!0,name:"h"}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state==="error"&&(this.state="active"),i?.name&&(!this._track&&ce.aliases.has(i.name)&&this.emit("cursor",ce.aliases.get(i.name)),ce.actions.has(i.name)&&this.emit("cursor",i.name)),t&&(t.toLowerCase()==="y"||t.toLowerCase()==="n")&&this.emit("confirm",t.toLowerCase()==="y"),this.emit("key",t?.toLowerCase(),i),i?.name==="return"){if(this.opts.validate){let s=this.opts.validate(this.value);s&&(this.error=s instanceof Error?s.message:s,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}Ps([t,i?.name,i?.sequence],"cancel")&&(this.state="cancel"),(this.state==="submit"||this.state==="cancel")&&this.emit("finalize"),this.render(),(this.state==="submit"||this.state==="cancel")&&this.close()}close(){this.input.unpipe(),this.input.removeListener("keypress",this.onKeypress),this.output.write(`
40
40
  `),Si(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let t=Is(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
41
41
  `).length-1;this.output.write(Re.cursor.move(-999,t*-1))}render(){let t=Is(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(t!==this._prevFrame){if(this.state==="initial")this.output.write(Re.cursor.hide);else{let i=Wa(this._prevFrame,t),s=Ds(this.output);if(this.restoreCursor(),i){let n=Math.max(0,i.numLinesAfter-s),r=Math.max(0,i.numLinesBefore-s),o=i.lines.find(a=>a>=n);if(o===void 0){this._prevFrame=t;return}if(i.lines.length===1){this.output.write(Re.cursor.move(0,o-r)),this.output.write(Re.erase.lines(1));let a=t.split(`
42
42
  `);this.output.write(a[o]),this._prevFrame=t,this.output.write(Re.cursor.move(0,a.length-o-1));return}else if(i.lines.length>1){if(n<r)o=n;else{let l=o-r;l>0&&this.output.write(Re.cursor.move(0,l))}this.output.write(Re.erase.down());let a=t.split(`
43
43
  `).slice(o);this.output.write(a.join(`
44
- `)),this._prevFrame=t;return}}this.output.write(Re.erase.down())}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t}}};ii=class extends st{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#e=0;#i="";#s;#t;get cursor(){return this.#e}get userInputWithCursor(){if(!this.userInput)return vt.default.inverse(vt.default.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}\u2588`;let t=this.userInput.slice(0,this._cursor),[i,...s]=this.userInput.slice(this._cursor);return`${t}${vt.default.inverse(i)}${s.join("")}`}get options(){return typeof this.#t=="function"?this.#t():this.#t}constructor(t){super(t),this.#t=t.options;let i=this.options;this.filteredOptions=[...i],this.multiple=t.multiple===!0,this.#s=t.filter??Ba;let s;if(t.initialValue&&Array.isArray(t.initialValue)?this.multiple?s=t.initialValue:s=t.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(s=[this.options[0].value]),s)for(let n of s){let r=i.findIndex(o=>o.value===n);r!==-1&&(this.toggleSelected(n),this.#e=r)}this.focusedValue=this.options[this.#e]?.value,this.on("key",(n,r)=>this.#n(n,r)),this.on("userInput",n=>this.#r(n))}_isActionKey(t,i){return t===" "||this.multiple&&this.isNavigating&&i.name==="space"&&t!==void 0&&t!==""}#n(t,i){let s=i.name==="up",n=i.name==="down",r=i.name==="return";s||n?(this.#e=ft(this.#e,s?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#e]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):r?this.value=Ga(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(i.name==="tab"||this.isNavigating&&i.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(t){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(t)?this.selectedValues=this.selectedValues.filter(i=>i!==t):this.selectedValues=[...this.selectedValues,t]:this.selectedValues=[t])}#r(t){if(t!==this.#i){this.#i=t;let i=this.options;t?this.filteredOptions=i.filter(r=>this.#s(t,r)):this.filteredOptions=[...i];let s=Ja(this.focusedValue,this.filteredOptions);this.#e=ft(s,0,this.filteredOptions);let n=this.filteredOptions[this.#e];n&&!n.disabled?this.focusedValue=n.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}},Ci=class extends st{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t){super(t,!1),this.value=!!t.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",i=>{this.output.write(Re.cursor.move(0,-1)),this.value=i,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}},Oi=class extends st{options;cursor=0;#e;getGroupItems(t){return this.options.filter(i=>i.group===t)}isGroupSelected(t){let i=this.getGroupItems(t),s=this.value;return s===void 0?!1:i.every(n=>s.includes(n.value))}toggleValue(){let t=this.options[this.cursor];if(this.value===void 0&&(this.value=[]),t.group===!0){let i=t.value,s=this.getGroupItems(i);this.isGroupSelected(i)?this.value=this.value.filter(n=>s.findIndex(r=>r.value===n)===-1):this.value=[...this.value,...s.map(n=>n.value)],this.value=Array.from(new Set(this.value))}else{let i=this.value.includes(t.value);this.value=i?this.value.filter(s=>s!==t.value):[...this.value,t.value]}}constructor(t){super(t,!1);let{options:i}=t;this.#e=t.selectableGroups!==!1,this.options=Object.entries(i).flatMap(([s,n])=>[{value:s,group:!0,label:s},...n.map(r=>({...r,group:s}))]),this.value=[...t.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:s})=>s===t.cursorAt),this.#e?0:1),this.on("cursor",s=>{switch(s){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let n=this.options[this.cursor]?.group===!0;!this.#e&&n&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let n=this.options[this.cursor]?.group===!0;!this.#e&&n&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},Ii=class extends st{options;cursor=0;get _value(){return this.options[this.cursor].value}get _enabledOptions(){return this.options.filter(t=>t.disabled!==!0)}toggleAll(){let t=this._enabledOptions,i=this.value!==void 0&&this.value.length===t.length;this.value=i?[]:t.map(s=>s.value)}toggleInvert(){let t=this.value;if(!t)return;let i=this._enabledOptions.filter(s=>!t.includes(s.value));this.value=i.map(s=>s.value)}toggleValue(){this.value===void 0&&(this.value=[]);let t=this.value.includes(this._value);this.value=t?this.value.filter(i=>i!==this._value):[...this.value,this._value]}constructor(t){super(t,!1),this.options=t.options,this.value=[...t.initialValues??[]];let i=Math.max(this.options.findIndex(({value:s})=>s===t.cursorAt),0);this.cursor=this.options[i].disabled?ft(i,1,this.options):i,this.on("key",s=>{s==="a"&&this.toggleAll(),s==="i"&&this.toggleInvert()}),this.on("cursor",s=>{switch(s){case"left":case"up":this.cursor=ft(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=ft(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}},ur=class extends st{_mask="\u2022";get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state==="submit"||this.state==="cancel")return this.masked;let e=this.userInput;if(this.cursor>=e.length)return`${this.masked}${vt.default.inverse(vt.default.hidden("_"))}`;let t=this.masked,i=t.slice(0,this.cursor),s=t.slice(this.cursor);return`${i}${vt.default.inverse(s[0])}${s.slice(1)}`}clear(){this._clearUserInput()}constructor({mask:e,...t}){super(t),this._mask=e??"\u2022",this.on("userInput",i=>{this._setValue(i)})}},Ri=class extends st{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}constructor(t){super(t,!1),this.options=t.options;let i=this.options.findIndex(({value:n})=>n===t.initialValue),s=i===-1?0:i;this.cursor=this.options[s].disabled?ft(s,1,this.options):s,this.changeValue(),this.on("cursor",n=>{switch(n){case"left":case"up":this.cursor=ft(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=ft(this.cursor,1,this.options);break}this.changeValue()})}},Ai=class extends st{options;cursor=0;constructor(t){super(t,!1),this.options=t.options;let i=t.caseSensitive===!0,s=this.options.map(({value:[n]})=>i?n:n?.toLowerCase());this.cursor=Math.max(s.indexOf(t.initialValue),0),this.on("key",(n,r)=>{if(!n)return;let o=i&&r.shift?n.toUpperCase():n;if(!s.includes(o))return;let a=this.options.find(({value:[l]})=>i?l===o:l?.toLowerCase()===n);a&&(this.value=a.value,this.state="submit",this.emit("submit"))})}},Ei=class extends st{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t=this.userInput;if(this.cursor>=t.length)return`${this.userInput}\u2588`;let i=t.slice(0,this.cursor),[s,...n]=t.slice(this.cursor);return`${i}${vt.default.inverse(s)}${n.join("")}`}get cursor(){return this._cursor}constructor(t){super({...t,initialUserInput:t.initialUserInput??t.initialValue}),this.on("userInput",i=>{this._setValue(i)}),this.on("finalize",()=>{this.value||(this.value=t.defaultValue),this.value===void 0&&(this.value="")})}}});var Qs={};Mt(Qs,{S_BAR:()=>A,S_BAR_END:()=>ke,S_BAR_END_RIGHT:()=>kr,S_BAR_H:()=>Li,S_BAR_START:()=>Vs,S_BAR_START_RIGHT:()=>wr,S_CHECKBOX_ACTIVE:()=>Mi,S_CHECKBOX_INACTIVE:()=>Gt,S_CHECKBOX_SELECTED:()=>Ot,S_CONNECT_LEFT:()=>jr,S_CORNER_BOTTOM_LEFT:()=>Js,S_CORNER_BOTTOM_RIGHT:()=>Hs,S_CORNER_TOP_LEFT:()=>xr,S_CORNER_TOP_RIGHT:()=>Ws,S_ERROR:()=>zs,S_INFO:()=>Bs,S_PASSWORD_MASK:()=>_r,S_RADIO_ACTIVE:()=>ri,S_RADIO_INACTIVE:()=>Rt,S_STEP_ACTIVE:()=>vr,S_STEP_CANCEL:()=>Ms,S_STEP_ERROR:()=>Ls,S_STEP_SUBMIT:()=>At,S_SUCCESS:()=>Gs,S_WARN:()=>Ks,autocomplete:()=>Ar,autocompleteMultiselect:()=>dl,box:()=>fl,cancel:()=>gl,confirm:()=>Ke,group:()=>pl,groupMultiselect:()=>hl,intro:()=>bl,isCI:()=>qs,isCancel:()=>le,isTTY:()=>$r,limitOptions:()=>zt,log:()=>Ve,multiselect:()=>$l,note:()=>kl,outro:()=>yl,password:()=>_l,path:()=>jl,progress:()=>Sl,select:()=>Qe,selectKey:()=>Cl,settings:()=>ce,spinner:()=>oi,stream:()=>Ct,symbol:()=>Ze,symbolBar:()=>Ys,taskLog:()=>Rl,tasks:()=>Ol,text:()=>Ae,unicode:()=>qi,unicodeOr:()=>oe,updateSettings:()=>dr});function Ka(){return Le.default.platform!=="win32"?Le.default.env.TERM!=="linux":!!Le.default.env.CI||!!Le.default.env.WT_SESSION||!!Le.default.env.TERMINUS_SUBLIME||Le.default.env.ConEmuTask==="{cmd::Cmder}"||Le.default.env.TERM_PROGRAM==="Terminus-Sublime"||Le.default.env.TERM_PROGRAM==="vscode"||Le.default.env.TERM==="xterm-256color"||Le.default.env.TERM==="alacritty"||Le.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}function Kt(e,t,i){return String(e).normalize().replaceAll(`\r
44
+ `)),this._prevFrame=t;return}}this.output.write(Re.erase.down())}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t}}};ii=class extends st{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#e=0;#i="";#s;#t;get cursor(){return this.#e}get userInputWithCursor(){if(!this.userInput)return vt.default.inverse(vt.default.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}\u2588`;let t=this.userInput.slice(0,this._cursor),[i,...s]=this.userInput.slice(this._cursor);return`${t}${vt.default.inverse(i)}${s.join("")}`}get options(){return typeof this.#t=="function"?this.#t():this.#t}constructor(t){super(t),this.#t=t.options;let i=this.options;this.filteredOptions=[...i],this.multiple=t.multiple===!0,this.#s=t.filter??Ba;let s;if(t.initialValue&&Array.isArray(t.initialValue)?this.multiple?s=t.initialValue:s=t.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(s=[this.options[0].value]),s)for(let n of s){let r=i.findIndex(o=>o.value===n);r!==-1&&(this.toggleSelected(n),this.#e=r)}this.focusedValue=this.options[this.#e]?.value,this.on("key",(n,r)=>this.#n(n,r)),this.on("userInput",n=>this.#r(n))}_isActionKey(t,i){return t===" "||this.multiple&&this.isNavigating&&i.name==="space"&&t!==void 0&&t!==""}#n(t,i){let s=i.name==="up",n=i.name==="down",r=i.name==="return";s||n?(this.#e=ft(this.#e,s?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#e]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):r?this.value=Ga(this.multiple,this.selectedValues):this.multiple?this.focusedValue!==void 0&&(i.name==="tab"||this.isNavigating&&i.name==="space")?this.toggleSelected(this.focusedValue):this.isNavigating=!1:(this.focusedValue&&(this.selectedValues=[this.focusedValue]),this.isNavigating=!1)}deselectAll(){this.selectedValues=[]}toggleSelected(t){this.filteredOptions.length!==0&&(this.multiple?this.selectedValues.includes(t)?this.selectedValues=this.selectedValues.filter(i=>i!==t):this.selectedValues=[...this.selectedValues,t]:this.selectedValues=[t])}#r(t){if(t!==this.#i){this.#i=t;let i=this.options;t?this.filteredOptions=i.filter(r=>this.#s(t,r)):this.filteredOptions=[...i];let s=Ja(this.focusedValue,this.filteredOptions);this.#e=ft(s,0,this.filteredOptions);let n=this.filteredOptions[this.#e];n&&!n.disabled?this.focusedValue=n.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}},Ci=class extends st{get cursor(){return this.value?0:1}get _value(){return this.cursor===0}constructor(t){super(t,!1),this.value=!!t.initialValue,this.on("userInput",()=>{this.value=this._value}),this.on("confirm",i=>{this.output.write(Re.cursor.move(0,-1)),this.value=i,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}},Oi=class extends st{options;cursor=0;#e;getGroupItems(t){return this.options.filter(i=>i.group===t)}isGroupSelected(t){let i=this.getGroupItems(t),s=this.value;return s===void 0?!1:i.every(n=>s.includes(n.value))}toggleValue(){let t=this.options[this.cursor];if(this.value===void 0&&(this.value=[]),t.group===!0){let i=t.value,s=this.getGroupItems(i);this.isGroupSelected(i)?this.value=this.value.filter(n=>s.findIndex(r=>r.value===n)===-1):this.value=[...this.value,...s.map(n=>n.value)],this.value=Array.from(new Set(this.value))}else{let i=this.value.includes(t.value);this.value=i?this.value.filter(s=>s!==t.value):[...this.value,t.value]}}constructor(t){super(t,!1);let{options:i}=t;this.#e=t.selectableGroups!==!1,this.options=Object.entries(i).flatMap(([s,n])=>[{value:s,group:!0,label:s},...n.map(r=>({...r,group:s}))]),this.value=[...t.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:s})=>s===t.cursorAt),this.#e?0:1),this.on("cursor",s=>{switch(s){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let n=this.options[this.cursor]?.group===!0;!this.#e&&n&&(this.cursor=this.cursor===0?this.options.length-1:this.cursor-1);break}case"down":case"right":{this.cursor=this.cursor===this.options.length-1?0:this.cursor+1;let n=this.options[this.cursor]?.group===!0;!this.#e&&n&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},Ii=class extends st{options;cursor=0;get _value(){return this.options[this.cursor].value}get _enabledOptions(){return this.options.filter(t=>t.disabled!==!0)}toggleAll(){let t=this._enabledOptions,i=this.value!==void 0&&this.value.length===t.length;this.value=i?[]:t.map(s=>s.value)}toggleInvert(){let t=this.value;if(!t)return;let i=this._enabledOptions.filter(s=>!t.includes(s.value));this.value=i.map(s=>s.value)}toggleValue(){this.value===void 0&&(this.value=[]);let t=this.value.includes(this._value);this.value=t?this.value.filter(i=>i!==this._value):[...this.value,this._value]}constructor(t){super(t,!1),this.options=t.options,this.value=[...t.initialValues??[]];let i=Math.max(this.options.findIndex(({value:s})=>s===t.cursorAt),0);this.cursor=this.options[i].disabled?ft(i,1,this.options):i,this.on("key",s=>{s==="a"&&this.toggleAll(),s==="i"&&this.toggleInvert()}),this.on("cursor",s=>{switch(s){case"left":case"up":this.cursor=ft(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=ft(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}},ur=class extends st{_mask="\u2022";get cursor(){return this._cursor}get masked(){return this.userInput.replaceAll(/./g,this._mask)}get userInputWithCursor(){if(this.state==="submit"||this.state==="cancel")return this.masked;let e=this.userInput;if(this.cursor>=e.length)return`${this.masked}${vt.default.inverse(vt.default.hidden("_"))}`;let t=this.masked,i=t.slice(0,this.cursor),s=t.slice(this.cursor);return`${i}${vt.default.inverse(s[0])}${s.slice(1)}`}clear(){this._clearUserInput()}constructor({mask:e,...t}){super(t),this._mask=e??"\u2022",this.on("userInput",i=>{this._setValue(i)})}},Ri=class extends st{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}constructor(t){super(t,!1),this.options=t.options;let i=this.options.findIndex(({value:n})=>n===t.initialValue),s=i===-1?0:i;this.cursor=this.options[s].disabled?ft(s,1,this.options):s,this.changeValue(),this.on("cursor",n=>{switch(n){case"left":case"up":this.cursor=ft(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=ft(this.cursor,1,this.options);break}this.changeValue()})}},Ai=class extends st{options;cursor=0;constructor(t){super(t,!1),this.options=t.options;let i=t.caseSensitive===!0,s=this.options.map(({value:[n]})=>i?n:n?.toLowerCase());this.cursor=Math.max(s.indexOf(t.initialValue),0),this.on("key",(n,r)=>{if(!n)return;let o=i&&r.shift?n.toUpperCase():n;if(!s.includes(o))return;let a=this.options.find(({value:[l]})=>i?l===o:l?.toLowerCase()===n);a&&(this.value=a.value,this.state="submit",this.emit("submit"))})}},Ei=class extends st{get userInputWithCursor(){if(this.state==="submit")return this.userInput;let t=this.userInput;if(this.cursor>=t.length)return`${this.userInput}\u2588`;let i=t.slice(0,this.cursor),[s,...n]=t.slice(this.cursor);return`${i}${vt.default.inverse(s)}${n.join("")}`}get cursor(){return this._cursor}constructor(t){super({...t,initialUserInput:t.initialUserInput??t.initialValue}),this.on("userInput",i=>{this._setValue(i)}),this.on("finalize",()=>{this.value||(this.value=t.defaultValue),this.value===void 0&&(this.value="")})}}});var Qs={};Mt(Qs,{S_BAR:()=>A,S_BAR_END:()=>_e,S_BAR_END_RIGHT:()=>kr,S_BAR_H:()=>Li,S_BAR_START:()=>Vs,S_BAR_START_RIGHT:()=>wr,S_CHECKBOX_ACTIVE:()=>Mi,S_CHECKBOX_INACTIVE:()=>Gt,S_CHECKBOX_SELECTED:()=>Ot,S_CONNECT_LEFT:()=>xr,S_CORNER_BOTTOM_LEFT:()=>Js,S_CORNER_BOTTOM_RIGHT:()=>Hs,S_CORNER_TOP_LEFT:()=>jr,S_CORNER_TOP_RIGHT:()=>Ws,S_ERROR:()=>zs,S_INFO:()=>Bs,S_PASSWORD_MASK:()=>_r,S_RADIO_ACTIVE:()=>ri,S_RADIO_INACTIVE:()=>Rt,S_STEP_ACTIVE:()=>vr,S_STEP_CANCEL:()=>Ms,S_STEP_ERROR:()=>Ls,S_STEP_SUBMIT:()=>At,S_SUCCESS:()=>Gs,S_WARN:()=>Ks,autocomplete:()=>Ar,autocompleteMultiselect:()=>dl,box:()=>fl,cancel:()=>gl,confirm:()=>Ke,group:()=>pl,groupMultiselect:()=>hl,intro:()=>bl,isCI:()=>qs,isCancel:()=>le,isTTY:()=>$r,limitOptions:()=>zt,log:()=>Ve,multiselect:()=>$l,note:()=>kl,outro:()=>yl,password:()=>_l,path:()=>xl,progress:()=>Sl,select:()=>Qe,selectKey:()=>Cl,settings:()=>ce,spinner:()=>oi,stream:()=>Ct,symbol:()=>Ze,symbolBar:()=>Ys,taskLog:()=>Rl,tasks:()=>Ol,text:()=>Ae,unicode:()=>qi,unicodeOr:()=>oe,updateSettings:()=>dr});function Ka(){return Le.default.platform!=="win32"?Le.default.env.TERM!=="linux":!!Le.default.env.CI||!!Le.default.env.WT_SESSION||!!Le.default.env.TERMINUS_SUBLIME||Le.default.env.ConEmuTask==="{cmd::Cmder}"||Le.default.env.TERM_PROGRAM==="Terminus-Sublime"||Le.default.env.TERM_PROGRAM==="vscode"||Le.default.env.TERM==="xterm-256color"||Le.default.env.TERM==="alacritty"||Le.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}function Kt(e,t,i){return String(e).normalize().replaceAll(`\r
45
45
  `,`
46
46
  `).split(`
47
47
  `).map(s=>ol(s,t,i)).join(`
48
- `)}function hr(e){return e.label??String(e.value??"")}function Rr(e,t){if(!e)return!0;let i=(t.label??String(t.value??"")).toLowerCase(),s=(t.hint??"").toLowerCase(),n=String(t.value).toLowerCase(),r=e.toLowerCase();return i.includes(r)||s.includes(r)||n.includes(r)}function ll(e,t){let i=[];for(let s of t)e.includes(s.value)&&i.push(s);return i}function gr(e,t,i,s){let n=i,r=i;return s==="center"?n=Math.floor((t-e)/2):s==="right"&&(n=t-e-i),r=t-n-e,[n,r]}function Sl({style:e="heavy",max:t=100,size:i=40,...s}={}){let n=oi(s),r=0,o="",a=Math.max(1,t),l=Math.max(1,i),m=v=>{switch(v){case"initial":case"active":return p.default.magenta;case"error":case"cancel":return p.default.red;case"submit":return p.default.green;default:return p.default.magenta}},f=(v,w)=>{let h=Math.floor(r/a*l);return`${m(v)(br[e].repeat(h))}${p.default.dim(br[e].repeat(l-h))} ${w}`},g=(v="")=>{o=v,n.start(f("initial",v))},b=(v=1,w)=>{r=Math.min(a,v+r),n.message(f("active",w??o)),o=w??o};return{start:g,stop:n.stop,cancel:n.cancel,error:n.error,clear:n.clear,advance:b,isCancelled:n.isCancelled,message:v=>b(0,v)}}var p,Le,It,ni,Bt,Fi,qi,qs,$r,oe,vr,Ms,Ls,At,Vs,A,ke,wr,kr,ri,Rt,Mi,Ot,Gt,_r,Li,Ws,jr,Hs,Js,xr,Bs,Gs,Ks,zs,Ze,Ys,za,Ya,Xa,Ns,Di,Ti,Us,Ni,Za,Qa,Sr,el,Pe,Vi,Cr,tl,Xs,Or,il,Ir,Zs,mr,sl,fr,pr,nl,Fs,rl,ol,al,zt,Ar,dl,cl,ul,ml,fl,Ke,pl,hl,Ve,gl,bl,yl,si,$l,vl,wl,kl,_l,jl,xl,oi,br,Ui,Qe,Cl,yr,Ct,Ol,Il,Rl,Ae,De=Ie(()=>{Ts();Ts();p=U(L(),1),Le=U(require("node:process"),1),It=require("node:fs"),ni=require("node:path"),Bt=U(js(),1),Fi=require("node:util");qi=Ka(),qs=()=>process.env.CI==="true",$r=e=>e.isTTY===!0,oe=(e,t)=>qi?e:t,vr=oe("\u25C6","*"),Ms=oe("\u25A0","x"),Ls=oe("\u25B2","x"),At=oe("\u25C7","o"),Vs=oe("\u250C","T"),A=oe("\u2502","|"),ke=oe("\u2514","\u2014"),wr=oe("\u2510","T"),kr=oe("\u2518","\u2014"),ri=oe("\u25CF",">"),Rt=oe("\u25CB"," "),Mi=oe("\u25FB","[\u2022]"),Ot=oe("\u25FC","[+]"),Gt=oe("\u25FB","[ ]"),_r=oe("\u25AA","\u2022"),Li=oe("\u2500","-"),Ws=oe("\u256E","+"),jr=oe("\u251C","+"),Hs=oe("\u256F","+"),Js=oe("\u2570","+"),xr=oe("\u256D","+"),Bs=oe("\u25CF","\u2022"),Gs=oe("\u25C6","*"),Ks=oe("\u25B2","!"),zs=oe("\u25A0","x"),Ze=e=>{switch(e){case"initial":case"active":return p.default.cyan(vr);case"cancel":return p.default.red(Ms);case"error":return p.default.yellow(Ls);case"submit":return p.default.green(At)}},Ys=e=>{switch(e){case"initial":case"active":return p.default.cyan(A);case"cancel":return p.default.red(A);case"error":return p.default.yellow(A);case"submit":return p.default.green(A)}},za=e=>e===161||e===164||e===167||e===168||e===170||e===173||e===174||e>=176&&e<=180||e>=182&&e<=186||e>=188&&e<=191||e===198||e===208||e===215||e===216||e>=222&&e<=225||e===230||e>=232&&e<=234||e===236||e===237||e===240||e===242||e===243||e>=247&&e<=250||e===252||e===254||e===257||e===273||e===275||e===283||e===294||e===295||e===299||e>=305&&e<=307||e===312||e>=319&&e<=322||e===324||e>=328&&e<=331||e===333||e===338||e===339||e===358||e===359||e===363||e===462||e===464||e===466||e===468||e===470||e===472||e===474||e===476||e===593||e===609||e===708||e===711||e>=713&&e<=715||e===717||e===720||e>=728&&e<=731||e===733||e===735||e>=768&&e<=879||e>=913&&e<=929||e>=931&&e<=937||e>=945&&e<=961||e>=963&&e<=969||e===1025||e>=1040&&e<=1103||e===1105||e===8208||e>=8211&&e<=8214||e===8216||e===8217||e===8220||e===8221||e>=8224&&e<=8226||e>=8228&&e<=8231||e===8240||e===8242||e===8243||e===8245||e===8251||e===8254||e===8308||e===8319||e>=8321&&e<=8324||e===8364||e===8451||e===8453||e===8457||e===8467||e===8470||e===8481||e===8482||e===8486||e===8491||e===8531||e===8532||e>=8539&&e<=8542||e>=8544&&e<=8555||e>=8560&&e<=8569||e===8585||e>=8592&&e<=8601||e===8632||e===8633||e===8658||e===8660||e===8679||e===8704||e===8706||e===8707||e===8711||e===8712||e===8715||e===8719||e===8721||e===8725||e===8730||e>=8733&&e<=8736||e===8739||e===8741||e>=8743&&e<=8748||e===8750||e>=8756&&e<=8759||e===8764||e===8765||e===8776||e===8780||e===8786||e===8800||e===8801||e>=8804&&e<=8807||e===8810||e===8811||e===8814||e===8815||e===8834||e===8835||e===8838||e===8839||e===8853||e===8857||e===8869||e===8895||e===8978||e>=9312&&e<=9449||e>=9451&&e<=9547||e>=9552&&e<=9587||e>=9600&&e<=9615||e>=9618&&e<=9621||e===9632||e===9633||e>=9635&&e<=9641||e===9650||e===9651||e===9654||e===9655||e===9660||e===9661||e===9664||e===9665||e>=9670&&e<=9672||e===9675||e>=9678&&e<=9681||e>=9698&&e<=9701||e===9711||e===9733||e===9734||e===9737||e===9742||e===9743||e===9756||e===9758||e===9792||e===9794||e===9824||e===9825||e>=9827&&e<=9829||e>=9831&&e<=9834||e===9836||e===9837||e===9839||e===9886||e===9887||e===9919||e>=9926&&e<=9933||e>=9935&&e<=9939||e>=9941&&e<=9953||e===9955||e===9960||e===9961||e>=9963&&e<=9969||e===9972||e>=9974&&e<=9977||e===9979||e===9980||e===9982||e===9983||e===10045||e>=10102&&e<=10111||e>=11094&&e<=11097||e>=12872&&e<=12879||e>=57344&&e<=63743||e>=65024&&e<=65039||e===65533||e>=127232&&e<=127242||e>=127248&&e<=127277||e>=127280&&e<=127337||e>=127344&&e<=127373||e===127375||e===127376||e>=127387&&e<=127404||e>=917760&&e<=917999||e>=983040&&e<=1048573||e>=1048576&&e<=1114109,Ya=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Xa=e=>e>=4352&&e<=4447||e===8986||e===8987||e===9001||e===9002||e>=9193&&e<=9196||e===9200||e===9203||e===9725||e===9726||e===9748||e===9749||e>=9800&&e<=9811||e===9855||e===9875||e===9889||e===9898||e===9899||e===9917||e===9918||e===9924||e===9925||e===9934||e===9940||e===9962||e===9970||e===9971||e===9973||e===9978||e===9981||e===9989||e===9994||e===9995||e===10024||e===10060||e===10062||e>=10067&&e<=10069||e===10071||e>=10133&&e<=10135||e===10160||e===10175||e===11035||e===11036||e===11088||e===11093||e>=11904&&e<=11929||e>=11931&&e<=12019||e>=12032&&e<=12245||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12353&&e<=12438||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=19968&&e<=42124||e>=42128&&e<=42182||e>=43360&&e<=43388||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=94176&&e<=94180||e===94192||e===94193||e>=94208&&e<=100343||e>=100352&&e<=101589||e>=101632&&e<=101640||e>=110576&&e<=110579||e>=110581&&e<=110587||e===110589||e===110590||e>=110592&&e<=110882||e===110898||e>=110928&&e<=110930||e===110933||e>=110948&&e<=110951||e>=110960&&e<=111355||e===126980||e===127183||e===127374||e>=127377&&e<=127386||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e===127568||e===127569||e>=127584&&e<=127589||e>=127744&&e<=127776||e>=127789&&e<=127797||e>=127799&&e<=127868||e>=127870&&e<=127891||e>=127904&&e<=127946||e>=127951&&e<=127955||e>=127968&&e<=127984||e===127988||e>=127992&&e<=128062||e===128064||e>=128066&&e<=128252||e>=128255&&e<=128317||e>=128331&&e<=128334||e>=128336&&e<=128359||e===128378||e===128405||e===128406||e===128420||e>=128507&&e<=128591||e>=128640&&e<=128709||e===128716||e>=128720&&e<=128722||e>=128725&&e<=128727||e>=128732&&e<=128735||e===128747||e===128748||e>=128756&&e<=128764||e>=128992&&e<=129003||e===129008||e>=129292&&e<=129338||e>=129340&&e<=129349||e>=129351&&e<=129535||e>=129648&&e<=129660||e>=129664&&e<=129672||e>=129680&&e<=129725||e>=129727&&e<=129733||e>=129742&&e<=129755||e>=129760&&e<=129768||e>=129776&&e<=129784||e>=131072&&e<=196605||e>=196608&&e<=262141,Ns=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,Di=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Ti=/\t{1,1000}/y,Us=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),Ni=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Za=new RegExp("\\p{M}+","gu"),Qa={limit:1/0,ellipsis:""},Sr=(e,t={},i={})=>{let s=t.limit??1/0,n=t.ellipsis??"",r=t?.ellipsisWidth??(n?Sr(n,Qa,i).width:0),o=i.ansiWidth??0,a=i.controlWidth??0,l=i.tabWidth??8,m=i.ambiguousWidth??1,f=i.emojiWidth??2,g=i.fullWidthWidth??2,b=i.regularWidth??1,v=i.wideWidth??2,w=0,h=0,_=e.length,j=0,O=!1,R=_,M=Math.max(0,s-r),V=0,ee=0,P=0,E=0;e:for(;;){if(ee>V||h>=_&&h>w){let N=e.slice(V,ee)||e.slice(w,h);j=0;for(let Z of N.replaceAll(Za,"")){let z=Z.codePointAt(0)||0;if(Ya(z)?E=g:Xa(z)?E=v:m!==b&&za(z)?E=m:E=b,P+E>M&&(R=Math.min(R,Math.max(V,w)+j)),P+E>s){O=!0;break e}j+=Z.length,P+=E}V=ee=0}if(h>=_)break;if(Ni.lastIndex=h,Ni.test(e)){if(j=Ni.lastIndex-h,E=j*b,P+E>M&&(R=Math.min(R,h+Math.floor((M-P)/b))),P+E>s){O=!0;break}P+=E,V=w,ee=h,h=w=Ni.lastIndex;continue}if(Ns.lastIndex=h,Ns.test(e)){if(P+o>M&&(R=Math.min(R,h)),P+o>s){O=!0;break}P+=o,V=w,ee=h,h=w=Ns.lastIndex;continue}if(Di.lastIndex=h,Di.test(e)){if(j=Di.lastIndex-h,E=j*a,P+E>M&&(R=Math.min(R,h+Math.floor((M-P)/a))),P+E>s){O=!0;break}P+=E,V=w,ee=h,h=w=Di.lastIndex;continue}if(Ti.lastIndex=h,Ti.test(e)){if(j=Ti.lastIndex-h,E=j*l,P+E>M&&(R=Math.min(R,h+Math.floor((M-P)/l))),P+E>s){O=!0;break}P+=E,V=w,ee=h,h=w=Ti.lastIndex;continue}if(Us.lastIndex=h,Us.test(e)){if(P+f>M&&(R=Math.min(R,h)),P+f>s){O=!0;break}P+=f,V=w,ee=h,h=w=Us.lastIndex;continue}h+=1}return{width:O?M:P,index:O?R:_,truncated:O,ellipsed:O&&s>=r}},el={limit:1/0,ellipsis:"",ellipsisWidth:0},Pe=(e,t={})=>Sr(e,el,t).width,Vi="\x1B",Cr="\x9B",tl=39,Xs="\x07",Or="[",il="]",Ir="m",Zs=`${il}8;;`,mr=new RegExp(`(?:\\${Or}(?<code>\\d+)m|\\${Zs}(?<uri>.*)${Xs})`,"y"),sl=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},fr=e=>`${Vi}${Or}${e}${Ir}`,pr=e=>`${Vi}${Zs}${e}${Xs}`,nl=e=>e.map(t=>Pe(t)),Fs=(e,t,i)=>{let s=t[Symbol.iterator](),n=!1,r=!1,o=e.at(-1),a=o===void 0?0:Pe(o),l=s.next(),m=s.next(),f=0;for(;!l.done;){let g=l.value,b=Pe(g);a+b<=i?e[e.length-1]+=g:(e.push(g),a=0),(g===Vi||g===Cr)&&(n=!0,r=t.startsWith(Zs,f+1)),n?r?g===Xs&&(n=!1,r=!1):g===Ir&&(n=!1):(a+=b,a===i&&!m.done&&(e.push(""),a=0)),l=m,m=s.next(),f+=g.length}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop())},rl=e=>{let t=e.split(" "),i=t.length;for(;i>0&&!(Pe(t[i-1])>0);)i--;return i===t.length?e:t.slice(0,i).join(" ")+t.slice(i).join("")},ol=(e,t,i={})=>{if(i.trim!==!1&&e.trim()==="")return"";let s="",n,r,o=e.split(" "),a=nl(o),l=[""];for(let[w,h]of o.entries()){i.trim!==!1&&(l[l.length-1]=(l.at(-1)??"").trimStart());let _=Pe(l.at(-1)??"");if(w!==0&&(_>=t&&(i.wordWrap===!1||i.trim===!1)&&(l.push(""),_=0),(_>0||i.trim===!1)&&(l[l.length-1]+=" ",_++)),i.hard&&a[w]>t){let j=t-_,O=1+Math.floor((a[w]-j-1)/t);Math.floor((a[w]-1)/t)<O&&l.push(""),Fs(l,h,t);continue}if(_+a[w]>t&&_>0&&a[w]>0){if(i.wordWrap===!1&&_<t){Fs(l,h,t);continue}l.push("")}if(_+a[w]>t&&i.wordWrap===!1){Fs(l,h,t);continue}l[l.length-1]+=h}i.trim!==!1&&(l=l.map(w=>rl(w)));let m=l.join(`
49
- `),f=m[Symbol.iterator](),g=f.next(),b=f.next(),v=0;for(;!g.done;){let w=g.value,h=b.value;if(s+=w,w===Vi||w===Cr){mr.lastIndex=v+1;let j=mr.exec(m)?.groups;if(j?.code!==void 0){let O=Number.parseFloat(j.code);n=O===tl?void 0:O}else j?.uri!==void 0&&(r=j.uri.length===0?void 0:j.uri)}let _=n?sl(n):void 0;h===`
50
- `?(r&&(s+=pr("")),n&&_&&(s+=fr(_))):w===`
51
- `&&(n&&_&&(s+=fr(n)),r&&(s+=pr(r))),v+=w.length,g=b,b=f.next()}return s};al=(e,t,i,s,n)=>{let r=t,o=0;for(let a=i;a<s;a++){let l=e[a];if(r=r-l.length,o++,r<=n)break}return{lineCount:r,removals:o}},zt=e=>{let{cursor:t,options:i,style:s}=e,n=e.output??process.stdout,r=St(n),o=e.columnPadding??0,a=e.rowPadding??4,l=r-o,m=Ds(n),f=p.default.dim("..."),g=e.maxItems??Number.POSITIVE_INFINITY,b=Math.max(m-a,0),v=Math.max(Math.min(g,b),5),w=0;t>=v-3&&(w=Math.max(Math.min(t-v+3,i.length-v),0));let h=v<i.length&&w>0,_=v<i.length&&w+v<i.length,j=Math.min(w+v,i.length),O=[],R=0;h&&R++,_&&R++;let M=w+(h?1:0),V=j-(_?1:0);for(let P=M;P<V;P++){let E=Kt(s(i[P],P===t),l,{hard:!0,trim:!1}).split(`
48
+ `)}function hr(e){return e.label??String(e.value??"")}function Rr(e,t){if(!e)return!0;let i=(t.label??String(t.value??"")).toLowerCase(),s=(t.hint??"").toLowerCase(),n=String(t.value).toLowerCase(),r=e.toLowerCase();return i.includes(r)||s.includes(r)||n.includes(r)}function ll(e,t){let i=[];for(let s of t)e.includes(s.value)&&i.push(s);return i}function gr(e,t,i,s){let n=i,r=i;return s==="center"?n=Math.floor((t-e)/2):s==="right"&&(n=t-e-i),r=t-n-e,[n,r]}function Sl({style:e="heavy",max:t=100,size:i=40,...s}={}){let n=oi(s),r=0,o="",a=Math.max(1,t),l=Math.max(1,i),m=w=>{switch(w){case"initial":case"active":return p.default.magenta;case"error":case"cancel":return p.default.red;case"submit":return p.default.green;default:return p.default.magenta}},f=(w,v)=>{let h=Math.floor(r/a*l);return`${m(w)(br[e].repeat(h))}${p.default.dim(br[e].repeat(l-h))} ${v}`},g=(w="")=>{o=w,n.start(f("initial",w))},b=(w=1,v)=>{r=Math.min(a,w+r),n.message(f("active",v??o)),o=v??o};return{start:g,stop:n.stop,cancel:n.cancel,error:n.error,clear:n.clear,advance:b,isCancelled:n.isCancelled,message:w=>b(0,w)}}var p,Le,It,ni,Bt,Fi,qi,qs,$r,oe,vr,Ms,Ls,At,Vs,A,_e,wr,kr,ri,Rt,Mi,Ot,Gt,_r,Li,Ws,xr,Hs,Js,jr,Bs,Gs,Ks,zs,Ze,Ys,za,Ya,Xa,Ns,Di,Ti,Us,Ni,Za,Qa,Sr,el,Pe,Vi,Cr,tl,Xs,Or,il,Ir,Zs,mr,sl,fr,pr,nl,Fs,rl,ol,al,zt,Ar,dl,cl,ul,ml,fl,Ke,pl,hl,Ve,gl,bl,yl,si,$l,vl,wl,kl,_l,xl,jl,oi,br,Ui,Qe,Cl,yr,Ct,Ol,Il,Rl,Ae,De=Ie(()=>{Ts();Ts();p=U(L(),1),Le=U(require("node:process"),1),It=require("node:fs"),ni=require("node:path"),Bt=U(xs(),1),Fi=require("node:util");qi=Ka(),qs=()=>process.env.CI==="true",$r=e=>e.isTTY===!0,oe=(e,t)=>qi?e:t,vr=oe("\u25C6","*"),Ms=oe("\u25A0","x"),Ls=oe("\u25B2","x"),At=oe("\u25C7","o"),Vs=oe("\u250C","T"),A=oe("\u2502","|"),_e=oe("\u2514","\u2014"),wr=oe("\u2510","T"),kr=oe("\u2518","\u2014"),ri=oe("\u25CF",">"),Rt=oe("\u25CB"," "),Mi=oe("\u25FB","[\u2022]"),Ot=oe("\u25FC","[+]"),Gt=oe("\u25FB","[ ]"),_r=oe("\u25AA","\u2022"),Li=oe("\u2500","-"),Ws=oe("\u256E","+"),xr=oe("\u251C","+"),Hs=oe("\u256F","+"),Js=oe("\u2570","+"),jr=oe("\u256D","+"),Bs=oe("\u25CF","\u2022"),Gs=oe("\u25C6","*"),Ks=oe("\u25B2","!"),zs=oe("\u25A0","x"),Ze=e=>{switch(e){case"initial":case"active":return p.default.cyan(vr);case"cancel":return p.default.red(Ms);case"error":return p.default.yellow(Ls);case"submit":return p.default.green(At)}},Ys=e=>{switch(e){case"initial":case"active":return p.default.cyan(A);case"cancel":return p.default.red(A);case"error":return p.default.yellow(A);case"submit":return p.default.green(A)}},za=e=>e===161||e===164||e===167||e===168||e===170||e===173||e===174||e>=176&&e<=180||e>=182&&e<=186||e>=188&&e<=191||e===198||e===208||e===215||e===216||e>=222&&e<=225||e===230||e>=232&&e<=234||e===236||e===237||e===240||e===242||e===243||e>=247&&e<=250||e===252||e===254||e===257||e===273||e===275||e===283||e===294||e===295||e===299||e>=305&&e<=307||e===312||e>=319&&e<=322||e===324||e>=328&&e<=331||e===333||e===338||e===339||e===358||e===359||e===363||e===462||e===464||e===466||e===468||e===470||e===472||e===474||e===476||e===593||e===609||e===708||e===711||e>=713&&e<=715||e===717||e===720||e>=728&&e<=731||e===733||e===735||e>=768&&e<=879||e>=913&&e<=929||e>=931&&e<=937||e>=945&&e<=961||e>=963&&e<=969||e===1025||e>=1040&&e<=1103||e===1105||e===8208||e>=8211&&e<=8214||e===8216||e===8217||e===8220||e===8221||e>=8224&&e<=8226||e>=8228&&e<=8231||e===8240||e===8242||e===8243||e===8245||e===8251||e===8254||e===8308||e===8319||e>=8321&&e<=8324||e===8364||e===8451||e===8453||e===8457||e===8467||e===8470||e===8481||e===8482||e===8486||e===8491||e===8531||e===8532||e>=8539&&e<=8542||e>=8544&&e<=8555||e>=8560&&e<=8569||e===8585||e>=8592&&e<=8601||e===8632||e===8633||e===8658||e===8660||e===8679||e===8704||e===8706||e===8707||e===8711||e===8712||e===8715||e===8719||e===8721||e===8725||e===8730||e>=8733&&e<=8736||e===8739||e===8741||e>=8743&&e<=8748||e===8750||e>=8756&&e<=8759||e===8764||e===8765||e===8776||e===8780||e===8786||e===8800||e===8801||e>=8804&&e<=8807||e===8810||e===8811||e===8814||e===8815||e===8834||e===8835||e===8838||e===8839||e===8853||e===8857||e===8869||e===8895||e===8978||e>=9312&&e<=9449||e>=9451&&e<=9547||e>=9552&&e<=9587||e>=9600&&e<=9615||e>=9618&&e<=9621||e===9632||e===9633||e>=9635&&e<=9641||e===9650||e===9651||e===9654||e===9655||e===9660||e===9661||e===9664||e===9665||e>=9670&&e<=9672||e===9675||e>=9678&&e<=9681||e>=9698&&e<=9701||e===9711||e===9733||e===9734||e===9737||e===9742||e===9743||e===9756||e===9758||e===9792||e===9794||e===9824||e===9825||e>=9827&&e<=9829||e>=9831&&e<=9834||e===9836||e===9837||e===9839||e===9886||e===9887||e===9919||e>=9926&&e<=9933||e>=9935&&e<=9939||e>=9941&&e<=9953||e===9955||e===9960||e===9961||e>=9963&&e<=9969||e===9972||e>=9974&&e<=9977||e===9979||e===9980||e===9982||e===9983||e===10045||e>=10102&&e<=10111||e>=11094&&e<=11097||e>=12872&&e<=12879||e>=57344&&e<=63743||e>=65024&&e<=65039||e===65533||e>=127232&&e<=127242||e>=127248&&e<=127277||e>=127280&&e<=127337||e>=127344&&e<=127373||e===127375||e===127376||e>=127387&&e<=127404||e>=917760&&e<=917999||e>=983040&&e<=1048573||e>=1048576&&e<=1114109,Ya=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Xa=e=>e>=4352&&e<=4447||e===8986||e===8987||e===9001||e===9002||e>=9193&&e<=9196||e===9200||e===9203||e===9725||e===9726||e===9748||e===9749||e>=9800&&e<=9811||e===9855||e===9875||e===9889||e===9898||e===9899||e===9917||e===9918||e===9924||e===9925||e===9934||e===9940||e===9962||e===9970||e===9971||e===9973||e===9978||e===9981||e===9989||e===9994||e===9995||e===10024||e===10060||e===10062||e>=10067&&e<=10069||e===10071||e>=10133&&e<=10135||e===10160||e===10175||e===11035||e===11036||e===11088||e===11093||e>=11904&&e<=11929||e>=11931&&e<=12019||e>=12032&&e<=12245||e>=12272&&e<=12287||e>=12289&&e<=12350||e>=12353&&e<=12438||e>=12441&&e<=12543||e>=12549&&e<=12591||e>=12593&&e<=12686||e>=12688&&e<=12771||e>=12783&&e<=12830||e>=12832&&e<=12871||e>=12880&&e<=19903||e>=19968&&e<=42124||e>=42128&&e<=42182||e>=43360&&e<=43388||e>=44032&&e<=55203||e>=63744&&e<=64255||e>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=94176&&e<=94180||e===94192||e===94193||e>=94208&&e<=100343||e>=100352&&e<=101589||e>=101632&&e<=101640||e>=110576&&e<=110579||e>=110581&&e<=110587||e===110589||e===110590||e>=110592&&e<=110882||e===110898||e>=110928&&e<=110930||e===110933||e>=110948&&e<=110951||e>=110960&&e<=111355||e===126980||e===127183||e===127374||e>=127377&&e<=127386||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e===127568||e===127569||e>=127584&&e<=127589||e>=127744&&e<=127776||e>=127789&&e<=127797||e>=127799&&e<=127868||e>=127870&&e<=127891||e>=127904&&e<=127946||e>=127951&&e<=127955||e>=127968&&e<=127984||e===127988||e>=127992&&e<=128062||e===128064||e>=128066&&e<=128252||e>=128255&&e<=128317||e>=128331&&e<=128334||e>=128336&&e<=128359||e===128378||e===128405||e===128406||e===128420||e>=128507&&e<=128591||e>=128640&&e<=128709||e===128716||e>=128720&&e<=128722||e>=128725&&e<=128727||e>=128732&&e<=128735||e===128747||e===128748||e>=128756&&e<=128764||e>=128992&&e<=129003||e===129008||e>=129292&&e<=129338||e>=129340&&e<=129349||e>=129351&&e<=129535||e>=129648&&e<=129660||e>=129664&&e<=129672||e>=129680&&e<=129725||e>=129727&&e<=129733||e>=129742&&e<=129755||e>=129760&&e<=129768||e>=129776&&e<=129784||e>=131072&&e<=196605||e>=196608&&e<=262141,Ns=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,Di=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Ti=/\t{1,1000}/y,Us=new RegExp("[\\u{1F1E6}-\\u{1F1FF}]{2}|\\u{1F3F4}[\\u{E0061}-\\u{E007A}]{2}[\\u{E0030}-\\u{E0039}\\u{E0061}-\\u{E007A}]{1,3}\\u{E007F}|(?:\\p{Emoji}\\uFE0F\\u20E3?|\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation})(?:\\u200D(?:\\p{Emoji_Modifier_Base}\\p{Emoji_Modifier}?|\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F\\u20E3?))*","yu"),Ni=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Za=new RegExp("\\p{M}+","gu"),Qa={limit:1/0,ellipsis:""},Sr=(e,t={},i={})=>{let s=t.limit??1/0,n=t.ellipsis??"",r=t?.ellipsisWidth??(n?Sr(n,Qa,i).width:0),o=i.ansiWidth??0,a=i.controlWidth??0,l=i.tabWidth??8,m=i.ambiguousWidth??1,f=i.emojiWidth??2,g=i.fullWidthWidth??2,b=i.regularWidth??1,w=i.wideWidth??2,v=0,h=0,_=e.length,x=0,O=!1,R=_,M=Math.max(0,s-r),V=0,ee=0,P=0,E=0;e:for(;;){if(ee>V||h>=_&&h>v){let N=e.slice(V,ee)||e.slice(v,h);x=0;for(let Z of N.replaceAll(Za,"")){let z=Z.codePointAt(0)||0;if(Ya(z)?E=g:Xa(z)?E=w:m!==b&&za(z)?E=m:E=b,P+E>M&&(R=Math.min(R,Math.max(V,v)+x)),P+E>s){O=!0;break e}x+=Z.length,P+=E}V=ee=0}if(h>=_)break;if(Ni.lastIndex=h,Ni.test(e)){if(x=Ni.lastIndex-h,E=x*b,P+E>M&&(R=Math.min(R,h+Math.floor((M-P)/b))),P+E>s){O=!0;break}P+=E,V=v,ee=h,h=v=Ni.lastIndex;continue}if(Ns.lastIndex=h,Ns.test(e)){if(P+o>M&&(R=Math.min(R,h)),P+o>s){O=!0;break}P+=o,V=v,ee=h,h=v=Ns.lastIndex;continue}if(Di.lastIndex=h,Di.test(e)){if(x=Di.lastIndex-h,E=x*a,P+E>M&&(R=Math.min(R,h+Math.floor((M-P)/a))),P+E>s){O=!0;break}P+=E,V=v,ee=h,h=v=Di.lastIndex;continue}if(Ti.lastIndex=h,Ti.test(e)){if(x=Ti.lastIndex-h,E=x*l,P+E>M&&(R=Math.min(R,h+Math.floor((M-P)/l))),P+E>s){O=!0;break}P+=E,V=v,ee=h,h=v=Ti.lastIndex;continue}if(Us.lastIndex=h,Us.test(e)){if(P+f>M&&(R=Math.min(R,h)),P+f>s){O=!0;break}P+=f,V=v,ee=h,h=v=Us.lastIndex;continue}h+=1}return{width:O?M:P,index:O?R:_,truncated:O,ellipsed:O&&s>=r}},el={limit:1/0,ellipsis:"",ellipsisWidth:0},Pe=(e,t={})=>Sr(e,el,t).width,Vi="\x1B",Cr="\x9B",tl=39,Xs="\x07",Or="[",il="]",Ir="m",Zs=`${il}8;;`,mr=new RegExp(`(?:\\${Or}(?<code>\\d+)m|\\${Zs}(?<uri>.*)${Xs})`,"y"),sl=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},fr=e=>`${Vi}${Or}${e}${Ir}`,pr=e=>`${Vi}${Zs}${e}${Xs}`,nl=e=>e.map(t=>Pe(t)),Fs=(e,t,i)=>{let s=t[Symbol.iterator](),n=!1,r=!1,o=e.at(-1),a=o===void 0?0:Pe(o),l=s.next(),m=s.next(),f=0;for(;!l.done;){let g=l.value,b=Pe(g);a+b<=i?e[e.length-1]+=g:(e.push(g),a=0),(g===Vi||g===Cr)&&(n=!0,r=t.startsWith(Zs,f+1)),n?r?g===Xs&&(n=!1,r=!1):g===Ir&&(n=!1):(a+=b,a===i&&!m.done&&(e.push(""),a=0)),l=m,m=s.next(),f+=g.length}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop())},rl=e=>{let t=e.split(" "),i=t.length;for(;i>0&&!(Pe(t[i-1])>0);)i--;return i===t.length?e:t.slice(0,i).join(" ")+t.slice(i).join("")},ol=(e,t,i={})=>{if(i.trim!==!1&&e.trim()==="")return"";let s="",n,r,o=e.split(" "),a=nl(o),l=[""];for(let[v,h]of o.entries()){i.trim!==!1&&(l[l.length-1]=(l.at(-1)??"").trimStart());let _=Pe(l.at(-1)??"");if(v!==0&&(_>=t&&(i.wordWrap===!1||i.trim===!1)&&(l.push(""),_=0),(_>0||i.trim===!1)&&(l[l.length-1]+=" ",_++)),i.hard&&a[v]>t){let x=t-_,O=1+Math.floor((a[v]-x-1)/t);Math.floor((a[v]-1)/t)<O&&l.push(""),Fs(l,h,t);continue}if(_+a[v]>t&&_>0&&a[v]>0){if(i.wordWrap===!1&&_<t){Fs(l,h,t);continue}l.push("")}if(_+a[v]>t&&i.wordWrap===!1){Fs(l,h,t);continue}l[l.length-1]+=h}i.trim!==!1&&(l=l.map(v=>rl(v)));let m=l.join(`
49
+ `),f=m[Symbol.iterator](),g=f.next(),b=f.next(),w=0;for(;!g.done;){let v=g.value,h=b.value;if(s+=v,v===Vi||v===Cr){mr.lastIndex=w+1;let x=mr.exec(m)?.groups;if(x?.code!==void 0){let O=Number.parseFloat(x.code);n=O===tl?void 0:O}else x?.uri!==void 0&&(r=x.uri.length===0?void 0:x.uri)}let _=n?sl(n):void 0;h===`
50
+ `?(r&&(s+=pr("")),n&&_&&(s+=fr(_))):v===`
51
+ `&&(n&&_&&(s+=fr(n)),r&&(s+=pr(r))),w+=v.length,g=b,b=f.next()}return s};al=(e,t,i,s,n)=>{let r=t,o=0;for(let a=i;a<s;a++){let l=e[a];if(r=r-l.length,o++,r<=n)break}return{lineCount:r,removals:o}},zt=e=>{let{cursor:t,options:i,style:s}=e,n=e.output??process.stdout,r=St(n),o=e.columnPadding??0,a=e.rowPadding??4,l=r-o,m=Ds(n),f=p.default.dim("..."),g=e.maxItems??Number.POSITIVE_INFINITY,b=Math.max(m-a,0),w=Math.max(Math.min(g,b),5),v=0;t>=w-3&&(v=Math.max(Math.min(t-w+3,i.length-w),0));let h=w<i.length&&v>0,_=w<i.length&&v+w<i.length,x=Math.min(v+w,i.length),O=[],R=0;h&&R++,_&&R++;let M=v+(h?1:0),V=x-(_?1:0);for(let P=M;P<V;P++){let E=Kt(s(i[P],P===t),l,{hard:!0,trim:!1}).split(`
52
52
  `);O.push(E),R+=E.length}if(R>b){let P=0,E=0,N=R,Z=t-M,z=(F,ie)=>al(O,N,F,ie,b);h?({lineCount:N,removals:P}=z(0,Z),N>b&&({lineCount:N,removals:E}=z(Z+1,O.length))):({lineCount:N,removals:E}=z(Z+1,O.length),N>b&&({lineCount:N,removals:P}=z(0,Z))),P>0&&(h=!0,O.splice(0,P)),E>0&&(_=!0,O.splice(O.length-E,E))}let ee=[];h&&ee.push(f);for(let P of O)for(let E of P)ee.push(E);return _&&ee.push(f),ee};Ar=e=>new ii({options:e.options,initialValue:e.initialValue?[e.initialValue]:void 0,initialUserInput:e.initialUserInput,filter:e.filter??((t,i)=>Rr(t,i)),signal:e.signal,input:e.input,output:e.output,validate:e.validate,render(){let t=e.withGuide??ce.withGuide,i=t?[`${p.default.gray(A)}`,`${Ze(this.state)} ${e.message}`]:[`${Ze(this.state)} ${e.message}`],s=this.userInput,n=this.options,r=e.placeholder,o=s===""&&r!==void 0,a=(l,m)=>{let f=hr(l),g=l.hint&&l.value===this.focusedValue?p.default.dim(` (${l.hint})`):"";switch(m){case"active":return`${p.default.green(ri)} ${f}${g}`;case"inactive":return`${p.default.dim(Rt)} ${p.default.dim(f)}`;case"disabled":return`${p.default.gray(Rt)} ${p.default.strikethrough(p.default.gray(f))}`}};switch(this.state){case"submit":{let l=ll(this.selectedValues,n),m=l.length>0?` ${p.default.dim(l.map(hr).join(", "))}`:"",f=t?p.default.gray(A):"";return`${i.join(`
53
53
  `)}
54
54
  ${f}${m}`}case"cancel":{let l=s?` ${p.default.strikethrough(p.default.dim(s))}`:"",m=t?p.default.gray(A):"";return`${i.join(`
55
55
  `)}
56
- ${m}${l}`}default:{let l=this.state==="error"?p.default.yellow:p.default.cyan,m=t?`${l(A)} `:"",f=t?l(ke):"",g="";if(this.isNavigating||o){let O=o?r:s;g=O!==""?` ${p.default.dim(O)}`:""}else g=` ${this.userInputWithCursor}`;let b=this.filteredOptions.length!==n.length?p.default.dim(` (${this.filteredOptions.length} match${this.filteredOptions.length===1?"":"es"})`):"",v=this.filteredOptions.length===0&&s?[`${m}${p.default.yellow("No matches found")}`]:[],w=this.state==="error"?[`${m}${p.default.yellow(this.error)}`]:[];t&&i.push(`${m.trimEnd()}`),i.push(`${m}${p.default.dim("Search:")}${g}${b}`,...v,...w);let h=[`${p.default.dim("\u2191/\u2193")} to select`,`${p.default.dim("Enter:")} confirm`,`${p.default.dim("Type:")} to search`],_=[`${m}${h.join(" \u2022 ")}`,f],j=this.filteredOptions.length===0?[]:zt({cursor:this.cursor,options:this.filteredOptions,columnPadding:t?3:0,rowPadding:i.length+_.length,style:(O,R)=>a(O,O.disabled?"disabled":R?"active":"inactive"),maxItems:e.maxItems,output:e.output});return[...i,...j.map(O=>`${m}${O}`),..._].join(`
56
+ ${m}${l}`}default:{let l=this.state==="error"?p.default.yellow:p.default.cyan,m=t?`${l(A)} `:"",f=t?l(_e):"",g="";if(this.isNavigating||o){let O=o?r:s;g=O!==""?` ${p.default.dim(O)}`:""}else g=` ${this.userInputWithCursor}`;let b=this.filteredOptions.length!==n.length?p.default.dim(` (${this.filteredOptions.length} match${this.filteredOptions.length===1?"":"es"})`):"",w=this.filteredOptions.length===0&&s?[`${m}${p.default.yellow("No matches found")}`]:[],v=this.state==="error"?[`${m}${p.default.yellow(this.error)}`]:[];t&&i.push(`${m.trimEnd()}`),i.push(`${m}${p.default.dim("Search:")}${g}${b}`,...w,...v);let h=[`${p.default.dim("\u2191/\u2193")} to select`,`${p.default.dim("Enter:")} confirm`,`${p.default.dim("Type:")} to search`],_=[`${m}${h.join(" \u2022 ")}`,f],x=this.filteredOptions.length===0?[]:zt({cursor:this.cursor,options:this.filteredOptions,columnPadding:t?3:0,rowPadding:i.length+_.length,style:(O,R)=>a(O,O.disabled?"disabled":R?"active":"inactive"),maxItems:e.maxItems,output:e.output});return[...i,...x.map(O=>`${m}${O}`),..._].join(`
57
57
  `)}}}}).prompt(),dl=e=>{let t=(s,n,r,o)=>{let a=r.includes(s.value),l=s.label??String(s.value??""),m=s.hint&&o!==void 0&&s.value===o?p.default.dim(` (${s.hint})`):"",f=a?p.default.green(Ot):p.default.dim(Gt);return s.disabled?`${p.default.gray(Gt)} ${p.default.strikethrough(p.default.gray(l))}`:n?`${f} ${l}${m}`:`${f} ${p.default.dim(l)}`},i=new ii({options:e.options,multiple:!0,filter:e.filter??((s,n)=>Rr(s,n)),validate:()=>{if(e.required&&i.selectedValues.length===0)return"Please select at least one item"},initialValue:e.initialValues,signal:e.signal,input:e.input,output:e.output,render(){let s=`${p.default.gray(A)}
58
58
  ${Ze(this.state)} ${e.message}
59
- `,n=this.userInput,r=e.placeholder,o=n===""&&r!==void 0,a=this.isNavigating||o?p.default.dim(o?r:n):this.userInputWithCursor,l=this.options,m=this.filteredOptions.length!==l.length?p.default.dim(` (${this.filteredOptions.length} match${this.filteredOptions.length===1?"":"es"})`):"";switch(this.state){case"submit":return`${s}${p.default.gray(A)} ${p.default.dim(`${this.selectedValues.length} items selected`)}`;case"cancel":return`${s}${p.default.gray(A)} ${p.default.strikethrough(p.default.dim(n))}`;default:{let f=this.state==="error"?p.default.yellow:p.default.cyan,g=[`${p.default.dim("\u2191/\u2193")} to navigate`,`${p.default.dim(this.isNavigating?"Space/Tab:":"Tab:")} select`,`${p.default.dim("Enter:")} confirm`,`${p.default.dim("Type:")} to search`],b=this.filteredOptions.length===0&&n?[`${f(A)} ${p.default.yellow("No matches found")}`]:[],v=this.state==="error"?[`${f(A)} ${p.default.yellow(this.error)}`]:[],w=[...`${s}${f(A)}`.split(`
60
- `),`${f(A)} ${p.default.dim("Search:")} ${a}${m}`,...b,...v],h=[`${f(A)} ${g.join(" \u2022 ")}`,`${f(ke)}`],_=zt({cursor:this.cursor,options:this.filteredOptions,style:(j,O)=>t(j,O,this.selectedValues,this.focusedValue),maxItems:e.maxItems,output:e.output,rowPadding:w.length+h.length});return[...w,..._.map(j=>`${f(A)} ${j}`),...h].join(`
61
- `)}}}});return i.prompt()},cl=[xr,Ws,Js,Hs],ul=[Vs,wr,ke,kr];ml=e=>e,fl=(e="",t="",i)=>{let s=i?.output??process.stdout,n=St(s),r=2,o=i?.titlePadding??1,a=i?.contentPadding??2,l=i?.width===void 0||i.width==="auto"?1:Math.min(1,i.width),m=i?.withGuide??ce.withGuide?`${A} `:"",f=i?.formatBorder??ml,g=(i?.rounded?cl:ul).map(f),b=f(Li),v=f(A),w=Pe(m),h=Pe(t),_=n-w,j=Math.floor(n*l)-w;if(i?.width==="auto"){let N=e.split(`
62
- `),Z=h+o*2;for(let F of N){let ie=Pe(F)+a*2;ie>Z&&(Z=ie)}let z=Z+r;z<j&&(j=z)}j%2!==0&&(j<_?j++:j--);let O=j-r,R=O-o*2,M=h>R?`${t.slice(0,R-3)}...`:t,[V,ee]=gr(Pe(M),O,o,i?.titleAlign),P=Kt(e,O-a*2,{hard:!0,trim:!1});s.write(`${m}${g[0]}${b.repeat(V)}${M}${b.repeat(ee)}${g[1]}
59
+ `,n=this.userInput,r=e.placeholder,o=n===""&&r!==void 0,a=this.isNavigating||o?p.default.dim(o?r:n):this.userInputWithCursor,l=this.options,m=this.filteredOptions.length!==l.length?p.default.dim(` (${this.filteredOptions.length} match${this.filteredOptions.length===1?"":"es"})`):"";switch(this.state){case"submit":return`${s}${p.default.gray(A)} ${p.default.dim(`${this.selectedValues.length} items selected`)}`;case"cancel":return`${s}${p.default.gray(A)} ${p.default.strikethrough(p.default.dim(n))}`;default:{let f=this.state==="error"?p.default.yellow:p.default.cyan,g=[`${p.default.dim("\u2191/\u2193")} to navigate`,`${p.default.dim(this.isNavigating?"Space/Tab:":"Tab:")} select`,`${p.default.dim("Enter:")} confirm`,`${p.default.dim("Type:")} to search`],b=this.filteredOptions.length===0&&n?[`${f(A)} ${p.default.yellow("No matches found")}`]:[],w=this.state==="error"?[`${f(A)} ${p.default.yellow(this.error)}`]:[],v=[...`${s}${f(A)}`.split(`
60
+ `),`${f(A)} ${p.default.dim("Search:")} ${a}${m}`,...b,...w],h=[`${f(A)} ${g.join(" \u2022 ")}`,`${f(_e)}`],_=zt({cursor:this.cursor,options:this.filteredOptions,style:(x,O)=>t(x,O,this.selectedValues,this.focusedValue),maxItems:e.maxItems,output:e.output,rowPadding:v.length+h.length});return[...v,..._.map(x=>`${f(A)} ${x}`),...h].join(`
61
+ `)}}}});return i.prompt()},cl=[jr,Ws,Js,Hs],ul=[Vs,wr,_e,kr];ml=e=>e,fl=(e="",t="",i)=>{let s=i?.output??process.stdout,n=St(s),r=2,o=i?.titlePadding??1,a=i?.contentPadding??2,l=i?.width===void 0||i.width==="auto"?1:Math.min(1,i.width),m=i?.withGuide??ce.withGuide?`${A} `:"",f=i?.formatBorder??ml,g=(i?.rounded?cl:ul).map(f),b=f(Li),w=f(A),v=Pe(m),h=Pe(t),_=n-v,x=Math.floor(n*l)-v;if(i?.width==="auto"){let N=e.split(`
62
+ `),Z=h+o*2;for(let F of N){let ie=Pe(F)+a*2;ie>Z&&(Z=ie)}let z=Z+r;z<x&&(x=z)}x%2!==0&&(x<_?x++:x--);let O=x-r,R=O-o*2,M=h>R?`${t.slice(0,R-3)}...`:t,[V,ee]=gr(Pe(M),O,o,i?.titleAlign),P=Kt(e,O-a*2,{hard:!0,trim:!1});s.write(`${m}${g[0]}${b.repeat(V)}${M}${b.repeat(ee)}${g[1]}
63
63
  `);let E=P.split(`
64
- `);for(let N of E){let[Z,z]=gr(Pe(N),O,a,i?.contentAlign);s.write(`${m}${v}${" ".repeat(Z)}${N}${" ".repeat(z)}${v}
64
+ `);for(let N of E){let[Z,z]=gr(Pe(N),O,a,i?.contentAlign);s.write(`${m}${w}${" ".repeat(Z)}${N}${" ".repeat(z)}${w}
65
65
  `)}s.write(`${m}${g[2]}${b.repeat(O)}${g[3]}
66
66
  `)},Ke=e=>{let t=e.active??"Yes",i=e.inactive??"No";return new Ci({active:t,inactive:i,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let s=e.withGuide??ce.withGuide,n=`${s?`${p.default.gray(A)}
67
67
  `:""}${Ze(this.state)} ${e.message}
68
68
  `,r=this.value?t:i;switch(this.state){case"submit":{let o=s?`${p.default.gray(A)} `:"";return`${n}${o}${p.default.dim(r)}`}case"cancel":{let o=s?`${p.default.gray(A)} `:"";return`${n}${o}${p.default.strikethrough(p.default.dim(r))}${s?`
69
- ${p.default.gray(A)}`:""}`}default:{let o=s?`${p.default.cyan(A)} `:"",a=s?p.default.cyan(ke):"";return`${n}${o}${this.value?`${p.default.green(ri)} ${t}`:`${p.default.dim(Rt)} ${p.default.dim(t)}`}${e.vertical?s?`
69
+ ${p.default.gray(A)}`:""}`}default:{let o=s?`${p.default.cyan(A)} `:"",a=s?p.default.cyan(_e):"";return`${n}${o}${this.value?`${p.default.green(ri)} ${t}`:`${p.default.dim(Rt)} ${p.default.dim(t)}`}${e.vertical?s?`
70
70
  ${p.default.cyan(A)} `:`
71
71
  `:` ${p.default.dim("/")} `}${this.value?`${p.default.dim(Rt)} ${p.default.dim(i)}`:`${p.default.green(ri)} ${i}`}
72
72
  ${a}
73
- `}}}}).prompt()},pl=async(e,t)=>{let i={},s=Object.keys(e);for(let n of s){let r=e[n],o=await r({results:i})?.catch(a=>{throw a});if(typeof t?.onCancel=="function"&&le(o)){i[n]="canceled",t.onCancel({results:i});continue}i[n]=o}return i},hl=e=>{let{selectableGroups:t=!0,groupSpacing:i=0}=e,s=(r,o,a=[])=>{let l=r.label??String(r.value),m=typeof r.group=="string",f=m&&(a[a.indexOf(r)+1]??{group:!0}),g=m&&f&&f.group===!0,b=m?t?`${g?ke:A} `:" ":"",v="";if(i>0&&!m){let h=`
74
- ${p.default.cyan(A)}`;v=`${h.repeat(i-1)}${h} `}if(o==="active")return`${v}${p.default.dim(b)}${p.default.cyan(Mi)} ${l}${r.hint?` ${p.default.dim(`(${r.hint})`)}`:""}`;if(o==="group-active")return`${v}${b}${p.default.cyan(Mi)} ${p.default.dim(l)}`;if(o==="group-active-selected")return`${v}${b}${p.default.green(Ot)} ${p.default.dim(l)}`;if(o==="selected"){let h=m||t?p.default.green(Ot):"";return`${v}${p.default.dim(b)}${h} ${p.default.dim(l)}${r.hint?` ${p.default.dim(`(${r.hint})`)}`:""}`}if(o==="cancelled")return`${p.default.strikethrough(p.default.dim(l))}`;if(o==="active-selected")return`${v}${p.default.dim(b)}${p.default.green(Ot)} ${l}${r.hint?` ${p.default.dim(`(${r.hint})`)}`:""}`;if(o==="submitted")return`${p.default.dim(l)}`;let w=m||t?p.default.dim(Gt):"";return`${v}${p.default.dim(b)}${w} ${p.default.dim(l)}`},n=e.required??!0;return new Oi({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:n,cursorAt:e.cursorAt,selectableGroups:t,validate(r){if(n&&(r===void 0||r.length===0))return`Please select at least one option.
73
+ `}}}}).prompt()},pl=async(e,t)=>{let i={},s=Object.keys(e);for(let n of s){let r=e[n],o=await r({results:i})?.catch(a=>{throw a});if(typeof t?.onCancel=="function"&&le(o)){i[n]="canceled",t.onCancel({results:i});continue}i[n]=o}return i},hl=e=>{let{selectableGroups:t=!0,groupSpacing:i=0}=e,s=(r,o,a=[])=>{let l=r.label??String(r.value),m=typeof r.group=="string",f=m&&(a[a.indexOf(r)+1]??{group:!0}),g=m&&f&&f.group===!0,b=m?t?`${g?_e:A} `:" ":"",w="";if(i>0&&!m){let h=`
74
+ ${p.default.cyan(A)}`;w=`${h.repeat(i-1)}${h} `}if(o==="active")return`${w}${p.default.dim(b)}${p.default.cyan(Mi)} ${l}${r.hint?` ${p.default.dim(`(${r.hint})`)}`:""}`;if(o==="group-active")return`${w}${b}${p.default.cyan(Mi)} ${p.default.dim(l)}`;if(o==="group-active-selected")return`${w}${b}${p.default.green(Ot)} ${p.default.dim(l)}`;if(o==="selected"){let h=m||t?p.default.green(Ot):"";return`${w}${p.default.dim(b)}${h} ${p.default.dim(l)}${r.hint?` ${p.default.dim(`(${r.hint})`)}`:""}`}if(o==="cancelled")return`${p.default.strikethrough(p.default.dim(l))}`;if(o==="active-selected")return`${w}${p.default.dim(b)}${p.default.green(Ot)} ${l}${r.hint?` ${p.default.dim(`(${r.hint})`)}`:""}`;if(o==="submitted")return`${p.default.dim(l)}`;let v=m||t?p.default.dim(Gt):"";return`${w}${p.default.dim(b)}${v} ${p.default.dim(l)}`},n=e.required??!0;return new Oi({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:n,cursorAt:e.cursorAt,selectableGroups:t,validate(r){if(n&&(r===void 0||r.length===0))return`Please select at least one option.
75
75
  ${p.default.reset(p.default.dim(`Press ${p.default.gray(p.default.bgWhite(p.default.inverse(" space ")))} to select, ${p.default.gray(p.default.bgWhite(p.default.inverse(" enter ")))} to submit`))}`},render(){let r=`${p.default.gray(A)}
76
76
  ${Ze(this.state)} ${e.message}
77
77
  `,o=this.value??[];switch(this.state){case"submit":{let a=this.options.filter(({value:m})=>o.includes(m)).map(m=>s(m,"submitted")),l=a.length===0?"":` ${a.join(p.default.dim(", "))}`;return`${r}${p.default.gray(A)}${l}`}case"cancel":{let a=this.options.filter(({value:l})=>o.includes(l)).map(l=>s(l,"cancelled")).join(p.default.dim(", "));return`${r}${p.default.gray(A)} ${a.trim()?`${a}
78
78
  ${p.default.gray(A)}`:""}`}case"error":{let a=this.error.split(`
79
- `).map((l,m)=>m===0?`${p.default.yellow(ke)} ${p.default.yellow(l)}`:` ${l}`).join(`
79
+ `).map((l,m)=>m===0?`${p.default.yellow(_e)} ${p.default.yellow(l)}`:` ${l}`).join(`
80
80
  `);return`${r}${p.default.yellow(A)} ${this.options.map((l,m,f)=>{let g=o.includes(l.value)||l.group===!0&&this.isGroupSelected(`${l.value}`),b=m===this.cursor;return!b&&typeof l.group=="string"&&this.options[this.cursor].value===l.group?s(l,g?"group-active-selected":"group-active",f):b&&g?s(l,"active-selected",f):g?s(l,"selected",f):s(l,b?"active":"inactive",f)}).join(`
81
81
  ${p.default.yellow(A)} `)}
82
82
  ${a}
83
- `}default:{let a=this.options.map((m,f,g)=>{let b=o.includes(m.value)||m.group===!0&&this.isGroupSelected(`${m.value}`),v=f===this.cursor,w=!v&&typeof m.group=="string"&&this.options[this.cursor].value===m.group,h="";return w?h=s(m,b?"group-active-selected":"group-active",g):v&&b?h=s(m,"active-selected",g):b?h=s(m,"selected",g):h=s(m,v?"active":"inactive",g),`${f!==0&&!h.startsWith(`
83
+ `}default:{let a=this.options.map((m,f,g)=>{let b=o.includes(m.value)||m.group===!0&&this.isGroupSelected(`${m.value}`),w=f===this.cursor,v=!w&&typeof m.group=="string"&&this.options[this.cursor].value===m.group,h="";return v?h=s(m,b?"group-active-selected":"group-active",g):w&&b?h=s(m,"active-selected",g):b?h=s(m,"selected",g):h=s(m,w?"active":"inactive",g),`${f!==0&&!h.startsWith(`
84
84
  `)?" ":""}${h}`}).join(`
85
85
  ${p.default.cyan(A)}`),l=a.startsWith(`
86
86
  `)?"":" ";return`${r}${p.default.cyan(A)}${l}${a}
87
- ${p.default.cyan(ke)}
87
+ ${p.default.cyan(_e)}
88
88
  `}}}}).prompt()},Ve={message:(e=[],{symbol:t=p.default.gray(A),secondarySymbol:i=p.default.gray(A),output:s=process.stdout,spacing:n=1,withGuide:r}={})=>{let o=[],a=r??ce.withGuide,l=a?i:"",m=a?`${t} `:"",f=a?`${i} `:"";for(let b=0;b<n;b++)o.push(l);let g=Array.isArray(e)?e:e.split(`
89
- `);if(g.length>0){let[b,...v]=g;b.length>0?o.push(`${m}${b}`):o.push(a?t:"");for(let w of v)w.length>0?o.push(`${f}${w}`):o.push(a?i:"")}s.write(`${o.join(`
89
+ `);if(g.length>0){let[b,...w]=g;b.length>0?o.push(`${m}${b}`):o.push(a?t:"");for(let v of w)v.length>0?o.push(`${f}${v}`):o.push(a?i:"")}s.write(`${o.join(`
90
90
  `)}
91
- `)},info:(e,t)=>{Ve.message(e,{...t,symbol:p.default.blue(Bs)})},success:(e,t)=>{Ve.message(e,{...t,symbol:p.default.green(Gs)})},step:(e,t)=>{Ve.message(e,{...t,symbol:p.default.green(At)})},warn:(e,t)=>{Ve.message(e,{...t,symbol:p.default.yellow(Ks)})},warning:(e,t)=>{Ve.warn(e,t)},error:(e,t)=>{Ve.message(e,{...t,symbol:p.default.red(zs)})}},gl=(e="",t)=>{(t?.output??process.stdout).write(`${p.default.gray(ke)} ${p.default.red(e)}
91
+ `)},info:(e,t)=>{Ve.message(e,{...t,symbol:p.default.blue(Bs)})},success:(e,t)=>{Ve.message(e,{...t,symbol:p.default.green(Gs)})},step:(e,t)=>{Ve.message(e,{...t,symbol:p.default.green(At)})},warn:(e,t)=>{Ve.message(e,{...t,symbol:p.default.yellow(Ks)})},warning:(e,t)=>{Ve.warn(e,t)},error:(e,t)=>{Ve.message(e,{...t,symbol:p.default.red(zs)})}},gl=(e="",t)=>{(t?.output??process.stdout).write(`${p.default.gray(_e)} ${p.default.red(e)}
92
92
 
93
93
  `)},bl=(e="",t)=>{(t?.output??process.stdout).write(`${p.default.gray(Vs)} ${e}
94
94
  `)},yl=(e="",t)=>{(t?.output??process.stdout).write(`${p.default.gray(A)}
95
- ${p.default.gray(ke)} ${e}
95
+ ${p.default.gray(_e)} ${e}
96
96
 
97
97
  `)},si=(e,t)=>e.split(`
98
98
  `).map(i=>t(i)).join(`
@@ -101,7 +101,7 @@ ${p.default.reset(p.default.dim(`Press ${p.default.gray(p.default.bgWhite(p.defa
101
101
  ${s}
102
102
  `,r=this.value??[],o=(a,l)=>{if(a.disabled)return t(a,"disabled");let m=r.includes(a.value);return l&&m?t(a,"active-selected"):m?t(a,"selected"):t(a,l?"active":"inactive")};switch(this.state){case"submit":{let a=this.options.filter(({value:m})=>r.includes(m)).map(m=>t(m,"submitted")).join(p.default.dim(", "))||p.default.dim("none"),l=nt(e.output,a,`${p.default.gray(A)} `);return`${n}${l}`}case"cancel":{let a=this.options.filter(({value:m})=>r.includes(m)).map(m=>t(m,"cancelled")).join(p.default.dim(", "));if(a.trim()==="")return`${n}${p.default.gray(A)}`;let l=nt(e.output,a,`${p.default.gray(A)} `);return`${n}${l}
103
103
  ${p.default.gray(A)}`}case"error":{let a=`${p.default.yellow(A)} `,l=this.error.split(`
104
- `).map((g,b)=>b===0?`${p.default.yellow(ke)} ${p.default.yellow(g)}`:` ${g}`).join(`
104
+ `).map((g,b)=>b===0?`${p.default.yellow(_e)} ${p.default.yellow(g)}`:` ${g}`).join(`
105
105
  `),m=n.split(`
106
106
  `).length,f=l.split(`
107
107
  `).length+1;return`${n}${a}${zt({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:a.length,rowPadding:m+f,style:o}).join(`
@@ -110,41 +110,41 @@ ${l}
110
110
  `}default:{let a=`${p.default.cyan(A)} `,l=n.split(`
111
111
  `).length;return`${n}${a}${zt({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:a.length,rowPadding:l+2,style:o}).join(`
112
112
  ${a}`)}
113
- ${p.default.cyan(ke)}
113
+ ${p.default.cyan(_e)}
114
114
  `}}}}).prompt()},vl=e=>p.default.dim(e),wl=(e,t,i)=>{let s={hard:!0,trim:!1},n=Kt(e,t,s).split(`
115
115
  `),r=n.reduce((l,m)=>Math.max(Pe(m),l),0),o=n.map(i).reduce((l,m)=>Math.max(Pe(m),l),0),a=t-(o-r);return Kt(e,a,s)},kl=(e="",t="",i)=>{let s=i?.output??Le.default.stdout,n=i?.withGuide??ce.withGuide,r=i?.format??vl,o=["",...wl(e,St(s)-6,r).split(`
116
- `).map(r),""],a=Pe(t),l=Math.max(o.reduce((b,v)=>{let w=Pe(v);return w>b?w:b},0),a)+2,m=o.map(b=>`${p.default.gray(A)} ${b}${" ".repeat(l-Pe(b))}${p.default.gray(A)}`).join(`
116
+ `).map(r),""],a=Pe(t),l=Math.max(o.reduce((b,w)=>{let v=Pe(w);return v>b?v:b},0),a)+2,m=o.map(b=>`${p.default.gray(A)} ${b}${" ".repeat(l-Pe(b))}${p.default.gray(A)}`).join(`
117
117
  `),f=n?`${p.default.gray(A)}
118
- `:"",g=n?jr:Js;s.write(`${f}${p.default.green(At)} ${p.default.reset(t)} ${p.default.gray(Li.repeat(Math.max(l-a-1,1))+Ws)}
118
+ `:"",g=n?xr:Js;s.write(`${f}${p.default.green(At)} ${p.default.reset(t)} ${p.default.gray(Li.repeat(Math.max(l-a-1,1))+Ws)}
119
119
  ${m}
120
120
  ${p.default.gray(g+Li.repeat(l+2)+Hs)}
121
121
  `)},_l=e=>new ur({validate:e.validate,mask:e.mask??_r,signal:e.signal,input:e.input,output:e.output,render(){let t=e.withGuide??ce.withGuide,i=`${t?`${p.default.gray(A)}
122
122
  `:""}${Ze(this.state)} ${e.message}
123
- `,s=this.userInputWithCursor,n=this.masked;switch(this.state){case"error":{let r=t?`${p.default.yellow(A)} `:"",o=t?`${p.default.yellow(ke)} `:"",a=n??"";return e.clearOnError&&this.clear(),`${i.trim()}
123
+ `,s=this.userInputWithCursor,n=this.masked;switch(this.state){case"error":{let r=t?`${p.default.yellow(A)} `:"",o=t?`${p.default.yellow(_e)} `:"",a=n??"";return e.clearOnError&&this.clear(),`${i.trim()}
124
124
  ${r}${a}
125
125
  ${o}${p.default.yellow(this.error)}
126
126
  `}case"submit":{let r=t?`${p.default.gray(A)} `:"",o=n?p.default.dim(n):"";return`${i}${r}${o}`}case"cancel":{let r=t?`${p.default.gray(A)} `:"",o=n?p.default.strikethrough(p.default.dim(n)):"";return`${i}${r}${o}${n&&t?`
127
- ${p.default.gray(A)}`:""}`}default:{let r=t?`${p.default.cyan(A)} `:"",o=t?p.default.cyan(ke):"";return`${i}${r}${s}
127
+ ${p.default.gray(A)}`:""}`}default:{let r=t?`${p.default.cyan(A)} `:"",o=t?p.default.cyan(_e):"";return`${i}${r}${s}
128
128
  ${o}
129
- `}}}}).prompt(),jl=e=>{let t=e.validate;return Ar({...e,initialUserInput:e.initialValue??e.root??process.cwd(),maxItems:5,validate(i){if(!Array.isArray(i)){if(!i)return"Please select a path";if(t)return t(i)}},options(){let i=this.userInput;if(i==="")return[];try{let s;return(0,It.existsSync)(i)?(0,It.lstatSync)(i).isDirectory()?s=i:s=(0,ni.dirname)(i):s=(0,ni.dirname)(i),(0,It.readdirSync)(s).map(n=>{let r=(0,ni.join)(s,n),o=(0,It.lstatSync)(r);return{name:n,path:r,isDirectory:o.isDirectory()}}).filter(({path:n,isDirectory:r})=>n.startsWith(i)&&(e.directory||!r)).map(n=>({value:n.path}))}catch{return[]}}})},xl=p.default.magenta,oi=({indicator:e="dots",onCancel:t,output:i=process.stdout,cancelMessage:s,errorMessage:n,frames:r=qi?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:o=qi?80:120,signal:a,...l}={})=>{let m=qs(),f,g,b=!1,v=!1,w="",h,_=performance.now(),j=St(i),O=l?.styleFrame??xl,R=q=>{let Y=q>1?n??ce.messages.error:s??ce.messages.cancel;v=q===1,b&&(ie(Y,q),v&&typeof t=="function"&&t())},M=()=>R(2),V=()=>R(1),ee=()=>{process.on("uncaughtExceptionMonitor",M),process.on("unhandledRejection",M),process.on("SIGINT",V),process.on("SIGTERM",V),process.on("exit",R),a&&a.addEventListener("abort",V)},P=()=>{process.removeListener("uncaughtExceptionMonitor",M),process.removeListener("unhandledRejection",M),process.removeListener("SIGINT",V),process.removeListener("SIGTERM",V),process.removeListener("exit",R),a&&a.removeEventListener("abort",V)},E=()=>{if(h===void 0)return;m&&i.write(`
130
- `);let q=Kt(h,j,{hard:!0,trim:!1}).split(`
131
- `);q.length>1&&i.write(Bt.cursor.up(q.length-1)),i.write(Bt.cursor.to(0)),i.write(Bt.erase.down())},N=q=>q.replace(/\.+$/,""),Z=q=>{let Y=(performance.now()-q)/1e3,Q=Math.floor(Y/60),G=Math.floor(Y%60);return Q>0?`[${Q}m ${G}s]`:`[${G}s]`},z=l.withGuide??ce.withGuide,F=(q="")=>{b=!0,f=cr({output:i}),w=N(q),_=performance.now(),z&&i.write(`${p.default.gray(A)}
132
- `);let Y=0,Q=0;ee(),g=setInterval(()=>{if(m&&w===h)return;E(),h=w;let G=O(r[Y]),Oe;if(m)Oe=`${G} ${w}...`;else if(e==="timer")Oe=`${G} ${w} ${Z(_)}`;else{let de=".".repeat(Math.floor(Q)).slice(0,3);Oe=`${G} ${w}${de}`}let Be=Kt(Oe,j,{hard:!0,trim:!1});i.write(Be),Y=Y+1<r.length?Y+1:0,Q=Q<4?Q+.125:0},o)},ie=(q="",Y=0,Q=!1)=>{if(!b)return;b=!1,clearInterval(g),E();let G=Y===0?p.default.green(At):Y===1?p.default.red(Ms):p.default.red(Ls);w=q??w,Q||(e==="timer"?i.write(`${G} ${w} ${Z(_)}
133
- `):i.write(`${G} ${w}
134
- `)),P(),f()};return{start:F,stop:(q="")=>ie(q,0),message:(q="")=>{w=N(q??w)},cancel:(q="")=>ie(q,1),error:(q="")=>ie(q,2),clear:()=>ie("",0,!0),get isCancelled(){return v}}},br={light:oe("\u2500","-"),heavy:oe("\u2501","="),block:oe("\u2588","#")};Ui=(e,t)=>e.includes(`
129
+ `}}}}).prompt(),xl=e=>{let t=e.validate;return Ar({...e,initialUserInput:e.initialValue??e.root??process.cwd(),maxItems:5,validate(i){if(!Array.isArray(i)){if(!i)return"Please select a path";if(t)return t(i)}},options(){let i=this.userInput;if(i==="")return[];try{let s;return(0,It.existsSync)(i)?(0,It.lstatSync)(i).isDirectory()?s=i:s=(0,ni.dirname)(i):s=(0,ni.dirname)(i),(0,It.readdirSync)(s).map(n=>{let r=(0,ni.join)(s,n),o=(0,It.lstatSync)(r);return{name:n,path:r,isDirectory:o.isDirectory()}}).filter(({path:n,isDirectory:r})=>n.startsWith(i)&&(e.directory||!r)).map(n=>({value:n.path}))}catch{return[]}}})},jl=p.default.magenta,oi=({indicator:e="dots",onCancel:t,output:i=process.stdout,cancelMessage:s,errorMessage:n,frames:r=qi?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:o=qi?80:120,signal:a,...l}={})=>{let m=qs(),f,g,b=!1,w=!1,v="",h,_=performance.now(),x=St(i),O=l?.styleFrame??jl,R=q=>{let Y=q>1?n??ce.messages.error:s??ce.messages.cancel;w=q===1,b&&(ie(Y,q),w&&typeof t=="function"&&t())},M=()=>R(2),V=()=>R(1),ee=()=>{process.on("uncaughtExceptionMonitor",M),process.on("unhandledRejection",M),process.on("SIGINT",V),process.on("SIGTERM",V),process.on("exit",R),a&&a.addEventListener("abort",V)},P=()=>{process.removeListener("uncaughtExceptionMonitor",M),process.removeListener("unhandledRejection",M),process.removeListener("SIGINT",V),process.removeListener("SIGTERM",V),process.removeListener("exit",R),a&&a.removeEventListener("abort",V)},E=()=>{if(h===void 0)return;m&&i.write(`
130
+ `);let q=Kt(h,x,{hard:!0,trim:!1}).split(`
131
+ `);q.length>1&&i.write(Bt.cursor.up(q.length-1)),i.write(Bt.cursor.to(0)),i.write(Bt.erase.down())},N=q=>q.replace(/\.+$/,""),Z=q=>{let Y=(performance.now()-q)/1e3,Q=Math.floor(Y/60),G=Math.floor(Y%60);return Q>0?`[${Q}m ${G}s]`:`[${G}s]`},z=l.withGuide??ce.withGuide,F=(q="")=>{b=!0,f=cr({output:i}),v=N(q),_=performance.now(),z&&i.write(`${p.default.gray(A)}
132
+ `);let Y=0,Q=0;ee(),g=setInterval(()=>{if(m&&v===h)return;E(),h=v;let G=O(r[Y]),Oe;if(m)Oe=`${G} ${v}...`;else if(e==="timer")Oe=`${G} ${v} ${Z(_)}`;else{let de=".".repeat(Math.floor(Q)).slice(0,3);Oe=`${G} ${v}${de}`}let Be=Kt(Oe,x,{hard:!0,trim:!1});i.write(Be),Y=Y+1<r.length?Y+1:0,Q=Q<4?Q+.125:0},o)},ie=(q="",Y=0,Q=!1)=>{if(!b)return;b=!1,clearInterval(g),E();let G=Y===0?p.default.green(At):Y===1?p.default.red(Ms):p.default.red(Ls);v=q??v,Q||(e==="timer"?i.write(`${G} ${v} ${Z(_)}
133
+ `):i.write(`${G} ${v}
134
+ `)),P(),f()};return{start:F,stop:(q="")=>ie(q,0),message:(q="")=>{v=N(q??v)},cancel:(q="")=>ie(q,1),error:(q="")=>ie(q,2),clear:()=>ie("",0,!0),get isCancelled(){return w}}},br={light:oe("\u2500","-"),heavy:oe("\u2501","="),block:oe("\u2588","#")};Ui=(e,t)=>e.includes(`
135
135
  `)?e.split(`
136
136
  `).map(i=>t(i)).join(`
137
137
  `):t(e),Qe=e=>{let t=(i,s)=>{let n=i.label??String(i.value);switch(s){case"disabled":return`${p.default.gray(Rt)} ${Ui(n,p.default.gray)}${i.hint?` ${p.default.dim(`(${i.hint??"disabled"})`)}`:""}`;case"selected":return`${Ui(n,p.default.dim)}`;case"active":return`${p.default.green(ri)} ${n}${i.hint?` ${p.default.dim(`(${i.hint})`)}`:""}`;case"cancelled":return`${Ui(n,r=>p.default.strikethrough(p.default.dim(r)))}`;default:return`${p.default.dim(Rt)} ${Ui(n,p.default.dim)}`}};return new Ri({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let i=e.withGuide??ce.withGuide,s=`${Ze(this.state)} `,n=`${Ys(this.state)} `,r=nt(e.output,e.message,n,s),o=`${i?`${p.default.gray(A)}
138
138
  `:""}${r}
139
139
  `;switch(this.state){case"submit":{let a=i?`${p.default.gray(A)} `:"",l=nt(e.output,t(this.options[this.cursor],"selected"),a);return`${o}${l}`}case"cancel":{let a=i?`${p.default.gray(A)} `:"",l=nt(e.output,t(this.options[this.cursor],"cancelled"),a);return`${o}${l}${i?`
140
- ${p.default.gray(A)}`:""}`}default:{let a=i?`${p.default.cyan(A)} `:"",l=i?p.default.cyan(ke):"",m=o.split(`
140
+ ${p.default.gray(A)}`:""}`}default:{let a=i?`${p.default.cyan(A)} `:"",l=i?p.default.cyan(_e):"",m=o.split(`
141
141
  `).length,f=i?2:1;return`${o}${a}${zt({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:a.length,rowPadding:m+f,style:(g,b)=>t(g,g.disabled?"disabled":b?"active":"inactive")}).join(`
142
142
  ${a}`)}
143
143
  ${l}
144
144
  `}}}}).prompt()},Cl=e=>{let t=(i,s="inactive")=>{let n=i.label??String(i.value);return s==="selected"?`${p.default.dim(n)}`:s==="cancelled"?`${p.default.strikethrough(p.default.dim(n))}`:s==="active"?`${p.default.bgCyan(p.default.gray(` ${i.value} `))} ${n}${i.hint?` ${p.default.dim(`(${i.hint})`)}`:""}`:`${p.default.gray(p.default.bgWhite(p.default.inverse(` ${i.value} `)))} ${n}${i.hint?` ${p.default.dim(`(${i.hint})`)}`:""}`};return new Ai({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,caseSensitive:e.caseSensitive,render(){let i=e.withGuide??ce.withGuide,s=`${i?`${p.default.gray(A)}
145
145
  `:""}${Ze(this.state)} ${e.message}
146
146
  `;switch(this.state){case"submit":{let n=i?`${p.default.gray(A)} `:"",r=this.options.find(a=>a.value===this.value)??e.options[0],o=nt(e.output,t(r,"selected"),n);return`${s}${o}`}case"cancel":{let n=i?`${p.default.gray(A)} `:"",r=nt(e.output,t(this.options[0],"cancelled"),n);return`${s}${r}${i?`
147
- ${p.default.gray(A)}`:""}`}default:{let n=i?`${p.default.cyan(A)} `:"",r=i?p.default.cyan(ke):"",o=this.options.map((a,l)=>nt(e.output,t(a,l===this.cursor?"active":"inactive"),n)).join(`
147
+ ${p.default.gray(A)}`:""}`}default:{let n=i?`${p.default.cyan(A)} `:"",r=i?p.default.cyan(_e):"",o=this.options.map((a,l)=>nt(e.output,t(a,l===this.cursor?"active":"inactive"),n)).join(`
148
148
  `);return`${s}${o}
149
149
  ${r}
150
150
  `}}}}).prompt()},yr=`${p.default.gray(A)} `,Ct={message:async(e,{symbol:t=p.default.gray(A)}={})=>{process.stdout.write(`${p.default.gray(A)}
@@ -156,63 +156,64 @@ ${yr}${s.trimStart()}`),i=3+(0,Fi.stripVTControlCharacters)(s.trimStart()).lengt
156
156
  `)},info:e=>Ct.message(e,{symbol:p.default.blue(Bs)}),success:e=>Ct.message(e,{symbol:p.default.green(Gs)}),step:e=>Ct.message(e,{symbol:p.default.green(At)}),warn:e=>Ct.message(e,{symbol:p.default.yellow(Ks)}),warning:e=>Ct.warn(e),error:e=>Ct.message(e,{symbol:p.default.red(zs)})},Ol=async(e,t)=>{for(let i of e){if(i.enabled===!1)continue;let s=oi(t);s.start(i.title);let n=await i.task(s.message);s.stop(n||i.title)}},Il=e=>e.replace(/\x1b\[(?:\d+;)*\d*[ABCDEFGHfJKSTsu]|\x1b\[(s|u)/g,""),Rl=e=>{let t=e.output??process.stdout,i=St(t),s=p.default.gray(A),n=e.spacing??1,r=3,o=e.retainLog===!0,a=!qs()&&$r(t);t.write(`${s}
157
157
  `),t.write(`${p.default.green(At)} ${e.title}
158
158
  `);for(let _=0;_<n;_++)t.write(`${s}
159
- `);let l=[{value:"",full:""}],m=!1,f=_=>{if(l.length===0)return;let j=0;_&&(j+=n+2);for(let O of l){let{value:R,result:M}=O,V=M?.message??R;if(V.length===0)continue;M===void 0&&O.header!==void 0&&O.header!==""&&(V+=`
159
+ `);let l=[{value:"",full:""}],m=!1,f=_=>{if(l.length===0)return;let x=0;_&&(x+=n+2);for(let O of l){let{value:R,result:M}=O,V=M?.message??R;if(V.length===0)continue;M===void 0&&O.header!==void 0&&O.header!==""&&(V+=`
160
160
  ${O.header}`);let ee=V.split(`
161
- `).reduce((P,E)=>E===""?P+1:P+Math.ceil((E.length+r)/i),0);j+=ee}j>0&&(j+=1,t.write(Bt.erase.lines(j)))},g=(_,j,O)=>{let R=O?`${_.full}
161
+ `).reduce((P,E)=>E===""?P+1:P+Math.ceil((E.length+r)/i),0);x+=ee}x>0&&(x+=1,t.write(Bt.erase.lines(x)))},g=(_,x,O)=>{let R=O?`${_.full}
162
162
  ${_.value}`:_.value;_.header!==void 0&&_.header!==""&&Ve.message(_.header.split(`
163
163
  `).map(p.default.bold),{output:t,secondarySymbol:s,symbol:s,spacing:0}),Ve.message(R.split(`
164
- `).map(p.default.dim),{output:t,secondarySymbol:s,symbol:s,spacing:j??n})},b=()=>{for(let _ of l){let{header:j,value:O,full:R}=_;(j===void 0||j.length===0)&&O.length===0||g(_,void 0,o===!0&&R.length>0)}},v=(_,j,O)=>{if(f(!1),(O?.raw!==!0||!m)&&_.value!==""&&(_.value+=`
165
- `),_.value+=Il(j),m=O?.raw===!0,e.limit!==void 0){let R=_.value.split(`
164
+ `).map(p.default.dim),{output:t,secondarySymbol:s,symbol:s,spacing:x??n})},b=()=>{for(let _ of l){let{header:x,value:O,full:R}=_;(x===void 0||x.length===0)&&O.length===0||g(_,void 0,o===!0&&R.length>0)}},w=(_,x,O)=>{if(f(!1),(O?.raw!==!0||!m)&&_.value!==""&&(_.value+=`
165
+ `),_.value+=Il(x),m=O?.raw===!0,e.limit!==void 0){let R=_.value.split(`
166
166
  `),M=R.length-e.limit;if(M>0){let V=R.splice(0,M);o&&(_.full+=(_.full===""?"":`
167
167
  `)+V.join(`
168
168
  `))}_.value=R.join(`
169
- `)}a&&w()},w=()=>{for(let _ of l)_.result?_.result.status==="error"?Ve.error(_.result.message,{output:t,secondarySymbol:s,spacing:0}):Ve.success(_.result.message,{output:t,secondarySymbol:s,spacing:0}):_.value!==""&&g(_,0)},h=(_,j)=>{f(!1),_.result=j,a&&w()};return{message(_,j){v(l[0],_,j)},group(_){let j={header:_,value:"",full:""};return l.push(j),{message(O,R){v(j,O,R)},error(O){h(j,{status:"error",message:O})},success(O){h(j,{status:"success",message:O})}}},error(_,j){f(!0),Ve.error(_,{output:t,secondarySymbol:s,spacing:1}),j?.showLog!==!1&&b(),l.splice(1,l.length-1),l[0].value="",l[0].full=""},success(_,j){f(!0),Ve.success(_,{output:t,secondarySymbol:s,spacing:1}),j?.showLog===!0&&b(),l.splice(1,l.length-1),l[0].value="",l[0].full=""}}},Ae=e=>new Ei({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,output:e.output,signal:e.signal,input:e.input,render(){let t=e?.withGuide??ce.withGuide,i=`${`${t?`${p.default.gray(A)}
169
+ `)}a&&v()},v=()=>{for(let _ of l)_.result?_.result.status==="error"?Ve.error(_.result.message,{output:t,secondarySymbol:s,spacing:0}):Ve.success(_.result.message,{output:t,secondarySymbol:s,spacing:0}):_.value!==""&&g(_,0)},h=(_,x)=>{f(!1),_.result=x,a&&v()};return{message(_,x){w(l[0],_,x)},group(_){let x={header:_,value:"",full:""};return l.push(x),{message(O,R){w(x,O,R)},error(O){h(x,{status:"error",message:O})},success(O){h(x,{status:"success",message:O})}}},error(_,x){f(!0),Ve.error(_,{output:t,secondarySymbol:s,spacing:1}),x?.showLog!==!1&&b(),l.splice(1,l.length-1),l[0].value="",l[0].full=""},success(_,x){f(!0),Ve.success(_,{output:t,secondarySymbol:s,spacing:1}),x?.showLog===!0&&b(),l.splice(1,l.length-1),l[0].value="",l[0].full=""}}},Ae=e=>new Ei({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,output:e.output,signal:e.signal,input:e.input,render(){let t=e?.withGuide??ce.withGuide,i=`${`${t?`${p.default.gray(A)}
170
170
  `:""}${Ze(this.state)} `}${e.message}
171
- `,s=e.placeholder?p.default.inverse(e.placeholder[0])+p.default.dim(e.placeholder.slice(1)):p.default.inverse(p.default.hidden("_")),n=this.userInput?this.userInputWithCursor:s,r=this.value??"";switch(this.state){case"error":{let o=this.error?` ${p.default.yellow(this.error)}`:"",a=t?`${p.default.yellow(A)} `:"",l=t?p.default.yellow(ke):"";return`${i.trim()}
171
+ `,s=e.placeholder?p.default.inverse(e.placeholder[0])+p.default.dim(e.placeholder.slice(1)):p.default.inverse(p.default.hidden("_")),n=this.userInput?this.userInputWithCursor:s,r=this.value??"";switch(this.state){case"error":{let o=this.error?` ${p.default.yellow(this.error)}`:"",a=t?`${p.default.yellow(A)} `:"",l=t?p.default.yellow(_e):"";return`${i.trim()}
172
172
  ${a}${n}
173
173
  ${l}${o}
174
174
  `}case"submit":{let o=r?` ${p.default.dim(r)}`:"",a=t?p.default.gray(A):"";return`${i}${a}${o}`}case"cancel":{let o=r?` ${p.default.strikethrough(p.default.dim(r))}`:"",a=t?p.default.gray(A):"";return`${i}${a}${o}${r.trim()?`
175
- ${a}`:""}`}default:{let o=t?`${p.default.cyan(A)} `:"",a=t?p.default.cyan(ke):"";return`${i}${o}${n}
175
+ ${a}`:""}`}default:{let o=t?`${p.default.cyan(A)} `:"",a=t?p.default.cyan(_e):"";return`${i}${o}${n}
176
176
  ${a}
177
- `}}}}).prompt()});function Al(e){return!!(e.json||!je)}function C(e,t=50){console.log(),console.log(` ${J.default.bold(e)}`),console.log(` ${J.default.dim("\u2500".repeat(t))}`)}function c(e,t,i=2){let s=" ".repeat(i);console.log(`${s}${J.default.dim(e.padEnd(16))} ${t}`)}function d(){console.log()}function ze(e){console.log(` ${J.default.dim(e)}`)}function I(e,t){console.log(` ${J.default.dim(e)} ${J.default.cyan(t)}`)}function Tr(e){return e.split(/(https?:\/\/[^\s]+)/g).map(i=>/^https?:\/\//.test(i)?`\x1B]8;;${i}\x1B\\${J.default.underline(J.default.cyan(i))}\x1B]8;;\x1B\\`:J.default.dim(i)).join("")}function tn(e,t){console.error(` ${y.error} ${J.default.red(e)}`),t&&console.error(` ${Tr(t)}`)}function S(e=!0){return e?oi():El}function Nr(e){return e.replace(Pl,"")}function Wi(e,t){let i=Nr(e).length,s=Math.max(0,t-i);return e+" ".repeat(s)}function se(e,t,i){let s=i||e.map((o,a)=>{let l=t.reduce((m,f)=>Math.max(m,Nr(f[a]||"").length),0);return Math.max(o.length,l)+2}),n=e.map((o,a)=>J.default.dim(o.padEnd(s[a]))).join(" "),r=s.map(o=>J.default.dim("\u2500".repeat(o))).join(" ");console.log(` ${n}`),console.log(` ${r}`);for(let o of t){let a=o.map((l,m)=>Wi(l,s[m])).join(" ");console.log(` ${a}`)}}function Dl(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function en(e){if(Array.isArray(e))return e.map(en);if(e&&typeof e=="object"&&!(e instanceof Date)){let t={};for(let[i,s]of Object.entries(e))t[Dl(i)]=en(s);return t}return e}function k(e,t){let i=en(e);if(!t){console.log(JSON.stringify(i,null,2));return}let s=t.split(",").map(n=>n.trim()).filter(Boolean);if(Array.isArray(i)){let n=i.map(r=>Er(r,s));console.log(JSON.stringify(n,null,2))}else console.log(JSON.stringify(i&&typeof i=="object"?Er(i,s):i,null,2))}function Er(e,t){let i={};for(let s of t)s in e&&(i[s]=e[s]);if(Object.keys(i).length===0){for(let[s,n]of Object.entries(e))if(Array.isArray(n)&&n.length>0&&typeof n[0]=="object"){let r=n.map(o=>{let a={};for(let l of t)l in o&&(a[l]=o[l]);return a});Object.keys(r[0]).length>0&&(i[s]=r)}}return i}function Et(e){return!!(e.yes||Al(e))}function B(e,t,i,s){if(i){k({dry_run:!0,action:e,...t},s);return}console.log(),console.log(` ${J.default.yellow("\u25B8 DRY RUN")} ${J.default.dim("- no changes made")}`),console.log(` ${J.default.dim("Action:")} ${J.default.bold(e)}`);for(let[n,r]of Object.entries(t))r!=null&&(Array.isArray(r)?console.log(` ${J.default.dim(n+":")} ${r.map(String).join(", ")}`):console.log(typeof r=="object"?` ${J.default.dim(n+":")} ${JSON.stringify(r)}`:` ${J.default.dim(n+":")} ${String(r)}`));console.log()}function Nl(e,t,i){return t===401||t===403?"auth_required":t===402||i?"payment_required":t===404?"not_found":t===409?"conflict":t===422?"validation_error":t===429?"rate_limited":/contact/i.test(e)?"contact_required":"error"}function u(e,t){let i=e||`Request failed${t?.status?` (${t.status})`:""}`,s=t?.code||Nl(i,t?.status,t?.fixUrl),n=t?.fixCommand||Tl[s];if(t?.json){let r={error:i,code:s};t.hint&&(r.hint=t.hint),n&&(r.fix_command=n),t.fixUrl&&(r.fix_url=t.fixUrl),k(r,t.fields)}else tn(i,t?.hint),n?console.error(` ${J.default.dim("Or run:")} ${J.default.cyan(n)}`):t?.fixUrl&&console.error(` ${Tr(`Add a payment method at ${t.fixUrl}`)}`);process.exit(1)}function We(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";(0,Dr.execFile)(t,[e])}function Pt(e){return new Promise(t=>setTimeout(t,e))}function Dt(e,t,i,s=!0){let n=process.stdout.isTTY??!1;if(!s)return{start(){},markDone(){},stop(){}};let r=0,o=null,a=2+t.length;function l(){let b=" "+e.map((h,_)=>J.default.dim(h.padEnd(i[_]))).join(" "),v=" "+i.map(h=>J.default.dim("\u2500".repeat(h))).join(" "),w=[b,v];for(let h of t){let _=h.status==="done"?h.icon??y.success:J.default.cyan(Pr[r%Pr.length]),j=h.cells.map((O,R)=>Wi(O,i[R])).join(" ");w.push(` ${_} ${j}`)}return w}let m=!1,f=()=>process.stdout.write("\x1B[?25h");function g(){let b=l();if(m&&n){process.stdout.write(`\x1B[${a}A`);for(let v of b)process.stdout.write(`\x1B[2K${v}
178
- `)}else{for(let v of b)console.log(v);m=!0}}return{start(){n&&(process.stdout.write("\x1B[?25l"),process.on("exit",f)),g(),n&&(o=setInterval(()=>{r++,g()},80))},markDone(b,v){t[b].status="done",v!==void 0&&(t[b].icon=v),n&&g()},stop(){o&&clearInterval(o);for(let b of t)b.status="done";g(),n&&(process.stdout.write("\x1B[?25h"),process.removeListener("exit",f))}}}var J,Dr,je,y,$,El,Pl,Tl,Pr,W=Ie(()=>{"use strict";J=U(L(),1),Dr=require("child_process");De();je=process.stdout.isTTY??!1;y={success:J.default.green("\u2713"),error:J.default.red("\u2717"),warning:J.default.yellow("!"),info:J.default.cyan("\u25CF"),arrow:J.default.dim("\u2192"),dot:J.default.dim("\xB7"),dash:J.default.dim("\u2500")},$={domain:e=>J.default.bold(J.default.white(e)),price:e=>J.default.green(`$${e}`),label:e=>J.default.dim(e),value:e=>J.default.white(e),dim:e=>J.default.dim(e),bold:e=>J.default.bold(e),success:e=>J.default.green(e),error:e=>J.default.red(e),warn:e=>J.default.yellow(e),cyan:e=>J.default.cyan(e),url:e=>`\x1B]8;;${e}\x1B\\${J.default.underline(J.default.cyan(e))}\x1B]8;;\x1B\\`};El={start:()=>{},stop:()=>{},message:()=>{}};Pl=/\x1b\]8;;[^\x1b]*\x1b\\|\x1b\[[0-9;]*m/g;Tl={auth_required:"domani login",payment_required:"domani card add",contact_required:"domani contact set"};Pr=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"]});function Ur(e){return typeof e=="string"&&["pro","agent","fleet","scale","mail_solo","mail_team","mail_business"].includes(e)}function Fr(e){return Ur(e.plan)||Array.isArray(e.workspace_plans)&&e.workspace_plans.some(Ur)}async function qr(){if(nn)return;let e=process.argv.includes("--json")||!ks,t=qe(),i=Me();try{let r=await(await fetch(`${t}/api/me`,{headers:{Authorization:`Bearer ${i}`}})).json();if(Fr(r)){nn=!0;return}}catch{}e&&(console.log(JSON.stringify({error:"Paid plan required",code:"upgrade_required",hint:"Upgrade at https://domani.run/settings",fix_command:"domani upgrade"},null,2)),process.exit(1)),d(),console.log(` ${ye.default.dim("This feature requires a")} ${ye.default.bold("paid plan")} ${ye.default.dim("(including an active Mailzero workspace plan or legacy Pro subscription).")}`),console.log(` ${ye.default.dim("Opening pricing page")} ${y.arrow} ${ye.default.cyan("domani.run/pricing")}`),We(`${t.replace("http://localhost:3000","https://domani.run")}/pricing`),d();let s=S(!0);s.start("Waiting for upgrade...");for(let n=0;n<120;n++){await new Promise(r=>setTimeout(r,5e3));try{let o=await(await fetch(`${t}/api/me`,{headers:{Authorization:`Bearer ${i}`}})).json();if(Fr(o)){nn=!0,s.stop(`${y.success} Paid plan active! Continuing...`),d();return}}catch{}}s.stop("Timed out"),console.error(` ${ye.default.red("\u2717")} No upgrade detected. Visit ${ye.default.cyan("domani.run/settings")} to upgrade.`),process.exit(1)}async function Mr(){if(sn||Me()){sn=!0;return}(process.argv.includes("--json")||!ks)&&(console.log(JSON.stringify({error:"Not logged in",code:"auth_required",hint:"Run 'domani login' or set DOMANI_API_KEY environment variable",fix_command:"domani login"},null,2)),process.exit(1)),d(),console.log(` ${ye.default.dim("You're not logged in.")} Starting authentication...`),d();let t=qe(),i=S(!0);i.start("Requesting auth code");let s;try{s=await fetch(`${t}/api/auth/cli`,{method:"POST",headers:{"Content-Type":"application/json"}})}catch{i.stop("Failed"),console.error(` ${ye.default.red("\u2717")} Could not reach ${t}. Check your connection.`),process.exit(1)}if(!s.ok){i.stop("Failed");let o=`Server error (${s.status})`;try{let a=await s.json();o=a.error||a.message||o}catch{}console.error(` ${ye.default.red("\u2717")} ${o}`),process.exit(1)}let n,r;try{({code:n,auth_url:r}=await s.json())}catch{i.stop("Failed"),console.error(` ${ye.default.red("\u2717")} Invalid response from server.`),process.exit(1)}i.stop(`${y.success} Auth code ready`),d(),console.log(` ${ye.default.dim("Verification code:")} ${ye.default.bold(ye.default.cyan(n))}`),console.log(` ${ye.default.dim("Opening browser")} ${y.arrow} ${$.url(r)}`),We(r),d(),i.start("Waiting for browser approval");for(let o=0;o<120;o++){await new Promise(m=>setTimeout(m,5e3));let a=await fetch(`${t}/api/auth/cli/poll?code=${n}`).catch(()=>null);if(!a||!a.ok&&a.status!==202)continue;let l=await a.json().catch(()=>({}));if(l.status==="complete"){Jt({...ut(),token:l.token,email:l.email,api_url:t}),sn=!0,i.stop(`${y.success} Logged in as ${ye.default.bold(l.email)}`),d();return}}i.stop("Timed out"),console.error(` ${ye.default.red("\u2717")} No approval received. Run ${ye.default.cyan("domani login")} to try again.`),process.exit(1)}var ye,sn,nn,rn=Ie(()=>{"use strict";ye=U(L(),1);mt();W();sn=!1,nn=!1});function Wr(e){return e.json=async()=>{let t=await e.clone().text();try{return JSON.parse(t)}catch{let i=t.trim().slice(0,120);return e.ok?(Object.defineProperty(e,"ok",{value:!1}),{error:`Unexpected non-JSON response (HTTP ${e.status})`,hint:`The server replied but not with JSON${i?` (got: "${i}")`:""}. This is usually transient (deploy or proxy) - retry in a few seconds.`}):{error:`Server error (${e.status})`,hint:"The server returned an unexpected response. Try again later."}}},e}async function x(e,t={},i=!1){let s=Me(),n=`${qe()}${e}`,r=await fetch(n,{...t,headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json","User-Agent":`domani-cli/${_e}`,...t.headers}});if(!i){let o=await r.clone().text();try{if(JSON.parse(o).code==="UPGRADE_REQUIRED")return await qr(),x(e,t,!0)}catch{}}return Wr(r)}async function be(e,t={}){let i=`${qe()}${e}`,s=Me(),n=await fetch(i,{...t,headers:{"Content-Type":"application/json","User-Agent":`domani-cli/${_e}`,...s?{Authorization:`Bearer ${s}`}:{},...t.headers}});return Wr(n)}var X=Ie(()=>{"use strict";mt();rn()});function kt(){return{ok:!0}}function pt(e,t,i){return{ok:!1,error:{message:e,code:t,hint:i}}}function Br(e){return ql.test(e)?pt("Input contains control characters","invalid_input","Remove non-printable characters from the input"):kt()}function Jl(e){return Ml.test(e)?pt("Input contains path traversal","invalid_input","Domain names cannot contain '../' or '..\\'"):kt()}function Bl(e){return Ll.test(e)?pt("Input contains query string or fragment","invalid_input","Remove '?' or '#' from the domain name"):kt()}function Gl(e){return Vl.test(e)?pt("Input contains percent-encoded characters","invalid_input","Use plain text, not URL-encoded values (e.g. 'example.com' not 'example%2Ecom')"):kt()}function Gr(e){if(!e)return pt("Domain name is required","validation_error");if(e.length>Jr)return pt(`Domain name too long (${e.length} chars, max ${Jr})`,"validation_error");for(let t of[Br,Jl,Bl,Gl]){let i=t(e);if(!i.ok)return i}return Wl.test(e)?kt():pt(`Invalid domain name: ${e}`,"validation_error","Domain names can only contain letters, digits, hyphens, and dots")}function Kl(e){if(!e)return pt("TLD is required","validation_error");let t=Br(e);return t.ok?Hl.test(e)?kt():pt(`Invalid TLD: ${e}`,"validation_error","TLDs contain only letters (e.g. 'com', '.dev', 'ai')"):t}function zl(e){for(let t of e){let i=Gr(t);if(!i.ok)return i}return kt()}function Yl(e){for(let t of e){let i=Kl(t);if(!i.ok)return i}return kt()}function K(e,t){let i=Gr(e);i.ok||u(i.error.message,{code:i.error.code,hint:i.error.hint,json:t?.json,fields:t?.fields})}function Kr(e,t){let i=zl(e);i.ok||u(i.error.message,{code:i.error.code,hint:i.error.hint,json:t?.json,fields:t?.fields})}function Hi(e,t){let i=Yl(e);i.ok||u(i.error.message,{code:i.error.code,hint:i.error.hint,json:t?.json,fields:t?.fields})}var ql,Ml,Ll,Vl,Wl,Hl,Jr,he=Ie(()=>{"use strict";W();ql=/[\x00-\x08\x0b\x0c\x0e-\x1f]/,Ml=/\.\.[/\\]/,Ll=/[?#]/,Vl=/%[0-9a-fA-F]{2}/,Wl=/^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?)*\.?$/,Hl=/^\.?[a-zA-Z]{2,63}$/,Jr=253});async function fe(){je||u("Missing required argument: domain",{hint:"Pass the domain as an argument, e.g. 'domani settings example.com'",code:"missing_argument",json:!0});let e=S(!0);e.start("Loading your domains");let t=await x("/api/domains"),i=await t.json();t.ok||(e.stop("Failed"),tn(i.error,i.hint),process.exit(1));let s=i.domains||[];s.length===0&&(e.stop("No domains"),d(),console.log(` ${an.default.dim("No domains yet.")} Use: ${an.default.cyan("domani buy <domain>")}`),d(),process.exit(0)),e.stop(`${s.length} domain(s)`);let n=await Qe({message:"Which domain?",options:s.map(r=>({value:r.domain,label:r.domain,hint:r.status!=="active"?r.status:void 0}))});return le(n)&&process.exit(0),n}var an,Ye=Ie(()=>{"use strict";X();De();an=U(L(),1);W()});var Yr={};Mt(Yr,{connect:()=>ln});async function ln(e,t,i){e||(e=await fe()),K(e,i);let s;if(t&&!i.provider?t.includes(".")?s=t:i.provider=t:s=t,!s&&!i.provider&&!i.list&&i.dryRun)return B("connect",{domain:e,note:"No provider specified. Pass --provider <name> to connect."},i.json,i.fields);if(!s&&!i.provider&&!i.list){let n=S(!i.json);n.start(`Loading providers for ${$.domain(e)}`);let r=await x(`/api/domains/${encodeURIComponent(e)}/connect`),o=await r.json();if(r.ok||(n.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:i.json,fields:i.fields})),n.stop("Providers loaded"),i.json){k(o,i.fields);return}let a=[];for(let h of["hosting","email"]){let _=o.providers?.[h]||[];for(let j of _)a.push({value:`${h}:${j.name}`,label:j.name,hint:h})}a.length===0&&u("No providers available",{code:"not_found",json:i.json,fields:i.fields});let l=await Qe({message:"Choose a provider",options:a});le(l)&&process.exit(0);let[m,f]=l.split(":"),b=(o.providers?.[m]||[]).find(h=>h.name===f),v;if(b&&b.methods.length>1){let h=await Qe({message:"Choose a method",options:b.methods.map(_=>({value:_.name,label:_.name,hint:_.default?"default":void 0}))});le(h)&&process.exit(0),v=h}let w;if(m==="hosting"&&b?.requires_target){b.notes?.setup&&ze(b.notes.setup);let h=await Ae({message:"Target hostname or IP"});le(h)&&process.exit(0),w=h.trim()}return zr(e,{target:w,provider:f,method:v,dryRun:i.dryRun,json:!1})}if(i.list){let n=S(!i.json);n.start(`Loading providers for ${$.domain(e)}`);let r=await x(`/api/domains/${encodeURIComponent(e)}/connect`),o=await r.json();if(r.ok||(n.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:i.json,fields:i.fields})),n.stop("Providers loaded"),i.json){k(o,i.fields);return}C(`Providers for ${$.domain(o.domain)}`);for(let a of["hosting","email"]){let l=o.providers?.[a];if(l?.length){d(),console.log(` ${ue.default.bold(a.toUpperCase())}`);for(let m of l){let f=m.methods.map(g=>g.default?ue.default.green(`${g.name} (default)`):ue.default.dim(g.name)).join(ue.default.dim(", "));console.log(` ${ue.default.cyan(m.name.padEnd(20))} ${f}`)}}}d();return}return zr(e,i)}async function zr(e,t){let i={};if(t.target&&(i.target=t.target),t.provider&&(i.provider=t.provider),t.method&&(i.method=t.method),t.dryRun)return B("connect",{domain:e,...i},t.json,t.fields);let s=S(!t.json);s.start(`Connecting ${$.domain(e)}`);let n=await x(`/api/domains/${encodeURIComponent(e)}/connect`,{method:"POST",body:JSON.stringify(i)}),r=await n.json();n.ok||(s.stop("Connection failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:t.json,fields:t.fields}));let o=r.status==="manual_setup_required";if(s.stop(o?`${y.success} DNS instructions for ${ue.default.cyan(r.provider)}`:`${y.success} Connected to ${ue.default.cyan(r.provider)}`),t.json){k(r,t.fields);return}if(C(o?`Add these records at your registrar for ${$.domain(r.domain)}`:`Connected ${$.domain(r.domain)}`),c("Provider",ue.default.cyan(r.provider)),c("Method",r.method),r.records?.length){let a=[8,22,40];d(),console.log(` ${ue.default.bold("DNS Records")}`);let l=["Type","Name","Value"].map((f,g)=>ue.default.dim(f.padEnd(a[g]))).join(" "),m=a.map(f=>ue.default.dim("\u2500".repeat(f))).join(" ");console.log(` ${l}`),console.log(` ${m}`);for(let f of r.records){let g=f.record,b=f.status!=="already_set";process.stdout.isTTY&&b&&await Pt(50);let w=[ue.default.yellow(g.type),g.name,ue.default.cyan(g.value)+(g.priority?ue.default.dim(` pri=${g.priority}`):"")].map((j,O)=>Wi(j,a[O])).join(" "),h=f.status==="already_set"?ue.default.dim("\u2713"):f.status==="updated"?ue.default.yellow("\u21BA"):f.status==="pending"?ue.default.yellow("\u2192"):y.success,_=f.status==="already_set"?ue.default.dim(" already set"):f.status==="updated"?ue.default.dim(" updated"):f.status==="pending"?ue.default.dim(" add this"):"";console.log(` ${h} ${w}${_}`)}}d(),r.next_steps?.length?(console.log(` ${ue.default.bold("Next steps")}`),r.next_steps.forEach((a,l)=>{console.log(` ${ue.default.dim(`${l+1}.`)} ${a}`)})):r.hint&&console.log(` ${ue.default.dim(r.hint)}`),r.docs&&console.log(` ${ue.default.dim("Docs:")} ${$.url(r.docs)}`),d()}var ue,dn=Ie(()=>{"use strict";X();ue=U(L(),1);De();W();he();Ye()});function Tt(e,t=process.env){if(e.clearHeaders&&(e.authorizationEnv||e.apiKeyEnv))throw new Error("--clear-headers cannot be combined with header environment options");if(e.clearHeaders)return{};let i={},s=[["Authorization",e.authorizationEnv],["X-API-Key",e.apiKeyEnv]];for(let[n,r]of s){if(!r)continue;let o=t[r];if(!o)throw new Error(`Environment variable ${r} is not set`);i[n]=o}return Object.keys(i).length>0?i:void 0}function Nt(e){return e?Object.keys(e):[]}var Ji=Ie(()=>{"use strict"});var so={};Mt(so,{email:()=>li,parseRecipients:()=>Bi,recipientField:()=>Gi});function Ql(e){return[D.default.yellow(e.type),e.name,D.default.cyan(e.value)+(e.priority?D.default.dim(` pri=${e.priority}`):"")]}function cn(e){return Zl[e]||e}function Bi(e){return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function Gi(e){if(e.length!==0)return e.length===1?e[0]:e}function ed(e,t){if(e&&e.includes("@")){let[i,s]=e.split("@",2);!t.slug&&i&&(t.slug=i),!t.domain&&s&&(t.domain=s)}}async function Xe(e){return e.domain?(K(e.domain,e),e.domain):fe()}async function li(e,t,i){if(e&&e.includes(".")&&!Xl.includes(e))return i.check?Zr(e,!!i.json,i.fields):t?Qr(e,t,!!i.json,i.fields):to(e,!!i.json,i.fields);if(ed(t,i),i.body&&!i.text&&(i.text=i.body),i.title&&!i.subject&&(i.subject=i.title),i.from&&i.from.includes("@")){let[s,n]=i.from.split("@",2);!i.slug&&s&&(i.slug=s),!i.domain&&n&&(i.domain=n)}switch(e){case void 0:return Xr(i);case"list":return Xr(i);case"inbox":return gd(i);case"folders":return bd(i);case"archive":case"trash":case"restore":case"read":case"unread":case"star":case"unstar":return yd(e,i);case"setup":return cd(i);case"status":return ud(i);case"remove":return md(i);case"create":return fd(i);case"delete":return pd(i);case"send":return hd(i);case"webhook":return $d(i);case"webhook-test":return vd(i);case"forward":return wd(i);case"work":return rd(i);case"triage":return od(i);case"note":return ad(i);case"notes":return ld(i);case"activity":return dd(i);case"changes":return nd(i);case"coordination":return td(i);case"presence":return id(i);case"release-presence":return sd(i);case"check":return Zr(i.domain||await fe(),!!i.json,i.fields);case"connect":return Qr(i.domain||await fe(),t||void 0,!!i.json,i.fields);default:u(`Unknown action: ${e}`,{hint:"Actions: list, inbox, folders, archive, trash, restore, read, unread, star, unstar, create, delete, send, forward, webhook, webhook-test, work, triage, notes, note, activity, changes, coordination, presence, release-presence, setup, status, check, connect",code:"validation_error",json:i.json,fields:i.fields})}}function un(e){let t=e.mailboxIds?.split(",").map(i=>i.trim()).filter(Boolean)[0];return(!t||!e.threadKey)&&u("Mailbox ID and thread key required",{hint:"Pass --mailbox-ids mb_1 --thread-key 'jmap:thread_1'",code:"validation_error",json:e.json,fields:e.fields}),{mailboxId:t,threadKey:e.threadKey}}async function td(e){let{mailboxId:t,threadKey:i}=un(e),s=new URLSearchParams({mailbox_id:t,thread_key:i}),n=await x(`/api/email/collaboration/coordination?${s}`),r=await n.json();if(n.ok||u(r.error||"Could not read coordination",{code:r.code||"api_error",json:e.json,fields:e.fields}),e.json)return k(r,e.fields);C("Conversation Coordination"),c("Conversation",r.conversation_id),c("Reply version",String(r.reply_version)),c("Presence",String(r.presence?.length||0)),c("Compose lease",r.compose_lease?.holder?.label||"none")}async function id(e){let{mailboxId:t,threadKey:i}=un(e);e.clientId||u("Client ID required",{hint:"Pass a stable --client-id for this agent process or app installation",code:"validation_error",json:e.json,fields:e.fields});let s=e.mode||"viewing";["viewing","composing"].includes(s)||u("Mode must be viewing or composing",{code:"validation_error",json:e.json,fields:e.fields});let n=await x("/api/email/collaboration/coordination",{method:"PUT",body:JSON.stringify({mailbox_id:t,thread_key:i,client_id:e.clientId,mode:s,acquire_lease:e.acquireLease!==!1})}),r=await n.json();if(n.ok||u(r.error||"Could not heartbeat presence",{code:r.code||"api_error",json:e.json,fields:e.fields}),e.json)return k(r,e.fields);C("Conversation Presence"),c("Mode",s),c("Reply version",String(r.reply_version)),c("Lease ID",r.compose_lease?.lease_id||"none"),c("Expires",r.compose_lease?.expires_at||r.presence?.find(o=>o.client_id===e.clientId)?.expires_at||"unknown")}async function sd(e){let{mailboxId:t,threadKey:i}=un(e);e.clientId||u("Client ID required",{hint:"Pass the same --client-id used for presence",code:"validation_error",json:e.json,fields:e.fields});let s=await x("/api/email/collaboration/coordination",{method:"DELETE",body:JSON.stringify({mailbox_id:t,thread_key:i,client_id:e.clientId,lease_id:e.leaseId})}),n=await s.json();if(s.ok||u(n.error||"Could not release presence",{code:n.code||"api_error",json:e.json,fields:e.fields}),e.json)return k(n,e.fields);C("Conversation Presence"),c("Released",e.clientId),c("Remaining presence",String(n.presence?.length||0))}async function nd(e){let t=e.mailboxIds?.split(",").map(r=>r.trim()).filter(Boolean)[0];t||u("Mailbox ID required",{hint:"Usage: domani email changes --mailbox-ids mb_1 [--cursor <opaque>]",code:"validation_error",json:e.json,fields:e.fields});let i=new URLSearchParams({mailbox_id:t});e.cursor&&i.set("cursor",e.cursor),e.limit&&i.set("limit",e.limit);let s=await x(`/api/email/changes?${i}`),n=await s.json();if(s.ok||u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields}),e.json)return k(n,e.fields);if(C("Mailbox Changes"),n.requires_full_sync){c("Full sync","Required"),c("Baseline cursor",n.next_cursor),ze("Take a bounded mailbox snapshot, then call this command again with --cursor to replay concurrent changes.");return}n.changes.length?se(["Sequence","Type","Resource","Created"],n.changes.map(r=>[r.sequence,r.type,`${r.resource_type}:${r.resource_id||"-"}`,r.created_at]),[12,32,40,24]):console.log(` ${D.default.dim("No changes since this cursor.")}`),c("Next cursor",n.next_cursor),n.has_more&&ze("More changes are available; call again with the next cursor.")}async function rd(e){let t=(e.mailboxIds||"").split(",").map(r=>r.trim()).filter(Boolean);t.length||u("Mailbox IDs required",{hint:"Usage: domani email work --mailbox-ids mb_1,mb_2",code:"validation_error",json:e.json,fields:e.fields});let i=new URLSearchParams({mailbox_ids:t.join(",")});e.status&&i.set("status",e.status),e.assigned&&i.set("assigned",e.assigned),e.limit&&i.set("limit",e.limit);let s=await x(`/api/email/work-queue?${i}`),n=await s.json();if(s.ok||u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields}),e.json)return k(n,e.fields);if(C("Shared Inbox Work"),!n.items.length)return console.log(` ${D.default.dim("No conversations match this queue.")}`);se(["Thread","Status","Assignee","Subject"],n.items.map(r=>[r.thread_key,r.status,r.assignee?.label||"Unassigned",r.subject||"(no subject)"]),[28,10,28,48]),n.partial&&ze("This is a bounded snapshot. Increase --limit or use the API scan_limit when you need a wider queue.")}async function od(e){(!e.mailboxIds||!e.threadKey)&&u("Mailbox ID and thread key required",{hint:"Usage: domani email triage --mailbox-ids mb_1 --thread-key <key> --status closed",code:"validation_error",json:e.json,fields:e.fields});let t=e.assigneeId&&e.assigneeType?{type:e.assigneeType,id:e.assigneeId}:void 0,i=await x("/api/email/collaboration",{method:"PATCH",body:JSON.stringify({mailbox_id:e.mailboxIds.split(",")[0],thread_key:e.threadKey,thread_aliases:e.threadAliases?.split(",").map(n=>n.trim()).filter(Boolean),status:e.status,assignee:t,version:e.ifVersion?Number.parseInt(e.ifVersion,10):void 0})}),s=await i.json();if(i.ok||u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields}),e.json)return k(s,e.fields);C("Conversation Updated"),c("Status",s.status),c("Assignee",s.assignee?.label||"Unassigned"),c("Version",s.version)}async function ad(e){(!e.conversationId||!e.note)&&u("Conversation ID and note required",{hint:'Usage: domani email note --conversation-id conv_1 --note "Waiting for finance"',code:"validation_error",json:e.json,fields:e.fields});let t=await x(`/api/email/collaboration/${encodeURIComponent(e.conversationId)}/notes`,{method:"POST",body:JSON.stringify({body:e.note})}),i=await t.json();if(t.ok||u(i.error||i.message,{hint:i.hint,status:t.status,json:e.json,fields:e.fields}),e.json)return k(i,e.fields);console.log(`${y.success} Private note added`)}async function ld(e){e.conversationId||u("Conversation ID required",{hint:"Usage: domani email notes --conversation-id conv_1",code:"validation_error",json:e.json,fields:e.fields});let t=await x(`/api/email/collaboration/${encodeURIComponent(e.conversationId)}/notes`),i=await t.json();if(t.ok||u(i.error||i.message,{hint:i.hint,status:t.status,json:e.json,fields:e.fields}),e.json)return k(i,e.fields);if(C("Private Notes"),!i.notes.length)return console.log(` ${D.default.dim("No private notes yet.")}`);se(["Author","Created","Note"],i.notes.map(s=>[s.author.label,s.created_at,s.body]),[28,24,64])}async function dd(e){e.conversationId||u("Conversation ID required",{hint:"Usage: domani email activity --conversation-id conv_1",code:"validation_error",json:e.json,fields:e.fields});let t=await x(`/api/email/collaboration/${encodeURIComponent(e.conversationId)}/activity`),i=await t.json();if(t.ok||u(i.error||i.message,{hint:i.hint,status:t.status,json:e.json,fields:e.fields}),e.json)return k(i,e.fields);if(C("Conversation Activity"),!i.activity.length)return console.log(` ${D.default.dim("No activity yet.")}`);se(["Type","Actor","Created"],i.activity.map(s=>[s.type,s.actor.label,s.created_at]),[36,32,24])}async function cd(e){let t=await Xe(e);if(e.dryRun)return B("email_setup",{domain:t},e.json,e.fields);let i=S(!e.json);i.start(`Setting up email on ${$.domain(t)}`);let s=await x(`/api/domains/${encodeURIComponent(t)}/email/setup`,{method:"POST"}),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields})),i.stop(`${y.success} Email ${n.status==="already_configured"?"already configured":"configured"}`),e.json){k(n,e.fields);return}if(n.records?.length){d(),C(`Email DNS Records ${$.domain(t)}`);let r=n.records.map(o=>[D.default.yellow(o.type),o.name,o.value.length>40?o.value.slice(0,40)+"...":o.value,o.status==="verified"||o.status==="created"?D.default.green(o.status):D.default.yellow(o.status)]);se(["Type","Name","Value","Status"],r,[8,28,44,12])}d(),n.hint&&ze(n.hint),I("Check status:",`domani email status --domain ${t}`),d()}async function ud(e){let t=await Xe(e),i=S(!e.json);i.start(`Checking email status for ${$.domain(t)}`);let s=await x(`/api/domains/${encodeURIComponent(t)}/email/status`),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields})),i.stop(`${y.success} Status loaded`),e.json){k(n,e.fields);return}if(C(`Email ${$.domain(t)}`),c("Enabled",n.enabled?D.default.green("yes"):D.default.dim("no")),n.enabled&&(c("Verified",n.verified?D.default.green("yes"):D.default.yellow("pending")),c("Mailboxes",String(n.mailbox_count))),d(),!n.enabled)I("Set up email:",`domani email setup --domain ${t}`),d();else if(!n.verified&&n.records?.length){console.log(` ${D.default.yellow("!")} Add these DNS records to verify:`);for(let r of n.records)console.log(` ${D.default.yellow(r.type)} ${r.name} ${D.default.dim("\u2192")} ${r.value.length>50?r.value.slice(0,50)+"...":r.value}`);d()}}async function md(e){let t=await Xe(e);if(e.dryRun)return B("email_remove",{domain:t},e.json,e.fields);let i=S(!e.json);i.start(`Removing email from ${$.domain(t)}`);let s=await x(`/api/domains/${encodeURIComponent(t)}/email/setup`,{method:"DELETE"}),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields})),i.stop(`${y.success} Email disabled`),e.json){k(n,e.fields);return}n.mailboxes_deleted>0&&console.log(` ${D.default.dim(`${n.mailboxes_deleted} mailbox(es) deleted.`)}`),d()}async function Xr(e){let t=S(!e.json);t.start("Loading mailboxes");let i=e.domain?`?domain=${encodeURIComponent(e.domain)}`:"",s=await x(`/api/emails${i}`),n=await s.json();s.ok||(t.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields}));let r=n.mailboxes||[];if(t.stop(`${y.success} ${r.length} mailbox(es)`),e.json){k(n,e.fields);return}if(r.length===0){d(),console.log(` ${D.default.dim("No mailboxes.")}`),d(),I("Create one:","domani email create hello@example.com"),d();return}d(),C("Mailboxes");let o=r.map(a=>[D.default.cyan(a.address),String(a.message_count),a.webhook_url?$.url(a.webhook_url):D.default.dim("-"),D.default.dim(new Date(a.created_at).toLocaleDateString())]);se(["Address","Messages","Webhook","Created"],o,[32,10,36,14]),d()}async function fd(e){let t=await Xe(e);if(e.dryRun)return B("email_create_mailbox",{domain:t,slug:e.slug,workspace_id:e.workspace},e.json,e.fields);let i=e.slug;if(!i&&!e.json){let m=await Ae({message:`Email handle for @${t}:`,placeholder:"hello"});le(m)&&process.exit(0),i=m}i||u("Slug required",{hint:`Usage: domani email create hello@${t}`,code:"validation_error",json:e.json,fields:e.fields});let s=`${i}@${t}`,n=S(!e.json);n.start("Creating mailbox");let r=await x("/api/emails",{method:"POST",body:JSON.stringify({address:s,workspace_id:e.workspace})}),o=await r.json();if(r.status===202&&!e.json){n.stop("");let m=o.txt_record,f=o.email_records||[],g=[{type:"TXT",name:m?.name||"@",value:m?.value||"",note:"ownership proof"},...f];d(),console.log(" Add these records at your DNS provider:"),d();for(let j of g){let O=j.priority!==void 0?` ${D.default.dim(`priority: ${j.priority}`)}`:"",R=j.note?` ${D.default.dim(`(${j.note})`)}`:"";console.log(` ${D.default.yellow(j.type)} ${D.default.bold(j.name)}${O}${R}`),console.log(` ${D.default.dim("\u2192")} ${D.default.cyan(j.value)}`),d()}ze("DNS propagation typically takes 5\u201330 minutes. Checking automatically..."),d();let b=g.map(j=>({cells:[D.default.yellow(j.type),j.name,j.note?D.default.dim(`(${j.note})`):""],status:"pending"})),v=Dt(["Type","Name",""],b,[6,24,16]);v.start();let w=0;for(;r.status===202&&w<60;)await Pt(15e3),w++,r=await x("/api/emails",{method:"POST",body:JSON.stringify({address:s,workspace_id:e.workspace})}),o=await r.json(),r.status!==202&&!r.ok&&(v.stop(),u(o.error||o.message,{hint:o.hint,status:r.status,json:e.json,fields:e.fields}));r.status===202&&(v.stop(),u("TXT record not detected after 15 minutes.",{hint:`Check the record is set, then retry: domani email create ${s}`,code:"timeout",json:e.json,fields:e.fields})),v.markDone(0);let h=j=>`${j.type}:${j.name}`,_=new Map;g.slice(1).forEach((j,O)=>_.set(h(j),O+1));for(let j=0;j<60;j++){await Pt(15e3);let O=await x(`/api/domains/${encodeURIComponent(t)}/email/status`),R=await O.json();if(O.ok&&R.records){for(let M of R.records)if(M.status==="verified"||M.status==="created"){let V=_.get(h(M));V!==void 0&&v.markDone(V)}}if(O.ok&&R.verified)break}v.stop(),d()}if(r.ok||(n.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:e.json,fields:e.fields})),n.stop(`${y.success} ${D.default.cyan(o.address)} created`),e.json){k(o,e.fields);return}let a=await x(`/api/domains/${encodeURIComponent(t)}/email/status`),l=await a.json();d(),a.ok&&l.verified?(I("Read inbox:",`domani email inbox ${o.address}`),I("Web inbox:",`${Qt}/inbox?address=${encodeURIComponent(o.address)}`)):(I("Check propagation:",`domani email status --domain ${t}`),I("Web inbox:",`${Qt}/inbox?address=${encodeURIComponent(o.address)}`)),d()}async function pd(e){let t=await Xe(e);if(e.slug||u("Slug required",{hint:"Usage: domani email delete hello@example.com",code:"validation_error",json:e.json,fields:e.fields}),e.dryRun)return B("email_delete_mailbox",{domain:t,address:`${e.slug}@${t}`},e.json,e.fields);let i=S(!e.json);i.start(`Deleting ${e.slug}@${t}`);let s=encodeURIComponent(`${e.slug}@${t}`),n=await x(`/api/emails/${s}`,{method:"DELETE",body:JSON.stringify({confirm:!0})}),r=await n.json();if(n.ok||(i.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:e.json,fields:e.fields})),i.stop(`${y.success} Mailbox deleted`),e.json){k(r,e.fields);return}console.log(` ${D.default.dim(`${r.address} and all messages deleted.`)}`),d()}async function hd(e){let t=await Xe(e);if(e.slug||u("Slug required",{hint:'Usage: domani email send hello@example.com --to user@test.com --subject "Hi" --body "Hello"',code:"validation_error",json:e.json,fields:e.fields}),e.to||u("Recipient required",{hint:"Usage: domani email send hello@example.com --to user@test.com",code:"validation_error",json:e.json,fields:e.fields}),e.dryRun)return B("email_send",{from:`${e.slug}@${t}`,to:e.to,subject:e.subject},e.json,e.fields);let i=S(!e.json);i.start(`Sending from ${e.slug}@${t}`);let s={to:Gi(Bi(e.to))},n=Gi(Bi(e.cc)),r=Gi(Bi(e.bcc));n&&(s.cc=n),r&&(s.bcc=r),e.subject&&(s.subject=e.subject),e.text&&(s.text=e.text),e.inReplyTo&&(s.in_reply_to=e.inReplyTo),e.references&&(s.references=e.references);let o=encodeURIComponent(`${e.slug}@${t}`),a=await x(`/api/emails/${o}/send`,{method:"POST",body:JSON.stringify(s)}),l=await a.json();if(!a.ok){i.stop("Failed");let f=l.code==="MONTHLY_LIMIT_EXCEEDED"?`Run ${D.default.cyan("domani upgrade")} to switch to Pro (10,000 emails/month).`:l.hint;u(l.error||l.message,{hint:f,status:a.status,json:e.json,fields:e.fields})}let m=Array.isArray(l.to)?l.to.join(", "):l.to;if(i.stop(`${y.success} Sent to ${D.default.cyan(m)}`),e.json){k(l,e.fields);return}}async function gd(e){let t=await Xe(e);e.slug||u("Slug required",{hint:"Usage: domani email inbox hello@example.com [--direction in|out] [--limit 20]",code:"validation_error",json:e.json,fields:e.fields});let i=new URLSearchParams;e.direction&&i.set("direction",e.direction),e.folder&&i.set("folder",e.folder),e.view&&i.set("view",e.view),e.limit&&i.set("limit",e.limit);let s=i.toString()?`?${i}`:"",n=S(!e.json);n.start(`Loading messages for ${e.slug}@${t}`);let r=encodeURIComponent(`${e.slug}@${t}`),o=await x(`/api/emails/${r}/messages${s}`),a=await o.json();o.ok||(n.stop("Failed"),u(a.error||a.message,{hint:a.hint,status:o.status,json:e.json,fields:e.fields}));let l=a.messages||[];if(e.json){n.stop(`${y.success} ${l.length} message(s)`),k(a,e.fields);return}if(l.length===0){n.stop(`${D.default.dim("No messages")}`);return}let m=l.length>1?"s":"";n.stop(`${y.success} ${D.default.cyan(`${e.slug}@${t}`)} ${D.default.dim("\xB7 "+l.length+" message"+m)}`);for(let f of l){let g=f.direction==="in"?D.default.green("in "):D.default.dim("out"),b=f.direction==="in"?f.from:f.to,v=f.subject||"(no subject)",w=D.default.dim(new Date(f.created_at).toLocaleString()),h=v;if(f.text){let _=f.text.replace(/\s+/g," ").trim(),j=_.length>60?_.slice(0,60)+"\u2026":_;h=`${v} ${D.default.dim("- "+j)}`}console.log(` ${g} ${b.padEnd(30)} ${h} ${w}`)}a.next_cursor&&console.log(` ${D.default.dim("\u2026 more available, use --limit to paginate")}`)}async function bd(e){let t=await Xe(e);e.slug||u("Slug required",{hint:"Usage: domani email folders hello@example.com",code:"validation_error",json:e.json,fields:e.fields});let i=encodeURIComponent(`${e.slug}@${t}`),s=await x(`/api/emails/${i}/folders`),n=await s.json();if(s.ok||u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields}),e.json)return k(n,e.fields);C(`Folders for ${e.slug}@${t}`);for(let r of n.folders||[])c(r.id,`${r.total} total, ${r.unread} unread`);for(let r of n.views||[])c(r.id,`${r.total} total, ${r.unread} unread`)}async function yd(e,t){let i=await Xe(t);t.slug||u("Slug required",{hint:`Usage: domani email ${e} hello@example.com --message-ids id1,id2`,code:"validation_error",json:t.json,fields:t.fields});let s=(t.messageIds||"").split(",").map(f=>f.trim()).filter(Boolean);s.length||u("Message IDs required",{hint:"Pass --message-ids id1,id2",code:"validation_error",json:t.json,fields:t.fields});let n={message_ids:s,idempotency_key:t.idempotencyKey||(0,eo.randomUUID)()};if((e==="archive"||e==="trash")&&Object.assign(n,{action:"move",destination:e==="archive"?"archive":"trash"}),e==="restore"&&(n.action="restore"),(e==="read"||e==="unread")&&Object.assign(n,{action:"mark_read",read:e==="read"}),(e==="star"||e==="unstar")&&Object.assign(n,{action:"star",starred:e==="star"}),t.dryRun)return B("email_messages_action",{address:`${t.slug}@${i}`,...n},t.json,t.fields);let r=encodeURIComponent(`${t.slug}@${i}`),o=await x(`/api/emails/${r}/messages/actions`,{method:"POST",body:JSON.stringify(n)}),a=await o.json();if(!o.ok&&o.status!==207&&u(a.error||a.message,{hint:a.hint,status:o.status,json:t.json,fields:t.fields}),t.json)return k(a,t.fields);let l=(a.results||[]).filter(f=>f.ok).length,m=(a.results||[]).length-l;console.log(`${y.success} ${l} updated${m?D.default.yellow(`, ${m} failed`):""}`),a.operation_id&&(c("Operation",a.operation_id),c("Idempotency key",a.idempotency_key),a.idempotent_replay&&c("Receipt","replayed (no duplicate mutation)"))}async function $d(e){let t=await Xe(e);e.slug||u("Slug required",{hint:"Usage: domani email webhook hello@example.com --url https://...",code:"validation_error",json:e.json,fields:e.fields});let i=`${e.slug}@${t}`,s=encodeURIComponent(i),n;try{n=Tt(e)}catch(o){u(o instanceof Error?o.message:"Invalid webhook headers",{hint:"Set the named environment variable, or remove the conflicting header option.",code:"validation_error",json:e.json,fields:e.fields})}if(!e.url&&n!==void 0&&u("--url is required when changing webhook auth headers",{hint:"Pass the existing webhook URL with --authorization-env, --api-key-env, or --clear-headers.",code:"validation_error",json:e.json,fields:e.fields}),e.dryRun)return B("email_webhook",{address:i,webhook_url:e.url||null,...n!==void 0?{header_names:Nt(n)}:{}},e.json,e.fields);let r=S(!e.json);if(e.url){r.start(`Setting webhook for ${i}`);let o=await x(`/api/emails/${s}/webhook`,{method:"PUT",body:JSON.stringify({url:e.url,...n!==void 0?{headers:n}:{}})}),a=await o.json();if(o.ok||(r.stop("Failed"),u(a.error||a.message,{hint:a.hint,status:o.status,json:e.json,fields:e.fields})),r.stop(`${y.success} Webhook set`),e.json){k(a,e.fields);return}C(`Mailbox ${a.address}`),c("Webhook",$.url(a.webhook_url)),c("Auth headers",a.header_names?.join(", ")||D.default.dim("none")),c("Signing secret",D.default.dim(a.signing_secret)),d()}else{r.start(`Removing webhook for ${i}`);let o=await x(`/api/emails/${s}/webhook`,{method:"DELETE"}),a=await o.json();if(o.ok||(r.stop("Failed"),u(a.error||a.message,{hint:a.hint,status:o.status,json:e.json,fields:e.fields})),r.stop(`${y.success} Webhook removed`),e.json){k(a,e.fields);return}C(`Mailbox ${a.address}`),c("Webhook",D.default.dim("none")),d()}}async function vd(e){let t=await Xe(e);e.slug||u("Slug required",{hint:"Usage: domani email webhook-test hello@example.com",code:"validation_error",json:e.json,fields:e.fields});let i=`${e.slug}@${t}`;if(e.dryRun)return B("email_webhook_test",{address:i},e.json,e.fields);let s=S(!e.json);s.start(`Testing webhook for ${i}`);let n=await x(`/api/emails/${encodeURIComponent(i)}/webhook/test`,{method:"POST"}),r=await n.json();if((!n.ok||!r.success)&&(s.stop("Failed"),u(r.error||r.message||"Webhook test failed",{hint:r.hint||"Check the endpoint and sender authentication, then retry.",status:n.status,json:e.json,fields:e.fields})),s.stop(`${y.success} Test delivered`),e.json)return k(r,e.fields);C(`Mailbox ${i}`),c("Delivery",D.default.green("successful")),typeof r.status=="number"&&c("Endpoint",`HTTP ${r.status}`),d()}async function wd(e){let t=await Xe(e);if(e.slug||u("Slug required",{hint:"Usage: domani email forward hello@example.com --forward-to me@gmail.com",code:"validation_error",json:e.json,fields:e.fields}),e.dryRun)return B("email_forward",{address:`${e.slug}@${t}`,forward_to:e.forwardTo||null},e.json,e.fields);let i=S(!e.json),s=e.forwardTo||null;i.start(`Updating forward for ${e.slug}@${t}`);let n=encodeURIComponent(`${e.slug}@${t}`),r=await x(`/api/emails/${n}`,{method:"PATCH",body:JSON.stringify({forward_to:s})}),o=await r.json();if(r.ok||(i.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:e.json,fields:e.fields})),i.stop(`${y.success} Forward ${s?"set":"removed"}`),e.json){k(o,e.fields);return}C(`Mailbox ${o.address}`),c("Forward to",o.forward_to?D.default.cyan(o.forward_to):D.default.dim("none")),d()}async function Zr(e,t,i){let s=S(!t);s.start(`Checking email health for ${$.domain(e)}`);let n=await x(`/api/domains/${encodeURIComponent(e)}/email/check`),r=await n.json();if(n.ok||(s.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:t,fields:i})),s.stop("Email health checked"),t){k(r,i);return}if(C(`Email Health ${$.domain(r.domain)}`),r.provider?c("Provider",D.default.cyan(cn(r.provider))):c("Provider",D.default.dim("unknown")),r.mx.configured?c("MX",`${y.success} ${D.default.green("propagated")} ${D.default.dim(`(${r.mx.records.length} record${r.mx.records.length!==1?"s":""})`)}`):c("MX",`${y.error} ${D.default.red("not configured")}`),r.spf.configured?c("SPF",`${y.success} ${D.default.green(r.spf.value)}`):c("SPF",`${y.error} ${D.default.red("missing")}`),r.dmarc.configured){let o=r.dmarc.value.length>50?r.dmarc.value.slice(0,50)+"...":r.dmarc.value;c("DMARC",`${y.success} ${D.default.green(o)}`)}else c("DMARC",`${y.error} ${D.default.red("missing")}`);r.dkim.configured?c("DKIM",`${y.success} ${D.default.green("found")} ${D.default.dim(`(${r.dkim.selectors.join(", ")})`)}`):c("DKIM",`${y.warning} ${D.default.yellow("not found")}`),d(),r.mx.configured?(!r.spf.configured||!r.dmarc.configured)&&(ze("SPF and DMARC protect against email spoofing. Re-run email setup to add them."),d()):(I("Set up email:",`domani email ${e} google`),d())}async function Qr(e,t,i,s){return t?io(e,t,i,s):to(e,i,s)}async function to(e,t,i){let s=S(!t);s.start("Loading email providers");let n=await x(`/api/domains/${encodeURIComponent(e)}/connect`),r=await n.json();n.ok||(s.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:t,fields:i})),s.stop("Providers loaded");let o=r.providers?.email||[];o.length===0&&u("No email providers available",{code:"not_found",json:t,fields:i});let a=await Qe({message:"Choose an email provider",options:o.map(l=>({value:l.name,label:cn(l.name)}))});return le(a)&&process.exit(0),io(e,a,t,i)}async function io(e,t,i,s){if(i){let m=await x(`/api/domains/${encodeURIComponent(e)}/connect`,{method:"POST",body:JSON.stringify({target:t})}),f=await m.json();m.ok||u(f.error||f.message,{hint:f.hint,status:m.status,json:i,fields:s}),k(f,s);return}let n=await x(`/api/domains/${encodeURIComponent(e)}/connect?provider=${encodeURIComponent(t)}`);if(!n.ok){let m=await n.json();u(m.error||m.message,{hint:m.hint,status:n.status,json:i,fields:s})}let r=await n.json(),o=r.preview?.records??[],a=r.preview?.provider??t,l=cn(a);if(C(`Email ${$.domain(e)}`),c("Provider",D.default.cyan(l)),o.length){d(),console.log(` ${D.default.bold("DNS Records")}`);let m=[8,24,40],f=Dt(["Type","Name","Value"],o.map(j=>({cells:Ql(j),status:"pending"})),m);f.start();let g=await x(`/api/domains/${encodeURIComponent(e)}/connect`,{method:"POST",body:JSON.stringify({target:t})}),b=await g.json();g.ok||(f.stop(),d(),u(b.error||b.message,{hint:b.hint,status:g.status,json:i,fields:s}));let v=b.records||[];for(let j=0;j<o.length;j++)v.find(R=>R.record.type===o[j].type&&R.record.name===o[j].name&&R.record.value===o[j].value)?.status==="already_set"||await Pt(60),f.markDone(j);await Pt(80),f.stop();let w=v.filter(j=>j.status==="created"||j.status==="updated").length,h=v.filter(j=>j.status==="already_set").length,_;h===v.length?_=`All ${h} records already set`:h>0?_=`${w} created, ${h} already set`:_=`${w} DNS records set`,d(),console.log(` ${y.success} ${D.default.green(`Email configured - ${_}`)}`)}else{let m=S(!0);m.start("Setting DNS records");let f=await x(`/api/domains/${encodeURIComponent(e)}/connect`,{method:"POST",body:JSON.stringify({target:t})}),g=await f.json();f.ok||(m.stop("Failed"),u(g.error||g.message,{hint:g.hint,status:f.status,json:i,fields:s})),m.stop(`${y.success} Email configured via ${D.default.cyan(l)}`)}d(),I("Verify propagation:",`domani email ${e} --check`),d()}var D,eo,Xl,Zl,mn=Ie(()=>{"use strict";X();ei();D=U(L(),1);De();W();he();Ye();eo=require("node:crypto");Ji();Xl=["setup","status","remove","list","create","delete","send","inbox","folders","archive","trash","restore","read","unread","star","unstar","webhook","forward","check","connect","work","triage","notes","note","activity","changes","coordination","presence","release-presence"],Zl={"google-workspace":"Google Workspace",fastmail:"Fastmail",proton:"Proton Mail"}});var no={};Mt(no,{dns:()=>pn});async function pn(e,t,i,s,n,r){e||(e=await fe()),K(e,r);let o=r?.json??!1,a=r?.type||i,l=r?.name||s,m=r?.value||n;if(!t||t==="get"){let f=S(!o);f.start(`Loading DNS for ${$.domain(e)}`);let g=await x(`/api/domains/${encodeURIComponent(e)}/dns`),b=await g.json();if(g.ok||(f.stop("Failed"),u(b.error||b.message,{hint:b.hint,status:g.status,json:o,fields:r?.fields})),f.stop(`${b.records.length} record(s)`),o){k(b,r?.fields);return}if(b.records.length===0){d(),console.log(` ${xe.default.dim(`No DNS records for ${e}`)}`),d(),I("Auto-configure DNS:",`domani connect ${e}`),d();return}let v=[8,24,40,8];C(`DNS ${$.domain(e)}`,v.reduce((h,_)=>h+_,0)+v.length-1);let w=b.records.map(h=>{let _=h.priority?xe.default.dim(` pri=${h.priority}`):"";return[xe.default.yellow(h.type),h.name,xe.default.cyan(h.value)+_,xe.default.dim(String(h.ttl))]});se(["Type","Name","Value","TTL"],w,v),d();return}if(t==="set"){if((!a||!l||!m)&&u("Missing arguments for dns set",{hint:"Usage: domani dns <domain> set --type A --name www --value 1.2.3.4",code:"validation_error",json:o,fields:r?.fields}),r?.dryRun)return B("dns_set",{domain:e,record:{type:a.toUpperCase(),name:l,value:m,ttl:3600}},o,r?.fields);let f=S(!o);f.start(`Setting ${xe.default.yellow(a.toUpperCase())} record`);let g=await x(`/api/domains/${encodeURIComponent(e)}/dns`),b=await g.json(),w=(g.ok?b.records:[]).filter(j=>!(j.type===a.toUpperCase()&&j.name===l));w.push({type:a.toUpperCase(),name:l,value:m,ttl:3600});let h=await x(`/api/domains/${encodeURIComponent(e)}/dns`,{method:"PUT",body:JSON.stringify({records:w})}),_=await h.json();h.ok||(f.stop("Failed"),u(_.error||_.message,{hint:_.hint,status:h.status,json:o,fields:r?.fields})),f.stop(`${y.success} ${xe.default.yellow(a.toUpperCase())} ${l} ${y.arrow} ${xe.default.cyan(m)}`),o?k(_,r?.fields):(d(),I("Check propagation:",`domani status ${e}`),d());return}if(t==="delete"){if((!a||!l)&&u("Missing arguments for dns delete",{hint:"Usage: domani dns <domain> delete --type A --name www",code:"validation_error",json:o,fields:r?.fields}),r?.dryRun)return B("dns_delete",{domain:e,record:{type:a.toUpperCase(),name:l}},o,r?.fields);let f=S(!o);f.start(`Deleting ${xe.default.yellow(a.toUpperCase())} ${l}`);let g=await x(`/api/domains/${encodeURIComponent(e)}/dns?type=${encodeURIComponent(a.toUpperCase())}&name=${encodeURIComponent(l)}`,{method:"DELETE"}),b=await g.json();g.ok||(f.stop("Failed"),u(b.error||b.message,{hint:b.hint,status:g.status,json:o,fields:r?.fields})),f.stop(`${y.success} Deleted ${xe.default.yellow(a.toUpperCase())} ${l}`),o?k(b,r?.fields):(d(),I("Check propagation:",`domani status ${e}`),d());return}if(t==="snapshot"){if(r?.dryRun)return B("dns_snapshot",{domain:e},o,r?.fields);let f=S(!o);f.start(`Capturing DNS snapshot for ${$.domain(e)}`);let g=await x(`/api/domains/${encodeURIComponent(e)}/dns/snapshot`,{method:"POST"}),b=await g.json();g.ok||(f.stop("Failed"),u(b.error||b.message,{hint:b.hint,status:g.status,json:o,fields:r?.fields}));let v=b.records?.length??0;if(f.stop(`${y.success} Captured ${v} record(s)`),o){k(b,r?.fields);return}let w=`${e}.dns.json`,h=(0,fn.resolve)(process.cwd(),w);(0,Ki.writeFileSync)(h,JSON.stringify(b,null,2)+`
179
- `),C("DNS Snapshot"),c("Domain",$.domain(b.domain)),c("Records",String(v)),c("Subdomains",String(b.subdomains?.length??0)),c("Sources",(b.sources||[]).join(", ")||"none"),c("Captured",b.capturedAt||b.captured_at||"now"),c("Saved to",xe.default.cyan(w)),d(),I("Restore from this snapshot:",`domani dns ${e} restore --file ${w}`),d();return}if(t==="restore"){if(r?.dryRun)return B("dns_restore",{domain:e,source:r?.file||"server_backup"},o,r?.fields);let f=S(!o),g;if(r?.file){let w=(0,fn.resolve)(process.cwd(),r.file);w.startsWith(process.cwd())||u("File path must be within the current directory",{hint:`Got: ${r.file}`,code:"validation_error",json:o,fields:r?.fields});try{let h=(0,Ki.readFileSync)(w,"utf-8"),_=JSON.parse(h);g=JSON.stringify({snapshot:_}),f.start(`Restoring DNS for ${$.domain(e)} from ${xe.default.cyan(r.file)}`)}catch(h){u(`Failed to read snapshot file: ${h instanceof Error?h.message:"unknown"}`,{hint:`Make sure ${r.file} exists and contains valid JSON.`,code:"validation_error",json:o,fields:r?.fields})}}else f.start(`Restoring DNS for ${$.domain(e)} from server backup`);let b=await x(`/api/domains/${encodeURIComponent(e)}/dns/restore`,{method:"POST",...g?{body:g}:{}}),v=await b.json();if(b.ok||(f.stop("Failed"),u(v.error||v.message,{hint:v.hint,status:b.status,json:o,fields:r?.fields})),f.stop(`${y.success} Restored DNS`),o){k(v,r?.fields);return}if(C("DNS Restored"),c("Domain",$.domain(v.domain)),c("Applied",xe.default.green(String(v.applied??0))),c("Skipped",xe.default.dim(String(v.skipped??0))),v.errors?.length>0){c("Errors",xe.default.red(String(v.errors.length)));for(let w of v.errors)console.log(` ${xe.default.red("\u2022")} ${w}`)}d(),I("Verify DNS records:",`domani dns ${e}`),d();return}u(`Unknown action: ${t}`,{hint:"Use 'get', 'set', 'delete', 'snapshot', or 'restore'.",code:"validation_error",json:o,fields:r?.fields})}var xe,Ki,fn,hn=Ie(()=>{"use strict";X();xe=U(L(),1);W();he();Ye();Ki=require("node:fs"),fn=require("node:path")});var ro={};Mt(ro,{status:()=>gn});function kd(e){return[et.default.yellow(e.type),e.name,et.default.cyan(e.value)+(e.priority?et.default.dim(` pri=${e.priority}`):"")]}function _d(e){if(C(`Status ${$.domain(e.domain)}`),e.expires){let t=new Date(e.expires).toLocaleDateString(),i=e.days_until_expiry,s=i!=null&&i<30?et.default.red:i!=null&&i<90?et.default.yellow:et.default.green;c("Expires",`${t} ${et.default.dim("(")}${s(`${i} days`)}${et.default.dim(")")}`)}}async function gn(e,t){if(e||(e=await fe()),K(e,t),t.json){let g=await x(`/api/domains/${encodeURIComponent(e)}/status`),b=await g.json();g.ok||u(b.error||b.message,{hint:b.hint,status:g.status,json:t.json,fields:t.fields}),k(b,t.fields);return}let i=S(!0);i.start(`Checking ${$.domain(e)}`);let s;try{s=await x(`/api/domains/${encodeURIComponent(e)}/status`,{headers:{Accept:"text/event-stream"},signal:AbortSignal.timeout(t.timeout?parseInt(t.timeout,10)*1e3:3e4)})}catch{i.stop("Failed"),u("Request timed out",{hint:"The status check took too long. Try again.",code:"timeout",json:t.json,fields:t.fields})}if(!s.ok){i.stop("Failed");try{let g=await s.json();u(g.error||g.message,{hint:g.hint,status:s.status,json:t.json,fields:t.fields})}catch{u(`Server error (${s.status})`,{status:s.status,json:t.json,fields:t.fields})}}let n=s.body;n||(i.stop("Failed"),u("Empty response"));let r=new TextDecoder,o="",a=null,l=[],m=!1,f="";try{for await(let g of n){o+=r.decode(g,{stream:!0});let b=o.split(`
180
- `);o=b.pop()??"";for(let v of b)if(v.startsWith("event: "))f=v.slice(7);else if(v.startsWith("data: ")){let w=JSON.parse(v.slice(6));if(f==="info"&&(i.stop("Status retrieved"),m=!0,_d(w)),f==="records")if(l=w,l.length>0){d(),console.log(` ${et.default.bold("DNS Records")}`);let h=[8,10,34];a=Dt(["Type","Name","Value"],l.map(_=>({cells:kd(_),status:"pending"})),h),a.start()}else d(),c("DNS",et.default.dim("no records")),I("Auto-configure DNS:",`domani connect ${e}`);if(f==="propagation"&&a){let{index:h,propagated:_}=w,j=_?y.success:`${y.warning}`;a.markDone(h,j)}f==="done"&&a&&a.stop(),f==="error"&&(m||i.stop("Failed"),a&&a.stop(),u(w.message||"Status check failed"))}}}catch{m||i.stop("Failed"),a&&a.stop(),u("Connection lost",{hint:"The status check was interrupted. Try again.",code:"connection_lost",json:t.json,fields:t.fields})}m||i.stop("Done"),d()}var et,bn=Ie(()=>{"use strict";X();et=U(L(),1);W();he();Ye()});var di={};Mt(di,{buy:()=>$n});async function yn(e){let t=await Qe({message:`What's next for ${Te.default.cyan(e)}?`,options:[{value:"connect",label:"Connect to a service",hint:"domani connect"},{value:"email",label:"Set up email",hint:"domani email setup"},{value:"dns",label:"Configure DNS",hint:"domani dns"},{value:"status",label:"Check status & DNS propagation",hint:"domani status"},{value:"done",label:"Done"}]});if(le(t)||t==="done"){d();return}if(d(),t==="connect"){let{connect:i}=await Promise.resolve().then(()=>(dn(),Yr));await i(e,void 0,{})}else if(t==="email"){let i=await Ae({message:`Mailbox name for ${Te.default.cyan(e)}`,placeholder:"e.g. hey, hello, contact"});if(le(i)||!i){d();return}d();let{email:s}=await Promise.resolve().then(()=>(mn(),so));await s("create",void 0,{domain:e,slug:i})}else if(t==="dns"){let{dns:i}=await Promise.resolve().then(()=>(hn(),no));await i(e)}else if(t==="status"){let{status:i}=await Promise.resolve().then(()=>(bn(),ro));await i(e,{})}}async function jd(e,t){K(e,t);let i;if(t.preChecked)i={available:!0,...t.preChecked};else{let f=S(!t.json);f.start(`Checking ${$.domain(e)}`);let g=await x(`/api/domains/search?q=${encodeURIComponent(e)}`);i=await g.json(),g.ok||(f.stop("Search failed"),u(i.error,{hint:i.hint,status:g.status,json:t.json,fields:t.fields})),i.available||(f.stop(`${y.error} ${$.domain(e)} is not available`),u(`${e} is not available`,{code:"not_available",json:t.json,fields:t.fields})),f.stop(`${y.success} ${$.domain(e)} ${y.dot} available ${y.dot} ${$.price(i.price)}/yr`)}if(t.dryRun)return B("buy",{domain:e,available:!0,price:i.price,currency:i.currency||"USD"},t.json,t.fields);if(!Et(t)){let f=await Ke({message:`Purchase ${Te.default.bold(e)} for ${$.price(i.price)}/yr?`});if(!f||typeof f=="symbol"){console.log(` ${Te.default.dim("Cancelled.")}`);return}}let s=S(!t.json);s.start("Purchasing");let n=await x("/api/domains/buy",{method:"POST",headers:{Accept:"text/event-stream"},body:JSON.stringify({domain:e})});if(!n.ok||!n.body){s.stop("Purchase failed");let f=await n.json().catch(()=>({}));u(f.error||f.message,{hint:f.hint,fixUrl:f.setup_url||f.payment_options?.card?.setup_url,status:n.status,json:t.json,fields:t.fields})}let r={},o=new TextDecoder,a="",l="";for await(let f of n.body){a+=o.decode(f,{stream:!0});let g=a.split(`
181
- `);a=g.pop()??"";for(let b of g)if(b.startsWith("event: "))l=b.slice(7).trim();else if(b.startsWith("data: ")){let v=JSON.parse(b.slice(6));l==="checking"?s.message(`Checking ${$.domain(v.domain)}`):l==="payment"?s.message(`Charging ${$.price(v.total)}`):l==="registering"?s.message(`Registering ${$.domain(v.domain)}`):l==="registered"?r=v:l==="error"&&(s.stop("Purchase failed"),u(v.error,{hint:v.hint,fixUrl:v.setup_url,status:n.status,json:t.json,fields:t.fields}))}}let m=r.expires?Te.default.dim(` \xB7 expires ${new Date(r.expires).toLocaleDateString()}`):"";if(s.stop(`${y.success} ${$.domain(r.domain)} is yours!${m}`),t.json){k(r,t.fields);return}je?await yn(r.domain):(I("Connect to a service:",`domani connect ${r.domain}`),I("Set up email:",`domani email setup ${r.domain}`),I("Configure DNS:",`domani dns ${r.domain}`),d())}async function xd(e,t){Kr(e,t);let i=!!t.json,s=S(!i);s.start(`Checking ${e.length} domains`);let n=await Promise.all(e.map(async h=>{try{let _=await x(`/api/domains/search?q=${encodeURIComponent(h)}`),j=await _.json();return{domain:h,available:_.ok&&j.available,price:j.price}}catch{return{domain:h,available:!1,price:void 0}}})),r=n.filter(h=>h.available),o=n.filter(h=>!h.available);r.length===0&&(s.stop(`${y.error} None of the ${e.length} domains are available`),process.exit(1));let a=r.reduce((h,_)=>h+(_.price||0),0);if(s.stop(`${y.success} ${r.length}/${e.length} available ${y.dot} ${$.price(a.toFixed(2))} total`),o.length>0)for(let h of o)console.log(` ${y.error} ${$.domain(h.domain)} ${Te.default.dim("not available")}`);if(t.dryRun)return B("buy_bulk",{domains:r.map(h=>({domain:h.domain,price:h.price})),unavailable:o.map(h=>h.domain),total_price:parseFloat(a.toFixed(2))},t.json,t.fields);if(!Et(t)){let h=await Ke({message:`Purchase ${Te.default.bold(String(r.length))} domain${r.length>1?"s":""} for ${$.price(a.toFixed(2))}?`});if(!h||typeof h=="symbol"){console.log(` ${Te.default.dim("Cancelled.")}`);return}}d();let l=r.map(h=>({cells:[$.domain(h.domain),h.price?`${$.price(h.price.toFixed(2))}/yr`:""],status:"pending"})),m=Dt(["Domain","Price"],l,[30,12],!i);m.start();let g=await(await x("/api/domains/buy",{method:"POST",body:JSON.stringify({domains:r.map(h=>h.domain)})})).json(),b=new Set((g.results||[]).map(h=>h.domain));for(let h=0;h<r.length;h++){let _=r[h].domain.toLowerCase().trim();b.has(_)?m.markDone(h,y.success):m.markDone(h,y.error)}if(m.stop(),i){k(g,t.fields);return}d();let v=g.summary?.succeeded??0,w=g.summary?.failed??0;if(v>0&&console.log(` ${y.success} ${Te.default.green(`${v} domain${v>1?"s":""} registered`)}`),w>0){console.log(` ${y.error} ${Te.default.red(`${w} failed`)}`);for(let h of g.errors||[])console.log(` ${Te.default.dim("\u2500")} ${$.domain(h.domain)}: ${Te.default.dim(h.error)}${h.hint?` ${Te.default.dim(`(${h.hint})`)}`:""}`)}if(d(),v>0&&je){let h=(g.results||[]).filter(_=>_.success).map(_=>_.domain);if(h.length===1)await yn(h[0]);else{let _=await Qe({message:"Set up one of your new domains?",options:[...h.map(j=>({value:j,label:Te.default.cyan(j)})),{value:"done",label:"Done"}]});!le(_)&&_!=="done"?(d(),await yn(_)):d()}}else v>0&&(I("Connect to a service:","domani connect <domain>"),I("Set up email:","domani email setup <domain>"),d())}async function $n(e,t){let i=e.filter(Boolean);if(i.length===0){je||u("Missing required argument: domain(s)",{hint:"Usage: domani buy <domain> [domain2 ...]",code:"missing_argument",json:t.json});let s=await Ae({message:"Domain to purchase",placeholder:"e.g. myapp.dev (space-separated for multiple)"});(le(s)||!s)&&process.exit(0),i=s.split(/\s+/).filter(Boolean)}return i.length===1?jd(i[0],t):xd(i,t)}var Te,Yt=Ie(()=>{"use strict";X();De();Te=U(L(),1);W();he()});var Fn=U(Un(),1),{program:$c,createCommand:vc,createArgument:wc,createOption:kc,CommanderError:_c,InvalidArgumentError:jc,InvalidOptionArgumentError:xc,Command:qn,Argument:Sc,Option:Cc,Help:Oc}=Fn.default;var at=U(L(),1);mt();rn();W();ei();mt();var rt=U(L(),1);W();var Ul=new Set(["cli","mcp","plugin","skill","api"]);function Fl(e){let t=e.scopes?.split(",").map(r=>r.trim()).filter(Boolean),i=!!(t?.length||e.label||e.expiresIn),s=e.surface||"cli";if(!Ul.has(s))throw new RangeError("--surface must be one of: cli, mcp, plugin, skill, api");let n=e.expiresIn===void 0?void 0:Number(e.expiresIn);if(n!==void 0&&(!Number.isInteger(n)||n<3600||n>31536e3))throw new RangeError("--expires-in must be an integer between 3600 and 31536000 seconds");return{delegated:i,body:{...t?.length?{scopes:t}:{},...e.label?{label:e.label}:{},...n!==void 0?{expires_in:n}:{},surface:s,intent:"programmatic_access"}}}async function Lr(e){let t=qe(),i=S(!e.json),s;try{s=Fl(e)}catch(v){u(v instanceof Error?v.message:"Invalid login options",{code:"invalid_expires_in",json:e.json})}let{body:n,delegated:r}=s,o=ut(),a=Me();if(a&&!r){i.start("Checking session");try{let v=await fetch(`${t}/api/me`,{headers:{Authorization:`Bearer ${a}`}});if(v.ok){let w=await v.json();i.stop(`Already logged in as ${rt.default.bold(w.email)}`),e.json&&k({status:"already_logged_in",email:w.email});return}}catch{}i.stop("Session expired, re-authenticating"),d()}i.start("Requesting auth code");let l=await fetch(`${t}/api/auth/cli`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!l.ok){i.stop("Failed to initiate login");try{let v=await l.json();u(v.error||v.message||`Server error (${l.status})`,{hint:v.hint,code:"login_failed",json:e.json})}catch{u(`Could not reach ${t}. Check your connection and try again.`,{code:"network_error",json:e.json})}}let{code:m,auth_url:f,expires_in:g}=await l.json();if(i.stop("Auth code received"),e.json){k({status:"awaiting_approval",code:m,auth_url:f,expires_in:g});return}d(),console.log(` ${rt.default.dim("Verification code:")} ${rt.default.bold(rt.default.cyan(m))}`),e.open!==!1?(console.log(` ${rt.default.dim("Opening browser")} ${y.arrow} ${$.url(f)}`),We(f)):console.log(` ${rt.default.dim("Open this URL to approve:")} ${$.url(f)}`),d(),i.start("Waiting for approval");let b=120;for(let v=0;v<b;v++){await new Promise(_=>setTimeout(_,5e3));let w=await fetch(`${t}/api/auth/cli/poll?code=${m}`);!w.ok&&w.status!==202&&(i.stop("Login failed"),u(`Server error (${w.status})`,{code:"login_failed"}));let h=await w.json();if(h.status==="complete"){Jt({...ut(),token:h.token,email:h.email,api_url:t}),i.stop(`Logged in as ${rt.default.bold(h.email)}`),d(),console.log(` ${rt.default.bold("Get one real result:")}`),I("1. Create your free inbox:","domani email create YOUR_HANDLE@domani.run"),I("2. Connect your webhook:","domani email webhook YOUR_HANDLE@domani.run --url https://YOUR_AGENT/webhook"),I("3. Prove delivery:","domani email webhook-test YOUR_HANDLE@domani.run"),console.log(` ${rt.default.dim("A custom domain can wait until this loop works.")}`),d();return}h.error&&(i.stop("Login failed"),u(h.error||h.message,{hint:h.hint,code:"login_failed"}))}i.stop("Login timed out"),u("No approval received within 10 minutes",{hint:"Run 'domani login' to try again",code:"timeout"})}mt();var on=U(L(),1);W();async function Vr(e){let t=ut();if(!t.token){e.json?k({status:"not_logged_in"}):console.log(` ${on.default.dim("Not logged in.")}`);return}let{api_url:i}=t;Zn(),i&&Jt({api_url:i}),e.json?k({status:"logged_out",email:t.email||null}):console.log(` ${y.success} Logged out${t.email?` ${on.default.dim(`(${t.email})`)}`:""}`)}X();var ai=U(L(),1);W();async function Hr(e){let[t,i]=await Promise.all([x("/api/me"),x("/api/me/activation")]),s=await t.json();t.ok||u(s.error||s.message,{hint:s.hint,status:t.status,json:e.json,fields:e.fields});let n=i.ok?await i.json():null;if(e.json){k({...s,activation:n},e.fields);return}if(C("Account"),c("Email",ai.default.bold(s.email)),c("Payment",s.has_payment_method?`${y.success} ${ai.default.green("active")}`:`${y.error} ${ai.default.dim("none")}`),c("Domains",String(s.domain_count)),c("API tokens",String(s.token_count)),c("Referral code",s.referral_code||ai.default.dim("-")),c("Created",new Date(s.created_at).toLocaleDateString()),n){c("Activation",n.status);let r=n.recommended_actions?.[0];r&&c("Next action",r.label)}d()}X();De();var T=U(L(),1);W();he();var He=10,Xt=200,zi=["com","io","ai","dev","app","co","net","org","xyz","sh","me","cc","tech","run","cloud","so","gg","fm","tv","pro","one","inc","ltd","llc","biz","group","global","ventures","capital","fund","agency","store","shop","market","sale","deals","auction","trade","studio","design","art","space","style","fashion","luxury","brand","media","digital","site","online","live","show","world","zone","land","place","city","town","blog","news","social","chat","link","page","fun","lol","meme","wtf","tools","build","works","work","team","solutions","services","systems","network","software","music","video","photo","photos","game","games","club","stream","film","movie","pizza","coffee","beer","bar","pub","restaurant","cafe","kitchen","food","wine","health","care","clinic","dental","fitness","yoga","bio","life","lifestyle","finance","money","legal","law","cash","academy","university","education","training","courses","science","wiki","guide","us","uk","eu","ca","au","de","fr","it","es","nl","jp","sg","nz","mx","house","homes","realty","estate","garden","nyc","london","berlin","paris","guru","ninja","rocks","fail","party","vip","gold","black","pink","red","events","travel","sport","jobs","careers","consulting","energy","eco","green","support","help","info","new","now","today","day"],Yi=null;async function oo(){if(Yi)return Yi;try{let e=await be("/api/tlds?sort=price&order=asc&limit=1000");if(e.ok){let i=(await e.json()).tlds.map(s=>s.tld);if(i.length>0){let s=new Set(zi),n=new Set(i),r=[...zi.filter(o=>n.has(o)),...i.filter(o=>!s.has(o))];return Yi=r,r}}}catch{}return Yi=zi,zi}async function Sd(e,t,i,s,n){let r=[],o=[],a=He,l=0,m=!0,f=0,g=0,b=!1,v=!1,w=null,h="",_=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],j=0,O=setInterval(()=>{v||!m||(j=(j+1)%_.length,E())},80);function R(){f>0&&(process.stdout.write(`\x1B[${f}A\x1B[0J`),f=0)}function M(){if(m)return[];let q=He+g*He;return r.length>a||s&&q<n.length?["more","new","skip"]:["new","skip"]}function V(){return r.slice(0,a)}function ee(){let q=M();return Math.max(0,V().length+q.length-1)}let P=6;function E(){R();let q=[],Y=V(),Q=!m&&Y.length===0&&o.length>0,G=Q?o.slice(0,P):Y,Oe=G.reduce((de,ae)=>Math.max(de,ae.domain.length),0),Be=M();for(let de=0;de<G.length;de++){let ae=G[de];if(Q)q.push(`${T.default.dim("\u2502")} ${T.default.dim("\u2715")} ${T.default.dim(ae.domain.padEnd(Oe))} ${T.default.dim("taken")}`);else{let we=de===l,lt=we?T.default.green("\u25CF"):T.default.dim("\u25CB"),te=ae.domain.padEnd(Oe),it=we?T.default.bold(T.default.cyan(te)):te,yt=ae.for_sale?T.default.cyan(`$${ae.for_sale.price} (for sale)`):T.default.dim(`$${ae.price}/yr`);q.push(`${T.default.dim("\u2502")} ${lt} ${it} ${yt}`)}}if(Q&&o.length>P&&q.push(`${T.default.dim("\u2502")} ${T.default.dim(`\u2026 and ${o.length-P} more taken`)}`),m){let de=h?T.default.dim(`checking ${h}\u2026`):T.default.dim("searching\u2026");q.push(`${T.default.dim("\u2502")} ${T.default.cyan(_[j])} ${de}`)}else{let de=He+g*He;s&&de>=n.length&&q.push(`${T.default.dim("\u2502")} ${T.default.dim(`All ${Math.min(de,n.length)} TLDs searched`)}`);for(let we=0;we<Be.length;we++){let it=V().length+we===l?T.default.green("\u25CF"):T.default.dim("\u25CB"),yt=Be[we]==="more"?T.default.dim("More \u2192"):Be[we]==="new"?T.default.dim("New search \u2192"):T.default.dim("Skip");q.push(`${T.default.dim("\u2502")} ${it} ${yt}`)}q.push(T.default.dim("\u2514"))}process.stdout.write(q.join(`
177
+ `}}}}).prompt()});function Al(e){return!!(e.json||!xe)}function C(e,t=50){console.log(),console.log(` ${J.default.bold(e)}`),console.log(` ${J.default.dim("\u2500".repeat(t))}`)}function c(e,t,i=2){let s=" ".repeat(i);console.log(`${s}${J.default.dim(e.padEnd(16))} ${t}`)}function d(){console.log()}function ze(e){console.log(` ${J.default.dim(e)}`)}function I(e,t){console.log(` ${J.default.dim(e)} ${J.default.cyan(t)}`)}function Tr(e){return e.split(/(https?:\/\/[^\s]+)/g).map(i=>/^https?:\/\//.test(i)?`\x1B]8;;${i}\x1B\\${J.default.underline(J.default.cyan(i))}\x1B]8;;\x1B\\`:J.default.dim(i)).join("")}function tn(e,t){console.error(` ${y.error} ${J.default.red(e)}`),t&&console.error(` ${Tr(t)}`)}function S(e=!0){return e?oi():El}function Nr(e){return e.replace(Pl,"")}function Wi(e,t){let i=Nr(e).length,s=Math.max(0,t-i);return e+" ".repeat(s)}function se(e,t,i){let s=i||e.map((o,a)=>{let l=t.reduce((m,f)=>Math.max(m,Nr(f[a]||"").length),0);return Math.max(o.length,l)+2}),n=e.map((o,a)=>J.default.dim(o.padEnd(s[a]))).join(" "),r=s.map(o=>J.default.dim("\u2500".repeat(o))).join(" ");console.log(` ${n}`),console.log(` ${r}`);for(let o of t){let a=o.map((l,m)=>Wi(l,s[m])).join(" ");console.log(` ${a}`)}}function Dl(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function en(e){if(Array.isArray(e))return e.map(en);if(e&&typeof e=="object"&&!(e instanceof Date)){let t={};for(let[i,s]of Object.entries(e))t[Dl(i)]=en(s);return t}return e}function k(e,t){let i=en(e);if(!t){console.log(JSON.stringify(i,null,2));return}let s=t.split(",").map(n=>n.trim()).filter(Boolean);if(Array.isArray(i)){let n=i.map(r=>Er(r,s));console.log(JSON.stringify(n,null,2))}else console.log(JSON.stringify(i&&typeof i=="object"?Er(i,s):i,null,2))}function Er(e,t){let i={};for(let s of t)s in e&&(i[s]=e[s]);if(Object.keys(i).length===0){for(let[s,n]of Object.entries(e))if(Array.isArray(n)&&n.length>0&&typeof n[0]=="object"){let r=n.map(o=>{let a={};for(let l of t)l in o&&(a[l]=o[l]);return a});Object.keys(r[0]).length>0&&(i[s]=r)}}return i}function Et(e){return!!(e.yes||Al(e))}function B(e,t,i,s){if(i){k({dry_run:!0,action:e,...t},s);return}console.log(),console.log(` ${J.default.yellow("\u25B8 DRY RUN")} ${J.default.dim("- no changes made")}`),console.log(` ${J.default.dim("Action:")} ${J.default.bold(e)}`);for(let[n,r]of Object.entries(t))r!=null&&(Array.isArray(r)?console.log(` ${J.default.dim(n+":")} ${r.map(String).join(", ")}`):console.log(typeof r=="object"?` ${J.default.dim(n+":")} ${JSON.stringify(r)}`:` ${J.default.dim(n+":")} ${String(r)}`));console.log()}function Nl(e,t,i){return t===401||t===403?"auth_required":t===402||i?"payment_required":t===404?"not_found":t===409?"conflict":t===422?"validation_error":t===429?"rate_limited":/contact/i.test(e)?"contact_required":"error"}function u(e,t){let i=e||`Request failed${t?.status?` (${t.status})`:""}`,s=t?.code||Nl(i,t?.status,t?.fixUrl),n=t?.fixCommand||Tl[s];if(t?.json){let r={error:i,code:s};t.hint&&(r.hint=t.hint),n&&(r.fix_command=n),t.fixUrl&&(r.fix_url=t.fixUrl),k(r,t.fields)}else tn(i,t?.hint),n?console.error(` ${J.default.dim("Or run:")} ${J.default.cyan(n)}`):t?.fixUrl&&console.error(` ${Tr(`Add a payment method at ${t.fixUrl}`)}`);process.exit(1)}function We(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";(0,Dr.execFile)(t,[e])}function Pt(e){return new Promise(t=>setTimeout(t,e))}function Dt(e,t,i,s=!0){let n=process.stdout.isTTY??!1;if(!s)return{start(){},markDone(){},stop(){}};let r=0,o=null,a=2+t.length;function l(){let b=" "+e.map((h,_)=>J.default.dim(h.padEnd(i[_]))).join(" "),w=" "+i.map(h=>J.default.dim("\u2500".repeat(h))).join(" "),v=[b,w];for(let h of t){let _=h.status==="done"?h.icon??y.success:J.default.cyan(Pr[r%Pr.length]),x=h.cells.map((O,R)=>Wi(O,i[R])).join(" ");v.push(` ${_} ${x}`)}return v}let m=!1,f=()=>process.stdout.write("\x1B[?25h");function g(){let b=l();if(m&&n){process.stdout.write(`\x1B[${a}A`);for(let w of b)process.stdout.write(`\x1B[2K${w}
178
+ `)}else{for(let w of b)console.log(w);m=!0}}return{start(){n&&(process.stdout.write("\x1B[?25l"),process.on("exit",f)),g(),n&&(o=setInterval(()=>{r++,g()},80))},markDone(b,w){t[b].status="done",w!==void 0&&(t[b].icon=w),n&&g()},stop(){o&&clearInterval(o);for(let b of t)b.status="done";g(),n&&(process.stdout.write("\x1B[?25h"),process.removeListener("exit",f))}}}var J,Dr,xe,y,$,El,Pl,Tl,Pr,W=Ie(()=>{"use strict";J=U(L(),1),Dr=require("child_process");De();xe=process.stdout.isTTY??!1;y={success:J.default.green("\u2713"),error:J.default.red("\u2717"),warning:J.default.yellow("!"),info:J.default.cyan("\u25CF"),arrow:J.default.dim("\u2192"),dot:J.default.dim("\xB7"),dash:J.default.dim("\u2500")},$={domain:e=>J.default.bold(J.default.white(e)),price:e=>J.default.green(`$${e}`),label:e=>J.default.dim(e),value:e=>J.default.white(e),dim:e=>J.default.dim(e),bold:e=>J.default.bold(e),success:e=>J.default.green(e),error:e=>J.default.red(e),warn:e=>J.default.yellow(e),cyan:e=>J.default.cyan(e),url:e=>`\x1B]8;;${e}\x1B\\${J.default.underline(J.default.cyan(e))}\x1B]8;;\x1B\\`};El={start:()=>{},stop:()=>{},message:()=>{}};Pl=/\x1b\]8;;[^\x1b]*\x1b\\|\x1b\[[0-9;]*m/g;Tl={auth_required:"domani login",payment_required:"domani card add",contact_required:"domani contact set"};Pr=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"]});function Ur(e){return typeof e=="string"&&["pro","agent","fleet","scale","mail_solo","mail_team","mail_business"].includes(e)}function Fr(e){return Ur(e.plan)||Array.isArray(e.workspace_plans)&&e.workspace_plans.some(Ur)}async function qr(){if(nn)return;let e=process.argv.includes("--json")||!ks,t=qe(),i=Me();try{let r=await(await fetch(`${t}/api/me`,{headers:{Authorization:`Bearer ${i}`}})).json();if(Fr(r)){nn=!0;return}}catch{}e&&(console.log(JSON.stringify({error:"Paid plan required",code:"upgrade_required",hint:"Upgrade at https://domani.run/settings",fix_command:"domani upgrade"},null,2)),process.exit(1)),d(),console.log(` ${ye.default.dim("This feature requires a")} ${ye.default.bold("paid plan")} ${ye.default.dim("(including an active Mailzero workspace plan or legacy Pro subscription).")}`),console.log(` ${ye.default.dim("Opening pricing page")} ${y.arrow} ${ye.default.cyan("domani.run/pricing")}`),We(`${t.replace("http://localhost:3000","https://domani.run")}/pricing`),d();let s=S(!0);s.start("Waiting for upgrade...");for(let n=0;n<120;n++){await new Promise(r=>setTimeout(r,5e3));try{let o=await(await fetch(`${t}/api/me`,{headers:{Authorization:`Bearer ${i}`}})).json();if(Fr(o)){nn=!0,s.stop(`${y.success} Paid plan active! Continuing...`),d();return}}catch{}}s.stop("Timed out"),console.error(` ${ye.default.red("\u2717")} No upgrade detected. Visit ${ye.default.cyan("domani.run/settings")} to upgrade.`),process.exit(1)}async function Mr(){if(sn||Me()){sn=!0;return}(process.argv.includes("--json")||!ks)&&(console.log(JSON.stringify({error:"Not logged in",code:"auth_required",hint:"Run 'domani login' or set DOMANI_API_KEY environment variable",fix_command:"domani login"},null,2)),process.exit(1)),d(),console.log(` ${ye.default.dim("You're not logged in.")} Starting authentication...`),d();let t=qe(),i=S(!0);i.start("Requesting auth code");let s;try{s=await fetch(`${t}/api/auth/cli`,{method:"POST",headers:{"Content-Type":"application/json"}})}catch{i.stop("Failed"),console.error(` ${ye.default.red("\u2717")} Could not reach ${t}. Check your connection.`),process.exit(1)}if(!s.ok){i.stop("Failed");let o=`Server error (${s.status})`;try{let a=await s.json();o=a.error||a.message||o}catch{}console.error(` ${ye.default.red("\u2717")} ${o}`),process.exit(1)}let n,r;try{({code:n,auth_url:r}=await s.json())}catch{i.stop("Failed"),console.error(` ${ye.default.red("\u2717")} Invalid response from server.`),process.exit(1)}i.stop(`${y.success} Auth code ready`),d(),console.log(` ${ye.default.dim("Verification code:")} ${ye.default.bold(ye.default.cyan(n))}`),console.log(` ${ye.default.dim("Opening browser")} ${y.arrow} ${$.url(r)}`),We(r),d(),i.start("Waiting for browser approval");for(let o=0;o<120;o++){await new Promise(m=>setTimeout(m,5e3));let a=await fetch(`${t}/api/auth/cli/poll?code=${n}`).catch(()=>null);if(!a||!a.ok&&a.status!==202)continue;let l=await a.json().catch(()=>({}));if(l.status==="complete"){Jt({...ut(),token:l.token,email:l.email,api_url:t}),sn=!0,i.stop(`${y.success} Logged in as ${ye.default.bold(l.email)}`),d();return}}i.stop("Timed out"),console.error(` ${ye.default.red("\u2717")} No approval received. Run ${ye.default.cyan("domani login")} to try again.`),process.exit(1)}var ye,sn,nn,rn=Ie(()=>{"use strict";ye=U(L(),1);mt();W();sn=!1,nn=!1});function Wr(e){return e.json=async()=>{let t=await e.clone().text();try{return JSON.parse(t)}catch{let i=t.trim().slice(0,120);return e.ok?(Object.defineProperty(e,"ok",{value:!1}),{error:`Unexpected non-JSON response (HTTP ${e.status})`,hint:`The server replied but not with JSON${i?` (got: "${i}")`:""}. This is usually transient (deploy or proxy) - retry in a few seconds.`}):{error:`Server error (${e.status})`,hint:"The server returned an unexpected response. Try again later."}}},e}async function j(e,t={},i=!1){let s=Me(),n=`${qe()}${e}`,r=await fetch(n,{...t,headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json","User-Agent":`domani-cli/${ke}`,...t.headers}});if(!i){let o=await r.clone().text();try{if(JSON.parse(o).code==="UPGRADE_REQUIRED")return await qr(),j(e,t,!0)}catch{}}return Wr(r)}async function be(e,t={}){let i=`${qe()}${e}`,s=Me(),n=await fetch(i,{...t,headers:{"Content-Type":"application/json","User-Agent":`domani-cli/${ke}`,...s?{Authorization:`Bearer ${s}`}:{},...t.headers}});return Wr(n)}var X=Ie(()=>{"use strict";mt();rn()});function kt(){return{ok:!0}}function pt(e,t,i){return{ok:!1,error:{message:e,code:t,hint:i}}}function Br(e){return ql.test(e)?pt("Input contains control characters","invalid_input","Remove non-printable characters from the input"):kt()}function Jl(e){return Ml.test(e)?pt("Input contains path traversal","invalid_input","Domain names cannot contain '../' or '..\\'"):kt()}function Bl(e){return Ll.test(e)?pt("Input contains query string or fragment","invalid_input","Remove '?' or '#' from the domain name"):kt()}function Gl(e){return Vl.test(e)?pt("Input contains percent-encoded characters","invalid_input","Use plain text, not URL-encoded values (e.g. 'example.com' not 'example%2Ecom')"):kt()}function Gr(e){if(!e)return pt("Domain name is required","validation_error");if(e.length>Jr)return pt(`Domain name too long (${e.length} chars, max ${Jr})`,"validation_error");for(let t of[Br,Jl,Bl,Gl]){let i=t(e);if(!i.ok)return i}return Wl.test(e)?kt():pt(`Invalid domain name: ${e}`,"validation_error","Domain names can only contain letters, digits, hyphens, and dots")}function Kl(e){if(!e)return pt("TLD is required","validation_error");let t=Br(e);return t.ok?Hl.test(e)?kt():pt(`Invalid TLD: ${e}`,"validation_error","TLDs contain only letters (e.g. 'com', '.dev', 'ai')"):t}function zl(e){for(let t of e){let i=Gr(t);if(!i.ok)return i}return kt()}function Yl(e){for(let t of e){let i=Kl(t);if(!i.ok)return i}return kt()}function K(e,t){let i=Gr(e);i.ok||u(i.error.message,{code:i.error.code,hint:i.error.hint,json:t?.json,fields:t?.fields})}function Kr(e,t){let i=zl(e);i.ok||u(i.error.message,{code:i.error.code,hint:i.error.hint,json:t?.json,fields:t?.fields})}function Hi(e,t){let i=Yl(e);i.ok||u(i.error.message,{code:i.error.code,hint:i.error.hint,json:t?.json,fields:t?.fields})}var ql,Ml,Ll,Vl,Wl,Hl,Jr,he=Ie(()=>{"use strict";W();ql=/[\x00-\x08\x0b\x0c\x0e-\x1f]/,Ml=/\.\.[/\\]/,Ll=/[?#]/,Vl=/%[0-9a-fA-F]{2}/,Wl=/^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?)*\.?$/,Hl=/^\.?[a-zA-Z]{2,63}$/,Jr=253});async function fe(){xe||u("Missing required argument: domain",{hint:"Pass the domain as an argument, e.g. 'domani settings example.com'",code:"missing_argument",json:!0});let e=S(!0);e.start("Loading your domains");let t=await j("/api/domains"),i=await t.json();t.ok||(e.stop("Failed"),tn(i.error,i.hint),process.exit(1));let s=i.domains||[];s.length===0&&(e.stop("No domains"),d(),console.log(` ${an.default.dim("No domains yet.")} Use: ${an.default.cyan("domani buy <domain>")}`),d(),process.exit(0)),e.stop(`${s.length} domain(s)`);let n=await Qe({message:"Which domain?",options:s.map(r=>({value:r.domain,label:r.domain,hint:r.status!=="active"?r.status:void 0}))});return le(n)&&process.exit(0),n}var an,Ye=Ie(()=>{"use strict";X();De();an=U(L(),1);W()});var Yr={};Mt(Yr,{connect:()=>ln});async function ln(e,t,i){e||(e=await fe()),K(e,i);let s;if(t&&!i.provider?t.includes(".")?s=t:i.provider=t:s=t,!s&&!i.provider&&!i.list&&i.dryRun)return B("connect",{domain:e,note:"No provider specified. Pass --provider <name> to connect."},i.json,i.fields);if(!s&&!i.provider&&!i.list){let n=S(!i.json);n.start(`Loading providers for ${$.domain(e)}`);let r=await j(`/api/domains/${encodeURIComponent(e)}/connect`),o=await r.json();if(r.ok||(n.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:i.json,fields:i.fields})),n.stop("Providers loaded"),i.json){k(o,i.fields);return}let a=[];for(let h of["hosting","email"]){let _=o.providers?.[h]||[];for(let x of _)a.push({value:`${h}:${x.name}`,label:x.name,hint:h})}a.length===0&&u("No providers available",{code:"not_found",json:i.json,fields:i.fields});let l=await Qe({message:"Choose a provider",options:a});le(l)&&process.exit(0);let[m,f]=l.split(":"),b=(o.providers?.[m]||[]).find(h=>h.name===f),w;if(b&&b.methods.length>1){let h=await Qe({message:"Choose a method",options:b.methods.map(_=>({value:_.name,label:_.name,hint:_.default?"default":void 0}))});le(h)&&process.exit(0),w=h}let v;if(m==="hosting"&&b?.requires_target){b.notes?.setup&&ze(b.notes.setup);let h=await Ae({message:"Target hostname or IP"});le(h)&&process.exit(0),v=h.trim()}return zr(e,{target:v,provider:f,method:w,dryRun:i.dryRun,json:!1})}if(i.list){let n=S(!i.json);n.start(`Loading providers for ${$.domain(e)}`);let r=await j(`/api/domains/${encodeURIComponent(e)}/connect`),o=await r.json();if(r.ok||(n.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:i.json,fields:i.fields})),n.stop("Providers loaded"),i.json){k(o,i.fields);return}C(`Providers for ${$.domain(o.domain)}`);for(let a of["hosting","email"]){let l=o.providers?.[a];if(l?.length){d(),console.log(` ${ue.default.bold(a.toUpperCase())}`);for(let m of l){let f=m.methods.map(g=>g.default?ue.default.green(`${g.name} (default)`):ue.default.dim(g.name)).join(ue.default.dim(", "));console.log(` ${ue.default.cyan(m.name.padEnd(20))} ${f}`)}}}d();return}return zr(e,i)}async function zr(e,t){let i={};if(t.target&&(i.target=t.target),t.provider&&(i.provider=t.provider),t.method&&(i.method=t.method),t.dryRun)return B("connect",{domain:e,...i},t.json,t.fields);let s=S(!t.json);s.start(`Connecting ${$.domain(e)}`);let n=await j(`/api/domains/${encodeURIComponent(e)}/connect`,{method:"POST",body:JSON.stringify(i)}),r=await n.json();n.ok||(s.stop("Connection failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:t.json,fields:t.fields}));let o=r.status==="manual_setup_required";if(s.stop(o?`${y.success} DNS instructions for ${ue.default.cyan(r.provider)}`:`${y.success} Connected to ${ue.default.cyan(r.provider)}`),t.json){k(r,t.fields);return}if(C(o?`Add these records at your registrar for ${$.domain(r.domain)}`:`Connected ${$.domain(r.domain)}`),c("Provider",ue.default.cyan(r.provider)),c("Method",r.method),r.records?.length){let a=[8,22,40];d(),console.log(` ${ue.default.bold("DNS Records")}`);let l=["Type","Name","Value"].map((f,g)=>ue.default.dim(f.padEnd(a[g]))).join(" "),m=a.map(f=>ue.default.dim("\u2500".repeat(f))).join(" ");console.log(` ${l}`),console.log(` ${m}`);for(let f of r.records){let g=f.record,b=f.status!=="already_set";process.stdout.isTTY&&b&&await Pt(50);let v=[ue.default.yellow(g.type),g.name,ue.default.cyan(g.value)+(g.priority?ue.default.dim(` pri=${g.priority}`):"")].map((x,O)=>Wi(x,a[O])).join(" "),h=f.status==="already_set"?ue.default.dim("\u2713"):f.status==="updated"?ue.default.yellow("\u21BA"):f.status==="pending"?ue.default.yellow("\u2192"):y.success,_=f.status==="already_set"?ue.default.dim(" already set"):f.status==="updated"?ue.default.dim(" updated"):f.status==="pending"?ue.default.dim(" add this"):"";console.log(` ${h} ${v}${_}`)}}d(),r.next_steps?.length?(console.log(` ${ue.default.bold("Next steps")}`),r.next_steps.forEach((a,l)=>{console.log(` ${ue.default.dim(`${l+1}.`)} ${a}`)})):r.hint&&console.log(` ${ue.default.dim(r.hint)}`),r.docs&&console.log(` ${ue.default.dim("Docs:")} ${$.url(r.docs)}`),d()}var ue,dn=Ie(()=>{"use strict";X();ue=U(L(),1);De();W();he();Ye()});function Tt(e,t=process.env){if(e.clearHeaders&&(e.authorizationEnv||e.apiKeyEnv))throw new Error("--clear-headers cannot be combined with header environment options");if(e.clearHeaders)return{};let i={},s=[["Authorization",e.authorizationEnv],["X-API-Key",e.apiKeyEnv]];for(let[n,r]of s){if(!r)continue;let o=t[r];if(!o)throw new Error(`Environment variable ${r} is not set`);i[n]=o}return Object.keys(i).length>0?i:void 0}function Nt(e){return e?Object.keys(e):[]}var Ji=Ie(()=>{"use strict"});var so={};Mt(so,{email:()=>li,parseRecipients:()=>Bi,recipientField:()=>Gi});function Ql(e){return[D.default.yellow(e.type),e.name,D.default.cyan(e.value)+(e.priority?D.default.dim(` pri=${e.priority}`):"")]}function cn(e){return Zl[e]||e}function Bi(e){return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function Gi(e){if(e.length!==0)return e.length===1?e[0]:e}function ed(e,t){if(e&&e.includes("@")){let[i,s]=e.split("@",2);!t.slug&&i&&(t.slug=i),!t.domain&&s&&(t.domain=s)}}async function Xe(e){return e.domain?(K(e.domain,e),e.domain):fe()}async function li(e,t,i){if(e&&e.includes(".")&&!Xl.includes(e))return i.check?Zr(e,!!i.json,i.fields):t?Qr(e,t,!!i.json,i.fields):to(e,!!i.json,i.fields);if(ed(t,i),i.body&&!i.text&&(i.text=i.body),i.title&&!i.subject&&(i.subject=i.title),i.from&&i.from.includes("@")){let[s,n]=i.from.split("@",2);!i.slug&&s&&(i.slug=s),!i.domain&&n&&(i.domain=n)}switch(e){case void 0:return Xr(i);case"list":return Xr(i);case"inbox":return gd(i);case"folders":return bd(i);case"archive":case"trash":case"restore":case"read":case"unread":case"star":case"unstar":return yd(e,i);case"setup":return cd(i);case"status":return ud(i);case"remove":return md(i);case"create":return fd(i);case"delete":return pd(i);case"send":return hd(i);case"webhook":return $d(i);case"webhook-test":return vd(i);case"forward":return wd(i);case"work":return rd(i);case"triage":return od(i);case"note":return ad(i);case"notes":return ld(i);case"activity":return dd(i);case"changes":return nd(i);case"coordination":return td(i);case"presence":return id(i);case"release-presence":return sd(i);case"check":return Zr(i.domain||await fe(),!!i.json,i.fields);case"connect":return Qr(i.domain||await fe(),t||void 0,!!i.json,i.fields);default:u(`Unknown action: ${e}`,{hint:"Actions: list, inbox, folders, archive, trash, restore, read, unread, star, unstar, create, delete, send, forward, webhook, webhook-test, work, triage, notes, note, activity, changes, coordination, presence, release-presence, setup, status, check, connect",code:"validation_error",json:i.json,fields:i.fields})}}function un(e){let t=e.mailboxIds?.split(",").map(i=>i.trim()).filter(Boolean)[0];return(!t||!e.threadKey)&&u("Mailbox ID and thread key required",{hint:"Pass --mailbox-ids mb_1 --thread-key 'jmap:thread_1'",code:"validation_error",json:e.json,fields:e.fields}),{mailboxId:t,threadKey:e.threadKey}}async function td(e){let{mailboxId:t,threadKey:i}=un(e),s=new URLSearchParams({mailbox_id:t,thread_key:i}),n=await j(`/api/email/collaboration/coordination?${s}`),r=await n.json();if(n.ok||u(r.error||"Could not read coordination",{code:r.code||"api_error",json:e.json,fields:e.fields}),e.json)return k(r,e.fields);C("Conversation Coordination"),c("Conversation",r.conversation_id),c("Reply version",String(r.reply_version)),c("Presence",String(r.presence?.length||0)),c("Compose lease",r.compose_lease?.holder?.label||"none")}async function id(e){let{mailboxId:t,threadKey:i}=un(e);e.clientId||u("Client ID required",{hint:"Pass a stable --client-id for this agent process or app installation",code:"validation_error",json:e.json,fields:e.fields});let s=e.mode||"viewing";["viewing","composing"].includes(s)||u("Mode must be viewing or composing",{code:"validation_error",json:e.json,fields:e.fields});let n=await j("/api/email/collaboration/coordination",{method:"PUT",body:JSON.stringify({mailbox_id:t,thread_key:i,client_id:e.clientId,mode:s,acquire_lease:e.acquireLease!==!1})}),r=await n.json();if(n.ok||u(r.error||"Could not heartbeat presence",{code:r.code||"api_error",json:e.json,fields:e.fields}),e.json)return k(r,e.fields);C("Conversation Presence"),c("Mode",s),c("Reply version",String(r.reply_version)),c("Lease ID",r.compose_lease?.lease_id||"none"),c("Expires",r.compose_lease?.expires_at||r.presence?.find(o=>o.client_id===e.clientId)?.expires_at||"unknown")}async function sd(e){let{mailboxId:t,threadKey:i}=un(e);e.clientId||u("Client ID required",{hint:"Pass the same --client-id used for presence",code:"validation_error",json:e.json,fields:e.fields});let s=await j("/api/email/collaboration/coordination",{method:"DELETE",body:JSON.stringify({mailbox_id:t,thread_key:i,client_id:e.clientId,lease_id:e.leaseId})}),n=await s.json();if(s.ok||u(n.error||"Could not release presence",{code:n.code||"api_error",json:e.json,fields:e.fields}),e.json)return k(n,e.fields);C("Conversation Presence"),c("Released",e.clientId),c("Remaining presence",String(n.presence?.length||0))}async function nd(e){let t=e.mailboxIds?.split(",").map(r=>r.trim()).filter(Boolean)[0];t||u("Mailbox ID required",{hint:"Usage: domani email changes --mailbox-ids mb_1 [--cursor <opaque>]",code:"validation_error",json:e.json,fields:e.fields});let i=new URLSearchParams({mailbox_id:t});e.cursor&&i.set("cursor",e.cursor),e.limit&&i.set("limit",e.limit);let s=await j(`/api/email/changes?${i}`),n=await s.json();if(s.ok||u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields}),e.json)return k(n,e.fields);if(C("Mailbox Changes"),n.requires_full_sync){c("Full sync","Required"),c("Baseline cursor",n.next_cursor),ze("Take a bounded mailbox snapshot, then call this command again with --cursor to replay concurrent changes.");return}n.changes.length?se(["Sequence","Type","Resource","Created"],n.changes.map(r=>[r.sequence,r.type,`${r.resource_type}:${r.resource_id||"-"}`,r.created_at]),[12,32,40,24]):console.log(` ${D.default.dim("No changes since this cursor.")}`),c("Next cursor",n.next_cursor),n.has_more&&ze("More changes are available; call again with the next cursor.")}async function rd(e){let t=(e.mailboxIds||"").split(",").map(r=>r.trim()).filter(Boolean);t.length||u("Mailbox IDs required",{hint:"Usage: domani email work --mailbox-ids mb_1,mb_2",code:"validation_error",json:e.json,fields:e.fields});let i=new URLSearchParams({mailbox_ids:t.join(",")});e.status&&i.set("status",e.status),e.assigned&&i.set("assigned",e.assigned),e.limit&&i.set("limit",e.limit);let s=await j(`/api/email/work-queue?${i}`),n=await s.json();if(s.ok||u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields}),e.json)return k(n,e.fields);if(C("Shared Inbox Work"),!n.items.length)return console.log(` ${D.default.dim("No conversations match this queue.")}`);se(["Thread","Status","Assignee","Subject"],n.items.map(r=>[r.thread_key,r.status,r.assignee?.label||"Unassigned",r.subject||"(no subject)"]),[28,10,28,48]),n.partial&&ze("This is a bounded snapshot. Increase --limit or use the API scan_limit when you need a wider queue.")}async function od(e){(!e.mailboxIds||!e.threadKey)&&u("Mailbox ID and thread key required",{hint:"Usage: domani email triage --mailbox-ids mb_1 --thread-key <key> --status closed",code:"validation_error",json:e.json,fields:e.fields});let t=e.assigneeId&&e.assigneeType?{type:e.assigneeType,id:e.assigneeId}:void 0,i=await j("/api/email/collaboration",{method:"PATCH",body:JSON.stringify({mailbox_id:e.mailboxIds.split(",")[0],thread_key:e.threadKey,thread_aliases:e.threadAliases?.split(",").map(n=>n.trim()).filter(Boolean),status:e.status,assignee:t,version:e.ifVersion?Number.parseInt(e.ifVersion,10):void 0})}),s=await i.json();if(i.ok||u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields}),e.json)return k(s,e.fields);C("Conversation Updated"),c("Status",s.status),c("Assignee",s.assignee?.label||"Unassigned"),c("Version",s.version)}async function ad(e){(!e.conversationId||!e.note)&&u("Conversation ID and note required",{hint:'Usage: domani email note --conversation-id conv_1 --note "Waiting for finance"',code:"validation_error",json:e.json,fields:e.fields});let t=await j(`/api/email/collaboration/${encodeURIComponent(e.conversationId)}/notes`,{method:"POST",body:JSON.stringify({body:e.note})}),i=await t.json();if(t.ok||u(i.error||i.message,{hint:i.hint,status:t.status,json:e.json,fields:e.fields}),e.json)return k(i,e.fields);console.log(`${y.success} Private note added`)}async function ld(e){e.conversationId||u("Conversation ID required",{hint:"Usage: domani email notes --conversation-id conv_1",code:"validation_error",json:e.json,fields:e.fields});let t=await j(`/api/email/collaboration/${encodeURIComponent(e.conversationId)}/notes`),i=await t.json();if(t.ok||u(i.error||i.message,{hint:i.hint,status:t.status,json:e.json,fields:e.fields}),e.json)return k(i,e.fields);if(C("Private Notes"),!i.notes.length)return console.log(` ${D.default.dim("No private notes yet.")}`);se(["Author","Created","Note"],i.notes.map(s=>[s.author.label,s.created_at,s.body]),[28,24,64])}async function dd(e){e.conversationId||u("Conversation ID required",{hint:"Usage: domani email activity --conversation-id conv_1",code:"validation_error",json:e.json,fields:e.fields});let t=await j(`/api/email/collaboration/${encodeURIComponent(e.conversationId)}/activity`),i=await t.json();if(t.ok||u(i.error||i.message,{hint:i.hint,status:t.status,json:e.json,fields:e.fields}),e.json)return k(i,e.fields);if(C("Conversation Activity"),!i.activity.length)return console.log(` ${D.default.dim("No activity yet.")}`);se(["Type","Actor","Created"],i.activity.map(s=>[s.type,s.actor.label,s.created_at]),[36,32,24])}async function cd(e){let t=await Xe(e);if(e.dryRun)return B("email_setup",{domain:t},e.json,e.fields);let i=S(!e.json);i.start(`Setting up email on ${$.domain(t)}`);let s=await j(`/api/domains/${encodeURIComponent(t)}/email/setup`,{method:"POST"}),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields})),i.stop(`${y.success} Email ${n.status==="already_configured"?"already configured":"configured"}`),e.json){k(n,e.fields);return}if(n.records?.length){d(),C(`Email DNS Records ${$.domain(t)}`);let r=n.records.map(o=>[D.default.yellow(o.type),o.name,o.value.length>40?o.value.slice(0,40)+"...":o.value,o.status==="verified"||o.status==="created"?D.default.green(o.status):D.default.yellow(o.status)]);se(["Type","Name","Value","Status"],r,[8,28,44,12])}d(),n.hint&&ze(n.hint),I("Check status:",`domani email status --domain ${t}`),d()}async function ud(e){let t=await Xe(e),i=S(!e.json);i.start(`Checking email status for ${$.domain(t)}`);let s=await j(`/api/domains/${encodeURIComponent(t)}/email/status`),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields})),i.stop(`${y.success} Status loaded`),e.json){k(n,e.fields);return}if(C(`Email ${$.domain(t)}`),c("Enabled",n.enabled?D.default.green("yes"):D.default.dim("no")),n.enabled&&(c("Verified",n.verified?D.default.green("yes"):D.default.yellow("pending")),c("Mailboxes",String(n.mailbox_count))),d(),!n.enabled)I("Set up email:",`domani email setup --domain ${t}`),d();else if(!n.verified&&n.records?.length){console.log(` ${D.default.yellow("!")} Add these DNS records to verify:`);for(let r of n.records)console.log(` ${D.default.yellow(r.type)} ${r.name} ${D.default.dim("\u2192")} ${r.value.length>50?r.value.slice(0,50)+"...":r.value}`);d()}}async function md(e){let t=await Xe(e);if(e.dryRun)return B("email_remove",{domain:t},e.json,e.fields);let i=S(!e.json);i.start(`Removing email from ${$.domain(t)}`);let s=await j(`/api/domains/${encodeURIComponent(t)}/email/setup`,{method:"DELETE"}),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields})),i.stop(`${y.success} Email disabled`),e.json){k(n,e.fields);return}n.mailboxes_deleted>0&&console.log(` ${D.default.dim(`${n.mailboxes_deleted} mailbox(es) deleted.`)}`),d()}async function Xr(e){let t=S(!e.json);t.start("Loading mailboxes");let i=e.domain?`?domain=${encodeURIComponent(e.domain)}`:"",s=await j(`/api/emails${i}`),n=await s.json();s.ok||(t.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields}));let r=n.mailboxes||[];if(t.stop(`${y.success} ${r.length} mailbox(es)`),e.json){k(n,e.fields);return}if(r.length===0){d(),console.log(` ${D.default.dim("No mailboxes.")}`),d(),I("Create one:","domani email create hello@example.com"),d();return}d(),C("Mailboxes");let o=r.map(a=>[D.default.cyan(a.address),String(a.message_count),a.webhook_url?$.url(a.webhook_url):D.default.dim("-"),D.default.dim(new Date(a.created_at).toLocaleDateString())]);se(["Address","Messages","Webhook","Created"],o,[32,10,36,14]),d()}async function fd(e){let t=await Xe(e);if(e.dryRun)return B("email_create_mailbox",{domain:t,slug:e.slug,workspace_id:e.workspace},e.json,e.fields);let i=e.slug;if(!i&&!e.json){let m=await Ae({message:`Email handle for @${t}:`,placeholder:"hello"});le(m)&&process.exit(0),i=m}i||u("Slug required",{hint:`Usage: domani email create hello@${t}`,code:"validation_error",json:e.json,fields:e.fields});let s=`${i}@${t}`,n=S(!e.json);n.start("Creating mailbox");let r=await j("/api/emails",{method:"POST",body:JSON.stringify({address:s,workspace_id:e.workspace})}),o=await r.json();if(r.status===202&&!e.json){n.stop("");let m=o.txt_record,f=o.email_records||[],g=[{type:"TXT",name:m?.name||"@",value:m?.value||"",note:"ownership proof"},...f];d(),console.log(" Add these records at your DNS provider:"),d();for(let x of g){let O=x.priority!==void 0?` ${D.default.dim(`priority: ${x.priority}`)}`:"",R=x.note?` ${D.default.dim(`(${x.note})`)}`:"";console.log(` ${D.default.yellow(x.type)} ${D.default.bold(x.name)}${O}${R}`),console.log(` ${D.default.dim("\u2192")} ${D.default.cyan(x.value)}`),d()}ze("DNS propagation typically takes 5\u201330 minutes. Checking automatically..."),d();let b=g.map(x=>({cells:[D.default.yellow(x.type),x.name,x.note?D.default.dim(`(${x.note})`):""],status:"pending"})),w=Dt(["Type","Name",""],b,[6,24,16]);w.start();let v=0;for(;r.status===202&&v<60;)await Pt(15e3),v++,r=await j("/api/emails",{method:"POST",body:JSON.stringify({address:s,workspace_id:e.workspace})}),o=await r.json(),r.status!==202&&!r.ok&&(w.stop(),u(o.error||o.message,{hint:o.hint,status:r.status,json:e.json,fields:e.fields}));r.status===202&&(w.stop(),u("TXT record not detected after 15 minutes.",{hint:`Check the record is set, then retry: domani email create ${s}`,code:"timeout",json:e.json,fields:e.fields})),w.markDone(0);let h=x=>`${x.type}:${x.name}`,_=new Map;g.slice(1).forEach((x,O)=>_.set(h(x),O+1));for(let x=0;x<60;x++){await Pt(15e3);let O=await j(`/api/domains/${encodeURIComponent(t)}/email/status`),R=await O.json();if(O.ok&&R.records){for(let M of R.records)if(M.status==="verified"||M.status==="created"){let V=_.get(h(M));V!==void 0&&w.markDone(V)}}if(O.ok&&R.verified)break}w.stop(),d()}if(r.ok||(n.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:e.json,fields:e.fields})),n.stop(`${y.success} ${D.default.cyan(o.address)} created`),e.json){k(o,e.fields);return}let a=await j(`/api/domains/${encodeURIComponent(t)}/email/status`),l=await a.json();d(),a.ok&&l.verified?(I("Read inbox:",`domani email inbox ${o.address}`),I("Web inbox:",`${Qt}/inbox?address=${encodeURIComponent(o.address)}`)):(I("Check propagation:",`domani email status --domain ${t}`),I("Web inbox:",`${Qt}/inbox?address=${encodeURIComponent(o.address)}`)),d()}async function pd(e){let t=await Xe(e);if(e.slug||u("Slug required",{hint:"Usage: domani email delete hello@example.com",code:"validation_error",json:e.json,fields:e.fields}),e.dryRun)return B("email_delete_mailbox",{domain:t,address:`${e.slug}@${t}`},e.json,e.fields);let i=S(!e.json);i.start(`Deleting ${e.slug}@${t}`);let s=encodeURIComponent(`${e.slug}@${t}`),n=await j(`/api/emails/${s}`,{method:"DELETE",body:JSON.stringify({confirm:!0})}),r=await n.json();if(n.ok||(i.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:e.json,fields:e.fields})),i.stop(`${y.success} Mailbox deleted`),e.json){k(r,e.fields);return}console.log(` ${D.default.dim(`${r.address} and all messages deleted.`)}`),d()}async function hd(e){let t=await Xe(e);if(e.slug||u("Slug required",{hint:'Usage: domani email send hello@example.com --to user@test.com --subject "Hi" --body "Hello"',code:"validation_error",json:e.json,fields:e.fields}),e.to||u("Recipient required",{hint:"Usage: domani email send hello@example.com --to user@test.com",code:"validation_error",json:e.json,fields:e.fields}),e.dryRun)return B("email_send",{from:`${e.slug}@${t}`,to:e.to,subject:e.subject},e.json,e.fields);let i=S(!e.json);i.start(`Sending from ${e.slug}@${t}`);let s={to:Gi(Bi(e.to))},n=Gi(Bi(e.cc)),r=Gi(Bi(e.bcc));n&&(s.cc=n),r&&(s.bcc=r),e.subject&&(s.subject=e.subject),e.text&&(s.text=e.text),e.inReplyTo&&(s.in_reply_to=e.inReplyTo),e.references&&(s.references=e.references);let o=encodeURIComponent(`${e.slug}@${t}`),a=await j(`/api/emails/${o}/send`,{method:"POST",body:JSON.stringify(s)}),l=await a.json();if(!a.ok){i.stop("Failed");let f=l.code==="MONTHLY_LIMIT_EXCEEDED"?`Run ${D.default.cyan("domani upgrade")} to switch to Pro (10,000 emails/month).`:l.hint;u(l.error||l.message,{hint:f,status:a.status,json:e.json,fields:e.fields})}let m=Array.isArray(l.to)?l.to.join(", "):l.to;if(i.stop(`${y.success} Sent to ${D.default.cyan(m)}`),e.json){k(l,e.fields);return}}async function gd(e){let t=await Xe(e);e.slug||u("Slug required",{hint:"Usage: domani email inbox hello@example.com [--direction in|out] [--limit 20]",code:"validation_error",json:e.json,fields:e.fields});let i=new URLSearchParams;e.direction&&i.set("direction",e.direction),e.folder&&i.set("folder",e.folder),e.view&&i.set("view",e.view),e.limit&&i.set("limit",e.limit);let s=i.toString()?`?${i}`:"",n=S(!e.json);n.start(`Loading messages for ${e.slug}@${t}`);let r=encodeURIComponent(`${e.slug}@${t}`),o=await j(`/api/emails/${r}/messages${s}`),a=await o.json();o.ok||(n.stop("Failed"),u(a.error||a.message,{hint:a.hint,status:o.status,json:e.json,fields:e.fields}));let l=a.messages||[];if(e.json){n.stop(`${y.success} ${l.length} message(s)`),k(a,e.fields);return}if(l.length===0){n.stop(`${D.default.dim("No messages")}`);return}let m=l.length>1?"s":"";n.stop(`${y.success} ${D.default.cyan(`${e.slug}@${t}`)} ${D.default.dim("\xB7 "+l.length+" message"+m)}`);for(let f of l){let g=f.direction==="in"?D.default.green("in "):D.default.dim("out"),b=f.direction==="in"?f.from:f.to,w=f.subject||"(no subject)",v=D.default.dim(new Date(f.created_at).toLocaleString()),h=w;if(f.text){let _=f.text.replace(/\s+/g," ").trim(),x=_.length>60?_.slice(0,60)+"\u2026":_;h=`${w} ${D.default.dim("- "+x)}`}console.log(` ${g} ${b.padEnd(30)} ${h} ${v}`)}a.next_cursor&&console.log(` ${D.default.dim("\u2026 more available, use --limit to paginate")}`)}async function bd(e){let t=await Xe(e);e.slug||u("Slug required",{hint:"Usage: domani email folders hello@example.com",code:"validation_error",json:e.json,fields:e.fields});let i=encodeURIComponent(`${e.slug}@${t}`),s=await j(`/api/emails/${i}/folders`),n=await s.json();if(s.ok||u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields}),e.json)return k(n,e.fields);C(`Folders for ${e.slug}@${t}`);for(let r of n.folders||[])c(r.id,`${r.total} total, ${r.unread} unread`);for(let r of n.views||[])c(r.id,`${r.total} total, ${r.unread} unread`)}async function yd(e,t){let i=await Xe(t);t.slug||u("Slug required",{hint:`Usage: domani email ${e} hello@example.com --message-ids id1,id2`,code:"validation_error",json:t.json,fields:t.fields});let s=(t.messageIds||"").split(",").map(f=>f.trim()).filter(Boolean);s.length||u("Message IDs required",{hint:"Pass --message-ids id1,id2",code:"validation_error",json:t.json,fields:t.fields});let n={message_ids:s,idempotency_key:t.idempotencyKey||(0,eo.randomUUID)()};if((e==="archive"||e==="trash")&&Object.assign(n,{action:"move",destination:e==="archive"?"archive":"trash"}),e==="restore"&&(n.action="restore"),(e==="read"||e==="unread")&&Object.assign(n,{action:"mark_read",read:e==="read"}),(e==="star"||e==="unstar")&&Object.assign(n,{action:"star",starred:e==="star"}),t.dryRun)return B("email_messages_action",{address:`${t.slug}@${i}`,...n},t.json,t.fields);let r=encodeURIComponent(`${t.slug}@${i}`),o=await j(`/api/emails/${r}/messages/actions`,{method:"POST",body:JSON.stringify(n)}),a=await o.json();if(!o.ok&&o.status!==207&&u(a.error||a.message,{hint:a.hint,status:o.status,json:t.json,fields:t.fields}),t.json)return k(a,t.fields);let l=(a.results||[]).filter(f=>f.ok).length,m=(a.results||[]).length-l;console.log(`${y.success} ${l} updated${m?D.default.yellow(`, ${m} failed`):""}`),a.operation_id&&(c("Operation",a.operation_id),c("Idempotency key",a.idempotency_key),a.idempotent_replay&&c("Receipt","replayed (no duplicate mutation)"))}async function $d(e){let t=await Xe(e);e.slug||u("Slug required",{hint:"Usage: domani email webhook hello@example.com --url https://...",code:"validation_error",json:e.json,fields:e.fields});let i=`${e.slug}@${t}`,s=encodeURIComponent(i),n;try{n=Tt(e)}catch(o){u(o instanceof Error?o.message:"Invalid webhook headers",{hint:"Set the named environment variable, or remove the conflicting header option.",code:"validation_error",json:e.json,fields:e.fields})}if(!e.url&&n!==void 0&&u("--url is required when changing webhook auth headers",{hint:"Pass the existing webhook URL with --authorization-env, --api-key-env, or --clear-headers.",code:"validation_error",json:e.json,fields:e.fields}),e.dryRun)return B("email_webhook",{address:i,webhook_url:e.url||null,...n!==void 0?{header_names:Nt(n)}:{}},e.json,e.fields);let r=S(!e.json);if(e.url){r.start(`Setting webhook for ${i}`);let o=await j(`/api/emails/${s}/webhook`,{method:"PUT",body:JSON.stringify({url:e.url,...n!==void 0?{headers:n}:{}})}),a=await o.json();if(o.ok||(r.stop("Failed"),u(a.error||a.message,{hint:a.hint,status:o.status,json:e.json,fields:e.fields})),r.stop(`${y.success} Webhook set`),e.json){k(a,e.fields);return}C(`Mailbox ${a.address}`),c("Webhook",$.url(a.webhook_url)),c("Auth headers",a.header_names?.join(", ")||D.default.dim("none")),c("Signing secret",D.default.dim(a.signing_secret)),d()}else{r.start(`Removing webhook for ${i}`);let o=await j(`/api/emails/${s}/webhook`,{method:"DELETE"}),a=await o.json();if(o.ok||(r.stop("Failed"),u(a.error||a.message,{hint:a.hint,status:o.status,json:e.json,fields:e.fields})),r.stop(`${y.success} Webhook removed`),e.json){k(a,e.fields);return}C(`Mailbox ${a.address}`),c("Webhook",D.default.dim("none")),d()}}async function vd(e){let t=await Xe(e);e.slug||u("Slug required",{hint:"Usage: domani email webhook-test hello@example.com",code:"validation_error",json:e.json,fields:e.fields});let i=`${e.slug}@${t}`;if(e.dryRun)return B("email_webhook_test",{address:i},e.json,e.fields);let s=S(!e.json);s.start(`Testing webhook for ${i}`);let n=await j(`/api/emails/${encodeURIComponent(i)}/webhook/test`,{method:"POST"}),r=await n.json();if((!n.ok||!r.success)&&(s.stop("Failed"),u(r.error||r.message||"Webhook test failed",{hint:r.hint||"Check the endpoint and sender authentication, then retry.",status:n.status,json:e.json,fields:e.fields})),s.stop(`${y.success} Test delivered`),e.json)return k(r,e.fields);C(`Mailbox ${i}`),c("Delivery",D.default.green("successful")),typeof r.status=="number"&&c("Endpoint",`HTTP ${r.status}`),d()}async function wd(e){let t=await Xe(e);if(e.slug||u("Slug required",{hint:"Usage: domani email forward hello@example.com --forward-to me@gmail.com",code:"validation_error",json:e.json,fields:e.fields}),e.dryRun)return B("email_forward",{address:`${e.slug}@${t}`,forward_to:e.forwardTo||null},e.json,e.fields);let i=S(!e.json),s=e.forwardTo||null;i.start(`Updating forward for ${e.slug}@${t}`);let n=encodeURIComponent(`${e.slug}@${t}`),r=await j(`/api/emails/${n}`,{method:"PATCH",body:JSON.stringify({forward_to:s})}),o=await r.json();if(r.ok||(i.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:e.json,fields:e.fields})),i.stop(`${y.success} Forward ${s?"set":"removed"}`),e.json){k(o,e.fields);return}C(`Mailbox ${o.address}`),c("Forward to",o.forward_to?D.default.cyan(o.forward_to):D.default.dim("none")),d()}async function Zr(e,t,i){let s=S(!t);s.start(`Checking email health for ${$.domain(e)}`);let n=await j(`/api/domains/${encodeURIComponent(e)}/email/check`),r=await n.json();if(n.ok||(s.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:t,fields:i})),s.stop("Email health checked"),t){k(r,i);return}if(C(`Email Health ${$.domain(r.domain)}`),r.provider?c("Provider",D.default.cyan(cn(r.provider))):c("Provider",D.default.dim("unknown")),r.mx.configured?c("MX",`${y.success} ${D.default.green("propagated")} ${D.default.dim(`(${r.mx.records.length} record${r.mx.records.length!==1?"s":""})`)}`):c("MX",`${y.error} ${D.default.red("not configured")}`),r.spf.configured?c("SPF",`${y.success} ${D.default.green(r.spf.value)}`):c("SPF",`${y.error} ${D.default.red("missing")}`),r.dmarc.configured){let o=r.dmarc.value.length>50?r.dmarc.value.slice(0,50)+"...":r.dmarc.value;c("DMARC",`${y.success} ${D.default.green(o)}`)}else c("DMARC",`${y.error} ${D.default.red("missing")}`);r.dkim.configured?c("DKIM",`${y.success} ${D.default.green("found")} ${D.default.dim(`(${r.dkim.selectors.join(", ")})`)}`):c("DKIM",`${y.warning} ${D.default.yellow("not found")}`),d(),r.mx.configured?(!r.spf.configured||!r.dmarc.configured)&&(ze("SPF and DMARC protect against email spoofing. Re-run email setup to add them."),d()):(I("Set up email:",`domani email ${e} google`),d())}async function Qr(e,t,i,s){return t?io(e,t,i,s):to(e,i,s)}async function to(e,t,i){let s=S(!t);s.start("Loading email providers");let n=await j(`/api/domains/${encodeURIComponent(e)}/connect`),r=await n.json();n.ok||(s.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:t,fields:i})),s.stop("Providers loaded");let o=r.providers?.email||[];o.length===0&&u("No email providers available",{code:"not_found",json:t,fields:i});let a=await Qe({message:"Choose an email provider",options:o.map(l=>({value:l.name,label:cn(l.name)}))});return le(a)&&process.exit(0),io(e,a,t,i)}async function io(e,t,i,s){if(i){let m=await j(`/api/domains/${encodeURIComponent(e)}/connect`,{method:"POST",body:JSON.stringify({target:t})}),f=await m.json();m.ok||u(f.error||f.message,{hint:f.hint,status:m.status,json:i,fields:s}),k(f,s);return}let n=await j(`/api/domains/${encodeURIComponent(e)}/connect?provider=${encodeURIComponent(t)}`);if(!n.ok){let m=await n.json();u(m.error||m.message,{hint:m.hint,status:n.status,json:i,fields:s})}let r=await n.json(),o=r.preview?.records??[],a=r.preview?.provider??t,l=cn(a);if(C(`Email ${$.domain(e)}`),c("Provider",D.default.cyan(l)),o.length){d(),console.log(` ${D.default.bold("DNS Records")}`);let m=[8,24,40],f=Dt(["Type","Name","Value"],o.map(x=>({cells:Ql(x),status:"pending"})),m);f.start();let g=await j(`/api/domains/${encodeURIComponent(e)}/connect`,{method:"POST",body:JSON.stringify({target:t})}),b=await g.json();g.ok||(f.stop(),d(),u(b.error||b.message,{hint:b.hint,status:g.status,json:i,fields:s}));let w=b.records||[];for(let x=0;x<o.length;x++)w.find(R=>R.record.type===o[x].type&&R.record.name===o[x].name&&R.record.value===o[x].value)?.status==="already_set"||await Pt(60),f.markDone(x);await Pt(80),f.stop();let v=w.filter(x=>x.status==="created"||x.status==="updated").length,h=w.filter(x=>x.status==="already_set").length,_;h===w.length?_=`All ${h} records already set`:h>0?_=`${v} created, ${h} already set`:_=`${v} DNS records set`,d(),console.log(` ${y.success} ${D.default.green(`Email configured - ${_}`)}`)}else{let m=S(!0);m.start("Setting DNS records");let f=await j(`/api/domains/${encodeURIComponent(e)}/connect`,{method:"POST",body:JSON.stringify({target:t})}),g=await f.json();f.ok||(m.stop("Failed"),u(g.error||g.message,{hint:g.hint,status:f.status,json:i,fields:s})),m.stop(`${y.success} Email configured via ${D.default.cyan(l)}`)}d(),I("Verify propagation:",`domani email ${e} --check`),d()}var D,eo,Xl,Zl,mn=Ie(()=>{"use strict";X();ei();D=U(L(),1);De();W();he();Ye();eo=require("node:crypto");Ji();Xl=["setup","status","remove","list","create","delete","send","inbox","folders","archive","trash","restore","read","unread","star","unstar","webhook","forward","check","connect","work","triage","notes","note","activity","changes","coordination","presence","release-presence"],Zl={"google-workspace":"Google Workspace",fastmail:"Fastmail",proton:"Proton Mail"}});var no={};Mt(no,{dns:()=>pn});async function pn(e,t,i,s,n,r){e||(e=await fe()),K(e,r);let o=r?.json??!1,a=r?.type||i,l=r?.name||s,m=r?.value||n;if(!t||t==="get"){let f=S(!o);f.start(`Loading DNS for ${$.domain(e)}`);let g=await j(`/api/domains/${encodeURIComponent(e)}/dns`),b=await g.json();if(g.ok||(f.stop("Failed"),u(b.error||b.message,{hint:b.hint,status:g.status,json:o,fields:r?.fields})),f.stop(`${b.records.length} record(s)`),o){k(b,r?.fields);return}if(b.records.length===0){d(),console.log(` ${je.default.dim(`No DNS records for ${e}`)}`),d(),I("Auto-configure DNS:",`domani connect ${e}`),d();return}let w=[8,24,40,8];C(`DNS ${$.domain(e)}`,w.reduce((h,_)=>h+_,0)+w.length-1);let v=b.records.map(h=>{let _=h.priority?je.default.dim(` pri=${h.priority}`):"";return[je.default.yellow(h.type),h.name,je.default.cyan(h.value)+_,je.default.dim(String(h.ttl))]});se(["Type","Name","Value","TTL"],v,w),d();return}if(t==="set"){if((!a||!l||!m)&&u("Missing arguments for dns set",{hint:"Usage: domani dns <domain> set --type A --name www --value 1.2.3.4",code:"validation_error",json:o,fields:r?.fields}),r?.dryRun)return B("dns_set",{domain:e,record:{type:a.toUpperCase(),name:l,value:m,ttl:3600}},o,r?.fields);let f=S(!o);f.start(`Setting ${je.default.yellow(a.toUpperCase())} record`);let g=await j(`/api/domains/${encodeURIComponent(e)}/dns`),b=await g.json(),v=(g.ok?b.records:[]).filter(x=>!(x.type===a.toUpperCase()&&x.name===l));v.push({type:a.toUpperCase(),name:l,value:m,ttl:3600});let h=await j(`/api/domains/${encodeURIComponent(e)}/dns`,{method:"PUT",body:JSON.stringify({records:v})}),_=await h.json();h.ok||(f.stop("Failed"),u(_.error||_.message,{hint:_.hint,status:h.status,json:o,fields:r?.fields})),f.stop(`${y.success} ${je.default.yellow(a.toUpperCase())} ${l} ${y.arrow} ${je.default.cyan(m)}`),o?k(_,r?.fields):(d(),I("Check propagation:",`domani status ${e}`),d());return}if(t==="delete"){if((!a||!l)&&u("Missing arguments for dns delete",{hint:"Usage: domani dns <domain> delete --type A --name www",code:"validation_error",json:o,fields:r?.fields}),r?.dryRun)return B("dns_delete",{domain:e,record:{type:a.toUpperCase(),name:l}},o,r?.fields);let f=S(!o);f.start(`Deleting ${je.default.yellow(a.toUpperCase())} ${l}`);let g=await j(`/api/domains/${encodeURIComponent(e)}/dns?type=${encodeURIComponent(a.toUpperCase())}&name=${encodeURIComponent(l)}`,{method:"DELETE"}),b=await g.json();g.ok||(f.stop("Failed"),u(b.error||b.message,{hint:b.hint,status:g.status,json:o,fields:r?.fields})),f.stop(`${y.success} Deleted ${je.default.yellow(a.toUpperCase())} ${l}`),o?k(b,r?.fields):(d(),I("Check propagation:",`domani status ${e}`),d());return}if(t==="snapshot"){if(r?.dryRun)return B("dns_snapshot",{domain:e},o,r?.fields);let f=S(!o);f.start(`Capturing DNS snapshot for ${$.domain(e)}`);let g=await j(`/api/domains/${encodeURIComponent(e)}/dns/snapshot`,{method:"POST"}),b=await g.json();g.ok||(f.stop("Failed"),u(b.error||b.message,{hint:b.hint,status:g.status,json:o,fields:r?.fields}));let w=b.records?.length??0;if(f.stop(`${y.success} Captured ${w} record(s)`),o){k(b,r?.fields);return}let v=`${e}.dns.json`,h=(0,fn.resolve)(process.cwd(),v);(0,Ki.writeFileSync)(h,JSON.stringify(b,null,2)+`
179
+ `),C("DNS Snapshot"),c("Domain",$.domain(b.domain)),c("Records",String(w)),c("Subdomains",String(b.subdomains?.length??0)),c("Sources",(b.sources||[]).join(", ")||"none"),c("Captured",b.capturedAt||b.captured_at||"now"),c("Saved to",je.default.cyan(v)),d(),I("Restore from this snapshot:",`domani dns ${e} restore --file ${v}`),d();return}if(t==="restore"){if(r?.dryRun)return B("dns_restore",{domain:e,source:r?.file||"server_backup"},o,r?.fields);let f=S(!o),g;if(r?.file){let v=(0,fn.resolve)(process.cwd(),r.file);v.startsWith(process.cwd())||u("File path must be within the current directory",{hint:`Got: ${r.file}`,code:"validation_error",json:o,fields:r?.fields});try{let h=(0,Ki.readFileSync)(v,"utf-8"),_=JSON.parse(h);g=JSON.stringify({snapshot:_}),f.start(`Restoring DNS for ${$.domain(e)} from ${je.default.cyan(r.file)}`)}catch(h){u(`Failed to read snapshot file: ${h instanceof Error?h.message:"unknown"}`,{hint:`Make sure ${r.file} exists and contains valid JSON.`,code:"validation_error",json:o,fields:r?.fields})}}else f.start(`Restoring DNS for ${$.domain(e)} from server backup`);let b=await j(`/api/domains/${encodeURIComponent(e)}/dns/restore`,{method:"POST",...g?{body:g}:{}}),w=await b.json();if(b.ok||(f.stop("Failed"),u(w.error||w.message,{hint:w.hint,status:b.status,json:o,fields:r?.fields})),f.stop(`${y.success} Restored DNS`),o){k(w,r?.fields);return}if(C("DNS Restored"),c("Domain",$.domain(w.domain)),c("Applied",je.default.green(String(w.applied??0))),c("Skipped",je.default.dim(String(w.skipped??0))),w.errors?.length>0){c("Errors",je.default.red(String(w.errors.length)));for(let v of w.errors)console.log(` ${je.default.red("\u2022")} ${v}`)}d(),I("Verify DNS records:",`domani dns ${e}`),d();return}u(`Unknown action: ${t}`,{hint:"Use 'get', 'set', 'delete', 'snapshot', or 'restore'.",code:"validation_error",json:o,fields:r?.fields})}var je,Ki,fn,hn=Ie(()=>{"use strict";X();je=U(L(),1);W();he();Ye();Ki=require("node:fs"),fn=require("node:path")});var ro={};Mt(ro,{status:()=>gn});function kd(e){return[et.default.yellow(e.type),e.name,et.default.cyan(e.value)+(e.priority?et.default.dim(` pri=${e.priority}`):"")]}function _d(e){if(C(`Status ${$.domain(e.domain)}`),e.expires){let t=new Date(e.expires).toLocaleDateString(),i=e.days_until_expiry,s=i!=null&&i<30?et.default.red:i!=null&&i<90?et.default.yellow:et.default.green;c("Expires",`${t} ${et.default.dim("(")}${s(`${i} days`)}${et.default.dim(")")}`)}}async function gn(e,t){if(e||(e=await fe()),K(e,t),t.json){let g=await j(`/api/domains/${encodeURIComponent(e)}/status`),b=await g.json();g.ok||u(b.error||b.message,{hint:b.hint,status:g.status,json:t.json,fields:t.fields}),k(b,t.fields);return}let i=S(!0);i.start(`Checking ${$.domain(e)}`);let s;try{s=await j(`/api/domains/${encodeURIComponent(e)}/status`,{headers:{Accept:"text/event-stream"},signal:AbortSignal.timeout(t.timeout?parseInt(t.timeout,10)*1e3:3e4)})}catch{i.stop("Failed"),u("Request timed out",{hint:"The status check took too long. Try again.",code:"timeout",json:t.json,fields:t.fields})}if(!s.ok){i.stop("Failed");try{let g=await s.json();u(g.error||g.message,{hint:g.hint,status:s.status,json:t.json,fields:t.fields})}catch{u(`Server error (${s.status})`,{status:s.status,json:t.json,fields:t.fields})}}let n=s.body;n||(i.stop("Failed"),u("Empty response"));let r=new TextDecoder,o="",a=null,l=[],m=!1,f="";try{for await(let g of n){o+=r.decode(g,{stream:!0});let b=o.split(`
180
+ `);o=b.pop()??"";for(let w of b)if(w.startsWith("event: "))f=w.slice(7);else if(w.startsWith("data: ")){let v=JSON.parse(w.slice(6));if(f==="info"&&(i.stop("Status retrieved"),m=!0,_d(v)),f==="records")if(l=v,l.length>0){d(),console.log(` ${et.default.bold("DNS Records")}`);let h=[8,10,34];a=Dt(["Type","Name","Value"],l.map(_=>({cells:kd(_),status:"pending"})),h),a.start()}else d(),c("DNS",et.default.dim("no records")),I("Auto-configure DNS:",`domani connect ${e}`);if(f==="propagation"&&a){let{index:h,propagated:_}=v,x=_?y.success:`${y.warning}`;a.markDone(h,x)}f==="done"&&a&&a.stop(),f==="error"&&(m||i.stop("Failed"),a&&a.stop(),u(v.message||"Status check failed"))}}}catch{m||i.stop("Failed"),a&&a.stop(),u("Connection lost",{hint:"The status check was interrupted. Try again.",code:"connection_lost",json:t.json,fields:t.fields})}m||i.stop("Done"),d()}var et,bn=Ie(()=>{"use strict";X();et=U(L(),1);W();he();Ye()});var di={};Mt(di,{buy:()=>$n});async function yn(e){let t=await Qe({message:`What's next for ${Te.default.cyan(e)}?`,options:[{value:"connect",label:"Connect to a service",hint:"domani connect"},{value:"email",label:"Set up email",hint:"domani email setup"},{value:"dns",label:"Configure DNS",hint:"domani dns"},{value:"status",label:"Check status & DNS propagation",hint:"domani status"},{value:"done",label:"Done"}]});if(le(t)||t==="done"){d();return}if(d(),t==="connect"){let{connect:i}=await Promise.resolve().then(()=>(dn(),Yr));await i(e,void 0,{})}else if(t==="email"){let i=await Ae({message:`Mailbox name for ${Te.default.cyan(e)}`,placeholder:"e.g. hey, hello, contact"});if(le(i)||!i){d();return}d();let{email:s}=await Promise.resolve().then(()=>(mn(),so));await s("create",void 0,{domain:e,slug:i})}else if(t==="dns"){let{dns:i}=await Promise.resolve().then(()=>(hn(),no));await i(e)}else if(t==="status"){let{status:i}=await Promise.resolve().then(()=>(bn(),ro));await i(e,{})}}async function xd(e,t){K(e,t);let i;if(t.preChecked)i={available:!0,...t.preChecked};else{let f=S(!t.json);f.start(`Checking ${$.domain(e)}`);let g=await j(`/api/domains/search?q=${encodeURIComponent(e)}`);i=await g.json(),g.ok||(f.stop("Search failed"),u(i.error,{hint:i.hint,status:g.status,json:t.json,fields:t.fields})),i.available||(f.stop(`${y.error} ${$.domain(e)} is not available`),u(`${e} is not available`,{code:"not_available",json:t.json,fields:t.fields})),f.stop(`${y.success} ${$.domain(e)} ${y.dot} available ${y.dot} ${$.price(i.price)}/yr`)}if(t.dryRun)return B("buy",{domain:e,available:!0,price:i.price,currency:i.currency||"USD"},t.json,t.fields);if(!Et(t)){let f=await Ke({message:`Purchase ${Te.default.bold(e)} for ${$.price(i.price)}/yr?`});if(!f||typeof f=="symbol"){console.log(` ${Te.default.dim("Cancelled.")}`);return}}let s=S(!t.json);s.start("Purchasing");let n=await j("/api/domains/buy",{method:"POST",headers:{Accept:"text/event-stream"},body:JSON.stringify({domain:e})});if(!n.ok||!n.body){s.stop("Purchase failed");let f=await n.json().catch(()=>({}));u(f.error||f.message,{hint:f.hint,fixUrl:f.setup_url||f.payment_options?.card?.setup_url,status:n.status,json:t.json,fields:t.fields})}let r={},o=new TextDecoder,a="",l="";for await(let f of n.body){a+=o.decode(f,{stream:!0});let g=a.split(`
181
+ `);a=g.pop()??"";for(let b of g)if(b.startsWith("event: "))l=b.slice(7).trim();else if(b.startsWith("data: ")){let w=JSON.parse(b.slice(6));l==="checking"?s.message(`Checking ${$.domain(w.domain)}`):l==="payment"?s.message(`Charging ${$.price(w.total)}`):l==="registering"?s.message(`Registering ${$.domain(w.domain)}`):l==="registered"?r=w:l==="error"&&(s.stop("Purchase failed"),u(w.error,{hint:w.hint,fixUrl:w.setup_url,status:n.status,json:t.json,fields:t.fields}))}}let m=r.expires?Te.default.dim(` \xB7 expires ${new Date(r.expires).toLocaleDateString()}`):"";if(s.stop(`${y.success} ${$.domain(r.domain)} is yours!${m}`),t.json){k(r,t.fields);return}xe?await yn(r.domain):(I("Connect to a service:",`domani connect ${r.domain}`),I("Set up email:",`domani email setup ${r.domain}`),I("Configure DNS:",`domani dns ${r.domain}`),d())}async function jd(e,t){Kr(e,t);let i=!!t.json,s=S(!i);s.start(`Checking ${e.length} domains`);let n=await Promise.all(e.map(async h=>{try{let _=await j(`/api/domains/search?q=${encodeURIComponent(h)}`),x=await _.json();return{domain:h,available:_.ok&&x.available,price:x.price}}catch{return{domain:h,available:!1,price:void 0}}})),r=n.filter(h=>h.available),o=n.filter(h=>!h.available);r.length===0&&(s.stop(`${y.error} None of the ${e.length} domains are available`),process.exit(1));let a=r.reduce((h,_)=>h+(_.price||0),0);if(s.stop(`${y.success} ${r.length}/${e.length} available ${y.dot} ${$.price(a.toFixed(2))} total`),o.length>0)for(let h of o)console.log(` ${y.error} ${$.domain(h.domain)} ${Te.default.dim("not available")}`);if(t.dryRun)return B("buy_bulk",{domains:r.map(h=>({domain:h.domain,price:h.price})),unavailable:o.map(h=>h.domain),total_price:parseFloat(a.toFixed(2))},t.json,t.fields);if(!Et(t)){let h=await Ke({message:`Purchase ${Te.default.bold(String(r.length))} domain${r.length>1?"s":""} for ${$.price(a.toFixed(2))}?`});if(!h||typeof h=="symbol"){console.log(` ${Te.default.dim("Cancelled.")}`);return}}d();let l=r.map(h=>({cells:[$.domain(h.domain),h.price?`${$.price(h.price.toFixed(2))}/yr`:""],status:"pending"})),m=Dt(["Domain","Price"],l,[30,12],!i);m.start();let g=await(await j("/api/domains/buy",{method:"POST",body:JSON.stringify({domains:r.map(h=>h.domain)})})).json(),b=new Set((g.results||[]).map(h=>h.domain));for(let h=0;h<r.length;h++){let _=r[h].domain.toLowerCase().trim();b.has(_)?m.markDone(h,y.success):m.markDone(h,y.error)}if(m.stop(),i){k(g,t.fields);return}d();let w=g.summary?.succeeded??0,v=g.summary?.failed??0;if(w>0&&console.log(` ${y.success} ${Te.default.green(`${w} domain${w>1?"s":""} registered`)}`),v>0){console.log(` ${y.error} ${Te.default.red(`${v} failed`)}`);for(let h of g.errors||[])console.log(` ${Te.default.dim("\u2500")} ${$.domain(h.domain)}: ${Te.default.dim(h.error)}${h.hint?` ${Te.default.dim(`(${h.hint})`)}`:""}`)}if(d(),w>0&&xe){let h=(g.results||[]).filter(_=>_.success).map(_=>_.domain);if(h.length===1)await yn(h[0]);else{let _=await Qe({message:"Set up one of your new domains?",options:[...h.map(x=>({value:x,label:Te.default.cyan(x)})),{value:"done",label:"Done"}]});!le(_)&&_!=="done"?(d(),await yn(_)):d()}}else w>0&&(I("Connect to a service:","domani connect <domain>"),I("Set up email:","domani email setup <domain>"),d())}async function $n(e,t){let i=e.filter(Boolean);if(i.length===0){xe||u("Missing required argument: domain(s)",{hint:"Usage: domani buy <domain> [domain2 ...]",code:"missing_argument",json:t.json});let s=await Ae({message:"Domain to purchase",placeholder:"e.g. myapp.dev (space-separated for multiple)"});(le(s)||!s)&&process.exit(0),i=s.split(/\s+/).filter(Boolean)}return i.length===1?xd(i[0],t):jd(i,t)}var Te,Yt=Ie(()=>{"use strict";X();De();Te=U(L(),1);W();he()});var Fn=U(Un(),1),{program:$c,createCommand:vc,createArgument:wc,createOption:kc,CommanderError:_c,InvalidArgumentError:xc,InvalidOptionArgumentError:jc,Command:qn,Argument:Sc,Option:Cc,Help:Oc}=Fn.default;var at=U(L(),1);mt();rn();W();ei();mt();var rt=U(L(),1);W();var Ul=new Set(["cli","mcp","plugin","skill","api"]);function Fl(e){let t=e.scopes?.split(",").map(o=>o.trim()).filter(Boolean),i=e.mailboxes?.split(",").map(o=>o.trim().toLowerCase()).filter(Boolean),s=!!(t?.length||i?.length||e.label||e.expiresIn),n=e.surface||"cli";if(!Ul.has(n))throw new RangeError("--surface must be one of: cli, mcp, plugin, skill, api");let r=e.expiresIn===void 0?void 0:Number(e.expiresIn);if(r!==void 0&&(!Number.isInteger(r)||r<3600||r>31536e3))throw new RangeError("--expires-in must be an integer between 3600 and 31536000 seconds");return{delegated:s,body:{...t?.length?{scopes:t}:{},...i?.length?{mailboxes:i}:{},...e.label?{label:e.label}:{},...r!==void 0?{expires_in:r}:{},surface:n,intent:"programmatic_access"}}}async function Lr(e){let t=qe(),i=S(!e.json),s;try{s=Fl(e)}catch(w){u(w instanceof Error?w.message:"Invalid login options",{code:"invalid_expires_in",json:e.json})}let{body:n,delegated:r}=s,o=ut(),a=Me();if(a&&!r){i.start("Checking session");try{let w=await fetch(`${t}/api/me`,{headers:{Authorization:`Bearer ${a}`}});if(w.ok){let v=await w.json();i.stop(`Already logged in as ${rt.default.bold(v.email)}`),e.json&&k({status:"already_logged_in",email:v.email});return}}catch{}i.stop("Session expired, re-authenticating"),d()}i.start("Requesting auth code");let l=await fetch(`${t}/api/auth/cli`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!l.ok){i.stop("Failed to initiate login");try{let w=await l.json();u(w.error||w.message||`Server error (${l.status})`,{hint:w.hint,code:"login_failed",json:e.json})}catch{u(`Could not reach ${t}. Check your connection and try again.`,{code:"network_error",json:e.json})}}let{code:m,auth_url:f,expires_in:g}=await l.json();if(i.stop("Auth code received"),e.json){k({status:"awaiting_approval",code:m,auth_url:f,expires_in:g});return}d(),console.log(` ${rt.default.dim("Verification code:")} ${rt.default.bold(rt.default.cyan(m))}`),e.open!==!1?(console.log(` ${rt.default.dim("Opening browser")} ${y.arrow} ${$.url(f)}`),We(f)):console.log(` ${rt.default.dim("Open this URL to approve:")} ${$.url(f)}`),d(),i.start("Waiting for approval");let b=120;for(let w=0;w<b;w++){await new Promise(_=>setTimeout(_,5e3));let v=await fetch(`${t}/api/auth/cli/poll?code=${m}`);!v.ok&&v.status!==202&&(i.stop("Login failed"),u(`Server error (${v.status})`,{code:"login_failed"}));let h=await v.json();if(h.status==="complete"){Jt({...ut(),token:h.token,email:h.email,api_url:t}),i.stop(`Logged in as ${rt.default.bold(h.email)}`),d(),console.log(` ${rt.default.bold("Get one real result:")}`),I("1. Create your free inbox:","domani email create YOUR_HANDLE@domani.run"),I("2. Connect your webhook:","domani email webhook YOUR_HANDLE@domani.run --url https://YOUR_AGENT/webhook"),I("3. Prove delivery:","domani email webhook-test YOUR_HANDLE@domani.run"),console.log(` ${rt.default.dim("A custom domain can wait until this loop works.")}`),d();return}h.error&&(i.stop("Login failed"),u(h.error||h.message,{hint:h.hint,code:"login_failed"}))}i.stop("Login timed out"),u("No approval received within 10 minutes",{hint:"Run 'domani login' to try again",code:"timeout"})}mt();var on=U(L(),1);W();async function Vr(e){let t=ut();if(!t.token){e.json?k({status:"not_logged_in"}):console.log(` ${on.default.dim("Not logged in.")}`);return}let{api_url:i}=t;Zn(),i&&Jt({api_url:i}),e.json?k({status:"logged_out",email:t.email||null}):console.log(` ${y.success} Logged out${t.email?` ${on.default.dim(`(${t.email})`)}`:""}`)}X();var ai=U(L(),1);W();async function Hr(e){let[t,i]=await Promise.all([j("/api/me"),j("/api/me/activation")]),s=await t.json();t.ok||u(s.error||s.message,{hint:s.hint,status:t.status,json:e.json,fields:e.fields});let n=i.ok?await i.json():null;if(e.json){k({...s,activation:n},e.fields);return}if(C("Account"),c("Email",ai.default.bold(s.email)),c("Payment",s.has_payment_method?`${y.success} ${ai.default.green("active")}`:`${y.error} ${ai.default.dim("none")}`),c("Domains",String(s.domain_count)),c("API tokens",String(s.token_count)),c("Referral code",s.referral_code||ai.default.dim("-")),c("Created",new Date(s.created_at).toLocaleDateString()),n){c("Activation",n.status);let r=n.recommended_actions?.[0];r&&c("Next action",r.label)}d()}X();De();var T=U(L(),1);W();he();var He=10,Xt=200,zi=["com","io","ai","dev","app","co","net","org","xyz","sh","me","cc","tech","run","cloud","so","gg","fm","tv","pro","one","inc","ltd","llc","biz","group","global","ventures","capital","fund","agency","store","shop","market","sale","deals","auction","trade","studio","design","art","space","style","fashion","luxury","brand","media","digital","site","online","live","show","world","zone","land","place","city","town","blog","news","social","chat","link","page","fun","lol","meme","wtf","tools","build","works","work","team","solutions","services","systems","network","software","music","video","photo","photos","game","games","club","stream","film","movie","pizza","coffee","beer","bar","pub","restaurant","cafe","kitchen","food","wine","health","care","clinic","dental","fitness","yoga","bio","life","lifestyle","finance","money","legal","law","cash","academy","university","education","training","courses","science","wiki","guide","us","uk","eu","ca","au","de","fr","it","es","nl","jp","sg","nz","mx","house","homes","realty","estate","garden","nyc","london","berlin","paris","guru","ninja","rocks","fail","party","vip","gold","black","pink","red","events","travel","sport","jobs","careers","consulting","energy","eco","green","support","help","info","new","now","today","day"],Yi=null;async function oo(){if(Yi)return Yi;try{let e=await be("/api/tlds?sort=price&order=asc&limit=1000");if(e.ok){let i=(await e.json()).tlds.map(s=>s.tld);if(i.length>0){let s=new Set(zi),n=new Set(i),r=[...zi.filter(o=>n.has(o)),...i.filter(o=>!s.has(o))];return Yi=r,r}}}catch{}return Yi=zi,zi}async function Sd(e,t,i,s,n){let r=[],o=[],a=He,l=0,m=!0,f=0,g=0,b=!1,w=!1,v=null,h="",_=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],x=0,O=setInterval(()=>{w||!m||(x=(x+1)%_.length,E())},80);function R(){f>0&&(process.stdout.write(`\x1B[${f}A\x1B[0J`),f=0)}function M(){if(m)return[];let q=He+g*He;return r.length>a||s&&q<n.length?["more","new","skip"]:["new","skip"]}function V(){return r.slice(0,a)}function ee(){let q=M();return Math.max(0,V().length+q.length-1)}let P=6;function E(){R();let q=[],Y=V(),Q=!m&&Y.length===0&&o.length>0,G=Q?o.slice(0,P):Y,Oe=G.reduce((de,ae)=>Math.max(de,ae.domain.length),0),Be=M();for(let de=0;de<G.length;de++){let ae=G[de];if(Q)q.push(`${T.default.dim("\u2502")} ${T.default.dim("\u2715")} ${T.default.dim(ae.domain.padEnd(Oe))} ${T.default.dim("taken")}`);else{let we=de===l,lt=we?T.default.green("\u25CF"):T.default.dim("\u25CB"),te=ae.domain.padEnd(Oe),it=we?T.default.bold(T.default.cyan(te)):te,yt=ae.for_sale?T.default.cyan(`$${ae.for_sale.price} (for sale)`):T.default.dim(`$${ae.price}/yr`);q.push(`${T.default.dim("\u2502")} ${lt} ${it} ${yt}`)}}if(Q&&o.length>P&&q.push(`${T.default.dim("\u2502")} ${T.default.dim(`\u2026 and ${o.length-P} more taken`)}`),m){let de=h?T.default.dim(`checking ${h}\u2026`):T.default.dim("searching\u2026");q.push(`${T.default.dim("\u2502")} ${T.default.cyan(_[x])} ${de}`)}else{let de=He+g*He;s&&de>=n.length&&q.push(`${T.default.dim("\u2502")} ${T.default.dim(`All ${Math.min(de,n.length)} TLDs searched`)}`);for(let we=0;we<Be.length;we++){let it=V().length+we===l?T.default.green("\u25CF"):T.default.dim("\u25CB"),yt=Be[we]==="more"?T.default.dim("More \u2192"):Be[we]==="new"?T.default.dim("New search \u2192"):T.default.dim("Skip");q.push(`${T.default.dim("\u2502")} ${it} ${yt}`)}q.push(T.default.dim("\u2514"))}process.stdout.write(q.join(`
182
182
  `)+`
183
183
  `),f=q.length}process.stdout.write(`${T.default.cyan("\u25C6")} Register a domain?
184
- `),process.stdout.write("\x1B[?25l"),process.stdin.setRawMode(!0),process.stdin.resume();let N=q=>{let Y=q.toString();if(Y==="\x1B[A")l=Math.max(0,l-1),E();else if(Y==="\x1B[B")l=Math.min(ee(),l+1),E();else if(Y==="\r"){let Q=V();if(m&&Q.length===0)return;if(l<Q.length)w=Q[l]?.domain??null,v=!0;else{let Oe=M()[l-Q.length];Oe==="more"?(a+=He,r.length<a?b=!0:(l=Math.min(l,ee()),E())):(Oe==="new"&&(w="__new__"),v=!0)}}else(Y===""||Y==="\x1B")&&(v=!0)};process.stdin.on("data",N),E();async function Z(q){let Y=new TextDecoder,Q="",G="";for await(let Oe of q){if(v)break;Q+=Y.decode(Oe,{stream:!0});let Be=Q.split(`
185
- `);Q=Be.pop()??"";for(let de of Be)if(de.startsWith("event: "))G=de.slice(7);else if(de.startsWith("data: ")){let ae=JSON.parse(de.slice(6));if(G==="error"&&(process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdout.write("\x1B[?25h"),u(ae.message||ae.error||"Search failed",{code:ae.code||"error"})),G==="result"&&(h=ae.domain),G==="result"&&(ae.available||ae.for_sale||i)){if(g===0){let we=r.findIndex(lt=>lt.price>ae.price);we===-1?r.push(ae):(r.splice(we,0,ae),we<=l&&l++)}else r.push(ae);E()}else if(G==="result"&&!ae.available&&!ae.error)o.length<8&&o.push(ae);else if(G==="done"){m=!1,l=Math.min(l,ee());let we=He+g*He;r.length<a&&s&&we<n.length&&(b=!0),b||E()}}}m=!1}for(await Z(e);!v;)if(await new Promise(q=>{let Y=setInterval(()=>{(v||b)&&(clearInterval(Y),q())},16)}),b&&!v){b=!1;let q=He+g*He,Y=n.slice(q,q+He);g++,m=!0,l=Math.min(l,Math.max(0,r.length-1)),E();let Q=new URLSearchParams;Q.set("domains",Y.map(G=>`${t}.${G}`).join(","));try{let G=await be(`/api/domains/search?${Q}`,{headers:{Accept:"text/event-stream"}});G.ok&&G.body?await Z(G.body):(m=!1,E())}catch{m=!1,E()}}clearInterval(O),process.stdin.removeListener("data",N),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.pause(),process.stdout.write("\x1B[?25h"),R();let z=w==="__new__",F=z?null:w,ie=F?r.find(q=>q.domain===F)??null:null;return F?process.stdout.write(`${T.default.dim("\u25C7")} Register a domain?
184
+ `),process.stdout.write("\x1B[?25l"),process.stdin.setRawMode(!0),process.stdin.resume();let N=q=>{let Y=q.toString();if(Y==="\x1B[A")l=Math.max(0,l-1),E();else if(Y==="\x1B[B")l=Math.min(ee(),l+1),E();else if(Y==="\r"){let Q=V();if(m&&Q.length===0)return;if(l<Q.length)v=Q[l]?.domain??null,w=!0;else{let Oe=M()[l-Q.length];Oe==="more"?(a+=He,r.length<a?b=!0:(l=Math.min(l,ee()),E())):(Oe==="new"&&(v="__new__"),w=!0)}}else(Y===""||Y==="\x1B")&&(w=!0)};process.stdin.on("data",N),E();async function Z(q){let Y=new TextDecoder,Q="",G="";for await(let Oe of q){if(w)break;Q+=Y.decode(Oe,{stream:!0});let Be=Q.split(`
185
+ `);Q=Be.pop()??"";for(let de of Be)if(de.startsWith("event: "))G=de.slice(7);else if(de.startsWith("data: ")){let ae=JSON.parse(de.slice(6));if(G==="error"&&(process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdout.write("\x1B[?25h"),u(ae.message||ae.error||"Search failed",{code:ae.code||"error"})),G==="result"&&(h=ae.domain),G==="result"&&(ae.available||ae.for_sale||i)){if(g===0){let we=r.findIndex(lt=>lt.price>ae.price);we===-1?r.push(ae):(r.splice(we,0,ae),we<=l&&l++)}else r.push(ae);E()}else if(G==="result"&&!ae.available&&!ae.error)o.length<8&&o.push(ae);else if(G==="done"){m=!1,l=Math.min(l,ee());let we=He+g*He;r.length<a&&s&&we<n.length&&(b=!0),b||E()}}}m=!1}for(await Z(e);!w;)if(await new Promise(q=>{let Y=setInterval(()=>{(w||b)&&(clearInterval(Y),q())},16)}),b&&!w){b=!1;let q=He+g*He,Y=n.slice(q,q+He);g++,m=!0,l=Math.min(l,Math.max(0,r.length-1)),E();let Q=new URLSearchParams;Q.set("domains",Y.map(G=>`${t}.${G}`).join(","));try{let G=await be(`/api/domains/search?${Q}`,{headers:{Accept:"text/event-stream"}});G.ok&&G.body?await Z(G.body):(m=!1,E())}catch{m=!1,E()}}clearInterval(O),process.stdin.removeListener("data",N),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.pause(),process.stdout.write("\x1B[?25h"),R();let z=v==="__new__",F=z?null:v,ie=F?r.find(q=>q.domain===F)??null:null;return F?process.stdout.write(`${T.default.dim("\u25C7")} Register a domain?
186
186
  ${T.default.dim("\u2502")} ${T.default.bold(T.default.cyan(F))}
187
187
  ${T.default.dim("\u2514")}
188
188
  `):process.stdout.write(`${T.default.dim("\u2514")}
189
- `),{chosen:F,chosenResult:ie,searchAgain:z,allTaken:r.length===0&&o.length>0,expanded:g>0}}async function ao(e,t,i){if(!e){je||u("Missing required argument: domain",{hint:"Usage: domani search <domain> [tlds...]",code:"missing_argument",json:i.json});let N=await Ae({message:"Search for a domain",placeholder:"e.g. myapp or myapp.dev"});(le(N)||!N)&&process.exit(0),e=N}let s=t.map(N=>N.replace(/^\./,"")),n=i.tlds?.split(",").map(N=>N.trim())||[],r=[...new Set([...s,...n])];if(r.length>0&&Hi(r,i),K(e,i),e.includes(".")&&r.length===0){let N=S(!i.json);N.start(`Checking ${$.domain(e)}`);let[Z,z]=await Promise.all([be(`/api/domains/search?q=${encodeURIComponent(e)}`),be(`/api/domains/${encodeURIComponent(e)}/og`).catch(()=>null)]),F=await Z.json();if(Z.ok||(N.stop("Search failed"),u(F.error||F.message,{hint:F.hint,status:Z.status,json:i.json,fields:i.fields})),i.json){let ie=F.domain.split(".")[0];k({name:ie,results:[F],total:1,available:F.available?1:0},i.fields);return}if(F.available)if(N.stop(`${y.success} ${$.domain(F.domain)} ${y.dot} available ${y.dot} ${$.price(F.price)}/yr`),je&&!i.json){let{buy:ie}=await Promise.resolve().then(()=>(Yt(),di));await ie([F.domain],{preChecked:{price:F.price,currency:F.currency}})}else d(),I("Register it:",`domani buy ${F.domain}`),d();else if(F.for_sale?.buyable)if(N.stop(`${y.info} ${$.domain(F.domain)} ${y.dot} ${T.default.cyan("for sale")} ${y.dot} ${$.price(F.for_sale.price)}`),je&&!i.json){let{buy:ie}=await Promise.resolve().then(()=>(Yt(),di));await ie([F.domain],{preChecked:{price:F.for_sale.price,currency:F.for_sale.currency,marketplace:!0}})}else d(),I("Buy it:",`domani buy ${F.domain}`),d();else if(F.error)N.stop(`${T.default.dim("?")} ${$.domain(F.domain)} ${y.dot} ${T.default.dim("lookup failed")}`);else{let ie;try{if(z?.ok){let Y=await z.json();Y?.title&&(ie=Y.title)}}catch{}let q=ie?` ${y.dot} ${T.default.dim(`"${ie}"`)}`:"";N.stop(`${y.error} ${$.domain(F.domain)} ${y.dot} ${T.default.red("taken")}${q}`)}return}let o=e.split(".")[0];if(je&&!i.json&&r.length>0){let N=new URLSearchParams;N.set("domains",r.map(te=>`${o}.${te}`).join(",")),i.maxPrice&&N.set("max_price",i.maxPrice);let Z=await be(`/api/domains/search?${N}`,{headers:{Accept:"text/event-stream"}});if(!Z.ok||!Z.body){u("Search failed",{json:i.json});return}let z=[],F=new TextDecoder,ie="",q="",Y=S(!0);Y.start(`Checking ${r.length} TLD${r.length>1?"s":""}`);for await(let te of Z.body){ie+=F.decode(te,{stream:!0});let it=ie.split(`
190
- `);ie=it.pop()??"";for(let yt of it)yt.startsWith("event: ")?q=yt.slice(7):yt.startsWith("data: ")&&q==="result"&&z.push(JSON.parse(yt.slice(6)))}Y.stop("");let Q=Math.max(...r.map(te=>`${o}.${te}`.length))+2,G=z.filter(te=>te.available),Oe=z.filter(te=>!te.available&&!te.error),Be=z.filter(te=>!te.available&&te.for_sale);for(let te of[...G,...Be,...Oe.filter(it=>!it.for_sale)])te.available?console.log(` ${T.default.green("\u2713")} ${T.default.bold(T.default.white(te.domain.padEnd(Q)))} ${T.default.green($.price(te.price)+"/yr")}`):te.for_sale?console.log(` ${T.default.cyan("$")} ${T.default.bold(T.default.white(te.domain.padEnd(Q)))} ${T.default.cyan($.price(te.for_sale.price))} ${T.default.dim("(for sale)")}`):console.log(` ${T.default.dim("\u2717")} ${T.default.dim(te.domain.padEnd(Q))} ${T.default.dim("taken")}`);if(G.length===0){console.log(` ${T.default.dim("No domains available")}`),d();return}let{buy:de}=await Promise.resolve().then(()=>(Yt(),di));if(G.length===1){await de([G[0].domain],{preChecked:{price:G[0].price,currency:G[0].currency}});return}let{select:ae,isCancel:we}=await Promise.resolve().then(()=>(De(),Qs)),lt=await ae({message:"Register one?",options:[...G.map(te=>({value:te.domain,label:$.domain(te.domain),hint:$.price(te.price)+"/yr"})),{value:"__skip__",label:"Skip"}]});if(!we(lt)&&lt!=="__skip__"){d();let te=G.find(it=>it.domain===lt);await de([lt],{preChecked:te?{price:te.price,currency:te.currency}:void 0})}else d();return}if(je&&!i.json){let N=await oo();for(i.expand&&N.length>Xt&&console.error(T.default.dim(` (--expand: checking the first ${Xt} of ${N.length} TLDs - server limit per request)`));;){let Z=i.expand?N.slice(0,Xt):N.slice(0,He),z=new URLSearchParams;z.set("domains",Z.map(ae=>`${o}.${ae}`).join(",")),i.maxPrice&&z.set("max_price",i.maxPrice);let F=S(!0);F.start(`Searching available domains for ${T.default.bold(o)}`);let ie=await be(`/api/domains/search?${z}`,{headers:{Accept:"text/event-stream"}});if(!ie.ok||!ie.body){F.stop("Search failed");break}F.stop("");let q=!i.expand,{chosen:Y,chosenResult:Q,searchAgain:G}=await Sd(ie.body,o,i.all??!1,q,N);if(Y){d();let{buy:ae}=await Promise.resolve().then(()=>(Yt(),di)),we=Q?{price:Q.price,currency:Q.currency}:void 0;await ae([Y],{preChecked:we});return}if(!G)break;let{text:Oe,isCancel:Be}=await Promise.resolve().then(()=>(De(),Qs)),de=await Oe({message:"Search for a domain",placeholder:"e.g. myapp or myapp.dev"});if(Be(de)||!de)break;o=de.split(".")[0]}d();return}let a=o,l=await oo(),m=r.length>0?r:i.expand?l.slice(0,Xt):l.slice(0,He);i.expand&&r.length===0&&l.length>Xt&&console.error(`(--expand: checking the first ${Xt} of ${l.length} TLDs - server limit per request; use --tlds to target others)`);let f=m.map(N=>`${a}.${N}`),g=new URLSearchParams;g.set("domains",f.join(",")),i.maxPrice&&g.set("max_price",i.maxPrice);let b=S(!i.json);b.start(`Searching available domains for ${T.default.bold(a)}`);let v=await be(`/api/domains/search?${g}`,{headers:{Accept:"text/event-stream"}});if(!v.ok){b.stop("Search failed");try{let N=await v.json();u(N.error||N.message||`Server error (${v.status})`,{hint:N.hint,status:v.status,json:i.json,fields:i.fields})}catch{u(`Server error (${v.status})`,{status:v.status,json:i.json,fields:i.fields})}}let w=v.body;w||(b.stop("Search failed"),u("Empty response",{code:"error",json:i.json,fields:i.fields}));let h=[],_=!1,j=0,O=i.all??!1;function R(){_||(_=!0,b.stop(`Checking TLDs for ${T.default.bold(a)}`),d())}function M(N){R(),N.available?console.log(` ${y.success} ${$.domain(N.domain).padEnd(37)} ${$.price(N.price)}${T.default.dim("/yr")}`):N.for_sale?console.log(` ${y.info} ${$.domain(N.domain).padEnd(37)} ${T.default.cyan($.price(N.for_sale.price))} ${T.default.dim("(for sale)")}`):N.error||console.log(` ${y.error} ${T.default.dim(N.domain.padEnd(38))} ${T.default.red("taken")}`)}function V(){_||b.message(`Checking TLDs for ${T.default.bold(a)} ${T.default.dim(`(${j} checked)`)}`)}let ee=new TextDecoder,P="",E="";for await(let N of w){P+=ee.decode(N,{stream:!0});let Z=P.split(`
191
- `);P=Z.pop()??"";for(let z of Z)if(z.startsWith("event: "))E=z.slice(7);else if(z.startsWith("data: ")){let F=JSON.parse(z.slice(6));if(E==="error")b.stop("Search failed"),u(F.message||F.error||"Search failed",{code:F.code||"error",json:i.json,fields:i.fields});else if(E==="result")j++,F.available||F.for_sale||O?(i.json||M(F),h.push(F)):i.json||V();else if(E==="done"){if(i.json){h.sort((Q,G)=>Q.price-G.price),k({name:a,results:h,total:F.total,available:F.available},i.fields);return}_&&console.log(` ${T.default.dim("\u2500".repeat(50))}`);let ie=F.total-F.available,q=F.total>=5&&ie/F.total>=.5,Y=`Checked ${F.total} TLDs \xB7 ${F.available} available${q?" \xB7 popular name":""}`;console.log(` ${T.default.dim(Y)}`),F.available===0&&!i.expand&&r.length===0&&(d(),I("Try more TLDs:",`domani search ${a} --expand`))}}}d()}Yt();X();var ci=U(L(),1);W();he();Ji();function lo(e,t,i=process.env){let s=Tt(t,i);if(s!==void 0&&!e)throw new Error("--webhook is required when setting webhook authentication");return{request:{...e?{webhook_url:e}:{},...s!==void 0?{webhook_headers:s}:{}},preview:{...e?{webhook_url:e}:{},...s!==void 0?{webhook_header_names:Nt(s)}:{}}}}async function co(e,t){K(e,t);let i={domain:e};t.slug&&(i.slug=t.slug),t.name&&(i.name=t.name);let s;try{s=lo(t.webhook,t)}catch(a){u(a instanceof Error?a.message:"Invalid webhook headers",{hint:"Set the named environment variable and retry.",code:"validation_error",json:t.json,fields:t.fields})}if(Object.assign(i,s.request),t.years&&(i.years=Number(t.years)),t.paymentMethod&&(i.payment_method=t.paymentMethod),t.dryRun){let a={...i};delete a.webhook_headers,Object.assign(a,s.preview),B("POST /api/agents/provision",a,t.json,t.fields);return}let n=S(!t.json);n.start(`Provisioning ${$.domain(e)}`);let r=await x("/api/agents/provision",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)}),o=await r.json();if(r.ok||(n.stop("Provisioning failed"),u(o.error||"Provisioning failed",{hint:o.hint,status:r.status,json:t.json,fields:t.fields})),n.stop(`${$.domain(e)} is ready`),t.json){k(o,t.fields);return}if(d(),C("Agent identity"),c("Domain",`${o.domain} (${o.domain_status})`),c("Mailbox",o.mailbox?ci.default.green(o.mailbox.address):ci.default.yellow("pending DNS")),c("Webhook",o.webhook?o.webhook.url:ci.default.dim("none")),o.webhook?.header_names.length&&c("Webhook auth",o.webhook.header_names.join(", ")),o.webhook?.secret&&c("Signing secret",o.webhook.secret),o.warnings?.length){d();for(let a of o.warnings)ze(ci.default.yellow(a))}if(o.next_steps?.length){d(),C("Next");for(let a of o.next_steps)ze(a)}d()}X();var ht=U(L(),1);W();async function uo(e){let t=S(!e.json);t.start("Loading domains");let i=await x("/api/domains"),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),t.stop(`${s.domains.length} domain(s)`),e.json){k({...s,count:s.domains.length},e.fields);return}if(s.domains.length===0){d(),console.log(` ${ht.default.dim("No domains yet.")} Use: ${ht.default.cyan("domani buy <domain>")}`),d();return}let n=[30,12,12,14];C(`Your Domains (${s.domains.length})`,n.reduce((o,a)=>o+a,0)+n.length-1);let r=s.domains.map(o=>{let a=new Date(o.expiresAt).toLocaleDateString(),l=o.status==="active"?ht.default.green:o.status==="pending"?ht.default.yellow:ht.default.red,m=o.autoRenew?ht.default.green("on"):ht.default.dim("off");return[$.domain(o.domain),l(o.status),m,ht.default.dim(a)]});se(["Domain","Status","Auto-renew","Expires"],r,n),d()}hn();X();var Ut=U(L(),1);W();async function mo(e){let t=new URLSearchParams;e.maxPrice&&t.set("max_price",e.maxPrice),e.minPrice&&t.set("min_price",e.minPrice),e.sort&&t.set("sort",e.sort),e.search&&t.set("search",e.search),e.limit&&t.set("limit",e.limit),t.set("order","asc");let i=S(!e.json);i.start("Loading TLDs");let s=await be(`/api/tlds?${t}`),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields})),i.stop(`${n.total} TLDs loaded`),e.json){k(n,e.fields);return}let r=n.tlds;if(r.length===0){d(),console.log(` ${Ut.default.dim("No TLDs match your filters.")}`),d();return}C("TLD Pricing");let o=r.map(a=>[Ut.default.bold(`.${a.tld}`),$.price(a.registration.toFixed(2))+Ut.default.dim("/yr"),Ut.default.dim("renew ")+$.price(a.renewal.toFixed(2))+Ut.default.dim("/yr")]);se(["TLD","Register","Renewal"],o,[22,16,20]),d(),console.log(` ${Ut.default.dim(`${n.total} TLDs total`)}`),d()}X();var Se=U(L(),1);W();he();async function fo(e,t){K(e,t);let i=S(!t.json);i.start(`Looking up ${$.domain(e)}`);let[s,n]=await Promise.all([be(`/api/domains/whois?q=${encodeURIComponent(e)}`),be(`/api/domains/${encodeURIComponent(e)}/og`).catch(()=>null)]),r=await s.json(),o=null;try{n?.ok&&(o=await n.json())}catch{}if(s.ok||(i.stop("Lookup failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:t.json,fields:t.fields})),i.stop("WHOIS data retrieved"),t.json){k({...r,...o?{og:o}:{}},t.fields);return}if(C(`WHOIS ${$.domain(r.domain)}`),!r.registered){c("Status",`${y.success} ${Se.default.green("not registered")}`),d(),I("Register it:",`domani buy ${r.domain}`),d();return}if(c("Status",`${y.error} ${Se.default.red("registered")}`),(o?.title||o?.description)&&(d(),console.log(` ${Se.default.bold("Website preview")}`),console.log(` ${Se.default.dim("\u2500".repeat(50))}`),o.title&&c("Title",o.title),o.description&&c("Description",Se.default.dim(o.description.length>80?o.description.slice(0,80)+"\u2026":o.description)),d()),r.registrar&&c("Registrar",r.registrar),r.created&&c("Created",r.created),r.expires&&c("Expires",r.expires),r.days_until_expiry!=null){let l=r.days_until_expiry,m=l<30?Se.default.red:l<90?Se.default.yellow:Se.default.green;c("Days left",m(String(l)))}r.updated&&c("Updated",r.updated),c("DNSSEC",r.dnssec?Se.default.green("yes"):Se.default.dim("no")),r.nameservers?.length>0&&c("Nameservers",r.nameservers.map(l=>Se.default.cyan(l)).join(Se.default.dim(", "))),r.status?.length>0&&c("Status codes",Se.default.dim(r.status.join(", ")));let a=r.contacts?.registrant;a&&!r.redacted?(d(),console.log(` ${Se.default.bold("Registrant")}`),console.log(` ${Se.default.dim("\u2500".repeat(50))}`),a.name&&c("Name",a.name),a.organization&&c("Organization",a.organization),a.email&&c("Email",$.url(a.email)),a.country&&c("Country",a.country)):r.redacted&&c("Contact",Se.default.dim("redacted (WHOIS privacy)")),d()}X();De();var gt=U(L(),1);W();he();async function po(e,t){if(!e){je||u("Missing required argument: prompt",{hint:'Usage: domani suggest "describe your project"',code:"missing_argument",json:t.json});let h=await Ae({message:"Describe your project or idea",placeholder:"e.g. AI coding assistant, pet food delivery..."});(le(h)||!h)&&process.exit(0),e=h}let i=new URLSearchParams({prompt:e});if(t.count&&i.set("count",t.count),t.tlds&&i.set("tlds",t.tlds),t.tlds&&Hi(t.tlds.split(",").map(h=>h.trim()),t),t.style&&i.set("style",t.style),t.lang&&i.set("lang",t.lang),t.json){let h=S(!1);h.start("Finding available domains");let _=t.timeout?parseInt(t.timeout,10)*1e3:6e4,j;try{j=await be(`/api/domains/suggest?${i}`,{signal:AbortSignal.timeout(_)})}catch{h.stop("Failed"),u("Request timed out",{hint:"Suggest took too long. Try --timeout <seconds> to increase.",code:"timeout",json:t.json,fields:t.fields})}let O=await j.json();j.ok||(h.stop("Failed"),u(O.error||O.message,{hint:O.hint,status:j.status,json:t.json,fields:t.fields})),k(O,t.fields);return}let s=S(!0);s.start("Finding available domains");let n=t.timeout?parseInt(t.timeout,10)*1e3:6e4,r;try{r=await be(`/api/domains/suggest?${i}`,{headers:{Accept:"text/event-stream"},signal:AbortSignal.timeout(n)})}catch{s.stop("Failed"),u("Request timed out",{hint:"Suggest took too long. Try --timeout <seconds> to increase.",code:"timeout"})}if(!r.ok){s.stop("Failed");try{let h=await r.json();u(h.error||h.message||`Server error (${r.status})`,{hint:h.hint,status:r.status})}catch{u(`Server error (${r.status})`,{status:r.status})}}let o=r.body;o||(s.stop("Failed"),u("Empty response"));let a=[],l=[],m=!1,f=0;function g(){m||(m=!0,s.stop("Finding available domains"),d())}let b=new TextDecoder,v="",w="";for await(let h of o){v+=b.decode(h,{stream:!0});let _=v.split(`
192
- `);v=_.pop()??"";for(let j of _)if(j.startsWith("event: "))w=j.slice(7);else if(j.startsWith("data: "))try{let O=JSON.parse(j.slice(6));if(w==="result")f++,O.available?a.push(O):l.push(O),m||s.message(`Finding available domains ${gt.default.dim(`(${f} checked, ${a.length} available)`)}`);else if(w==="iteration")m||s.message(`Finding available domains ${gt.default.dim(`(round ${O.n})`)}`);else if(w==="done"){g();for(let R of a){let M=R.reason?` ${gt.default.dim(R.reason)}`:"";console.log(` ${y.success} ${$.domain(R.domain).padEnd(37)} ${$.price(R.price)}${gt.default.dim("/yr")}${M}`)}for(let R of l)console.log(` ${y.error} ${gt.default.dim(R.domain.padEnd(38))} ${gt.default.red("taken")}`);console.log(` ${gt.default.dim("\u2500".repeat(50))}`),console.log(` ${gt.default.dim(`Found ${O.total} available \xB7 checked ${O.checked} \xB7 ${O.iterations} round${O.iterations>1?"s":""}`)}`)}else w==="error"&&(m||s.stop("Failed"),u(O.message))}catch{}}a.length===0&&l.length===0&&(m||s.stop("No results"),u("Could not find available domains for this prompt.")),d(),a.length>0&&(I("Register one:",`domani buy ${a[0].domain}`),d())}dn();bn();X();De();var Ft=U(L(),1);W();he();ei();async function ho(e,t){K(e,t);let i=S(!t.json);i.start(`Planning safe adoption for ${$.domain(e)}`);let s=await x(`/api/domains/adoption-plan?domain=${encodeURIComponent(e)}`),n=await s.json();if(s.ok||(i.stop("Check failed"),u(n.error,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),n.options?.transfer?.eligible||(i.stop(`${y.error} Not eligible`),u(n.options?.transfer?.reason||"Domain is not eligible for transfer.",{hint:n.warnings?.join(" "),code:"not_eligible",json:t.json,fields:t.fields})),i.stop(`${y.success} Eligible for transfer`),t.dryRun)return B("transfer",{domain:e,eligible:!0,price:n.options.transfer.price,currency:n.options.transfer.currency||"USD",includes_renewal:!0,preserves_nameservers:!0,migrates_dns:!1,nameservers:n.current.nameservers,dns_provider:n.current.dns_provider,dnssec_enabled:n.current.dnssec_enabled},t.json,t.fields);if(!Et(t)){C("Transfer Safety Plan"),c("Registrar",n.current.registrar||"Unknown"),c("DNS provider",n.current.dns_provider),c("Nameservers",`${n.current.nameservers.length} preserved`),c("DNSSEC",n.current.dnssec_enabled?Ft.default.yellow("Enabled, DS will be verified"):"Not enabled"),c("DNS migration","Not requested"),d();let a=n.options.transfer.price!=null?` for ${$.price(n.options.transfer.price.toFixed(2))}`:"",l=await Ke({message:`Transfer ${Ft.default.bold(e)} to ${Lt}${a}? Nameservers stay unchanged and 1 year is included.`});if(!l||typeof l=="symbol"){console.log(` ${Ft.default.dim("Cancelled.")}`);return}}if(!t.authCode){(t.json||!process.stdout.isTTY)&&u("--auth-code is required",{hint:"The safety plan passed. Get the EPP/auth code from the current registrar and retry.",code:"validation_error",json:t.json,fields:t.fields});let a=await Ae({message:"Enter the EPP/auth code from your current registrar:",validate:l=>!l||l.trim().length===0?"Auth code is required":void 0});le(a)&&process.exit(0),t.authCode=a}i.start(`Initiating transfer for ${$.domain(e)}`);let r=await x("/api/domains/transfer",{method:"POST",body:JSON.stringify({domain:e,auth_code:t.authCode})}),o=await r.json();if(r.ok||(i.stop("Transfer failed"),u(o.error||o.message,{hint:o.hint,fixUrl:o.setup_url||o.payment_options?.card?.setup_url,status:r.status,json:t.json,fields:t.fields})),i.stop(`${y.success} Transfer initiated`),t.json){k(o,t.fields);return}C("Transfer Initiated"),c("Domain",$.domain(o.domain)),c("Status",Ft.default.yellow(o.status||"pending")),o.price&&c("Price",$.price(o.price)+Ft.default.dim(` ${o.currency||"USD"}`)),o.payment_method&&c("Payment",o.payment_method),o.expires&&c("Expires",new Date(o.expires).toLocaleDateString()),o.hint&&(d(),console.log(` ${Ft.default.dim(o.hint)}`)),d(),I("Check transfer progress:",`domani status ${o.domain}`),d()}X();var Xi=U(L(),1);W();he();async function go(e,t){K(e,t);let i=S(!t.json);i.start(`Inspecting ${$.domain(e)}`);let s=await x(`/api/domains/adoption-plan?domain=${encodeURIComponent(e)}`),n=await s.json();if(s.ok||(i.stop("Inspection failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),i.stop(`${y.success} Adoption plan ready`),t.json){k(n,t.fields);return}if(C(`Adopt ${$.domain(n.domain)}`),c("Registrar",n.current.registrar||"Unknown"),c("DNS provider",n.current.dns_provider),c("Nameservers",n.current.nameservers.join(", ")||"None detected"),c("DNSSEC",n.current.dnssec_enabled?Xi.default.yellow("Enabled"):"Not enabled"),c("Account",n.account_state),c("Recommended",Xi.default.cyan(n.recommended_action)),d(),n.recommended_action==="connect"&&I("Connect free, without changing registrar or DNS:",`domani import ${n.domain}`),n.options.transfer.available){let r=n.options.transfer.price==null?"price unavailable":`$${n.options.transfer.price.toFixed(2)} ${n.options.transfer.currency}`;I(`Transfer registration for ${r}, preserving nameservers:`,`domani transfer ${n.domain}`)}for(let r of n.warnings||[])console.log(` ${Xi.default.yellow("!")} ${r}`);d()}X();De();var Zi=U(L(),1);W();he();Ye();async function bo(e,t){e||(e=await fe()),K(e,t);let i=t.years?parseInt(t.years,10):1;if((isNaN(i)||i<1||i>10)&&u("--years must be between 1 and 10",{code:"validation_error",json:t.json,fields:t.fields}),t.dryRun)return B("renew",{domain:e,years:i},t.json,t.fields);if(!Et(t)){let o=await Ke({message:`Renew ${Zi.default.bold(e)} for ${i} year${i>1?"s":""}? You will be charged.`});if(!o||typeof o=="symbol"){console.log(` ${Zi.default.dim("Cancelled.")}`);return}}let s=S(!t.json);s.start(`Renewing ${$.domain(e)}`);let n=await x(`/api/domains/${encodeURIComponent(e)}/renew`,{method:"POST",body:JSON.stringify({years:i})}),r=await n.json();if(n.ok||(s.stop("Renewal failed"),u(r.error||r.message,{hint:r.hint,fixUrl:r.setup_url||r.payment_options?.card?.setup_url,status:n.status,json:t.json,fields:t.fields})),s.stop(`${y.success} Domain renewed`),t.json){k(r,t.fields);return}C("Renewal Complete"),c("Domain",$.domain(r.domain)),c("Years",String(r.renewed_years)),c("New expiry",new Date(r.new_expiry).toLocaleDateString()),r.price&&c("Price",$.price(r.price)+Zi.default.dim(` ${r.currency||"USD"}`)),r.payment_method&&c("Payment",r.payment_method),d(),I("Verify renewal:",`domani status ${r.domain}`),d()}X();var ot=U(L(),1);W();he();async function yo(e,t){e||u("Domain is required",{hint:`Usage: domani import <domain>
193
- domani import <domain> --verify`,code:"validation_error",json:t.json,fields:t.fields}),K(e,t);let i=t.verify?"/api/domains/import/verify":"/api/domains/import",s=S(!t.json);s.start(t.verify?`Verifying ownership of ${$.domain(e)}`:`Initiating import for ${$.domain(e)}`);let n=await x(i,{method:"POST",body:JSON.stringify({domain:e})}),r=await n.json();if(n.ok||(s.stop(t.verify?"Verification failed":"Import failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:t.json,fields:t.fields})),t.json){s.stop(""),k(r,t.fields);return}t.verify?(s.stop(`${y.success} ${$.domain(e)} imported!`),C("Domain Imported"),c("Domain",$.domain(r.domain)),c("Status",ot.default.green(r.status||"active")),r.expires_at&&c("Expires",new Date(r.expires_at).toLocaleDateString()),r.registrar&&c("Registrar",r.registrar),d(),I("Check domain health:",`domani status ${r.domain}`),d()):(s.stop(`${y.success} Verification record ready`),C("Import Domain"),c("Domain",$.domain(r.domain)),c("Status",ot.default.yellow("pending verification")),d(),console.log(" Add this TXT record at your DNS provider:"),d(),console.log(` ${ot.default.dim("Type:")} ${ot.default.bold("TXT")}`),console.log(` ${ot.default.dim("Name:")} ${ot.default.bold(r.txt_record?.name||"@")}`),console.log(` ${ot.default.dim("Value:")} ${ot.default.bold(r.txt_record?.value||`domani-verify=${r.token}`)}`),d(),console.log(` ${ot.default.dim("DNS propagation may take a few minutes to 48 hours.")}`),d(),I("Once the record is set, verify:",`domani import ${e} --verify`),d())}mn();mt();W();function $o(e){let t=Me();if(t||(d(),u("Not logged in",{hint:"Run 'domani login' first",code:"auth_required",json:e.json})),!e.reveal&&!e.json&&process.stdout.isTTY){let i=`${t.slice(0,12)}...${t.slice(-4)}`;console.log(i),console.log("Run 'domani token --reveal' to print the full key.");return}e.json?k({token:t}):console.log(t)}X();var Ne=U(L(),1);W();async function vo(e,t){switch(e){case void 0:case"list":return Cd(t.json,t.fields);case"create":return Od(t);case"revoke":return Id(t);default:u(`Unknown action: ${e}`,{hint:"Actions: list, create, revoke",code:"validation_error",json:t.json,fields:t.fields})}}async function Cd(e,t){let i=S(!e);i.start("Loading tokens");let s=await x("/api/tokens"),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e,fields:t})),i.stop(`${y.success} ${n.tokens.length} token(s)`),e){k(n,t);return}if(n.tokens.length===0){d(),console.log(` ${Ne.default.dim("No tokens.")}`),d(),I("Create one:",'domani tokens create --name "My App"'),d();return}d(),C("API Tokens");let r=n.tokens.map(o=>{let a;o.expired?a=Ne.default.red("Expired"):o.expiresAt?a=Ne.default.dim(`Expires ${new Date(o.expiresAt).toLocaleDateString()}`):a=Ne.default.dim("No expiration");let l=o.scopes.includes("*")?Ne.default.dim("all"):Ne.default.dim(o.scopes.join(", "));return[Ne.default.dim(o.id),Ne.default.bold(o.name),o.agent_identity?Ne.default.dim(o.agent_identity.name||o.agent_identity.slug):Ne.default.dim("\u2014"),l,a]});se(["ID","Name","Agent","Scopes","Expiration"],r,[28,16,18,32,20]),d()}async function Od(e){let t={};if(e.name&&(t.name=e.name),e.scopes&&(t.scopes=e.scopes.split(",").map(r=>r.trim())),e.expiresIn){let r=Number(e.expiresIn);(isNaN(r)||r<3600||r>31536e3)&&u("Invalid --expires-in value",{hint:"Must be between 3600 (1 hour) and 31536000 (1 year) seconds",code:"validation_error",json:e.json,fields:e.fields}),t.expires_in=r}e.agentIdentity&&(t.agent_identity_id=e.agentIdentity);let i=S(!e.json);i.start("Creating token");let s=await x("/api/tokens",{method:"POST",body:JSON.stringify(t)}),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields})),i.stop(`${y.success} Token created`),e.json){k(n,e.fields);return}d(),C("Token Created"),c("ID",n.id),c("Name",n.name),c("Scopes",n.scopes?.includes("*")?"All (full access)":n.scopes?.join(", ")||"All"),n.agent_identity&&c("Agent",n.agent_identity.name||n.agent_identity.slug),c("Expires",n.expiresAt?new Date(n.expiresAt).toLocaleString():"Never"),d(),console.log(` ${Ne.default.yellow("!")} ${Ne.default.bold("Key:")} ${n.key}`),console.log(` ${Ne.default.dim("Save this key - it will not be shown again.")}`),d()}async function Id(e){e.tokenId||u("Token ID required",{hint:`Usage: domani tokens revoke --token-id <id>
194
- Run 'domani tokens list' to see your tokens.`,code:"validation_error",json:e.json,fields:e.fields});let t=S(!e.json);t.start("Revoking token");let i=await x(`/api/tokens/${encodeURIComponent(e.tokenId)}`,{method:"DELETE"}),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),t.stop(`${y.success} Token revoked`),e.json){k(s,e.fields);return}console.log(` ${Ne.default.dim("Any applications using this key will need a new one.")}`),d()}X();var Ce=U(L(),1);W();he();Ye();async function wo(e,t){e||(e=await fe()),K(e,t);let i=t.autoRenew!==void 0,s=t.whoisPrivacy!==void 0,n=t.securityLock!==void 0;if(!i&&!s&&!n)return Rd(e,t.json,t.fields);let r={};if(i){let m=vn(t.autoRenew);m===null&&u("--auto-renew must be on or off",{code:"validation_error",json:t.json,fields:t.fields}),r.auto_renew=m}if(s){let m=vn(t.whoisPrivacy);m===null&&u("--whois-privacy must be on or off",{code:"validation_error",json:t.json,fields:t.fields}),r.whois_privacy=m}if(n){let m=vn(t.securityLock);m===null&&u("--security-lock must be on or off",{code:"validation_error",json:t.json,fields:t.fields}),r.security_lock=m}if(t.dryRun)return B("settings_update",{domain:e,...r},t.json,t.fields);let o=S(!t.json);o.start(`Updating ${$.domain(e)}`);let a=await x(`/api/domains/${encodeURIComponent(e)}/settings`,{method:"PUT",body:JSON.stringify(r)}),l=await a.json();if(a.ok||(o.stop("Failed"),u(l.error||l.message,{hint:l.hint,status:a.status,json:t.json,fields:t.fields})),o.stop(`${y.success} Settings updated`),t.json){k(l,t.fields);return}C("Settings Updated"),c("Domain",$.domain(l.domain)),l.auto_renew!==void 0&&c("Auto-renew",l.auto_renew?Ce.default.green("on"):Ce.default.dim("off")),l.whois_privacy!==void 0&&c("WHOIS privacy",l.whois_privacy?Ce.default.green("on"):Ce.default.dim("off")),l.security_lock!==void 0&&c("Security lock",l.security_lock?Ce.default.green("locked"):Ce.default.dim("unlocked")),l.hint&&c("",Ce.default.dim(l.hint)),d()}async function Rd(e,t,i){let s=S(!t);s.start(`Loading ${$.domain(e)}`);let n=await x(`/api/domains/${encodeURIComponent(e)}`),r=await n.json();if(n.ok||(s.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:t,fields:i})),s.stop(`${y.success} ${$.domain(e)}`),t){k(r,i);return}C("Domain Settings"),c("Domain",$.domain(r.domain)),c("Status",r.status==="active"?Ce.default.green(r.status):Ce.default.yellow(r.status)),c("Auto-renew",r.auto_renew?Ce.default.green("on"):Ce.default.dim("off")),r.registrar&&(c("WHOIS privacy",r.registrar.whois_privacy?Ce.default.green("on"):Ce.default.dim("off")),c("Security lock",r.registrar.security_lock?Ce.default.green("locked"):Ce.default.dim("unlocked"))),c("Expires",new Date(r.expires_at).toLocaleDateString()+Ce.default.dim(` (${r.days_until_expiry} days)`)),d(),I("Toggle auto-renew:",`domani settings ${e} --auto-renew off`),I("Toggle WHOIS privacy:",`domani settings ${e} --whois-privacy off`),I("Toggle security lock:",`domani settings ${e} --security-lock off`),I("Get transfer auth code:",`domani auth-code ${e}`),d()}function vn(e){let t=e.toLowerCase();return t==="on"||t==="true"||t==="1"||t==="enable"?!0:t==="off"||t==="false"||t==="0"||t==="disable"?!1:null}X();var qt=U(L(),1);W();he();Ye();async function ko(e,t){e||(e=await fe()),K(e,t);let i=S(!t.json);i.start(`Getting auth code for ${$.domain(e)}`);let s=await x(`/api/domains/${encodeURIComponent(e)}/auth-code`),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),i.stop(`${y.success} Auth code retrieved`),t.json){k(n,t.fields);return}if(C("Auth Code"),c("Domain",$.domain(n.domain)),c("Auth code",qt.default.bold(qt.default.green(n.auth_code))),n.was_unlocked&&c("",qt.default.yellow("Domain was automatically unlocked to allow transfer.")),n.hint&&(d(),console.log(` ${qt.default.dim(n.hint)}`)),n.next_steps?.length){d();for(let r of n.next_steps)console.log(` ${qt.default.dim("\u2192")} ${qt.default.dim(r)}`)}d(),I("Check transfer status:",`domani transfer-away ${e}`),I("Re-lock domain:",`domani settings ${e} --security-lock on`),d()}X();var bt=U(L(),1);W();he();Ye();var Ad={none:bt.default.dim,pending:bt.default.yellow,approved:bt.default.yellow,completed:bt.default.green,rejected:bt.default.red,expired:bt.default.red};async function _o(e,t){e||(e=await fe()),K(e,t);let i=S(!t.json);i.start(`Checking transfer status for ${$.domain(e)}`);let s=await x(`/api/domains/${encodeURIComponent(e)}/transfer-away`),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),i.stop(`${y.success} ${$.domain(e)}`),t.json){k(n,t.fields);return}C("Transfer Away Status"),c("Domain",$.domain(n.domain));let r=Ad[n.status]||bt.default.dim;c("Status",r(n.status)),n.gaining_registrar&&c("New registrar",n.gaining_registrar),n.request_date&&c("Requested",new Date(n.request_date).toLocaleDateString()),n.hint&&(d(),console.log(` ${bt.default.dim(n.hint)}`)),d(),n.status==="none"?I("Get auth code to start:",`domani auth-code ${e}`):n.status==="pending"||n.status==="approved"?I("Check again later:",`domani transfer-away ${e}`):n.status==="completed"?I("Search for a new domain:","domani search <name>"):(n.status==="rejected"||n.status==="expired")&&I("Retry with a new auth code:",`domani auth-code ${e}`),d()}X();De();var Qi=U(L(),1);W();async function jo(e,t){return e==="set"?Pd(t):Ed(t)}async function Ed(e){let t=S(!e.json);t.start("Loading contact info");let i=await x("/api/me/contact"),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),t.stop(`${y.success} Contact info`),e.json){k(s,e.fields);return}if(C("Contact Info"),!s.has_contact){console.log(` ${y.warning} ${Qi.default.yellow("No contact info set.")} Run ${Qi.default.bold("domani contact set")} to add.`),d(),console.log(` ${Qi.default.dim("Contact info is required before purchasing domains.")}`),d();return}let n=s.contact;c("Name",`${n.first_name} ${n.last_name}`),n.org_name&&c("Organization",n.org_name),c("Address",n.address1),n.address2&&c("",n.address2),c("",`${n.city}, ${n.state} ${n.postal_code}`),c("Country",n.country),c("Phone",n.phone),c("Email",n.email),d()}async function Pd(e){let t={},i=e.firstName||e.lastName||e.address1;if(!je&&!i&&u("Missing required flags for contact set",{hint:"Usage: domani contact set --first-name John --last-name Doe --address1 '123 Main St' --city SF --state CA --postal-code 94105 --country US --phone +1.5551234567 --email john@example.com",code:"missing_argument",json:e.json}),i){let a=["firstName","lastName","address1","city","state","postalCode","country","phone","email"],l={firstName:"first_name",lastName:"last_name",orgName:"org_name",address1:"address1",address2:"address2",city:"city",state:"state",postalCode:"postal_code",country:"country",phone:"phone",email:"email"},m=a.filter(f=>!e[f]);m.length>0&&u(`Missing required flags: ${m.map(f=>`--${f.replace(/[A-Z]/g,g=>`-${g.toLowerCase()}`)}`).join(", ")}`,{code:"missing_argument",json:e.json});for(let[f,g]of Object.entries(l)){let b=e[f];b&&(t[g]=b)}}else{let a=await x("/api/me/contact"),m=(a.ok?await a.json():null)?.contact,f=[{key:"first_name",message:"First name",placeholder:"John",required:!0},{key:"last_name",message:"Last name",placeholder:"Doe",required:!0},{key:"org_name",message:"Organization (optional, press Enter to skip)",placeholder:"Acme Inc.",required:!1},{key:"address1",message:"Address line 1",placeholder:"123 Main St",required:!0},{key:"address2",message:"Address line 2 (optional)",placeholder:"Suite 100",required:!1},{key:"city",message:"City",placeholder:"San Francisco",required:!0},{key:"state",message:"State / Province",placeholder:"CA",required:!0},{key:"postal_code",message:"Postal / ZIP code",placeholder:"94105",required:!0},{key:"country",message:"Country code (ISO 3166-1 alpha-2)",placeholder:"US",required:!0},{key:"phone",message:"Phone (+CC.NUMBER)",placeholder:"+1.5551234567",required:!0},{key:"email",message:"Contact email",placeholder:"john@example.com",required:!0}];for(let g of f){let b=m?.[g.key]||"",v=await Ae({message:g.message,placeholder:g.placeholder,defaultValue:b,validate:g.required?h=>h?.trim()?void 0:`${g.message} is required`:void 0});le(v)&&process.exit(0);let w=v.trim();w&&(t[g.key]=w)}}if(e.dryRun)return B("contact_set",t,e.json,e.fields);let s=S(!e.json);s.start("Saving contact info");let n=await x("/api/me/contact",{method:"PUT",body:JSON.stringify(t)}),r=await n.json();if(n.ok||(s.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:e.json,fields:e.fields})),s.stop(`${y.success} Contact info saved`),e.json){k(r,e.fields);return}C("Contact Saved");let o=r.contact;c("Name",`${o.first_name} ${o.last_name}`),o.org_name&&c("Organization",o.org_name),c("Address",o.address1),o.address2&&c("",o.address2),c("",`${o.city}, ${o.state} ${o.postal_code}`),c("Country",o.country),c("Phone",o.phone),c("Email",o.email),d(),I("Search for a domain:","domani search <name>"),d()}X();var Ee=U(L(),1);W();he();Ye();async function Co(e,t,i,s){if(e||(e=await fe()),K(e,s),!t)return Dd(e,s.json,s.fields);switch(t){case"enable":case"on":return s.dryRun?B("parking_enable",{domain:e},s.json,s.fields):xo(e,!0,s.json,s.fields);case"disable":case"off":return s.dryRun?B("parking_disable",{domain:e},s.json,s.fields):xo(e,!1,s.json,s.fields);case"price":{i||u("Price required",{hint:"Usage: domani parking <domain> price <amount>",code:"validation_error",json:s.json,fields:s.fields});let n=parseFloat(i);return(isNaN(n)||n<=0)&&u("Price must be a positive number",{hint:`Got: "${i}"`,code:"validation_error",json:s.json,fields:s.fields}),s.dryRun?B("parking_price",{domain:e,price:n},s.json,s.fields):So(e,n,s.json,s.fields)}case"unprice":case"unlist":return s.dryRun?B("parking_unlist",{domain:e},s.json,s.fields):So(e,null,s.json,s.fields);default:u(`Unknown action: ${t}`,{hint:"Actions: enable, disable, price <amount>, unprice",code:"validation_error",json:s.json,fields:s.fields})}}async function Dd(e,t,i){let s=S(!t);s.start(`Loading ${$.domain(e)}`);let n=await x(`/api/domains/${encodeURIComponent(e)}`),r=await n.json();if(n.ok||(s.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:t,fields:i})),s.stop(`${y.success} ${$.domain(e)}`),t){k({domain:r.domain,parking_enabled:r.parking_enabled,listing_price:r.listing_price},i);return}C("Parking"),c("Domain",$.domain(r.domain)),c("Parking",r.parking_enabled?Ee.default.green("enabled"):Ee.default.dim("disabled")),c("Listing",r.listing_price?`${$.price(r.listing_price)} ${Ee.default.dim("(for sale)")}`:Ee.default.dim("not listed")),d(),I("Enable parking:",`domani parking ${e} enable`),I("Set sale price:",`domani parking ${e} price 499`),I("View analytics:",`domani analytics ${e}`),d()}async function xo(e,t,i,s){let n=S(!i);n.start(`${t?"Enabling":"Disabling"} parking for ${$.domain(e)}`);let r=await x(`/api/domains/${encodeURIComponent(e)}/parking`,{method:"PUT",body:JSON.stringify({enabled:t})}),o=await r.json();if(r.status===409&&o.requires_confirmation){if(n.stop(`${y.warning} DNS records will be replaced`),i){k(o,s);return}console.log(`
189
+ `),{chosen:F,chosenResult:ie,searchAgain:z,allTaken:r.length===0&&o.length>0,expanded:g>0}}async function ao(e,t,i){if(!e){xe||u("Missing required argument: domain",{hint:"Usage: domani search <domain> [tlds...]",code:"missing_argument",json:i.json});let N=await Ae({message:"Search for a domain",placeholder:"e.g. myapp or myapp.dev"});(le(N)||!N)&&process.exit(0),e=N}let s=t.map(N=>N.replace(/^\./,"")),n=i.tlds?.split(",").map(N=>N.trim())||[],r=[...new Set([...s,...n])];if(r.length>0&&Hi(r,i),K(e,i),e.includes(".")&&r.length===0){let N=S(!i.json);N.start(`Checking ${$.domain(e)}`);let[Z,z]=await Promise.all([be(`/api/domains/search?q=${encodeURIComponent(e)}`),be(`/api/domains/${encodeURIComponent(e)}/og`).catch(()=>null)]),F=await Z.json();if(Z.ok||(N.stop("Search failed"),u(F.error||F.message,{hint:F.hint,status:Z.status,json:i.json,fields:i.fields})),i.json){let ie=F.domain.split(".")[0];k({name:ie,results:[F],total:1,available:F.available?1:0},i.fields);return}if(F.available)if(N.stop(`${y.success} ${$.domain(F.domain)} ${y.dot} available ${y.dot} ${$.price(F.price)}/yr`),xe&&!i.json){let{buy:ie}=await Promise.resolve().then(()=>(Yt(),di));await ie([F.domain],{preChecked:{price:F.price,currency:F.currency}})}else d(),I("Register it:",`domani buy ${F.domain}`),d();else if(F.for_sale?.buyable)if(N.stop(`${y.info} ${$.domain(F.domain)} ${y.dot} ${T.default.cyan("for sale")} ${y.dot} ${$.price(F.for_sale.price)}`),xe&&!i.json){let{buy:ie}=await Promise.resolve().then(()=>(Yt(),di));await ie([F.domain],{preChecked:{price:F.for_sale.price,currency:F.for_sale.currency,marketplace:!0}})}else d(),I("Buy it:",`domani buy ${F.domain}`),d();else if(F.error)N.stop(`${T.default.dim("?")} ${$.domain(F.domain)} ${y.dot} ${T.default.dim("lookup failed")}`);else{let ie;try{if(z?.ok){let Y=await z.json();Y?.title&&(ie=Y.title)}}catch{}let q=ie?` ${y.dot} ${T.default.dim(`"${ie}"`)}`:"";N.stop(`${y.error} ${$.domain(F.domain)} ${y.dot} ${T.default.red("taken")}${q}`)}return}let o=e.split(".")[0];if(xe&&!i.json&&r.length>0){let N=new URLSearchParams;N.set("domains",r.map(te=>`${o}.${te}`).join(",")),i.maxPrice&&N.set("max_price",i.maxPrice);let Z=await be(`/api/domains/search?${N}`,{headers:{Accept:"text/event-stream"}});if(!Z.ok||!Z.body){u("Search failed",{json:i.json});return}let z=[],F=new TextDecoder,ie="",q="",Y=S(!0);Y.start(`Checking ${r.length} TLD${r.length>1?"s":""}`);for await(let te of Z.body){ie+=F.decode(te,{stream:!0});let it=ie.split(`
190
+ `);ie=it.pop()??"";for(let yt of it)yt.startsWith("event: ")?q=yt.slice(7):yt.startsWith("data: ")&&q==="result"&&z.push(JSON.parse(yt.slice(6)))}Y.stop("");let Q=Math.max(...r.map(te=>`${o}.${te}`.length))+2,G=z.filter(te=>te.available),Oe=z.filter(te=>!te.available&&!te.error),Be=z.filter(te=>!te.available&&te.for_sale);for(let te of[...G,...Be,...Oe.filter(it=>!it.for_sale)])te.available?console.log(` ${T.default.green("\u2713")} ${T.default.bold(T.default.white(te.domain.padEnd(Q)))} ${T.default.green($.price(te.price)+"/yr")}`):te.for_sale?console.log(` ${T.default.cyan("$")} ${T.default.bold(T.default.white(te.domain.padEnd(Q)))} ${T.default.cyan($.price(te.for_sale.price))} ${T.default.dim("(for sale)")}`):console.log(` ${T.default.dim("\u2717")} ${T.default.dim(te.domain.padEnd(Q))} ${T.default.dim("taken")}`);if(G.length===0){console.log(` ${T.default.dim("No domains available")}`),d();return}let{buy:de}=await Promise.resolve().then(()=>(Yt(),di));if(G.length===1){await de([G[0].domain],{preChecked:{price:G[0].price,currency:G[0].currency}});return}let{select:ae,isCancel:we}=await Promise.resolve().then(()=>(De(),Qs)),lt=await ae({message:"Register one?",options:[...G.map(te=>({value:te.domain,label:$.domain(te.domain),hint:$.price(te.price)+"/yr"})),{value:"__skip__",label:"Skip"}]});if(!we(lt)&&lt!=="__skip__"){d();let te=G.find(it=>it.domain===lt);await de([lt],{preChecked:te?{price:te.price,currency:te.currency}:void 0})}else d();return}if(xe&&!i.json){let N=await oo();for(i.expand&&N.length>Xt&&console.error(T.default.dim(` (--expand: checking the first ${Xt} of ${N.length} TLDs - server limit per request)`));;){let Z=i.expand?N.slice(0,Xt):N.slice(0,He),z=new URLSearchParams;z.set("domains",Z.map(ae=>`${o}.${ae}`).join(",")),i.maxPrice&&z.set("max_price",i.maxPrice);let F=S(!0);F.start(`Searching available domains for ${T.default.bold(o)}`);let ie=await be(`/api/domains/search?${z}`,{headers:{Accept:"text/event-stream"}});if(!ie.ok||!ie.body){F.stop("Search failed");break}F.stop("");let q=!i.expand,{chosen:Y,chosenResult:Q,searchAgain:G}=await Sd(ie.body,o,i.all??!1,q,N);if(Y){d();let{buy:ae}=await Promise.resolve().then(()=>(Yt(),di)),we=Q?{price:Q.price,currency:Q.currency}:void 0;await ae([Y],{preChecked:we});return}if(!G)break;let{text:Oe,isCancel:Be}=await Promise.resolve().then(()=>(De(),Qs)),de=await Oe({message:"Search for a domain",placeholder:"e.g. myapp or myapp.dev"});if(Be(de)||!de)break;o=de.split(".")[0]}d();return}let a=o,l=await oo(),m=r.length>0?r:i.expand?l.slice(0,Xt):l.slice(0,He);i.expand&&r.length===0&&l.length>Xt&&console.error(`(--expand: checking the first ${Xt} of ${l.length} TLDs - server limit per request; use --tlds to target others)`);let f=m.map(N=>`${a}.${N}`),g=new URLSearchParams;g.set("domains",f.join(",")),i.maxPrice&&g.set("max_price",i.maxPrice);let b=S(!i.json);b.start(`Searching available domains for ${T.default.bold(a)}`);let w=await be(`/api/domains/search?${g}`,{headers:{Accept:"text/event-stream"}});if(!w.ok){b.stop("Search failed");try{let N=await w.json();u(N.error||N.message||`Server error (${w.status})`,{hint:N.hint,status:w.status,json:i.json,fields:i.fields})}catch{u(`Server error (${w.status})`,{status:w.status,json:i.json,fields:i.fields})}}let v=w.body;v||(b.stop("Search failed"),u("Empty response",{code:"error",json:i.json,fields:i.fields}));let h=[],_=!1,x=0,O=i.all??!1;function R(){_||(_=!0,b.stop(`Checking TLDs for ${T.default.bold(a)}`),d())}function M(N){R(),N.available?console.log(` ${y.success} ${$.domain(N.domain).padEnd(37)} ${$.price(N.price)}${T.default.dim("/yr")}`):N.for_sale?console.log(` ${y.info} ${$.domain(N.domain).padEnd(37)} ${T.default.cyan($.price(N.for_sale.price))} ${T.default.dim("(for sale)")}`):N.error||console.log(` ${y.error} ${T.default.dim(N.domain.padEnd(38))} ${T.default.red("taken")}`)}function V(){_||b.message(`Checking TLDs for ${T.default.bold(a)} ${T.default.dim(`(${x} checked)`)}`)}let ee=new TextDecoder,P="",E="";for await(let N of v){P+=ee.decode(N,{stream:!0});let Z=P.split(`
191
+ `);P=Z.pop()??"";for(let z of Z)if(z.startsWith("event: "))E=z.slice(7);else if(z.startsWith("data: ")){let F=JSON.parse(z.slice(6));if(E==="error")b.stop("Search failed"),u(F.message||F.error||"Search failed",{code:F.code||"error",json:i.json,fields:i.fields});else if(E==="result")x++,F.available||F.for_sale||O?(i.json||M(F),h.push(F)):i.json||V();else if(E==="done"){if(i.json){h.sort((Q,G)=>Q.price-G.price),k({name:a,results:h,total:F.total,available:F.available},i.fields);return}_&&console.log(` ${T.default.dim("\u2500".repeat(50))}`);let ie=F.total-F.available,q=F.total>=5&&ie/F.total>=.5,Y=`Checked ${F.total} TLDs \xB7 ${F.available} available${q?" \xB7 popular name":""}`;console.log(` ${T.default.dim(Y)}`),F.available===0&&!i.expand&&r.length===0&&(d(),I("Try more TLDs:",`domani search ${a} --expand`))}}}d()}Yt();X();var ci=U(L(),1);W();he();Ji();function lo(e,t,i=process.env){let s=Tt(t,i);if(s!==void 0&&!e)throw new Error("--webhook is required when setting webhook authentication");return{request:{...e?{webhook_url:e}:{},...s!==void 0?{webhook_headers:s}:{}},preview:{...e?{webhook_url:e}:{},...s!==void 0?{webhook_header_names:Nt(s)}:{}}}}async function co(e,t){K(e,t);let i={domain:e};t.slug&&(i.slug=t.slug),t.name&&(i.name=t.name);let s;try{s=lo(t.webhook,t)}catch(a){u(a instanceof Error?a.message:"Invalid webhook headers",{hint:"Set the named environment variable and retry.",code:"validation_error",json:t.json,fields:t.fields})}if(Object.assign(i,s.request),t.years&&(i.years=Number(t.years)),t.paymentMethod&&(i.payment_method=t.paymentMethod),t.dryRun){let a={...i};delete a.webhook_headers,Object.assign(a,s.preview),B("POST /api/agents/provision",a,t.json,t.fields);return}let n=S(!t.json);n.start(`Provisioning ${$.domain(e)}`);let r=await j("/api/agents/provision",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)}),o=await r.json();if(r.ok||(n.stop("Provisioning failed"),u(o.error||"Provisioning failed",{hint:o.hint,status:r.status,json:t.json,fields:t.fields})),n.stop(`${$.domain(e)} is ready`),t.json){k(o,t.fields);return}if(d(),C("Agent identity"),c("Domain",`${o.domain} (${o.domain_status})`),c("Mailbox",o.mailbox?ci.default.green(o.mailbox.address):ci.default.yellow("pending DNS")),c("Webhook",o.webhook?o.webhook.url:ci.default.dim("none")),o.webhook?.header_names.length&&c("Webhook auth",o.webhook.header_names.join(", ")),o.webhook?.secret&&c("Signing secret",o.webhook.secret),o.warnings?.length){d();for(let a of o.warnings)ze(ci.default.yellow(a))}if(o.next_steps?.length){d(),C("Next");for(let a of o.next_steps)ze(a)}d()}X();var ht=U(L(),1);W();async function uo(e){let t=S(!e.json);t.start("Loading domains");let i=await j("/api/domains"),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),t.stop(`${s.domains.length} domain(s)`),e.json){k({...s,count:s.domains.length},e.fields);return}if(s.domains.length===0){d(),console.log(` ${ht.default.dim("No domains yet.")} Use: ${ht.default.cyan("domani buy <domain>")}`),d();return}let n=[30,12,12,14];C(`Your Domains (${s.domains.length})`,n.reduce((o,a)=>o+a,0)+n.length-1);let r=s.domains.map(o=>{let a=new Date(o.expiresAt).toLocaleDateString(),l=o.status==="active"?ht.default.green:o.status==="pending"?ht.default.yellow:ht.default.red,m=o.autoRenew?ht.default.green("on"):ht.default.dim("off");return[$.domain(o.domain),l(o.status),m,ht.default.dim(a)]});se(["Domain","Status","Auto-renew","Expires"],r,n),d()}hn();X();var Ut=U(L(),1);W();async function mo(e){let t=new URLSearchParams;e.maxPrice&&t.set("max_price",e.maxPrice),e.minPrice&&t.set("min_price",e.minPrice),e.sort&&t.set("sort",e.sort),e.search&&t.set("search",e.search),e.limit&&t.set("limit",e.limit),t.set("order","asc");let i=S(!e.json);i.start("Loading TLDs");let s=await be(`/api/tlds?${t}`),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields})),i.stop(`${n.total} TLDs loaded`),e.json){k(n,e.fields);return}let r=n.tlds;if(r.length===0){d(),console.log(` ${Ut.default.dim("No TLDs match your filters.")}`),d();return}C("TLD Pricing");let o=r.map(a=>[Ut.default.bold(`.${a.tld}`),$.price(a.registration.toFixed(2))+Ut.default.dim("/yr"),Ut.default.dim("renew ")+$.price(a.renewal.toFixed(2))+Ut.default.dim("/yr")]);se(["TLD","Register","Renewal"],o,[22,16,20]),d(),console.log(` ${Ut.default.dim(`${n.total} TLDs total`)}`),d()}X();var Se=U(L(),1);W();he();async function fo(e,t){K(e,t);let i=S(!t.json);i.start(`Looking up ${$.domain(e)}`);let[s,n]=await Promise.all([be(`/api/domains/whois?q=${encodeURIComponent(e)}`),be(`/api/domains/${encodeURIComponent(e)}/og`).catch(()=>null)]),r=await s.json(),o=null;try{n?.ok&&(o=await n.json())}catch{}if(s.ok||(i.stop("Lookup failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:t.json,fields:t.fields})),i.stop("WHOIS data retrieved"),t.json){k({...r,...o?{og:o}:{}},t.fields);return}if(C(`WHOIS ${$.domain(r.domain)}`),!r.registered){c("Status",`${y.success} ${Se.default.green("not registered")}`),d(),I("Register it:",`domani buy ${r.domain}`),d();return}if(c("Status",`${y.error} ${Se.default.red("registered")}`),(o?.title||o?.description)&&(d(),console.log(` ${Se.default.bold("Website preview")}`),console.log(` ${Se.default.dim("\u2500".repeat(50))}`),o.title&&c("Title",o.title),o.description&&c("Description",Se.default.dim(o.description.length>80?o.description.slice(0,80)+"\u2026":o.description)),d()),r.registrar&&c("Registrar",r.registrar),r.created&&c("Created",r.created),r.expires&&c("Expires",r.expires),r.days_until_expiry!=null){let l=r.days_until_expiry,m=l<30?Se.default.red:l<90?Se.default.yellow:Se.default.green;c("Days left",m(String(l)))}r.updated&&c("Updated",r.updated),c("DNSSEC",r.dnssec?Se.default.green("yes"):Se.default.dim("no")),r.nameservers?.length>0&&c("Nameservers",r.nameservers.map(l=>Se.default.cyan(l)).join(Se.default.dim(", "))),r.status?.length>0&&c("Status codes",Se.default.dim(r.status.join(", ")));let a=r.contacts?.registrant;a&&!r.redacted?(d(),console.log(` ${Se.default.bold("Registrant")}`),console.log(` ${Se.default.dim("\u2500".repeat(50))}`),a.name&&c("Name",a.name),a.organization&&c("Organization",a.organization),a.email&&c("Email",$.url(a.email)),a.country&&c("Country",a.country)):r.redacted&&c("Contact",Se.default.dim("redacted (WHOIS privacy)")),d()}X();De();var gt=U(L(),1);W();he();async function po(e,t){if(!e){xe||u("Missing required argument: prompt",{hint:'Usage: domani suggest "describe your project"',code:"missing_argument",json:t.json});let h=await Ae({message:"Describe your project or idea",placeholder:"e.g. AI coding assistant, pet food delivery..."});(le(h)||!h)&&process.exit(0),e=h}let i=new URLSearchParams({prompt:e});if(t.count&&i.set("count",t.count),t.tlds&&i.set("tlds",t.tlds),t.tlds&&Hi(t.tlds.split(",").map(h=>h.trim()),t),t.style&&i.set("style",t.style),t.lang&&i.set("lang",t.lang),t.json){let h=S(!1);h.start("Finding available domains");let _=t.timeout?parseInt(t.timeout,10)*1e3:6e4,x;try{x=await be(`/api/domains/suggest?${i}`,{signal:AbortSignal.timeout(_)})}catch{h.stop("Failed"),u("Request timed out",{hint:"Suggest took too long. Try --timeout <seconds> to increase.",code:"timeout",json:t.json,fields:t.fields})}let O=await x.json();x.ok||(h.stop("Failed"),u(O.error||O.message,{hint:O.hint,status:x.status,json:t.json,fields:t.fields})),k(O,t.fields);return}let s=S(!0);s.start("Finding available domains");let n=t.timeout?parseInt(t.timeout,10)*1e3:6e4,r;try{r=await be(`/api/domains/suggest?${i}`,{headers:{Accept:"text/event-stream"},signal:AbortSignal.timeout(n)})}catch{s.stop("Failed"),u("Request timed out",{hint:"Suggest took too long. Try --timeout <seconds> to increase.",code:"timeout"})}if(!r.ok){s.stop("Failed");try{let h=await r.json();u(h.error||h.message||`Server error (${r.status})`,{hint:h.hint,status:r.status})}catch{u(`Server error (${r.status})`,{status:r.status})}}let o=r.body;o||(s.stop("Failed"),u("Empty response"));let a=[],l=[],m=!1,f=0;function g(){m||(m=!0,s.stop("Finding available domains"),d())}let b=new TextDecoder,w="",v="";for await(let h of o){w+=b.decode(h,{stream:!0});let _=w.split(`
192
+ `);w=_.pop()??"";for(let x of _)if(x.startsWith("event: "))v=x.slice(7);else if(x.startsWith("data: "))try{let O=JSON.parse(x.slice(6));if(v==="result")f++,O.available?a.push(O):l.push(O),m||s.message(`Finding available domains ${gt.default.dim(`(${f} checked, ${a.length} available)`)}`);else if(v==="iteration")m||s.message(`Finding available domains ${gt.default.dim(`(round ${O.n})`)}`);else if(v==="done"){g();for(let R of a){let M=R.reason?` ${gt.default.dim(R.reason)}`:"";console.log(` ${y.success} ${$.domain(R.domain).padEnd(37)} ${$.price(R.price)}${gt.default.dim("/yr")}${M}`)}for(let R of l)console.log(` ${y.error} ${gt.default.dim(R.domain.padEnd(38))} ${gt.default.red("taken")}`);console.log(` ${gt.default.dim("\u2500".repeat(50))}`),console.log(` ${gt.default.dim(`Found ${O.total} available \xB7 checked ${O.checked} \xB7 ${O.iterations} round${O.iterations>1?"s":""}`)}`)}else v==="error"&&(m||s.stop("Failed"),u(O.message))}catch{}}a.length===0&&l.length===0&&(m||s.stop("No results"),u("Could not find available domains for this prompt.")),d(),a.length>0&&(I("Register one:",`domani buy ${a[0].domain}`),d())}dn();bn();X();De();var Ft=U(L(),1);W();he();ei();async function ho(e,t){K(e,t);let i=S(!t.json);i.start(`Planning safe adoption for ${$.domain(e)}`);let s=await j(`/api/domains/adoption-plan?domain=${encodeURIComponent(e)}`),n=await s.json();if(s.ok||(i.stop("Check failed"),u(n.error,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),n.options?.transfer?.eligible||(i.stop(`${y.error} Not eligible`),u(n.options?.transfer?.reason||"Domain is not eligible for transfer.",{hint:n.warnings?.join(" "),code:"not_eligible",json:t.json,fields:t.fields})),i.stop(`${y.success} Eligible for transfer`),t.dryRun)return B("transfer",{domain:e,eligible:!0,price:n.options.transfer.price,currency:n.options.transfer.currency||"USD",includes_renewal:!0,preserves_nameservers:!0,migrates_dns:!1,nameservers:n.current.nameservers,dns_provider:n.current.dns_provider,dnssec_enabled:n.current.dnssec_enabled},t.json,t.fields);if(!Et(t)){C("Transfer Safety Plan"),c("Registrar",n.current.registrar||"Unknown"),c("DNS provider",n.current.dns_provider),c("Nameservers",`${n.current.nameservers.length} preserved`),c("DNSSEC",n.current.dnssec_enabled?Ft.default.yellow("Enabled, DS will be verified"):"Not enabled"),c("DNS migration","Not requested"),d();let a=n.options.transfer.price!=null?` for ${$.price(n.options.transfer.price.toFixed(2))}`:"",l=await Ke({message:`Transfer ${Ft.default.bold(e)} to ${Lt}${a}? Nameservers stay unchanged and 1 year is included.`});if(!l||typeof l=="symbol"){console.log(` ${Ft.default.dim("Cancelled.")}`);return}}if(!t.authCode){(t.json||!process.stdout.isTTY)&&u("--auth-code is required",{hint:"The safety plan passed. Get the EPP/auth code from the current registrar and retry.",code:"validation_error",json:t.json,fields:t.fields});let a=await Ae({message:"Enter the EPP/auth code from your current registrar:",validate:l=>!l||l.trim().length===0?"Auth code is required":void 0});le(a)&&process.exit(0),t.authCode=a}i.start(`Initiating transfer for ${$.domain(e)}`);let r=await j("/api/domains/transfer",{method:"POST",body:JSON.stringify({domain:e,auth_code:t.authCode})}),o=await r.json();if(r.ok||(i.stop("Transfer failed"),u(o.error||o.message,{hint:o.hint,fixUrl:o.setup_url||o.payment_options?.card?.setup_url,status:r.status,json:t.json,fields:t.fields})),i.stop(`${y.success} Transfer initiated`),t.json){k(o,t.fields);return}C("Transfer Initiated"),c("Domain",$.domain(o.domain)),c("Status",Ft.default.yellow(o.status||"pending")),o.price&&c("Price",$.price(o.price)+Ft.default.dim(` ${o.currency||"USD"}`)),o.payment_method&&c("Payment",o.payment_method),o.expires&&c("Expires",new Date(o.expires).toLocaleDateString()),o.hint&&(d(),console.log(` ${Ft.default.dim(o.hint)}`)),d(),I("Check transfer progress:",`domani status ${o.domain}`),d()}X();var Xi=U(L(),1);W();he();async function go(e,t){K(e,t);let i=S(!t.json);i.start(`Inspecting ${$.domain(e)}`);let s=await j(`/api/domains/adoption-plan?domain=${encodeURIComponent(e)}`),n=await s.json();if(s.ok||(i.stop("Inspection failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),i.stop(`${y.success} Adoption plan ready`),t.json){k(n,t.fields);return}if(C(`Adopt ${$.domain(n.domain)}`),c("Registrar",n.current.registrar||"Unknown"),c("DNS provider",n.current.dns_provider),c("Nameservers",n.current.nameservers.join(", ")||"None detected"),c("DNSSEC",n.current.dnssec_enabled?Xi.default.yellow("Enabled"):"Not enabled"),c("Account",n.account_state),c("Recommended",Xi.default.cyan(n.recommended_action)),d(),n.recommended_action==="connect"&&I("Connect free, without changing registrar or DNS:",`domani import ${n.domain}`),n.options.transfer.available){let r=n.options.transfer.price==null?"price unavailable":`$${n.options.transfer.price.toFixed(2)} ${n.options.transfer.currency}`;I(`Transfer registration for ${r}, preserving nameservers:`,`domani transfer ${n.domain}`)}for(let r of n.warnings||[])console.log(` ${Xi.default.yellow("!")} ${r}`);d()}X();De();var Zi=U(L(),1);W();he();Ye();async function bo(e,t){e||(e=await fe()),K(e,t);let i=t.years?parseInt(t.years,10):1;if((isNaN(i)||i<1||i>10)&&u("--years must be between 1 and 10",{code:"validation_error",json:t.json,fields:t.fields}),t.dryRun)return B("renew",{domain:e,years:i},t.json,t.fields);if(!Et(t)){let o=await Ke({message:`Renew ${Zi.default.bold(e)} for ${i} year${i>1?"s":""}? You will be charged.`});if(!o||typeof o=="symbol"){console.log(` ${Zi.default.dim("Cancelled.")}`);return}}let s=S(!t.json);s.start(`Renewing ${$.domain(e)}`);let n=await j(`/api/domains/${encodeURIComponent(e)}/renew`,{method:"POST",body:JSON.stringify({years:i})}),r=await n.json();if(n.ok||(s.stop("Renewal failed"),u(r.error||r.message,{hint:r.hint,fixUrl:r.setup_url||r.payment_options?.card?.setup_url,status:n.status,json:t.json,fields:t.fields})),s.stop(`${y.success} Domain renewed`),t.json){k(r,t.fields);return}C("Renewal Complete"),c("Domain",$.domain(r.domain)),c("Years",String(r.renewed_years)),c("New expiry",new Date(r.new_expiry).toLocaleDateString()),r.price&&c("Price",$.price(r.price)+Zi.default.dim(` ${r.currency||"USD"}`)),r.payment_method&&c("Payment",r.payment_method),d(),I("Verify renewal:",`domani status ${r.domain}`),d()}X();var ot=U(L(),1);W();he();async function yo(e,t){e||u("Domain is required",{hint:`Usage: domani import <domain>
193
+ domani import <domain> --verify`,code:"validation_error",json:t.json,fields:t.fields}),K(e,t);let i=t.verify?"/api/domains/import/verify":"/api/domains/import",s=S(!t.json);s.start(t.verify?`Verifying ownership of ${$.domain(e)}`:`Initiating import for ${$.domain(e)}`);let n=await j(i,{method:"POST",body:JSON.stringify({domain:e})}),r=await n.json();if(n.ok||(s.stop(t.verify?"Verification failed":"Import failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:t.json,fields:t.fields})),t.json){s.stop(""),k(r,t.fields);return}t.verify?(s.stop(`${y.success} ${$.domain(e)} imported!`),C("Domain Imported"),c("Domain",$.domain(r.domain)),c("Status",ot.default.green(r.status||"active")),r.expires_at&&c("Expires",new Date(r.expires_at).toLocaleDateString()),r.registrar&&c("Registrar",r.registrar),d(),I("Check domain health:",`domani status ${r.domain}`),d()):(s.stop(`${y.success} Verification record ready`),C("Import Domain"),c("Domain",$.domain(r.domain)),c("Status",ot.default.yellow("pending verification")),d(),console.log(" Add this TXT record at your DNS provider:"),d(),console.log(` ${ot.default.dim("Type:")} ${ot.default.bold("TXT")}`),console.log(` ${ot.default.dim("Name:")} ${ot.default.bold(r.txt_record?.name||"@")}`),console.log(` ${ot.default.dim("Value:")} ${ot.default.bold(r.txt_record?.value||`domani-verify=${r.token}`)}`),d(),console.log(` ${ot.default.dim("DNS propagation may take a few minutes to 48 hours.")}`),d(),I("Once the record is set, verify:",`domani import ${e} --verify`),d())}mn();mt();W();function $o(e){let t=Me();if(t||(d(),u("Not logged in",{hint:"Run 'domani login' first",code:"auth_required",json:e.json})),!e.reveal&&!e.json&&process.stdout.isTTY){let i=`${t.slice(0,12)}...${t.slice(-4)}`;console.log(i),console.log("Run 'domani token --reveal' to print the full key.");return}e.json?k({token:t}):console.log(t)}X();var Ne=U(L(),1);W();async function vo(e,t){switch(e){case void 0:case"list":return Cd(t.json,t.fields);case"create":return Od(t);case"revoke":return Id(t);default:u(`Unknown action: ${e}`,{hint:"Actions: list, create, revoke",code:"validation_error",json:t.json,fields:t.fields})}}async function Cd(e,t){let i=S(!e);i.start("Loading tokens");let s=await j("/api/tokens"),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e,fields:t})),i.stop(`${y.success} ${n.tokens.length} token(s)`),e){k(n,t);return}if(n.tokens.length===0){d(),console.log(` ${Ne.default.dim("No tokens.")}`),d(),I("Create one:",'domani tokens create --name "My App"'),d();return}d(),C("API Tokens");let r=n.tokens.map(o=>{let a;o.expired?a=Ne.default.red("Expired"):o.expiresAt?a=Ne.default.dim(`Expires ${new Date(o.expiresAt).toLocaleDateString()}`):a=Ne.default.dim("No expiration");let l=o.scopes.includes("*")?Ne.default.dim("all"):Ne.default.dim(o.scopes.join(", "));return[Ne.default.dim(o.id),Ne.default.bold(o.name),o.agent_identity?Ne.default.dim(o.agent_identity.name||o.agent_identity.slug):Ne.default.dim("\u2014"),l,a]});se(["ID","Name","Agent","Scopes","Expiration"],r,[28,16,18,32,20]),d()}async function Od(e){let t={};if(e.name&&(t.name=e.name),e.scopes&&(t.scopes=e.scopes.split(",").map(r=>r.trim())),e.expiresIn){let r=Number(e.expiresIn);(isNaN(r)||r<3600||r>31536e3)&&u("Invalid --expires-in value",{hint:"Must be between 3600 (1 hour) and 31536000 (1 year) seconds",code:"validation_error",json:e.json,fields:e.fields}),t.expires_in=r}e.agentIdentity&&(t.agent_identity_id=e.agentIdentity);let i=S(!e.json);i.start("Creating token");let s=await j("/api/tokens",{method:"POST",body:JSON.stringify(t)}),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields})),i.stop(`${y.success} Token created`),e.json){k(n,e.fields);return}d(),C("Token Created"),c("ID",n.id),c("Name",n.name),c("Scopes",n.scopes?.includes("*")?"All (full access)":n.scopes?.join(", ")||"All"),n.agent_identity&&c("Agent",n.agent_identity.name||n.agent_identity.slug),c("Expires",n.expiresAt?new Date(n.expiresAt).toLocaleString():"Never"),d(),console.log(` ${Ne.default.yellow("!")} ${Ne.default.bold("Key:")} ${n.key}`),console.log(` ${Ne.default.dim("Save this key - it will not be shown again.")}`),d()}async function Id(e){e.tokenId||u("Token ID required",{hint:`Usage: domani tokens revoke --token-id <id>
194
+ Run 'domani tokens list' to see your tokens.`,code:"validation_error",json:e.json,fields:e.fields});let t=S(!e.json);t.start("Revoking token");let i=await j(`/api/tokens/${encodeURIComponent(e.tokenId)}`,{method:"DELETE"}),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),t.stop(`${y.success} Token revoked`),e.json){k(s,e.fields);return}console.log(` ${Ne.default.dim("Any applications using this key will need a new one.")}`),d()}X();var Ce=U(L(),1);W();he();Ye();async function wo(e,t){e||(e=await fe()),K(e,t);let i=t.autoRenew!==void 0,s=t.whoisPrivacy!==void 0,n=t.securityLock!==void 0;if(!i&&!s&&!n)return Rd(e,t.json,t.fields);let r={};if(i){let m=vn(t.autoRenew);m===null&&u("--auto-renew must be on or off",{code:"validation_error",json:t.json,fields:t.fields}),r.auto_renew=m}if(s){let m=vn(t.whoisPrivacy);m===null&&u("--whois-privacy must be on or off",{code:"validation_error",json:t.json,fields:t.fields}),r.whois_privacy=m}if(n){let m=vn(t.securityLock);m===null&&u("--security-lock must be on or off",{code:"validation_error",json:t.json,fields:t.fields}),r.security_lock=m}if(t.dryRun)return B("settings_update",{domain:e,...r},t.json,t.fields);let o=S(!t.json);o.start(`Updating ${$.domain(e)}`);let a=await j(`/api/domains/${encodeURIComponent(e)}/settings`,{method:"PUT",body:JSON.stringify(r)}),l=await a.json();if(a.ok||(o.stop("Failed"),u(l.error||l.message,{hint:l.hint,status:a.status,json:t.json,fields:t.fields})),o.stop(`${y.success} Settings updated`),t.json){k(l,t.fields);return}C("Settings Updated"),c("Domain",$.domain(l.domain)),l.auto_renew!==void 0&&c("Auto-renew",l.auto_renew?Ce.default.green("on"):Ce.default.dim("off")),l.whois_privacy!==void 0&&c("WHOIS privacy",l.whois_privacy?Ce.default.green("on"):Ce.default.dim("off")),l.security_lock!==void 0&&c("Security lock",l.security_lock?Ce.default.green("locked"):Ce.default.dim("unlocked")),l.hint&&c("",Ce.default.dim(l.hint)),d()}async function Rd(e,t,i){let s=S(!t);s.start(`Loading ${$.domain(e)}`);let n=await j(`/api/domains/${encodeURIComponent(e)}`),r=await n.json();if(n.ok||(s.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:t,fields:i})),s.stop(`${y.success} ${$.domain(e)}`),t){k(r,i);return}C("Domain Settings"),c("Domain",$.domain(r.domain)),c("Status",r.status==="active"?Ce.default.green(r.status):Ce.default.yellow(r.status)),c("Auto-renew",r.auto_renew?Ce.default.green("on"):Ce.default.dim("off")),r.registrar&&(c("WHOIS privacy",r.registrar.whois_privacy?Ce.default.green("on"):Ce.default.dim("off")),c("Security lock",r.registrar.security_lock?Ce.default.green("locked"):Ce.default.dim("unlocked"))),c("Expires",new Date(r.expires_at).toLocaleDateString()+Ce.default.dim(` (${r.days_until_expiry} days)`)),d(),I("Toggle auto-renew:",`domani settings ${e} --auto-renew off`),I("Toggle WHOIS privacy:",`domani settings ${e} --whois-privacy off`),I("Toggle security lock:",`domani settings ${e} --security-lock off`),I("Get transfer auth code:",`domani auth-code ${e}`),d()}function vn(e){let t=e.toLowerCase();return t==="on"||t==="true"||t==="1"||t==="enable"?!0:t==="off"||t==="false"||t==="0"||t==="disable"?!1:null}X();var qt=U(L(),1);W();he();Ye();async function ko(e,t){e||(e=await fe()),K(e,t);let i=S(!t.json);i.start(`Getting auth code for ${$.domain(e)}`);let s=await j(`/api/domains/${encodeURIComponent(e)}/auth-code`),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),i.stop(`${y.success} Auth code retrieved`),t.json){k(n,t.fields);return}if(C("Auth Code"),c("Domain",$.domain(n.domain)),c("Auth code",qt.default.bold(qt.default.green(n.auth_code))),n.was_unlocked&&c("",qt.default.yellow("Domain was automatically unlocked to allow transfer.")),n.hint&&(d(),console.log(` ${qt.default.dim(n.hint)}`)),n.next_steps?.length){d();for(let r of n.next_steps)console.log(` ${qt.default.dim("\u2192")} ${qt.default.dim(r)}`)}d(),I("Check transfer status:",`domani transfer-away ${e}`),I("Re-lock domain:",`domani settings ${e} --security-lock on`),d()}X();var bt=U(L(),1);W();he();Ye();var Ad={none:bt.default.dim,pending:bt.default.yellow,approved:bt.default.yellow,completed:bt.default.green,rejected:bt.default.red,expired:bt.default.red};async function _o(e,t){e||(e=await fe()),K(e,t);let i=S(!t.json);i.start(`Checking transfer status for ${$.domain(e)}`);let s=await j(`/api/domains/${encodeURIComponent(e)}/transfer-away`),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),i.stop(`${y.success} ${$.domain(e)}`),t.json){k(n,t.fields);return}C("Transfer Away Status"),c("Domain",$.domain(n.domain));let r=Ad[n.status]||bt.default.dim;c("Status",r(n.status)),n.gaining_registrar&&c("New registrar",n.gaining_registrar),n.request_date&&c("Requested",new Date(n.request_date).toLocaleDateString()),n.hint&&(d(),console.log(` ${bt.default.dim(n.hint)}`)),d(),n.status==="none"?I("Get auth code to start:",`domani auth-code ${e}`):n.status==="pending"||n.status==="approved"?I("Check again later:",`domani transfer-away ${e}`):n.status==="completed"?I("Search for a new domain:","domani search <name>"):(n.status==="rejected"||n.status==="expired")&&I("Retry with a new auth code:",`domani auth-code ${e}`),d()}X();De();var Qi=U(L(),1);W();async function xo(e,t){return e==="set"?Pd(t):Ed(t)}async function Ed(e){let t=S(!e.json);t.start("Loading contact info");let i=await j("/api/me/contact"),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),t.stop(`${y.success} Contact info`),e.json){k(s,e.fields);return}if(C("Contact Info"),!s.has_contact){console.log(` ${y.warning} ${Qi.default.yellow("No contact info set.")} Run ${Qi.default.bold("domani contact set")} to add.`),d(),console.log(` ${Qi.default.dim("Contact info is required before purchasing domains.")}`),d();return}let n=s.contact;c("Name",`${n.first_name} ${n.last_name}`),n.org_name&&c("Organization",n.org_name),c("Address",n.address1),n.address2&&c("",n.address2),c("",`${n.city}, ${n.state} ${n.postal_code}`),c("Country",n.country),c("Phone",n.phone),c("Email",n.email),d()}async function Pd(e){let t={},i=e.firstName||e.lastName||e.address1;if(!xe&&!i&&u("Missing required flags for contact set",{hint:"Usage: domani contact set --first-name John --last-name Doe --address1 '123 Main St' --city SF --state CA --postal-code 94105 --country US --phone +1.5551234567 --email john@example.com",code:"missing_argument",json:e.json}),i){let a=["firstName","lastName","address1","city","state","postalCode","country","phone","email"],l={firstName:"first_name",lastName:"last_name",orgName:"org_name",address1:"address1",address2:"address2",city:"city",state:"state",postalCode:"postal_code",country:"country",phone:"phone",email:"email"},m=a.filter(f=>!e[f]);m.length>0&&u(`Missing required flags: ${m.map(f=>`--${f.replace(/[A-Z]/g,g=>`-${g.toLowerCase()}`)}`).join(", ")}`,{code:"missing_argument",json:e.json});for(let[f,g]of Object.entries(l)){let b=e[f];b&&(t[g]=b)}}else{let a=await j("/api/me/contact"),m=(a.ok?await a.json():null)?.contact,f=[{key:"first_name",message:"First name",placeholder:"John",required:!0},{key:"last_name",message:"Last name",placeholder:"Doe",required:!0},{key:"org_name",message:"Organization (optional, press Enter to skip)",placeholder:"Acme Inc.",required:!1},{key:"address1",message:"Address line 1",placeholder:"123 Main St",required:!0},{key:"address2",message:"Address line 2 (optional)",placeholder:"Suite 100",required:!1},{key:"city",message:"City",placeholder:"San Francisco",required:!0},{key:"state",message:"State / Province",placeholder:"CA",required:!0},{key:"postal_code",message:"Postal / ZIP code",placeholder:"94105",required:!0},{key:"country",message:"Country code (ISO 3166-1 alpha-2)",placeholder:"US",required:!0},{key:"phone",message:"Phone (+CC.NUMBER)",placeholder:"+1.5551234567",required:!0},{key:"email",message:"Contact email",placeholder:"john@example.com",required:!0}];for(let g of f){let b=m?.[g.key]||"",w=await Ae({message:g.message,placeholder:g.placeholder,defaultValue:b,validate:g.required?h=>h?.trim()?void 0:`${g.message} is required`:void 0});le(w)&&process.exit(0);let v=w.trim();v&&(t[g.key]=v)}}if(e.dryRun)return B("contact_set",t,e.json,e.fields);let s=S(!e.json);s.start("Saving contact info");let n=await j("/api/me/contact",{method:"PUT",body:JSON.stringify(t)}),r=await n.json();if(n.ok||(s.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:e.json,fields:e.fields})),s.stop(`${y.success} Contact info saved`),e.json){k(r,e.fields);return}C("Contact Saved");let o=r.contact;c("Name",`${o.first_name} ${o.last_name}`),o.org_name&&c("Organization",o.org_name),c("Address",o.address1),o.address2&&c("",o.address2),c("",`${o.city}, ${o.state} ${o.postal_code}`),c("Country",o.country),c("Phone",o.phone),c("Email",o.email),d(),I("Search for a domain:","domani search <name>"),d()}X();var Ee=U(L(),1);W();he();Ye();async function Co(e,t,i,s){if(e||(e=await fe()),K(e,s),!t)return Dd(e,s.json,s.fields);switch(t){case"enable":case"on":return s.dryRun?B("parking_enable",{domain:e},s.json,s.fields):jo(e,!0,s.json,s.fields);case"disable":case"off":return s.dryRun?B("parking_disable",{domain:e},s.json,s.fields):jo(e,!1,s.json,s.fields);case"price":{i||u("Price required",{hint:"Usage: domani parking <domain> price <amount>",code:"validation_error",json:s.json,fields:s.fields});let n=parseFloat(i);return(isNaN(n)||n<=0)&&u("Price must be a positive number",{hint:`Got: "${i}"`,code:"validation_error",json:s.json,fields:s.fields}),s.dryRun?B("parking_price",{domain:e,price:n},s.json,s.fields):So(e,n,s.json,s.fields)}case"unprice":case"unlist":return s.dryRun?B("parking_unlist",{domain:e},s.json,s.fields):So(e,null,s.json,s.fields);default:u(`Unknown action: ${t}`,{hint:"Actions: enable, disable, price <amount>, unprice",code:"validation_error",json:s.json,fields:s.fields})}}async function Dd(e,t,i){let s=S(!t);s.start(`Loading ${$.domain(e)}`);let n=await j(`/api/domains/${encodeURIComponent(e)}`),r=await n.json();if(n.ok||(s.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:t,fields:i})),s.stop(`${y.success} ${$.domain(e)}`),t){k({domain:r.domain,parking_enabled:r.parking_enabled,listing_price:r.listing_price},i);return}C("Parking"),c("Domain",$.domain(r.domain)),c("Parking",r.parking_enabled?Ee.default.green("enabled"):Ee.default.dim("disabled")),c("Listing",r.listing_price?`${$.price(r.listing_price)} ${Ee.default.dim("(for sale)")}`:Ee.default.dim("not listed")),d(),I("Enable parking:",`domani parking ${e} enable`),I("Set sale price:",`domani parking ${e} price 499`),I("View analytics:",`domani analytics ${e}`),d()}async function jo(e,t,i,s){let n=S(!i);n.start(`${t?"Enabling":"Disabling"} parking for ${$.domain(e)}`);let r=await j(`/api/domains/${encodeURIComponent(e)}/parking`,{method:"PUT",body:JSON.stringify({enabled:t})}),o=await r.json();if(r.status===409&&o.requires_confirmation){if(n.stop(`${y.warning} DNS records will be replaced`),i){k(o,s);return}console.log(`
195
195
  ${Ee.default.yellow("Enabling parking will replace these DNS records:")}`);for(let a of o.existing_dns||[])console.log(` ${Ee.default.dim(a.type)} ${a.name} ${Ee.default.dim("\u2192")} ${a.value}`);console.log(`
196
- ${Ee.default.dim("Run again with --confirm to proceed (not implemented yet).")}`),console.log(` ${Ee.default.dim("Or use the dashboard to confirm.")}`),d();return}if(r.ok||(n.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:i,fields:s})),n.stop(`${y.success} Parking ${t?"enabled":"disabled"}`),i){k(o,s);return}C("Parking Updated"),c("Domain",$.domain(o.domain)),c("Parking",o.parking_enabled?Ee.default.green("enabled"):Ee.default.dim("disabled")),o.hint&&c("",Ee.default.dim(o.hint)),d()}async function So(e,t,i,s){let n=S(!i);n.start(t!==null?`Setting price for ${$.domain(e)} to ${$.price(t)}`:`Removing listing for ${$.domain(e)}`);let r=await x(`/api/domains/${encodeURIComponent(e)}/parking`,{method:"PUT",body:JSON.stringify({listing_price:t})}),o=await r.json();if(r.ok||(n.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:i,fields:s})),n.stop(`${y.success} ${t!==null?"Price set":"Listing removed"}`),i){k(o,s);return}C("Listing Updated"),c("Domain",$.domain(o.domain)),c("Listing",o.listing_price?`${$.price(o.listing_price)} ${Ee.default.dim("(for sale)")}`:Ee.default.dim("not listed")),o.hint&&c("",Ee.default.dim(o.hint)),d()}X();var Je=U(L(),1);W();he();Ye();var Td=" \u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588";function Nd(e){let t=Math.max(...e,1);return e.map(i=>Td[Math.min(Math.round(i/t*8),8)]).join("")}async function Oo(e,t){e||(e=await fe()),K(e,t);let i=S(!t.json);i.start(`Loading analytics for ${$.domain(e)}`);let s=await x(`/api/domains/${encodeURIComponent(e)}/analytics`),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),i.stop("Analytics loaded"),t.json){k(n,t.fields);return}if(d(),C(`Analytics: ${$.domain(e)}`),c("Views (7d)",Je.default.cyan(n.views_7d.toLocaleString())),c("Views (30d)",Je.default.cyan(n.views_30d.toLocaleString())),c("Inquiries",Je.default.cyan(String(n.inquiries_30d))),c("Conversion",n.conversion_rate>0?Je.default.green(`${n.conversion_rate}%`):Je.default.dim("0%")),n.daily_views&&n.daily_views.length>0){let r=n.daily_views.map(m=>m.views),o=Nd(r),a=n.daily_views[0].date.slice(5),l=n.daily_views[n.daily_views.length-1].date.slice(5);d(),console.log(` ${Je.default.dim(a)} ${Je.default.cyan(o)} ${Je.default.dim(l)}`)}if(n.recent_inquiries&&n.recent_inquiries.length>0){d(),console.log(` ${Je.default.bold("Recent Inquiries")}`);let r=n.recent_inquiries.map(o=>[Je.default.dim(o.email),o.offer?$.price(o.offer):Je.default.dim("-"),Je.default.dim(new Date(o.date).toLocaleDateString())]);se(["Email","Offer","Date"],r,[30,12,14])}d(),I("Set a listing price:",`domani parking ${e} price <amount>`),I("Set up email:",`domani email setup ${e}`),I("Domain settings:",`domani settings ${e}`),d()}X();var pe=U(L(),1);W();Ji();async function Io(e,t){switch(e){case void 0:case"list":return Fd(t.json,t.fields);case"create":return qd(t);case"update":return Md(t);case"delete":return Ld(t);case"deliveries":return Vd(t);case"replay":return Ud(t);case"events":return Wd(t.json,t.fields);default:u(`Unknown action: ${e}`,{hint:"Actions: list, create, update, delete, deliveries, replay, events",code:"validation_error",json:t.json,fields:t.fields})}}async function Ud(e){(!e.webhookId||!e.deliveryId||!e.idempotencyKey)&&u("Webhook ID, delivery ID, and idempotency key are required",{hint:"Usage: domani webhooks replay --webhook-id <id> --delivery-id <id> --idempotency-key <stable-key>",code:"validation_error",json:e.json,fields:e.fields});let t=S(!e.json);t.start("Replaying webhook delivery");let i=await x(`/api/webhooks/${encodeURIComponent(e.webhookId)}/deliveries/${encodeURIComponent(e.deliveryId)}/replay`,{method:"POST",body:JSON.stringify({idempotency_key:e.idempotencyKey})}),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),t.stop(`${y.success} Webhook replay ${s.status}`),e.json)return k(s,e.fields);C("Webhook Replay Receipt"),c("Delivery",s.delivery_id),c("Original",s.original_delivery_id),c("Status",s.status),c("Attempts",s.attempts),c("Idempotent retry",s.idempotent_replay?"yes":"no"),d()}async function Fd(e,t){let i=S(!e);i.start("Loading webhooks");let s=await x("/api/webhooks"),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e,fields:t})),i.stop(`${y.success} ${n.webhooks.length} webhook(s)`),e){k(n,t);return}if(n.webhooks.length===0){d(),console.log(` ${pe.default.dim("No webhooks configured.")}`),d(),I("Create one:","domani webhooks create --url https://... --events domain.purchased,dns.updated"),I("List events:","domani webhooks events"),d();return}d(),C("Webhooks");let r=n.webhooks.map(o=>[pe.default.dim(o.id),$.url(o.url),o.events.length<=3?o.events.join(", "):`${o.events.length} events`,o.header_names?.join(", ")||pe.default.dim("none"),o.active?pe.default.green("active"):pe.default.dim("paused")]);se(["ID","URL","Events","Auth headers","Status"],r,[28,40,24,20,10]),d()}async function qd(e){e.url||u("URL required",{hint:"Usage: domani webhooks create --url https://example.com/hook --events domain.purchased,dns.updated",code:"validation_error",json:e.json,fields:e.fields}),e.events||u("Events required",{hint:`Usage: domani webhooks create --url https://... --events domain.purchased,dns.updated
197
- Run 'domani webhooks events' to see available event types.`,code:"validation_error",json:e.json,fields:e.fields});let t=e.events.split(",").map(o=>o.trim()),i;try{i=Tt(e)}catch(o){u(o instanceof Error?o.message:"Invalid webhook headers",{hint:"Set the named environment variable, or remove the conflicting header option.",code:"validation_error",json:e.json,fields:e.fields})}if(e.dryRun)return B("webhook_create",{url:e.url,events:t,header_names:Nt(i)},e.json,e.fields);let s=S(!e.json);s.start("Creating webhook");let n=await x("/api/webhooks",{method:"POST",body:JSON.stringify({url:e.url,events:t,...i!==void 0?{headers:i}:{}})}),r=await n.json();if(n.ok||(s.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:e.json,fields:e.fields})),s.stop(`${y.success} Webhook created`),e.json){k(r,e.fields);return}d(),C("Webhook Created"),c("ID",r.id),c("URL",$.url(r.url)),c("Events",r.events.join(", ")),c("Auth headers",r.header_names?.join(", ")||pe.default.dim("none")),c("Status",pe.default.green("active")),d(),console.log(` ${pe.default.yellow("!")} ${pe.default.bold("Secret:")} ${r.secret}`),console.log(` ${pe.default.dim("Save this secret - it won't be shown again.")}`),console.log(` ${pe.default.dim("Use it to verify payloads with HMAC-SHA256.")}`),d()}async function Md(e){e.webhookId||u("Webhook ID required",{hint:"Usage: domani webhooks update --webhook-id <id> [--url ...] [--events ...] [--active on|off]",code:"validation_error",json:e.json,fields:e.fields});let t={};e.url&&(t.url=e.url),e.events&&(t.events=e.events.split(",").map(r=>r.trim())),e.active!==void 0&&(t.active=e.active==="on"||e.active==="true");try{let r=Tt(e);r!==void 0&&(t.headers=r)}catch(r){u(r instanceof Error?r.message:"Invalid webhook headers",{hint:"Set the named environment variable, or remove the conflicting header option.",code:"validation_error",json:e.json,fields:e.fields})}if(e.dryRun){let{headers:r,...o}=t;return B("webhook_update",{webhook_id:e.webhookId,...o,...r!==void 0?{header_names:Nt(r)}:{}},e.json,e.fields)}let i=S(!e.json);i.start("Updating webhook");let s=await x(`/api/webhooks/${encodeURIComponent(e.webhookId)}`,{method:"PATCH",body:JSON.stringify(t)}),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields})),i.stop(`${y.success} Webhook updated`),e.json){k(n,e.fields);return}C("Webhook Updated"),c("ID",n.id),c("URL",$.url(n.url)),c("Events",n.events.join(", ")),c("Auth headers",n.header_names?.join(", ")||pe.default.dim("none")),c("Status",n.active?pe.default.green("active"):pe.default.dim("paused")),d()}async function Ld(e){if(e.webhookId||u("Webhook ID required",{hint:"Usage: domani webhooks delete --webhook-id <id>",code:"validation_error",json:e.json,fields:e.fields}),e.dryRun)return B("webhook_delete",{webhook_id:e.webhookId},e.json,e.fields);let t=S(!e.json);t.start("Deleting webhook");let i=await x(`/api/webhooks/${encodeURIComponent(e.webhookId)}`,{method:"DELETE"}),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),t.stop(`${y.success} Webhook deleted`),e.json){k(s,e.fields);return}console.log(` ${pe.default.dim("Pending deliveries have been cancelled.")}`),d()}async function Vd(e){e.webhookId||u("Webhook ID required",{hint:"Usage: domani webhooks deliveries --webhook-id <id> [--limit 20]",code:"validation_error",json:e.json,fields:e.fields});let t=e.limit?`?limit=${e.limit}`:"",i=S(!e.json);i.start("Loading deliveries");let s=await x(`/api/webhooks/${encodeURIComponent(e.webhookId)}/deliveries${t}`),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields})),i.stop(`${y.success} ${n.deliveries.length} delivery(ies)`),e.json){k(n,e.fields);return}if(n.deliveries.length===0){d(),console.log(` ${pe.default.dim("No deliveries yet.")}`),d();return}d(),C("Deliveries");let r=n.deliveries.map(o=>{let a=o.status==="delivered"?pe.default.green("delivered"):o.status==="failed"?pe.default.red("failed"):pe.default.yellow("pending");return[o.event_type,a,o.http_status?String(o.http_status):pe.default.dim("-"),String(o.attempts),pe.default.dim(new Date(o.created_at).toLocaleString())]});se(["Event","Status","HTTP","Tries","Date"],r,[22,12,6,6,22]),d()}async function Wd(e,t){let i=S(!e);i.start("Loading event types");let s=await be("/api/webhooks/events"),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e,fields:t})),i.stop(`${y.success} ${n.events.length} event type(s)`),e){k(n,t);return}d(),C("Webhook Event Types");let r=n.events.map(o=>[pe.default.cyan(o.type),pe.default.dim(o.description)]);se(["Event","Description"],r,[24,50]),d()}X();var $e=U(L(),1);W();he();async function Ro(e,t){if(e||u("Domain is required",{hint:`Usage: domani sell <domain> --price <amount>
196
+ ${Ee.default.dim("Run again with --confirm to proceed (not implemented yet).")}`),console.log(` ${Ee.default.dim("Or use the dashboard to confirm.")}`),d();return}if(r.ok||(n.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:i,fields:s})),n.stop(`${y.success} Parking ${t?"enabled":"disabled"}`),i){k(o,s);return}C("Parking Updated"),c("Domain",$.domain(o.domain)),c("Parking",o.parking_enabled?Ee.default.green("enabled"):Ee.default.dim("disabled")),o.hint&&c("",Ee.default.dim(o.hint)),d()}async function So(e,t,i,s){let n=S(!i);n.start(t!==null?`Setting price for ${$.domain(e)} to ${$.price(t)}`:`Removing listing for ${$.domain(e)}`);let r=await j(`/api/domains/${encodeURIComponent(e)}/parking`,{method:"PUT",body:JSON.stringify({listing_price:t})}),o=await r.json();if(r.ok||(n.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:i,fields:s})),n.stop(`${y.success} ${t!==null?"Price set":"Listing removed"}`),i){k(o,s);return}C("Listing Updated"),c("Domain",$.domain(o.domain)),c("Listing",o.listing_price?`${$.price(o.listing_price)} ${Ee.default.dim("(for sale)")}`:Ee.default.dim("not listed")),o.hint&&c("",Ee.default.dim(o.hint)),d()}X();var Je=U(L(),1);W();he();Ye();var Td=" \u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588";function Nd(e){let t=Math.max(...e,1);return e.map(i=>Td[Math.min(Math.round(i/t*8),8)]).join("")}async function Oo(e,t){e||(e=await fe()),K(e,t);let i=S(!t.json);i.start(`Loading analytics for ${$.domain(e)}`);let s=await j(`/api/domains/${encodeURIComponent(e)}/analytics`),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),i.stop("Analytics loaded"),t.json){k(n,t.fields);return}if(d(),C(`Analytics: ${$.domain(e)}`),c("Views (7d)",Je.default.cyan(n.views_7d.toLocaleString())),c("Views (30d)",Je.default.cyan(n.views_30d.toLocaleString())),c("Inquiries",Je.default.cyan(String(n.inquiries_30d))),c("Conversion",n.conversion_rate>0?Je.default.green(`${n.conversion_rate}%`):Je.default.dim("0%")),n.daily_views&&n.daily_views.length>0){let r=n.daily_views.map(m=>m.views),o=Nd(r),a=n.daily_views[0].date.slice(5),l=n.daily_views[n.daily_views.length-1].date.slice(5);d(),console.log(` ${Je.default.dim(a)} ${Je.default.cyan(o)} ${Je.default.dim(l)}`)}if(n.recent_inquiries&&n.recent_inquiries.length>0){d(),console.log(` ${Je.default.bold("Recent Inquiries")}`);let r=n.recent_inquiries.map(o=>[Je.default.dim(o.email),o.offer?$.price(o.offer):Je.default.dim("-"),Je.default.dim(new Date(o.date).toLocaleDateString())]);se(["Email","Offer","Date"],r,[30,12,14])}d(),I("Set a listing price:",`domani parking ${e} price <amount>`),I("Set up email:",`domani email setup ${e}`),I("Domain settings:",`domani settings ${e}`),d()}X();var pe=U(L(),1);W();Ji();async function Io(e,t){switch(e){case void 0:case"list":return Fd(t.json,t.fields);case"create":return qd(t);case"update":return Md(t);case"delete":return Ld(t);case"deliveries":return Vd(t);case"replay":return Ud(t);case"events":return Wd(t.json,t.fields);default:u(`Unknown action: ${e}`,{hint:"Actions: list, create, update, delete, deliveries, replay, events",code:"validation_error",json:t.json,fields:t.fields})}}async function Ud(e){(!e.webhookId||!e.deliveryId||!e.idempotencyKey)&&u("Webhook ID, delivery ID, and idempotency key are required",{hint:"Usage: domani webhooks replay --webhook-id <id> --delivery-id <id> --idempotency-key <stable-key>",code:"validation_error",json:e.json,fields:e.fields});let t=S(!e.json);t.start("Replaying webhook delivery");let i=await j(`/api/webhooks/${encodeURIComponent(e.webhookId)}/deliveries/${encodeURIComponent(e.deliveryId)}/replay`,{method:"POST",body:JSON.stringify({idempotency_key:e.idempotencyKey})}),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),t.stop(`${y.success} Webhook replay ${s.status}`),e.json)return k(s,e.fields);C("Webhook Replay Receipt"),c("Delivery",s.delivery_id),c("Original",s.original_delivery_id),c("Status",s.status),c("Attempts",s.attempts),c("Idempotent retry",s.idempotent_replay?"yes":"no"),d()}async function Fd(e,t){let i=S(!e);i.start("Loading webhooks");let s=await j("/api/webhooks"),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e,fields:t})),i.stop(`${y.success} ${n.webhooks.length} webhook(s)`),e){k(n,t);return}if(n.webhooks.length===0){d(),console.log(` ${pe.default.dim("No webhooks configured.")}`),d(),I("Create one:","domani webhooks create --url https://... --events domain.purchased,dns.updated"),I("List events:","domani webhooks events"),d();return}d(),C("Webhooks");let r=n.webhooks.map(o=>[pe.default.dim(o.id),$.url(o.url),o.events.length<=3?o.events.join(", "):`${o.events.length} events`,o.header_names?.join(", ")||pe.default.dim("none"),o.active?pe.default.green("active"):pe.default.dim("paused")]);se(["ID","URL","Events","Auth headers","Status"],r,[28,40,24,20,10]),d()}async function qd(e){e.url||u("URL required",{hint:"Usage: domani webhooks create --url https://example.com/hook --events domain.purchased,dns.updated",code:"validation_error",json:e.json,fields:e.fields}),e.events||u("Events required",{hint:`Usage: domani webhooks create --url https://... --events domain.purchased,dns.updated
197
+ Run 'domani webhooks events' to see available event types.`,code:"validation_error",json:e.json,fields:e.fields});let t=e.events.split(",").map(o=>o.trim()),i;try{i=Tt(e)}catch(o){u(o instanceof Error?o.message:"Invalid webhook headers",{hint:"Set the named environment variable, or remove the conflicting header option.",code:"validation_error",json:e.json,fields:e.fields})}if(e.dryRun)return B("webhook_create",{url:e.url,events:t,header_names:Nt(i)},e.json,e.fields);let s=S(!e.json);s.start("Creating webhook");let n=await j("/api/webhooks",{method:"POST",body:JSON.stringify({url:e.url,events:t,...i!==void 0?{headers:i}:{}})}),r=await n.json();if(n.ok||(s.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:e.json,fields:e.fields})),s.stop(`${y.success} Webhook created`),e.json){k(r,e.fields);return}d(),C("Webhook Created"),c("ID",r.id),c("URL",$.url(r.url)),c("Events",r.events.join(", ")),c("Auth headers",r.header_names?.join(", ")||pe.default.dim("none")),c("Status",pe.default.green("active")),d(),console.log(` ${pe.default.yellow("!")} ${pe.default.bold("Secret:")} ${r.secret}`),console.log(` ${pe.default.dim("Save this secret - it won't be shown again.")}`),console.log(` ${pe.default.dim("Use it to verify payloads with HMAC-SHA256.")}`),d()}async function Md(e){e.webhookId||u("Webhook ID required",{hint:"Usage: domani webhooks update --webhook-id <id> [--url ...] [--events ...] [--active on|off]",code:"validation_error",json:e.json,fields:e.fields});let t={};e.url&&(t.url=e.url),e.events&&(t.events=e.events.split(",").map(r=>r.trim())),e.active!==void 0&&(t.active=e.active==="on"||e.active==="true");try{let r=Tt(e);r!==void 0&&(t.headers=r)}catch(r){u(r instanceof Error?r.message:"Invalid webhook headers",{hint:"Set the named environment variable, or remove the conflicting header option.",code:"validation_error",json:e.json,fields:e.fields})}if(e.dryRun){let{headers:r,...o}=t;return B("webhook_update",{webhook_id:e.webhookId,...o,...r!==void 0?{header_names:Nt(r)}:{}},e.json,e.fields)}let i=S(!e.json);i.start("Updating webhook");let s=await j(`/api/webhooks/${encodeURIComponent(e.webhookId)}`,{method:"PATCH",body:JSON.stringify(t)}),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields})),i.stop(`${y.success} Webhook updated`),e.json){k(n,e.fields);return}C("Webhook Updated"),c("ID",n.id),c("URL",$.url(n.url)),c("Events",n.events.join(", ")),c("Auth headers",n.header_names?.join(", ")||pe.default.dim("none")),c("Status",n.active?pe.default.green("active"):pe.default.dim("paused")),d()}async function Ld(e){if(e.webhookId||u("Webhook ID required",{hint:"Usage: domani webhooks delete --webhook-id <id>",code:"validation_error",json:e.json,fields:e.fields}),e.dryRun)return B("webhook_delete",{webhook_id:e.webhookId},e.json,e.fields);let t=S(!e.json);t.start("Deleting webhook");let i=await j(`/api/webhooks/${encodeURIComponent(e.webhookId)}`,{method:"DELETE"}),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),t.stop(`${y.success} Webhook deleted`),e.json){k(s,e.fields);return}console.log(` ${pe.default.dim("Pending deliveries have been cancelled.")}`),d()}async function Vd(e){e.webhookId||u("Webhook ID required",{hint:"Usage: domani webhooks deliveries --webhook-id <id> [--limit 20]",code:"validation_error",json:e.json,fields:e.fields});let t=e.limit?`?limit=${e.limit}`:"",i=S(!e.json);i.start("Loading deliveries");let s=await j(`/api/webhooks/${encodeURIComponent(e.webhookId)}/deliveries${t}`),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields})),i.stop(`${y.success} ${n.deliveries.length} delivery(ies)`),e.json){k(n,e.fields);return}if(n.deliveries.length===0){d(),console.log(` ${pe.default.dim("No deliveries yet.")}`),d();return}d(),C("Deliveries");let r=n.deliveries.map(o=>{let a=o.status==="delivered"?pe.default.green("delivered"):o.status==="failed"?pe.default.red("failed"):pe.default.yellow("pending");return[o.event_type,a,o.http_status?String(o.http_status):pe.default.dim("-"),String(o.attempts),pe.default.dim(new Date(o.created_at).toLocaleString())]});se(["Event","Status","HTTP","Tries","Date"],r,[22,12,6,6,22]),d()}async function Wd(e,t){let i=S(!e);i.start("Loading event types");let s=await be("/api/webhooks/events"),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e,fields:t})),i.stop(`${y.success} ${n.events.length} event type(s)`),e){k(n,t);return}d(),C("Webhook Event Types");let r=n.events.map(o=>[pe.default.cyan(o.type),pe.default.dim(o.description)]);se(["Event","Description"],r,[24,50]),d()}X();var $e=U(L(),1);W();he();async function Ro(e,t){if(e||u("Domain is required",{hint:`Usage: domani sell <domain> --price <amount>
198
198
  domani sell <domain> --verify
199
199
  domani sell <domain> --status
200
200
  domani sell <domain> --cancel`,code:"validation_error",json:t.json,fields:t.fields}),K(e,t),t.status)return Bd(e,t);if(t.verify)return Jd(e,t);if(t.cancel)return Gd(e,t);if(t.transferCode)return Kd(e,t.transferCode,t);if(t.price)return Hd(e,t);u("No action specified",{hint:`Usage: domani sell <domain> --price <amount>
201
201
  domani sell <domain> --verify
202
202
  domani sell <domain> --status
203
203
  domani sell <domain> --cancel
204
- domani sell <domain> --transfer-code <code>`,code:"validation_error",json:t.json,fields:t.fields})}async function Hd(e,t){let i=parseFloat(t.price);(isNaN(i)||i<=0)&&u("Invalid price",{hint:"Price must be a positive number, e.g. --price 5000",code:"validation_error",json:t.json,fields:t.fields});let s=S(!t.json);s.start(`Listing ${$.domain(e)} for sale`);let n={domain:e,price:i};t.description&&(n.description=t.description);let r=await x("/api/domains/sell",{method:"POST",body:JSON.stringify(n)}),o=await r.json();if(r.ok||(s.stop("Listing failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:t.json,fields:t.fields})),t.json){s.stop(""),k(o,t.fields);return}(o.listing?.status??"pending_verification")==="active"?(s.stop(`${y.success} Listed for sale`),C("Sell Domain"),c("Domain",$.domain(o.listing?.domain||e)),c("Price",$.price(i)),c("Status",$e.default.green("active")),d(),console.log(` ${$e.default.dim("Your listing is live on the marketplace.")}`),d()):(s.stop(`${y.success} Verification record ready`),C("Sell Domain"),c("Domain",$.domain(o.listing?.domain||e)),c("Price",$.price(i)),c("Status",$e.default.yellow("pending verification")),d(),console.log(" Add this TXT record at your DNS provider:"),d(),console.log(` ${$e.default.dim("Type:")} ${$e.default.bold("TXT")}`),console.log(` ${$e.default.dim("Name:")} ${$e.default.bold(o.txt_record?.name||"@")}`),console.log(` ${$e.default.dim("Value:")} ${$e.default.bold(o.txt_record?.value||`domani-verify=${o.token}`)}`),d(),console.log(` ${$e.default.dim("DNS propagation may take a few minutes to 48 hours.")}`),d(),I("Once the record is set, verify:",`domani sell ${e} --verify`),d())}async function Jd(e,t){let i=S(!t.json);i.start(`Verifying ownership of ${$.domain(e)}`);let s=await x("/api/domains/sell/verify",{method:"POST",body:JSON.stringify({domain:e})}),n=await s.json();if(s.ok||(i.stop("Verification failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),t.json){i.stop(""),k(n,t.fields);return}i.stop(`${y.success} ${$.domain(e)} is now listed for sale!`),C("Domain Listed"),c("Domain",$.domain(n.domain||e)),c("Status",$e.default.green(n.status||"active")),n.price&&c("Price",$.price(n.price)),d(),I("Check listing status:",`domani sell ${e} --status`),I("View your deals:","domani deals"),d()}async function Bd(e,t){let i=S(!t.json);i.start(`Checking listing status for ${$.domain(e)}`);let s=await x(`/api/domains/sell/status?domain=${encodeURIComponent(e)}`),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),i.stop(`${y.success} Listing status loaded`),t.json){k(n,t.fields);return}let r=n.listing;if(C("Listing Status"),c("Domain",$.domain(n.domain||e)),r){let o=r.status;c("Status",o==="active"?$e.default.green(o):$e.default.yellow(o||"unknown")),r.price&&c("Price",$.price(r.price)),r.description&&c("Description",r.description),r.created_at&&c("Listed",$e.default.dim(new Date(r.created_at).toLocaleDateString()))}else c("Status",$e.default.dim("No listing found"));n.deal&&c("Deal",`${n.deal.status} ($${n.deal.price})`),d()}async function Gd(e,t){let i=S(!t.json);i.start(`Removing ${$.domain(e)} from sale`);let s=await x(`/api/domains/sell?domain=${encodeURIComponent(e)}`,{method:"DELETE"}),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),t.json){i.stop(""),k(n,t.fields);return}i.stop(`${y.success} ${$.domain(e)} removed from sale`),d()}async function Kd(e,t,i){let s=S(!i.json);s.start(`Looking up active deal for ${$.domain(e)}`);let n=await x(`/api/deals?role=seller&domain=${encodeURIComponent(e)}&status=active`),r=await n.json();n.ok||(s.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:i.json,fields:i.fields}));let a=(r.deals||r.data||[]).filter(g=>g.domain.toLowerCase()===e.toLowerCase());a.length===0&&(s.stop("No active deal found"),u(`No active deal found for ${e}`,{hint:`Make sure you have an active sale for this domain.
205
- Run 'domani deals --role seller' to see your deals.`,code:"not_found",json:i.json,fields:i.fields}));let l=a[0].id;s.message(`Submitting transfer code for deal ${$e.default.dim(l)}`);let m=await x(`/api/deals/${encodeURIComponent(l)}`,{method:"PATCH",body:JSON.stringify({auth_code:t})}),f=await m.json();if(m.ok||(s.stop("Failed"),u(f.error||f.message,{hint:f.hint,status:m.status,json:i.json,fields:i.fields})),i.json){s.stop(""),k(f,i.fields);return}s.stop(`${y.success} Transfer code submitted for ${$.domain(e)}`),C("Transfer Code Submitted"),c("Domain",$.domain(e)),c("Deal",$e.default.dim(l)),c("Status",$e.default.green(f.status||"code_submitted")),d(),I("Track the deal:",`domani deals ${l}`),d()}X();var ve=U(L(),1);W();async function Ao(e,t){return e?Yd(e,t):zd(t)}async function zd(e){let t=S(!e.json);t.start("Loading deals");let i=new URLSearchParams;e.role&&i.set("role",e.role),e.status&&i.set("status",e.status);let s=i.toString()?`?${i.toString()}`:"",n=await x(`/api/deals${s}`),r=await n.json();n.ok||(t.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:e.json,fields:e.fields}));let o=r.deals||r.data||[];if(t.stop(`${y.success} ${o.length} deal(s)`),e.json){k(r,e.fields);return}if(o.length===0){d(),console.log(` ${ve.default.dim("No deals found.")}`),d(),I("List a domain for sale:","domani sell <domain> --price <amount>"),d();return}d(),C("Deals");let a=o.map(l=>{let m=l.status==="completed"?ve.default.green:l.status==="active"?ve.default.cyan:l.status==="cancelled"?ve.default.red:ve.default.yellow;return[$.domain(l.domain),$.price(l.price),m(l.status),ve.default.dim(l.role||"-"),ve.default.dim(new Date(l.created_at).toLocaleDateString())]});se(["Domain","Price","Status","Role","Created"],a,[28,12,14,10,14]),d()}async function Yd(e,t){let i=S(!t.json);i.start(`Loading deal ${ve.default.dim(e)}`);let s=await x(`/api/deals/${encodeURIComponent(e)}`),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),i.stop(`${y.success} Deal loaded`),t.json){k(n,t.fields);return}let r=n.deal||n;C("Deal Details"),c("ID",ve.default.dim(r.id)),c("Domain",$.domain(r.domain)),c("Price",$.price(r.price));let o=r.status==="completed"?ve.default.green:r.status==="active"?ve.default.cyan:r.status==="cancelled"?ve.default.red:ve.default.yellow;c("Status",o(r.status)),r.role&&c("Your Role",r.role),r.buyer&&c("Buyer",ve.default.dim(r.buyer)),r.seller&&c("Seller",ve.default.dim(r.seller)),r.created_at&&c("Created",ve.default.dim(new Date(r.created_at).toLocaleDateString())),r.updated_at&&c("Updated",ve.default.dim(new Date(r.updated_at).toLocaleDateString())),d();let a=r.events||[];if(a.length>0){C("Timeline");for(let l of a){let m=ve.default.dim(new Date(l.created_at).toLocaleString()),f=l.status==="completed"?y.success:l.status==="expired"||l.status==="refunded"?y.error:y.info;console.log(` ${f} ${m} ${l.detail||l.status}`)}d()}(r.status==="escrow_held"||r.status==="epp_pending")&&r.role==="seller"&&(I("Submit transfer code:",`domani sell ${r.domain} --transfer-code <code>`),d())}X();var Ue=U(L(),1);W();he();async function Do(e,t,i){switch(e){case void 0:case"list":case"ls":return Xd(i);case"request":case"acquire":case"new":return Eo(t,i);case"status":case"get":return Po(t,i);case"cancel":case"rm":return Zd(t,i);default:return e.includes(".")?Eo(e,i):Po(e,i)}}async function Eo(e,t){e||u("A domain is required.",{hint:"domani broker request dream.com --max-budget 5000",json:t.json}),K(e,{json:t.json});let i=S(!t.json);i.start(`Requesting acquisition of ${$.domain(e)}`);let s={domain:e};if(t.maxBudget){let a=Number(t.maxBudget);(!Number.isFinite(a)||a<=0)&&u("--max-budget must be a positive number (USD).",{json:t.json}),s.max_budget=a}let n=await x("/api/broker",{method:"POST",body:JSON.stringify(s)}),r=await n.json();n.ok||(i.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:t.json,fields:t.fields}));let o=r.request||r;if(i.stop(`${y.success} Acquisition requested`),t.json)return k(r,t.fields);C("Broker request"),c("Domain",$.domain(o.domain)),c("Status",wn(o.status)),o.max_budget!=null&&c("Max budget",$.price(o.max_budget)),c("ID",Ue.default.dim(o.id)),d(),console.log(` ${Ue.default.dim("We'll source the owner and reach out anonymously. Commission-only - you pay nothing unless a deal closes.")}`),d(),I("Check progress:",`domani broker status ${o.id}`),d()}async function Xd(e){let t=S(!e.json);t.start("Loading broker requests");let i=e.status?`?status=${encodeURIComponent(e.status)}`:"",s=await x(`/api/broker${i}`),n=await s.json();s.ok||(t.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields}));let r=n.requests||n.data||[];if(t.stop(`${y.success} ${r.length} request(s)`),e.json)return k(n,e.fields);if(r.length===0){d(),console.log(` ${Ue.default.dim("No broker requests yet.")}`),d(),I("Acquire a taken domain:","domani broker request <domain> --max-budget <amount>"),d();return}d(),C("Broker requests"),se(["Domain","Status","Budget","ID"],r.map(o=>[$.domain(o.domain),wn(o.status),o.max_budget!=null?$.price(o.max_budget):Ue.default.dim("-"),Ue.default.dim(o.id)])),d()}async function Po(e,t){e||u("A request ID is required.",{hint:"domani broker status <id> (list with: domani broker)",json:t.json});let i=S(!t.json);i.start("Loading request");let s=await x(`/api/broker/${encodeURIComponent(e)}`),n=await s.json();s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields}));let r=n.request||n;if(i.stop(`${y.success} ${$.domain(r.domain)}`),t.json)return k(n,t.fields);C("Broker request"),c("Domain",$.domain(r.domain)),c("Status",wn(r.status)),r.max_budget!=null&&c("Max budget",$.price(r.max_budget)),c("Contacted",r.contacted?Ue.default.green("yes"):Ue.default.dim("not yet")),r.failure_reason&&c("Reason",Ue.default.yellow(r.failure_reason)),c("ID",Ue.default.dim(r.id)),d(),r.negotiation_id?(console.log(` ${Ue.default.dim("The owner responded - an anonymous negotiation is open.")}`),d(),I("Review the offer:","domani deals"),d()):["sourcing","contacted","negotiating"].includes(r.status)&&(I("Cancel this request:",`domani broker cancel ${r.id}`),d())}async function Zd(e,t){e||u("A request ID is required.",{hint:"domani broker cancel <id>",json:t.json});let i=S(!t.json);i.start("Cancelling request");let s=await x(`/api/broker/${encodeURIComponent(e)}`,{method:"DELETE"}),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),i.stop(`${y.success} Request cancelled`),t.json)return k(n,t.fields);d()}function wn(e){return["completed","agreed"].includes(e)?Ue.default.green(e):["negotiating","contacted","sourcing"].includes(e)?Ue.default.cyan(e):["declined","no_contact","failed","expired","cancelled"].includes(e)?Ue.default.dim(e):e}X();var ge=U(L(),1);W();async function No(e){return e.read?ec(e):Qd(e)}async function Qd(e){let t=S(!e.json);t.start("Loading notifications");let i=new URLSearchParams;e.unread&&i.set("unread","true"),e.limit&&i.set("limit",e.limit);let s=i.toString()?`?${i.toString()}`:"",n=await x(`/api/notifications${s}`),r=await n.json();n.ok||(t.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:e.json,fields:e.fields}));let o=r.notifications||r.data||[],a=r.unread_count??o.filter(m=>!m.read).length;if(t.stop(`${y.success} ${o.length} notification(s)${a>0?` ${y.dot} ${ge.default.yellow(`${a} unread`)}`:""}`),e.json){k(r,e.fields);return}if(o.length===0){d(),console.log(` ${ge.default.dim("No notifications.")}`),d();return}d(),C("Notifications");let l=o.map(m=>{let f=m.read?ge.default.dim(y.dot):ge.default.cyan(y.info),g=tc(m.type),b=m.read?ge.default.dim(m.title):ge.default.white(m.title),v=m.body?m.read?ge.default.dim(To(m.body,40)):ge.default.dim(To(m.body,40)):ge.default.dim("-"),w=ge.default.dim(new Date(m.created_at).toLocaleDateString());return[f,g,b,v,w]});se(["","Type","Title","Body","Date"],l,[3,16,28,42,14]),d(),a>0&&(console.log(` ${ge.default.dim("Mark all as read:")} ${ge.default.cyan("domani notifications --read")}`),d())}async function ec(e){let t=S(!e.json);t.start("Marking all notifications as read");let i=await x("/api/notifications/read-all",{method:"POST"}),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),e.json){t.stop(""),k(s,e.fields);return}let n=s.count??0;t.stop(`${y.success} ${n} notification(s) marked as read`),d()}function tc(e){let t={deal:ge.default.cyan,sale:ge.default.green,purchase:ge.default.green,transfer:ge.default.yellow,expiry:ge.default.red,security:ge.default.red,billing:ge.default.yellow,email:ge.default.blue},i=e.split(".")[0].split("_")[0];return(t[i]||ge.default.dim)(e)}function To(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}X();var _t=U(L(),1);W();async function Uo(e){let t=e.limit?Number(e.limit):20,i=await x(`/api/billing/invoices?limit=${t}`),s=await i.json();if(i.ok||u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields}),e.json){k({...s,count:s.invoices.length},e.fields);return}if(s.invoices.length===0){console.log(` ${_t.default.dim("No invoices yet.")}`);return}C(`Invoices (${s.invoices.length})`),d();for(let n of s.invoices){let r=`$${(n.amount_paid/100).toFixed(2)}`,o=new Date(n.created).toLocaleDateString(),a=n.number||n.id;console.log(` ${y.success} ${_t.default.bold(a)} ${_t.default.green(r)} ${_t.default.dim(o)}`),n.description&&console.log(` ${_t.default.dim(n.description)}`),n.hosted_invoice_url&&console.log(` ${_t.default.dim(n.hosted_invoice_url)}`)}d(),s.has_more&&(console.log(` ${_t.default.dim(`Showing ${s.invoices.length} most recent. Use --limit to see more.`)}`),d())}X();var ui=U(L(),1);W();async function Fo(e){let t=S(!e?.json);t.start("Setting up billing session");let i=await x("/api/billing/setup",{method:"POST",body:JSON.stringify({mode:"checkout"})}),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e?.json})),s.url||(t.stop("Failed"),u("No checkout URL returned",{hint:"Try again or add a payment method at the dashboard.",json:e?.json})),t.stop("Checkout ready"),e?.json){k({url:s.url});return}d(),console.log(` ${ui.default.dim("Opening browser")} ${y.arrow} ${$.url(s.url)}`),d(),We(s.url),console.log(` ${y.info} ${ui.default.dim("Complete payment setup in your browser.")}`),console.log(` ${ui.default.dim(" After setup, you can purchase domains with")} ${ui.default.cyan("domani buy")}`),d()}X();var kn=U(L(),1);W();async function qo(e){let t=S(!e?.json);t.start("Creating upgrade session");let i=await x("/api/billing/subscribe",{method:"POST"}),s=await i.json();if(!i.ok){t.stop("Failed"),s.code==="ALREADY_SUBSCRIBED"||s.code==="ALREADY_PRO"?u("You're already on a paid plan.",{json:e?.json}):u(s.error||s.message,{hint:s.hint,status:i.status,json:e?.json});return}if(t.stop("Ready"),e?.json){k({url:s.url},e?.fields);return}d(),console.log(` ${kn.default.dim("Opening browser")} ${y.arrow} ${$.url(s.url)}`),d(),We(s.url),console.log(` ${y.info} ${kn.default.dim("Complete your plan upgrade in the browser.")}`),d()}X();var _n=U(L(),1);W();async function Mo(e){let t=S(!e?.json);t.start("Cancelling subscription");let i=await x("/api/billing/cancel",{method:"POST"}),s=await i.json();if(!i.ok){t.stop("Failed"),s.code==="NOT_PAID"||s.code==="NOT_PRO"?u("You're not on a paid plan.",{json:e?.json}):u(s.error||s.message,{hint:s.hint,status:i.status,json:e?.json});return}if(t.stop("Done"),e?.json){k(s,e?.fields);return}d();let n=s.cancel_at?new Date(s.cancel_at).toLocaleDateString():"end of billing period";console.log(` ${y.success} ${_n.default.dim("Subscription cancelled.")} Access continues until ${_n.default.cyan(n)}.`),d()}X();var tt=U(L(),1);W();he();Ye();async function Lo(e,t,i){e||(e=await fe()),K(e,i);let s=[];if(t?.length&&s.push(...t),i.set&&s.push(...i.set.split(",").map(n=>n.trim()).filter(Boolean)),s.length>0||i.reset){await sc(e,s,i);return}await ic(e,i)}async function ic(e,t){let i=S(!t.json);i.start(`Fetching nameservers for ${$.domain(e)}`);let s=await x(`/api/domains/${encodeURIComponent(e)}/nameservers`),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),i.stop(`Nameservers for ${$.domain(e)}`),t.json){k(n,t.fields);return}if(d(),n.nameservers.length===0)console.log(` ${y.warning} ${tt.default.yellow("No nameservers configured.")}`),console.log(` ${tt.default.dim("DNS operations (parking, email, connect) will not work.")}`),d(),I("Set default nameservers:",`domani nameservers ${e} --reset`);else{C("Nameservers");for(let r of n.nameservers)console.log(` ${y.success} ${tt.default.cyan(r)}`);n.default_nameservers&&n.nameservers.length===n.default_nameservers.length&&n.nameservers.every(o=>n.default_nameservers.includes(o))&&(d(),console.log(` ${tt.default.dim("Using default nameservers.")}`))}n.default_nameservers?.length&&(d(),c("Defaults",n.default_nameservers.map(r=>tt.default.dim(r)).join(tt.default.dim(", ")))),d()}async function sc(e,t,i){let s=S(!i.json);if(i.reset){s.start(`Fetching default nameservers for ${$.domain(e)}`);let o=await x(`/api/domains/${encodeURIComponent(e)}/nameservers`),a=await o.json();o.ok||(s.stop("Failed"),u(a.error,{hint:a.hint,status:o.status,json:i.json,fields:i.fields})),a.default_nameservers?.length||(s.stop("No defaults"),u("No default nameservers available for this domain's registrar.",{code:"not_found",json:i.json,fields:i.fields})),t=a.default_nameservers,s.stop(`Using defaults: ${t.map(l=>tt.default.cyan(l)).join(tt.default.dim(", "))}`)}if(t.length<2&&u("At least 2 nameservers required.",{hint:"Example: domani nameservers example.com ns1.dns.com ns2.dns.com",code:"validation_error",json:i.json,fields:i.fields}),i.dryRun)return B("nameservers_set",{domain:e,nameservers:t},i.json,i.fields);s.start(`Setting nameservers for ${$.domain(e)}`);let n=await x(`/api/domains/${encodeURIComponent(e)}/nameservers`,{method:"PUT",body:JSON.stringify({nameservers:t})}),r=await n.json();if(n.ok||(s.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:i.json,fields:i.fields})),s.stop(`${y.success} Nameservers updated`),i.json){k(r,i.fields);return}d();for(let o of r.nameservers)console.log(` ${y.success} ${tt.default.cyan(o)}`);d(),console.log(` ${tt.default.dim("Changes may take up to 48 hours to propagate.")}`),d(),I("Check propagation:",`domani status ${e}`),d()}var Vo=require("crypto"),es=U(require("fs"),1);mt();var mi=U(L(),1);W();function nc(e,t){let i=e.split(".").map(Number),s=t.split(".").map(Number);for(let n=0;n<3;n++){if((i[n]||0)>(s[n]||0))return 1;if((i[n]||0)<(s[n]||0))return-1}return 0}async function Wo(e){let t=S(!e?.json);t.start("Checking for updates");let i=qe();try{let s=await fetch(`${i}/api/cli/version`);s.ok||(t.stop("Failed"),u("Could not check for updates"));let n=await s.json(),r=n.version,o=n.sha256;if(nc(r,_e)<=0){t.stop(`${y.success} Already up to date (v${_e})`),e?.json&&k({current:_e,latest:r,up_to_date:!0});return}if(e?.json){t.stop(""),k({current:_e,latest:r,up_to_date:!1,hint:"Run `domani update` to upgrade."});return}t.stop(`New version available: ${mi.default.cyan(_e)} ${y.arrow} ${mi.default.green(r)}`);let a=S();a.start("Downloading update");let l=`${i}/cli/domani.js`,m=await fetch(l);m.ok||(a.stop("Download failed"),u(`Failed to download from ${l}`));let f=await m.text();o&&(0,Vo.createHash)("sha256").update(f).digest("hex")!==o&&(a.stop("Integrity check failed"),u("Downloaded file does not match expected hash - update aborted"));let g=process.argv[1];g||(a.stop("Failed"),u("Could not determine binary path"));let b=es.default.realpathSync(g),v=b+".tmp";es.default.writeFileSync(v,f,{mode:493}),es.default.renameSync(v,b),a.stop(`${y.success} Updated to v${r}`),d(),console.log(` ${mi.default.dim("Restart your terminal or run")} domani --version ${mi.default.dim("to verify")}`),d()}catch(s){u(`Update failed: ${s instanceof Error?s.message:String(s)}`)}}var ts=U(require("fs"),1),Ho=U(require("path"),1),Jo=U(require("os"),1);De();var fi=U(L(),1);W();async function Bo(){let e=process.argv[1],t=e?ts.default.realpathSync(e):null,i=Ho.default.join(Jo.default.homedir(),".domani");if(d(),console.log(` ${fi.default.bold("This will remove:")}`),t&&console.log(` ${y.dot} CLI binary: ${fi.default.dim(t)}`),console.log(` ${y.dot} Config dir: ${fi.default.dim(i)}`),d(),await Ke({message:"Uninstall domani?"})!==!0){console.log(` ${fi.default.dim("Cancelled.")}`);return}ts.default.rmSync(i,{recursive:!0,force:!0}),t&&ts.default.unlinkSync(t),d(),console.log(` ${y.success} domani uninstalled.`),d()}X();var re=U(L(),1);W();async function Ko(e,t){let i=t?.json,s=t?.fields,n=e?`/api/schema?command=${encodeURIComponent(e)}`:"/api/schema",r=S(!i);r.start("Loading schema");let o=await be(n),a=await o.json();if(o.ok||(r.stop("Failed"),u(a.error||a.message,{hint:a.hint,status:o.status,json:i,fields:s})),r.stop("Schema loaded"),i){k(a,s);return}e?oc(e,a):rc(a.commands)}function rc(e){C("Commands");let t=Object.entries(e).map(([i,s])=>[re.default.bold(re.default.cyan(i)),s.description]);se(["Command","Description"],t,[20,50]),d(),console.log(` ${re.default.dim("Run")} ${re.default.cyan("domani schema <command>")} ${re.default.dim("for full details")}`),d()}function oc(e,t){if(C(`domani ${e}`),console.log(` ${t.description}`),d(),console.log(` ${$.label("Usage:")} ${re.default.cyan(t.usage)}`),t.arguments&&Object.keys(t.arguments).length>0){d(),console.log(` ${re.default.bold("Arguments")}`);for(let[i,s]of Object.entries(t.arguments)){let n=s.required?re.default.red("*"):"",r=re.default.dim(`(${s.type}${s.variadic?", variadic":""})`);console.log(` ${re.default.cyan(i)}${n} ${r}`),s.description&&console.log(` ${re.default.dim(s.description)}`)}}if(t.options&&Object.keys(t.options).length>0){d(),console.log(` ${re.default.bold("Options")}`);for(let[i,s]of Object.entries(t.options)){let n=s.required?re.default.red("*"):"",r=re.default.dim(`(${s.type})`),o=s.choices?re.default.dim(` [${s.choices.join(", ")}]`):"";console.log(` ${re.default.cyan(`--${i}`)}${n} ${r}${o}`),console.log(` ${re.default.dim(s.description)}`)}}if(t.api)if(d(),console.log(` ${re.default.bold("API")}`),ac(t.api))Go(t.api);else for(let[i,s]of Object.entries(t.api))console.log(` ${re.default.bold(re.default.yellow(i))}`),Go(s,6);t.errors&&t.errors.length>0&&(d(),console.log(` ${re.default.bold("Errors")}`),console.log(` ${t.errors.map(i=>re.default.dim(i)).join(re.default.dim(", "))}`)),d()}function ac(e){return typeof e=="object"&&e!==null&&"method"in e&&"path"in e}function Go(e,t=4){let i=" ".repeat(t);if(console.log(`${i}${re.default.green(e.method)} ${re.default.white(e.path)}`),e.parameters&&Object.keys(e.parameters).length>0)for(let[s,n]of Object.entries(e.parameters)){let r=n.required?re.default.red("*"):"",o=[n.type];n.enum&&o.push(`enum: ${n.enum.join(", ")}`),n.minimum!==void 0&&o.push(`min: ${n.minimum}`),n.maximum!==void 0&&o.push(`max: ${n.maximum}`),n.maxItems!==void 0&&o.push(`maxItems: ${n.maxItems}`),n.items&&o.push(`items: ${n.items}`),n.in==="path"&&o.push("in: path");let a=re.default.dim(`(${o.join(", ")})`);console.log(`${i} ${re.default.cyan(s)}${r} ${a}`),n.description&&console.log(`${i} ${re.default.dim(n.description)}`)}}X();var Fe=U(L(),1);De();W();async function zo(e){let t=S(!e.json);t.start("Loading payment method");let i=await x("/api/me"),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),e.json){t.stop(""),k(s.card?{has_payment_method:s.has_payment_method,card:s.card}:{has_payment_method:!1},e.fields);return}if(!s.has_payment_method||!s.card){t.stop("No payment method on file"),d(),console.log(` ${Fe.default.dim("Add a card with")} ${Fe.default.cyan("domani card add")}`),d();return}let{brand:n,last4:r,exp_month:o,exp_year:a}=s.card,l=`${String(o).padStart(2,"0")}/${a}`,m=n.charAt(0).toUpperCase()+n.slice(1);t.stop("Payment method loaded"),C("Payment method"),c("Card",`${Fe.default.bold(m)} \u2022\u2022\u2022\u2022 ${Fe.default.bold(r)}`),c("Expires",l),d(),console.log(` ${Fe.default.dim("Update with")} ${Fe.default.cyan("domani card add")}`),d()}async function Yo(e){let t=S(!e?.json);t.start("Setting up payment session");let i=await x("/api/billing/setup",{method:"POST",body:JSON.stringify({mode:"checkout"})}),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e?.json})),s.url||(t.stop("Failed"),u("No checkout URL returned",{json:e?.json})),t.stop("Checkout ready"),e?.json){k({url:s.url},e?.fields);return}d(),console.log(` ${Fe.default.dim("Opening browser")} ${y.arrow} ${$.url(s.url)}`),d(),We(s.url),console.log(` ${y.info} ${Fe.default.dim("Complete payment setup in your browser.")}`),console.log(` ${Fe.default.dim(" After setup, you can purchase domains with")} ${Fe.default.cyan("domani buy")}`),d()}async function Xo(e){if(!e?.yes&&!e?.json){let n=await Ke({message:"Remove your saved payment method?"});if(le(n)||!n){console.log(` ${Fe.default.dim("Cancelled.")}`);return}}let t=S(!e?.json);t.start("Removing payment method");let i=await x("/api/billing/card",{method:"DELETE"}),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e?.json})),t.stop(`${y.success} Payment method removed`),e?.json){k({removed:!0},e?.fields);return}d(),console.log(` ${Fe.default.dim("Add a new card with")} ${Fe.default.cyan("domani card add")}`),d()}var jn=U(L(),1);X();W();async function me(e,t,i,s){let n=S(!i.json);n.start(s);let r=await x(e,t),o=await r.json();return r.ok||(n.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:i.json,fields:i.fields})),n.stop(`${y.success} Done`),o}async function Zo(e,t){if(!e||e==="list"){let i=await me("/api/workspaces",void 0,t,"Loading workspaces");if(t.json)return k(i,t.fields);if(d(),C("Workspaces"),!i.workspaces.length){console.log(` ${jn.default.dim("No workspaces yet.")}`),I("Create one:","domani workspace create --name Acme");return}se(["ID","Name","Role","Mailboxes","Members"],i.workspaces.map(s=>[s.id,s.name,s.role,String(s.mailbox_count),String(s.member_count)]),[28,28,10,10,8]),d();return}if(e==="create"){t.name||u("Workspace name required",{hint:"Usage: domani workspace create --name Acme",code:"validation_error",json:t.json});let i=await me("/api/workspaces",{method:"POST",body:JSON.stringify({name:t.name})},t,"Creating workspace");if(t.json)return k(i,t.fields);d(),C("Workspace Created"),c("ID",i.id),c("Name",i.name),d();return}if(e==="show"){t.id||u("Workspace ID required",{hint:"Usage: domani workspace show --id <id>",code:"validation_error",json:t.json});let i=await me(`/api/workspaces/${encodeURIComponent(t.id)}`,void 0,t,"Loading workspace");if(t.json)return k(i,t.fields);d(),C(i.name),c("Role",i.role),c("Mailboxes",i.mailboxes.length),c("Members",i.members.length),d(),se(["Email","Role","Mailbox grants"],i.members.map(s=>[s.email,s.role,String(s.mailbox_grants.length)]),[42,12,16]),d();return}if(e==="access"){if(t.id||u("Workspace ID required",{hint:"Usage: domani workspace access --id <id>",code:"validation_error",json:t.json}),!t.subject&&!t.resource&&!t.profile){let a=await me(`/api/workspaces/${encodeURIComponent(t.id)}/access`,void 0,t,"Loading access graph");if(t.json)return k(a,t.fields);d(),C("Access Graph"),c("Principals",a.principals.length),c("Mailboxes",a.mailboxes.length),c("Groups",a.groups.length),c("Collections",a.collections.length),c("Active grants",a.grants.length),c("Pending offers",a.offers.length),d();return}(!t.subject||!t.resource||!t.profile)&&u("Subject, resource, and profile are required together",{hint:"Usage: domani workspace access --id <id> --subject human:<id> --resource mailbox:<id> --profile responder [--apply]",code:"validation_error",json:t.json});let[i,s]=t.subject.split(":",2),[n,r]=t.resource.split(":",2);(!s||!["human","agent","service","token","group"].includes(i))&&u("Invalid --subject",{hint:"Use human:<id>, agent:<id>, service:<id>, token:<id>, or group:<id>",json:t.json}),(!r||!["mailbox","collection"].includes(n))&&u("Invalid --resource",{hint:"Use mailbox:<id> or collection:<id>",json:t.json});let o=await me(`/api/workspaces/${encodeURIComponent(t.id)}/access`,{method:"PUT",body:JSON.stringify({mode:t.apply?"apply":"plan",subject:i==="group"?{type:"group",id:s}:{type:"principal",principal:{type:i,id:s}},resource:{type:n,id:r},profile:t.profile,expected_version:t.expectedVersion?Number(t.expectedVersion):void 0})},t,t.apply?"Applying access":"Planning access");if(t.json)return k(o,t.fields);d(),C(t.apply?"Access Applied":"Access Plan"),c("Action",o.action),c("Changed",String(o.changed)),o.grant_id&&c("Grant",o.grant_id),d();return}if(e==="group"){(!t.id||!t.name)&&u("Workspace ID and group name required",{hint:"Usage: domani workspace group --id <id> --name Support --principals human:u1,agent:a1",code:"validation_error",json:t.json});let i=(t.principals||"").split(",").map(n=>n.trim()).filter(Boolean).map(n=>{let[r,o]=n.split(":",2);return o||u(`Invalid principal: ${n}`,{hint:"Use type:id",json:t.json}),{type:r,id:o,label:o}}),s=await me(`/api/workspaces/${encodeURIComponent(t.id)}/access/groups`,{method:"PUT",body:JSON.stringify({id:t.groupId,name:t.name,principals:i})},t,"Syncing access group");if(t.json)return k(s,t.fields);d(),C("Access Group Synced"),c("ID",s.id),c("Principals",s.principal_count),d();return}if(e==="collection"){(!t.id||!t.name)&&u("Workspace ID and collection name required",{hint:"Usage: domani workspace collection --id <id> --name Admin --mailboxes mb1,mb2",code:"validation_error",json:t.json});let i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/access/collections`,{method:"PUT",body:JSON.stringify({id:t.collectionId,name:t.name,mailbox_ids:t.mailboxes?.split(",").map(s=>s.trim()).filter(Boolean)??[]})},t,"Syncing mailbox collection");if(t.json)return k(i,t.fields);d(),C("Mailbox Collection Synced"),c("ID",i.id),c("Mailboxes",i.mailbox_count),d();return}if(e==="offer"){(!t.id||!t.email)&&u("Workspace ID and recipient email required",{hint:"Usage: domani workspace offer --id <id> --email person@example.com --mailboxes mb1,mb2 --profile responder",code:"validation_error",json:t.json});let i=(t.mailboxes||"").split(",").map(n=>n.trim()).filter(Boolean).map(n=>({resource:{type:"mailbox",id:n},profile:t.profile||"responder"})),s=await me(`/api/workspaces/${encodeURIComponent(t.id)}/access/offers`,{method:"POST",body:JSON.stringify({email:t.email,grants:i,ownership_disposition:t.ownershipDisposition,creator_disposition:t.creatorDisposition,billing_disposition:t.billingDisposition})},t,"Sending access offer");if(t.json)return k(s,t.fields);d(),C("Access Offered"),c("Email",s.email),c("Expires",s.expires_at),d();return}if(e==="accept-offer"){t.token||u("Access offer token required",{hint:"Usage: domani workspace accept-offer --token <token>",code:"validation_error",json:t.json});let i=await me("/api/workspaces/access/offers/accept",{method:"POST",body:JSON.stringify({token:t.token})},t,"Accepting access offer");if(t.json)return k(i,t.fields);d(),C("Access Accepted"),c("Workspace",i.workspace_name),c("Ownership",i.ownership),d();return}if(e==="revoke-access"){(!t.id||!t.grantId)&&u("Workspace and grant IDs required",{hint:"Usage: domani workspace revoke-access --id <id> --grant-id <id>",code:"validation_error",json:t.json});let i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/access/grants/${encodeURIComponent(t.grantId)}`,{method:"DELETE",body:JSON.stringify({expected_version:t.expectedVersion?Number(t.expectedVersion):void 0})},t,"Revoking access");if(t.json)return k(i,t.fields);d(),C("Access Revoked"),c("Grant",i.grant_id),c("Version",i.version),d();return}if(e==="rename"){(!t.id||!t.name)&&u("Workspace ID and name required",{hint:"Usage: domani workspace rename --id <id> --name <name>",code:"validation_error",json:t.json});let i=await me(`/api/workspaces/${encodeURIComponent(t.id)}`,{method:"PATCH",body:JSON.stringify({name:t.name})},t,"Renaming workspace");if(t.json)return k(i,t.fields);d(),C("Workspace Renamed"),c("ID",i.id),c("Name",i.name),d();return}if(e==="invite"){(!t.id||!t.email)&&u("Workspace ID and email required",{hint:"Usage: domani workspace invite --id <id> --email person@example.com",code:"validation_error",json:t.json});let i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/invitations`,{method:"POST",body:JSON.stringify({email:t.email,role:t.role,mailbox_ids:t.mailboxes?.split(",").map(s=>s.trim()).filter(Boolean),mailbox_role:t.mailboxRole})},t,"Sending invitation");if(t.json)return k(i,t.fields);d(),C("Invitation Sent"),c("Email",i.email),c("Role",i.role),c("Expires",i.expires_at),d();return}if(e==="accept"){t.token||u("Invitation token required",{hint:"Usage: domani workspace accept --token <token>",code:"validation_error",json:t.json});let i=await me("/api/workspaces/invitations/accept",{method:"POST",body:JSON.stringify({token:t.token})},t,"Accepting invitation");if(t.json)return k(i,t.fields);d(),C("Workspace Joined"),c("Workspace",i.workspace_name),c("Role",i.role),d();return}if(e==="revoke-invite"){(!t.id||!t.invitationId)&&u("Workspace ID and invitation ID required",{hint:"Usage: domani workspace revoke-invite --id <id> --invitation-id <id>",code:"validation_error",json:t.json});let i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/invitations/${encodeURIComponent(t.invitationId)}`,{method:"DELETE"},t,"Revoking invitation");if(t.json)return k(i,t.fields);d(),C("Invitation Revoked"),c("Invitation",i.invitation_id),d();return}if(e==="member-role"){(!t.id||!t.membershipId||!t.role)&&u("Workspace ID, membership ID, and role required",{hint:"Usage: domani workspace member-role --id <id> --membership-id <id> --role admin|member",code:"validation_error",json:t.json});let i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/members/${encodeURIComponent(t.membershipId)}`,{method:"PATCH",body:JSON.stringify({role:t.role})},t,"Updating member role");if(t.json)return k(i,t.fields);d(),C("Member Updated"),c("Membership",i.id),c("Role",i.role),d();return}if(e==="remove-member"){(!t.id||!t.membershipId)&&u("Workspace ID and membership ID required",{hint:"Usage: domani workspace remove-member --id <id> --membership-id <id>",code:"validation_error",json:t.json});let i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/members/${encodeURIComponent(t.membershipId)}`,{method:"DELETE"},t,"Removing member and revoking access");if(t.json)return k(i,t.fields);d(),C("Member Removed"),c("Membership",i.membership_id),d();return}if(e==="leave"){t.id||u("Workspace ID required",{hint:"Usage: domani workspace leave --id <id>",code:"validation_error",json:t.json});let i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/members/me`,{method:"DELETE"},t,"Leaving workspace and revoking access");if(t.json)return k(i,t.fields);d(),C("Workspace Left"),c("Workspace",i.workspace_id),d();return}if(e==="transfer"){(!t.id||!t.membershipId)&&u("Workspace ID and target membership ID required",{hint:"Usage: domani workspace transfer --id <workspace-id> --membership-id <membership-id>",code:"validation_error",json:t.json});let i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/ownership-transfer`,{method:"POST",body:JSON.stringify({membership_id:t.membershipId})},t,"Requesting ownership transfer");if(t.json)return k(i,t.fields);d(),C("Ownership Transfer Requested"),c("To",i.to_email),c("Expires",i.expires_at),c("Billing",i.billing),d();return}if(e==="accept-ownership"){t.token||u("Ownership transfer token required",{hint:"Usage: domani workspace accept-ownership --token <token>",code:"validation_error",json:t.json});let i=await me("/api/workspaces/ownership-transfers/accept",{method:"POST",body:JSON.stringify({token:t.token})},t,"Accepting ownership");if(t.json)return k(i,t.fields);d(),C("Ownership Transferred"),c("Workspace",i.workspace_id),c("Domains",i.domains_transferred),c("Mailboxes",i.mailboxes_transferred),c("Previous owner",i.previous_owner_role),d();return}if(e==="revoke-transfer"){(!t.id||!t.transferId)&&u("Workspace ID and transfer ID required",{hint:"Usage: domani workspace revoke-transfer --id <workspace-id> --transfer-id <transfer-id>",code:"validation_error",json:t.json});let i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/ownership-transfer/${encodeURIComponent(t.transferId)}`,{method:"DELETE"},t,"Revoking ownership transfer");if(t.json)return k(i,t.fields);d(),C("Ownership Transfer Revoked"),c("Transfer",i.transfer_id),d();return}if(e==="adopt-mailbox"){(!t.id||!t.mailboxId)&&u("Workspace ID and mailbox ID required",{hint:"Usage: domani workspace adopt-mailbox --id <workspace-id> --mailbox-id <mailbox-id>",code:"validation_error",json:t.json});let i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/mailboxes`,{method:"POST",body:JSON.stringify({mailbox_id:t.mailboxId})},t,"Adopting mailbox boundary");if(t.json)return k(i,t.fields);d(),C(i.adopted?"Mailbox Boundary Adopted":"Already in Workspace"),c("Address",i.address),c("Mailboxes",i.mailbox_ids?.length??1),d();return}if(e==="grant"){(!t.id||!t.mailboxId||!t.membershipId||!t.role)&&u("Workspace, mailbox, membership, and role required",{hint:"Usage: domani workspace grant --id <id> --mailbox-id <id> --membership-id <id> --role viewer|responder|manager",code:"validation_error",json:t.json});let i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/mailboxes/${encodeURIComponent(t.mailboxId)}/grants`,{method:"PUT",body:JSON.stringify({membership_id:t.membershipId,role:t.role})},t,"Granting mailbox access");if(t.json)return k(i,t.fields);d(),C("Mailbox Access Granted"),c("Membership",i.membership_id),c("Mailbox",i.mailbox_id),c("Role",i.role),d();return}if(e==="revoke-grant"){(!t.id||!t.mailboxId||!t.membershipId)&&u("Workspace, mailbox, and membership required",{hint:"Usage: domani workspace revoke-grant --id <id> --mailbox-id <id> --membership-id <id>",code:"validation_error",json:t.json});let i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/mailboxes/${encodeURIComponent(t.mailboxId)}/grants`,{method:"DELETE",body:JSON.stringify({membership_id:t.membershipId})},t,"Revoking mailbox access");if(t.json)return k(i,t.fields);d(),C("Mailbox Access Revoked"),c("Membership",i.membership_id),c("Mailbox",i.mailbox_id),d();return}if(e==="checkout"){(!t.id||!t.plan)&&u("Workspace ID and plan required",{hint:"Usage: domani workspace checkout --id <id> --plan mail_team",code:"validation_error",json:t.json});let i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/billing/checkout`,{method:"POST",body:JSON.stringify({plan:t.plan})},t,"Creating secure checkout");if(t.json)return k(i,t.fields);d(),C("Workspace Checkout"),c("Plan",i.plan),c("URL",i.url),d(),i.url&&t.open!==!1&&(console.log(` ${jn.default.dim("Opening browser")} ${y.arrow} ${$.url(i.url)}`),We(i.url));return}if(e==="cancel"){t.id||u("Workspace ID required",{hint:"Usage: domani workspace cancel --id <id>",code:"validation_error",json:t.json});let i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/billing/cancel`,{method:"POST"},t,"Scheduling cancellation");if(t.json)return k(i,t.fields);d(),C("Cancellation Scheduled"),c("Message",i.message),i.cancel_at&&c("Cancels",i.cancel_at),d();return}u(`Unknown action: ${e}`,{hint:"Actions: list, create, show, access, group, collection, offer, accept-offer, revoke-access, rename, invite, accept, revoke-invite, member-role, remove-member, leave, transfer, accept-ownership, revoke-transfer, adopt-mailbox, grant, revoke-grant, checkout, cancel",code:"validation_error",json:t.json,fields:t.fields})}var Qo=U(require("node:readline"),1);mt();function lc(e){return(Array.isArray(e)?e:[e]).filter(i=>!!i&&typeof i=="object")}function xn(e,t,i,s){return{jsonrpc:"2.0",id:e,error:{code:t,message:i,...s?{data:s}:{}}}}function pi(e,t,i,s){let n=lc(e).filter(r=>Object.prototype.hasOwnProperty.call(r,"id")).map(r=>xn(r.id??null,t,i,s));if(n.length!==0)return Array.isArray(e)?n:n[0]}function dc(e){let t=[];for(let i of e.split(/\r?\n/)){if(!i.startsWith("data:"))continue;let s=i.slice(5).trim();if(!(!s||s==="[DONE]"))try{t.push(JSON.parse(s))}catch{}}return t}async function cc(e,t={}){let i=t.fetchImpl??fetch,s=t.getAuthToken?t.getAuthToken():Me(),n=(t.apiUrl??qe()).replace(/\/$/,""),r={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};s&&(r.Authorization=`Bearer ${s}`);let o=()=>i(`${n}/mcp`,{method:"POST",headers:r,body:JSON.stringify(e)}),a;try{a=await o()}catch(f){let g=f instanceof Error?f.message:"Unknown network error",b=pi(e,-32002,"Domani MCP is unreachable",{code:"MCP_NETWORK_ERROR",hint:`Check your connection and that ${n} is reachable.`,detail:g});return b===void 0?[]:[b]}if(a.status===401){let f=t.refreshAuthToken?t.refreshAuthToken():t.getAuthToken?void 0:Me({refreshKeychain:!0});if(f&&f!==s){await a.body?.cancel(),s=f,r.Authorization=`Bearer ${s}`;try{a=await o()}catch(g){let b=g instanceof Error?g.message:"Unknown network error",v=pi(e,-32002,"Domani MCP is unreachable",{code:"MCP_NETWORK_ERROR",hint:`Check your connection and that ${n} is reachable.`,detail:b});return v===void 0?[]:[v]}}}if(a.status===202||a.status===204)return[];let l=await a.text();if(a.status===401){let f=pi(e,-32001,"Domani authentication required",{code:"AUTH_REQUIRED",hint:"Run `npx -y domani-cli@latest login`, approve access in the browser, then retry. Never paste an API key into chat.",fix_command:"npx -y domani-cli@latest login"});return f===void 0?[]:[f]}if(!a.ok){let f=pi(e,-32e3,`Domani MCP request failed (${a.status})`,{code:"MCP_HTTP_ERROR",hint:"Retry once. If the error persists, check https://domani.run/status."});return f===void 0?[]:[f]}if(!l.trim())return[];if((a.headers.get("content-type")??"").includes("text/event-stream"))return dc(l);try{return[JSON.parse(l)]}catch{let f=pi(e,-32700,"Domani MCP returned invalid JSON",{code:"MCP_INVALID_RESPONSE"});return f===void 0?[]:[f]}}async function ea(e={}){let t=e.stderr??process.stderr,i=Qo.default.createInterface({input:process.stdin,crlfDelay:1/0}),s=new Set;e.verbose&&t.write(`domani MCP bridge ready
206
- `);for await(let n of i){if(!n.trim())continue;let r=(async()=>{let o;try{o=JSON.parse(n)}catch{process.stdout.write(`${JSON.stringify(xn(null,-32700,"Parse error"))}
204
+ domani sell <domain> --transfer-code <code>`,code:"validation_error",json:t.json,fields:t.fields})}async function Hd(e,t){let i=parseFloat(t.price);(isNaN(i)||i<=0)&&u("Invalid price",{hint:"Price must be a positive number, e.g. --price 5000",code:"validation_error",json:t.json,fields:t.fields});let s=S(!t.json);s.start(`Listing ${$.domain(e)} for sale`);let n={domain:e,price:i};t.description&&(n.description=t.description);let r=await j("/api/domains/sell",{method:"POST",body:JSON.stringify(n)}),o=await r.json();if(r.ok||(s.stop("Listing failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:t.json,fields:t.fields})),t.json){s.stop(""),k(o,t.fields);return}(o.listing?.status??"pending_verification")==="active"?(s.stop(`${y.success} Listed for sale`),C("Sell Domain"),c("Domain",$.domain(o.listing?.domain||e)),c("Price",$.price(i)),c("Status",$e.default.green("active")),d(),console.log(` ${$e.default.dim("Your listing is live on the marketplace.")}`),d()):(s.stop(`${y.success} Verification record ready`),C("Sell Domain"),c("Domain",$.domain(o.listing?.domain||e)),c("Price",$.price(i)),c("Status",$e.default.yellow("pending verification")),d(),console.log(" Add this TXT record at your DNS provider:"),d(),console.log(` ${$e.default.dim("Type:")} ${$e.default.bold("TXT")}`),console.log(` ${$e.default.dim("Name:")} ${$e.default.bold(o.txt_record?.name||"@")}`),console.log(` ${$e.default.dim("Value:")} ${$e.default.bold(o.txt_record?.value||`domani-verify=${o.token}`)}`),d(),console.log(` ${$e.default.dim("DNS propagation may take a few minutes to 48 hours.")}`),d(),I("Once the record is set, verify:",`domani sell ${e} --verify`),d())}async function Jd(e,t){let i=S(!t.json);i.start(`Verifying ownership of ${$.domain(e)}`);let s=await j("/api/domains/sell/verify",{method:"POST",body:JSON.stringify({domain:e})}),n=await s.json();if(s.ok||(i.stop("Verification failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),t.json){i.stop(""),k(n,t.fields);return}i.stop(`${y.success} ${$.domain(e)} is now listed for sale!`),C("Domain Listed"),c("Domain",$.domain(n.domain||e)),c("Status",$e.default.green(n.status||"active")),n.price&&c("Price",$.price(n.price)),d(),I("Check listing status:",`domani sell ${e} --status`),I("View your deals:","domani deals"),d()}async function Bd(e,t){let i=S(!t.json);i.start(`Checking listing status for ${$.domain(e)}`);let s=await j(`/api/domains/sell/status?domain=${encodeURIComponent(e)}`),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),i.stop(`${y.success} Listing status loaded`),t.json){k(n,t.fields);return}let r=n.listing;if(C("Listing Status"),c("Domain",$.domain(n.domain||e)),r){let o=r.status;c("Status",o==="active"?$e.default.green(o):$e.default.yellow(o||"unknown")),r.price&&c("Price",$.price(r.price)),r.description&&c("Description",r.description),r.created_at&&c("Listed",$e.default.dim(new Date(r.created_at).toLocaleDateString()))}else c("Status",$e.default.dim("No listing found"));n.deal&&c("Deal",`${n.deal.status} ($${n.deal.price})`),d()}async function Gd(e,t){let i=S(!t.json);i.start(`Removing ${$.domain(e)} from sale`);let s=await j(`/api/domains/sell?domain=${encodeURIComponent(e)}`,{method:"DELETE"}),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),t.json){i.stop(""),k(n,t.fields);return}i.stop(`${y.success} ${$.domain(e)} removed from sale`),d()}async function Kd(e,t,i){let s=S(!i.json);s.start(`Looking up active deal for ${$.domain(e)}`);let n=await j(`/api/deals?role=seller&domain=${encodeURIComponent(e)}&status=active`),r=await n.json();n.ok||(s.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:i.json,fields:i.fields}));let a=(r.deals||r.data||[]).filter(g=>g.domain.toLowerCase()===e.toLowerCase());a.length===0&&(s.stop("No active deal found"),u(`No active deal found for ${e}`,{hint:`Make sure you have an active sale for this domain.
205
+ Run 'domani deals --role seller' to see your deals.`,code:"not_found",json:i.json,fields:i.fields}));let l=a[0].id;s.message(`Submitting transfer code for deal ${$e.default.dim(l)}`);let m=await j(`/api/deals/${encodeURIComponent(l)}`,{method:"PATCH",body:JSON.stringify({auth_code:t})}),f=await m.json();if(m.ok||(s.stop("Failed"),u(f.error||f.message,{hint:f.hint,status:m.status,json:i.json,fields:i.fields})),i.json){s.stop(""),k(f,i.fields);return}s.stop(`${y.success} Transfer code submitted for ${$.domain(e)}`),C("Transfer Code Submitted"),c("Domain",$.domain(e)),c("Deal",$e.default.dim(l)),c("Status",$e.default.green(f.status||"code_submitted")),d(),I("Track the deal:",`domani deals ${l}`),d()}X();var ve=U(L(),1);W();async function Ao(e,t){return e?Yd(e,t):zd(t)}async function zd(e){let t=S(!e.json);t.start("Loading deals");let i=new URLSearchParams;e.role&&i.set("role",e.role),e.status&&i.set("status",e.status);let s=i.toString()?`?${i.toString()}`:"",n=await j(`/api/deals${s}`),r=await n.json();n.ok||(t.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:e.json,fields:e.fields}));let o=r.deals||r.data||[];if(t.stop(`${y.success} ${o.length} deal(s)`),e.json){k(r,e.fields);return}if(o.length===0){d(),console.log(` ${ve.default.dim("No deals found.")}`),d(),I("List a domain for sale:","domani sell <domain> --price <amount>"),d();return}d(),C("Deals");let a=o.map(l=>{let m=l.status==="completed"?ve.default.green:l.status==="active"?ve.default.cyan:l.status==="cancelled"?ve.default.red:ve.default.yellow;return[$.domain(l.domain),$.price(l.price),m(l.status),ve.default.dim(l.role||"-"),ve.default.dim(new Date(l.created_at).toLocaleDateString())]});se(["Domain","Price","Status","Role","Created"],a,[28,12,14,10,14]),d()}async function Yd(e,t){let i=S(!t.json);i.start(`Loading deal ${ve.default.dim(e)}`);let s=await j(`/api/deals/${encodeURIComponent(e)}`),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),i.stop(`${y.success} Deal loaded`),t.json){k(n,t.fields);return}let r=n.deal||n;C("Deal Details"),c("ID",ve.default.dim(r.id)),c("Domain",$.domain(r.domain)),c("Price",$.price(r.price));let o=r.status==="completed"?ve.default.green:r.status==="active"?ve.default.cyan:r.status==="cancelled"?ve.default.red:ve.default.yellow;c("Status",o(r.status)),r.role&&c("Your Role",r.role),r.buyer&&c("Buyer",ve.default.dim(r.buyer)),r.seller&&c("Seller",ve.default.dim(r.seller)),r.created_at&&c("Created",ve.default.dim(new Date(r.created_at).toLocaleDateString())),r.updated_at&&c("Updated",ve.default.dim(new Date(r.updated_at).toLocaleDateString())),d();let a=r.events||[];if(a.length>0){C("Timeline");for(let l of a){let m=ve.default.dim(new Date(l.created_at).toLocaleString()),f=l.status==="completed"?y.success:l.status==="expired"||l.status==="refunded"?y.error:y.info;console.log(` ${f} ${m} ${l.detail||l.status}`)}d()}(r.status==="escrow_held"||r.status==="epp_pending")&&r.role==="seller"&&(I("Submit transfer code:",`domani sell ${r.domain} --transfer-code <code>`),d())}X();var Ue=U(L(),1);W();he();async function Do(e,t,i){switch(e){case void 0:case"list":case"ls":return Xd(i);case"request":case"acquire":case"new":return Eo(t,i);case"status":case"get":return Po(t,i);case"cancel":case"rm":return Zd(t,i);default:return e.includes(".")?Eo(e,i):Po(e,i)}}async function Eo(e,t){e||u("A domain is required.",{hint:"domani broker request dream.com --max-budget 5000",json:t.json}),K(e,{json:t.json});let i=S(!t.json);i.start(`Requesting acquisition of ${$.domain(e)}`);let s={domain:e};if(t.maxBudget){let a=Number(t.maxBudget);(!Number.isFinite(a)||a<=0)&&u("--max-budget must be a positive number (USD).",{json:t.json}),s.max_budget=a}let n=await j("/api/broker",{method:"POST",body:JSON.stringify(s)}),r=await n.json();n.ok||(i.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:t.json,fields:t.fields}));let o=r.request||r;if(i.stop(`${y.success} Acquisition requested`),t.json)return k(r,t.fields);C("Broker request"),c("Domain",$.domain(o.domain)),c("Status",wn(o.status)),o.max_budget!=null&&c("Max budget",$.price(o.max_budget)),c("ID",Ue.default.dim(o.id)),d(),console.log(` ${Ue.default.dim("We'll source the owner and reach out anonymously. Commission-only - you pay nothing unless a deal closes.")}`),d(),I("Check progress:",`domani broker status ${o.id}`),d()}async function Xd(e){let t=S(!e.json);t.start("Loading broker requests");let i=e.status?`?status=${encodeURIComponent(e.status)}`:"",s=await j(`/api/broker${i}`),n=await s.json();s.ok||(t.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields}));let r=n.requests||n.data||[];if(t.stop(`${y.success} ${r.length} request(s)`),e.json)return k(n,e.fields);if(r.length===0){d(),console.log(` ${Ue.default.dim("No broker requests yet.")}`),d(),I("Acquire a taken domain:","domani broker request <domain> --max-budget <amount>"),d();return}d(),C("Broker requests"),se(["Domain","Status","Budget","ID"],r.map(o=>[$.domain(o.domain),wn(o.status),o.max_budget!=null?$.price(o.max_budget):Ue.default.dim("-"),Ue.default.dim(o.id)])),d()}async function Po(e,t){e||u("A request ID is required.",{hint:"domani broker status <id> (list with: domani broker)",json:t.json});let i=S(!t.json);i.start("Loading request");let s=await j(`/api/broker/${encodeURIComponent(e)}`),n=await s.json();s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields}));let r=n.request||n;if(i.stop(`${y.success} ${$.domain(r.domain)}`),t.json)return k(n,t.fields);C("Broker request"),c("Domain",$.domain(r.domain)),c("Status",wn(r.status)),r.max_budget!=null&&c("Max budget",$.price(r.max_budget)),c("Contacted",r.contacted?Ue.default.green("yes"):Ue.default.dim("not yet")),r.failure_reason&&c("Reason",Ue.default.yellow(r.failure_reason)),c("ID",Ue.default.dim(r.id)),d(),r.negotiation_id?(console.log(` ${Ue.default.dim("The owner responded - an anonymous negotiation is open.")}`),d(),I("Review the offer:","domani deals"),d()):["sourcing","contacted","negotiating"].includes(r.status)&&(I("Cancel this request:",`domani broker cancel ${r.id}`),d())}async function Zd(e,t){e||u("A request ID is required.",{hint:"domani broker cancel <id>",json:t.json});let i=S(!t.json);i.start("Cancelling request");let s=await j(`/api/broker/${encodeURIComponent(e)}`,{method:"DELETE"}),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),i.stop(`${y.success} Request cancelled`),t.json)return k(n,t.fields);d()}function wn(e){return["completed","agreed"].includes(e)?Ue.default.green(e):["negotiating","contacted","sourcing"].includes(e)?Ue.default.cyan(e):["declined","no_contact","failed","expired","cancelled"].includes(e)?Ue.default.dim(e):e}X();var ge=U(L(),1);W();async function No(e){return e.read?ec(e):Qd(e)}async function Qd(e){let t=S(!e.json);t.start("Loading notifications");let i=new URLSearchParams;e.unread&&i.set("unread","true"),e.limit&&i.set("limit",e.limit);let s=i.toString()?`?${i.toString()}`:"",n=await j(`/api/notifications${s}`),r=await n.json();n.ok||(t.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:e.json,fields:e.fields}));let o=r.notifications||r.data||[],a=r.unread_count??o.filter(m=>!m.read).length;if(t.stop(`${y.success} ${o.length} notification(s)${a>0?` ${y.dot} ${ge.default.yellow(`${a} unread`)}`:""}`),e.json){k(r,e.fields);return}if(o.length===0){d(),console.log(` ${ge.default.dim("No notifications.")}`),d();return}d(),C("Notifications");let l=o.map(m=>{let f=m.read?ge.default.dim(y.dot):ge.default.cyan(y.info),g=tc(m.type),b=m.read?ge.default.dim(m.title):ge.default.white(m.title),w=m.body?m.read?ge.default.dim(To(m.body,40)):ge.default.dim(To(m.body,40)):ge.default.dim("-"),v=ge.default.dim(new Date(m.created_at).toLocaleDateString());return[f,g,b,w,v]});se(["","Type","Title","Body","Date"],l,[3,16,28,42,14]),d(),a>0&&(console.log(` ${ge.default.dim("Mark all as read:")} ${ge.default.cyan("domani notifications --read")}`),d())}async function ec(e){let t=S(!e.json);t.start("Marking all notifications as read");let i=await j("/api/notifications/read-all",{method:"POST"}),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),e.json){t.stop(""),k(s,e.fields);return}let n=s.count??0;t.stop(`${y.success} ${n} notification(s) marked as read`),d()}function tc(e){let t={deal:ge.default.cyan,sale:ge.default.green,purchase:ge.default.green,transfer:ge.default.yellow,expiry:ge.default.red,security:ge.default.red,billing:ge.default.yellow,email:ge.default.blue},i=e.split(".")[0].split("_")[0];return(t[i]||ge.default.dim)(e)}function To(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}X();var _t=U(L(),1);W();async function Uo(e){let t=e.limit?Number(e.limit):20,i=await j(`/api/billing/invoices?limit=${t}`),s=await i.json();if(i.ok||u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields}),e.json){k({...s,count:s.invoices.length},e.fields);return}if(s.invoices.length===0){console.log(` ${_t.default.dim("No invoices yet.")}`);return}C(`Invoices (${s.invoices.length})`),d();for(let n of s.invoices){let r=`$${(n.amount_paid/100).toFixed(2)}`,o=new Date(n.created).toLocaleDateString(),a=n.number||n.id;console.log(` ${y.success} ${_t.default.bold(a)} ${_t.default.green(r)} ${_t.default.dim(o)}`),n.description&&console.log(` ${_t.default.dim(n.description)}`),n.hosted_invoice_url&&console.log(` ${_t.default.dim(n.hosted_invoice_url)}`)}d(),s.has_more&&(console.log(` ${_t.default.dim(`Showing ${s.invoices.length} most recent. Use --limit to see more.`)}`),d())}X();var ui=U(L(),1);W();async function Fo(e){let t=S(!e?.json);t.start("Setting up billing session");let i=await j("/api/billing/setup",{method:"POST",body:JSON.stringify({mode:"checkout"})}),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e?.json})),s.url||(t.stop("Failed"),u("No checkout URL returned",{hint:"Try again or add a payment method at the dashboard.",json:e?.json})),t.stop("Checkout ready"),e?.json){k({url:s.url});return}d(),console.log(` ${ui.default.dim("Opening browser")} ${y.arrow} ${$.url(s.url)}`),d(),We(s.url),console.log(` ${y.info} ${ui.default.dim("Complete payment setup in your browser.")}`),console.log(` ${ui.default.dim(" After setup, you can purchase domains with")} ${ui.default.cyan("domani buy")}`),d()}X();var kn=U(L(),1);W();async function qo(e){let t=S(!e?.json);t.start("Creating upgrade session");let i=await j("/api/billing/subscribe",{method:"POST"}),s=await i.json();if(!i.ok){t.stop("Failed"),s.code==="ALREADY_SUBSCRIBED"||s.code==="ALREADY_PRO"?u("You're already on a paid plan.",{json:e?.json}):u(s.error||s.message,{hint:s.hint,status:i.status,json:e?.json});return}if(t.stop("Ready"),e?.json){k({url:s.url},e?.fields);return}d(),console.log(` ${kn.default.dim("Opening browser")} ${y.arrow} ${$.url(s.url)}`),d(),We(s.url),console.log(` ${y.info} ${kn.default.dim("Complete your plan upgrade in the browser.")}`),d()}X();var _n=U(L(),1);W();async function Mo(e){let t=S(!e?.json);t.start("Cancelling subscription");let i=await j("/api/billing/cancel",{method:"POST"}),s=await i.json();if(!i.ok){t.stop("Failed"),s.code==="NOT_PAID"||s.code==="NOT_PRO"?u("You're not on a paid plan.",{json:e?.json}):u(s.error||s.message,{hint:s.hint,status:i.status,json:e?.json});return}if(t.stop("Done"),e?.json){k(s,e?.fields);return}d();let n=s.cancel_at?new Date(s.cancel_at).toLocaleDateString():"end of billing period";console.log(` ${y.success} ${_n.default.dim("Subscription cancelled.")} Access continues until ${_n.default.cyan(n)}.`),d()}X();var tt=U(L(),1);W();he();Ye();async function Lo(e,t,i){e||(e=await fe()),K(e,i);let s=[];if(t?.length&&s.push(...t),i.set&&s.push(...i.set.split(",").map(n=>n.trim()).filter(Boolean)),s.length>0||i.reset){await sc(e,s,i);return}await ic(e,i)}async function ic(e,t){let i=S(!t.json);i.start(`Fetching nameservers for ${$.domain(e)}`);let s=await j(`/api/domains/${encodeURIComponent(e)}/nameservers`),n=await s.json();if(s.ok||(i.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),i.stop(`Nameservers for ${$.domain(e)}`),t.json){k(n,t.fields);return}if(d(),n.nameservers.length===0)console.log(` ${y.warning} ${tt.default.yellow("No nameservers configured.")}`),console.log(` ${tt.default.dim("DNS operations (parking, email, connect) will not work.")}`),d(),I("Set default nameservers:",`domani nameservers ${e} --reset`);else{C("Nameservers");for(let r of n.nameservers)console.log(` ${y.success} ${tt.default.cyan(r)}`);n.default_nameservers&&n.nameservers.length===n.default_nameservers.length&&n.nameservers.every(o=>n.default_nameservers.includes(o))&&(d(),console.log(` ${tt.default.dim("Using default nameservers.")}`))}n.default_nameservers?.length&&(d(),c("Defaults",n.default_nameservers.map(r=>tt.default.dim(r)).join(tt.default.dim(", ")))),d()}async function sc(e,t,i){let s=S(!i.json);if(i.reset){s.start(`Fetching default nameservers for ${$.domain(e)}`);let o=await j(`/api/domains/${encodeURIComponent(e)}/nameservers`),a=await o.json();o.ok||(s.stop("Failed"),u(a.error,{hint:a.hint,status:o.status,json:i.json,fields:i.fields})),a.default_nameservers?.length||(s.stop("No defaults"),u("No default nameservers available for this domain's registrar.",{code:"not_found",json:i.json,fields:i.fields})),t=a.default_nameservers,s.stop(`Using defaults: ${t.map(l=>tt.default.cyan(l)).join(tt.default.dim(", "))}`)}if(t.length<2&&u("At least 2 nameservers required.",{hint:"Example: domani nameservers example.com ns1.dns.com ns2.dns.com",code:"validation_error",json:i.json,fields:i.fields}),i.dryRun)return B("nameservers_set",{domain:e,nameservers:t},i.json,i.fields);s.start(`Setting nameservers for ${$.domain(e)}`);let n=await j(`/api/domains/${encodeURIComponent(e)}/nameservers`,{method:"PUT",body:JSON.stringify({nameservers:t})}),r=await n.json();if(n.ok||(s.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:i.json,fields:i.fields})),s.stop(`${y.success} Nameservers updated`),i.json){k(r,i.fields);return}d();for(let o of r.nameservers)console.log(` ${y.success} ${tt.default.cyan(o)}`);d(),console.log(` ${tt.default.dim("Changes may take up to 48 hours to propagate.")}`),d(),I("Check propagation:",`domani status ${e}`),d()}var Vo=require("crypto"),es=U(require("fs"),1);mt();var mi=U(L(),1);W();function nc(e,t){let i=e.split(".").map(Number),s=t.split(".").map(Number);for(let n=0;n<3;n++){if((i[n]||0)>(s[n]||0))return 1;if((i[n]||0)<(s[n]||0))return-1}return 0}async function Wo(e){let t=!!e?.json,i=S(!t);i.start("Checking for updates");let s=qe();try{let n=await fetch(`${s}/api/cli/version`);n.ok||(i.stop("Failed"),u("Could not check for updates"));let r=await n.json(),o=r.version,a=r.sha256;if(nc(o,ke)<=0){i.stop(`${y.success} Already up to date (v${ke})`),t&&k({current:ke,latest:o,up_to_date:!0});return}if(t&&!e?.yes){i.stop(""),k({current:ke,latest:o,up_to_date:!1,hint:"Run `domani update --yes` to upgrade non-interactively, or `domani update` in an interactive terminal."});return}i.stop(t?"":`New version available: ${mi.default.cyan(ke)} ${y.arrow} ${mi.default.green(o)}`);let l=S(!t);l.start("Downloading update");let m=`${s}/cli/domani.js`,f=await fetch(m);f.ok||(l.stop("Download failed"),u(`Failed to download from ${m}`));let g=await f.text();a&&(0,Vo.createHash)("sha256").update(g).digest("hex")!==a&&(l.stop("Integrity check failed"),u("Downloaded file does not match expected hash - update aborted"));let b=process.argv[1];b||(l.stop("Failed"),u("Could not determine binary path"));let w=es.default.realpathSync(b),v=w+".tmp";if(es.default.writeFileSync(v,g,{mode:493}),es.default.renameSync(v,w),l.stop(`${y.success} Updated to v${o}`),t){k({updated:!0,from:ke,to:o});return}d(),console.log(` ${mi.default.dim("Restart your terminal or run")} domani --version ${mi.default.dim("to verify")}`),d()}catch(n){u(`Update failed: ${n instanceof Error?n.message:String(n)}`)}}var ts=U(require("fs"),1),Ho=U(require("path"),1),Jo=U(require("os"),1);De();var fi=U(L(),1);W();async function Bo(){let e=process.argv[1],t=e?ts.default.realpathSync(e):null,i=Ho.default.join(Jo.default.homedir(),".domani");if(d(),console.log(` ${fi.default.bold("This will remove:")}`),t&&console.log(` ${y.dot} CLI binary: ${fi.default.dim(t)}`),console.log(` ${y.dot} Config dir: ${fi.default.dim(i)}`),d(),await Ke({message:"Uninstall domani?"})!==!0){console.log(` ${fi.default.dim("Cancelled.")}`);return}ts.default.rmSync(i,{recursive:!0,force:!0}),t&&ts.default.unlinkSync(t),d(),console.log(` ${y.success} domani uninstalled.`),d()}X();var re=U(L(),1);W();async function Ko(e,t){let i=t?.json,s=t?.fields,n=e?`/api/schema?command=${encodeURIComponent(e)}`:"/api/schema",r=S(!i);r.start("Loading schema");let o=await be(n),a=await o.json();if(o.ok||(r.stop("Failed"),u(a.error||a.message,{hint:a.hint,status:o.status,json:i,fields:s})),r.stop("Schema loaded"),i){k(a,s);return}e?oc(e,a):rc(a.commands)}function rc(e){C("Commands");let t=Object.entries(e).map(([i,s])=>[re.default.bold(re.default.cyan(i)),s.description]);se(["Command","Description"],t,[20,50]),d(),console.log(` ${re.default.dim("Run")} ${re.default.cyan("domani schema <command>")} ${re.default.dim("for full details")}`),d()}function oc(e,t){if(C(`domani ${e}`),console.log(` ${t.description}`),d(),console.log(` ${$.label("Usage:")} ${re.default.cyan(t.usage)}`),t.arguments&&Object.keys(t.arguments).length>0){d(),console.log(` ${re.default.bold("Arguments")}`);for(let[i,s]of Object.entries(t.arguments)){let n=s.required?re.default.red("*"):"",r=re.default.dim(`(${s.type}${s.variadic?", variadic":""})`);console.log(` ${re.default.cyan(i)}${n} ${r}`),s.description&&console.log(` ${re.default.dim(s.description)}`)}}if(t.options&&Object.keys(t.options).length>0){d(),console.log(` ${re.default.bold("Options")}`);for(let[i,s]of Object.entries(t.options)){let n=s.required?re.default.red("*"):"",r=re.default.dim(`(${s.type})`),o=s.choices?re.default.dim(` [${s.choices.join(", ")}]`):"";console.log(` ${re.default.cyan(`--${i}`)}${n} ${r}${o}`),console.log(` ${re.default.dim(s.description)}`)}}if(t.api)if(d(),console.log(` ${re.default.bold("API")}`),ac(t.api))Go(t.api);else for(let[i,s]of Object.entries(t.api))console.log(` ${re.default.bold(re.default.yellow(i))}`),Go(s,6);t.errors&&t.errors.length>0&&(d(),console.log(` ${re.default.bold("Errors")}`),console.log(` ${t.errors.map(i=>re.default.dim(i)).join(re.default.dim(", "))}`)),d()}function ac(e){return typeof e=="object"&&e!==null&&"method"in e&&"path"in e}function Go(e,t=4){let i=" ".repeat(t);if(console.log(`${i}${re.default.green(e.method)} ${re.default.white(e.path)}`),e.parameters&&Object.keys(e.parameters).length>0)for(let[s,n]of Object.entries(e.parameters)){let r=n.required?re.default.red("*"):"",o=[n.type];n.enum&&o.push(`enum: ${n.enum.join(", ")}`),n.minimum!==void 0&&o.push(`min: ${n.minimum}`),n.maximum!==void 0&&o.push(`max: ${n.maximum}`),n.maxItems!==void 0&&o.push(`maxItems: ${n.maxItems}`),n.items&&o.push(`items: ${n.items}`),n.in==="path"&&o.push("in: path");let a=re.default.dim(`(${o.join(", ")})`);console.log(`${i} ${re.default.cyan(s)}${r} ${a}`),n.description&&console.log(`${i} ${re.default.dim(n.description)}`)}}X();var Fe=U(L(),1);De();W();async function zo(e){let t=S(!e.json);t.start("Loading payment method");let i=await j("/api/me"),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),e.json){t.stop(""),k(s.card?{has_payment_method:s.has_payment_method,card:s.card}:{has_payment_method:!1},e.fields);return}if(!s.has_payment_method||!s.card){t.stop("No payment method on file"),d(),console.log(` ${Fe.default.dim("Add a card with")} ${Fe.default.cyan("domani card add")}`),d();return}let{brand:n,last4:r,exp_month:o,exp_year:a}=s.card,l=`${String(o).padStart(2,"0")}/${a}`,m=n.charAt(0).toUpperCase()+n.slice(1);t.stop("Payment method loaded"),C("Payment method"),c("Card",`${Fe.default.bold(m)} \u2022\u2022\u2022\u2022 ${Fe.default.bold(r)}`),c("Expires",l),d(),console.log(` ${Fe.default.dim("Update with")} ${Fe.default.cyan("domani card add")}`),d()}async function Yo(e){let t=S(!e?.json);t.start("Setting up payment session");let i=await j("/api/billing/setup",{method:"POST",body:JSON.stringify({mode:"checkout"})}),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e?.json})),s.url||(t.stop("Failed"),u("No checkout URL returned",{json:e?.json})),t.stop("Checkout ready"),e?.json){k({url:s.url},e?.fields);return}d(),console.log(` ${Fe.default.dim("Opening browser")} ${y.arrow} ${$.url(s.url)}`),d(),We(s.url),console.log(` ${y.info} ${Fe.default.dim("Complete payment setup in your browser.")}`),console.log(` ${Fe.default.dim(" After setup, you can purchase domains with")} ${Fe.default.cyan("domani buy")}`),d()}async function Xo(e){if(!e?.yes&&!e?.json){let n=await Ke({message:"Remove your saved payment method?"});if(le(n)||!n){console.log(` ${Fe.default.dim("Cancelled.")}`);return}}let t=S(!e?.json);t.start("Removing payment method");let i=await j("/api/billing/card",{method:"DELETE"}),s=await i.json();if(i.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:i.status,json:e?.json})),t.stop(`${y.success} Payment method removed`),e?.json){k({removed:!0},e?.fields);return}d(),console.log(` ${Fe.default.dim("Add a new card with")} ${Fe.default.cyan("domani card add")}`),d()}var xn=U(L(),1);X();W();async function me(e,t,i,s){let n=S(!i.json);n.start(s);let r=await j(e,t),o=await r.json();return r.ok||(n.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:i.json,fields:i.fields})),n.stop(`${y.success} Done`),o}async function Zo(e,t){if(!e||e==="list"){let i=await me("/api/workspaces",void 0,t,"Loading workspaces");if(t.json)return k(i,t.fields);if(d(),C("Workspaces"),!i.workspaces.length){console.log(` ${xn.default.dim("No workspaces yet.")}`),I("Create one:","domani workspace create --name Acme");return}se(["ID","Name","Role","Mailboxes","Members"],i.workspaces.map(s=>[s.id,s.name,s.role,String(s.mailbox_count),String(s.member_count)]),[28,28,10,10,8]),d();return}if(e==="create"){t.name||u("Workspace name required",{hint:"Usage: domani workspace create --name Acme",code:"validation_error",json:t.json});let i=await me("/api/workspaces",{method:"POST",body:JSON.stringify({name:t.name})},t,"Creating workspace");if(t.json)return k(i,t.fields);d(),C("Workspace Created"),c("ID",i.id),c("Name",i.name),d();return}if(e==="show"){t.id||u("Workspace ID required",{hint:"Usage: domani workspace show --id <id>",code:"validation_error",json:t.json});let i=await me(`/api/workspaces/${encodeURIComponent(t.id)}`,void 0,t,"Loading workspace");if(t.json)return k(i,t.fields);d(),C(i.name),c("Role",i.role),c("Mailboxes",i.mailboxes.length),c("Members",i.members.length),d(),se(["Email","Role","Mailbox grants"],i.members.map(s=>[s.email,s.role,String(s.mailbox_grants.length)]),[42,12,16]),d();return}if(e==="access"){if(t.id||u("Workspace ID required",{hint:"Usage: domani workspace access --id <id>",code:"validation_error",json:t.json}),!t.subject&&!t.resource&&!t.profile){let a=await me(`/api/workspaces/${encodeURIComponent(t.id)}/access`,void 0,t,"Loading access graph");if(t.json)return k(a,t.fields);d(),C("Access Graph"),c("Principals",a.principals.length),c("Mailboxes",a.mailboxes.length),c("Groups",a.groups.length),c("Collections",a.collections.length),c("Active grants",a.grants.length),c("Pending offers",a.offers.length),d();return}(!t.subject||!t.resource||!t.profile)&&u("Subject, resource, and profile are required together",{hint:"Usage: domani workspace access --id <id> --subject human:<id> --resource mailbox:<id> --profile responder [--apply]",code:"validation_error",json:t.json});let[i,s]=t.subject.split(":",2),[n,r]=t.resource.split(":",2);(!s||!["human","agent","service","token","group"].includes(i))&&u("Invalid --subject",{hint:"Use human:<id>, agent:<id>, service:<id>, token:<id>, or group:<id>",json:t.json}),(!r||!["mailbox","collection"].includes(n))&&u("Invalid --resource",{hint:"Use mailbox:<id> or collection:<id>",json:t.json});let o=await me(`/api/workspaces/${encodeURIComponent(t.id)}/access`,{method:"PUT",body:JSON.stringify({mode:t.apply?"apply":"plan",subject:i==="group"?{type:"group",id:s}:{type:"principal",principal:{type:i,id:s}},resource:{type:n,id:r},profile:t.profile,expected_version:t.expectedVersion?Number(t.expectedVersion):void 0})},t,t.apply?"Applying access":"Planning access");if(t.json)return k(o,t.fields);d(),C(t.apply?"Access Applied":"Access Plan"),c("Action",o.action),c("Changed",String(o.changed)),o.grant_id&&c("Grant",o.grant_id),d();return}if(e==="group"){(!t.id||!t.name)&&u("Workspace ID and group name required",{hint:"Usage: domani workspace group --id <id> --name Support --principals human:u1,agent:a1",code:"validation_error",json:t.json});let i=(t.principals||"").split(",").map(n=>n.trim()).filter(Boolean).map(n=>{let[r,o]=n.split(":",2);return o||u(`Invalid principal: ${n}`,{hint:"Use type:id",json:t.json}),{type:r,id:o,label:o}}),s=await me(`/api/workspaces/${encodeURIComponent(t.id)}/access/groups`,{method:"PUT",body:JSON.stringify({id:t.groupId,name:t.name,principals:i})},t,"Syncing access group");if(t.json)return k(s,t.fields);d(),C("Access Group Synced"),c("ID",s.id),c("Principals",s.principal_count),d();return}if(e==="collection"){(!t.id||!t.name)&&u("Workspace ID and collection name required",{hint:"Usage: domani workspace collection --id <id> --name Admin --mailboxes mb1,mb2",code:"validation_error",json:t.json});let i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/access/collections`,{method:"PUT",body:JSON.stringify({id:t.collectionId,name:t.name,mailbox_ids:t.mailboxes?.split(",").map(s=>s.trim()).filter(Boolean)??[]})},t,"Syncing mailbox collection");if(t.json)return k(i,t.fields);d(),C("Mailbox Collection Synced"),c("ID",i.id),c("Mailboxes",i.mailbox_count),d();return}if(e==="offer"){(!t.id||!t.email)&&u("Workspace ID and recipient email required",{hint:"Usage: domani workspace offer --id <id> --email person@example.com --mailboxes mb1,mb2 --profile responder",code:"validation_error",json:t.json});let i=(t.mailboxes||"").split(",").map(n=>n.trim()).filter(Boolean).map(n=>({resource:{type:"mailbox",id:n},profile:t.profile||"responder"})),s=await me(`/api/workspaces/${encodeURIComponent(t.id)}/access/offers`,{method:"POST",body:JSON.stringify({email:t.email,grants:i,ownership_disposition:t.ownershipDisposition,creator_disposition:t.creatorDisposition,billing_disposition:t.billingDisposition})},t,"Sending access offer");if(t.json)return k(s,t.fields);d(),C("Access Offered"),c("Email",s.email),c("Expires",s.expires_at),d();return}if(e==="accept-offer"){t.token||u("Access offer token required",{hint:"Usage: domani workspace accept-offer --token <token>",code:"validation_error",json:t.json});let i=await me("/api/workspaces/access/offers/accept",{method:"POST",body:JSON.stringify({token:t.token})},t,"Accepting access offer");if(t.json)return k(i,t.fields);d(),C("Access Accepted"),c("Workspace",i.workspace_name),c("Ownership",i.ownership),d();return}if(e==="revoke-access"){(!t.id||!t.grantId)&&u("Workspace and grant IDs required",{hint:"Usage: domani workspace revoke-access --id <id> --grant-id <id>",code:"validation_error",json:t.json});let i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/access/grants/${encodeURIComponent(t.grantId)}`,{method:"DELETE",body:JSON.stringify({expected_version:t.expectedVersion?Number(t.expectedVersion):void 0})},t,"Revoking access");if(t.json)return k(i,t.fields);d(),C("Access Revoked"),c("Grant",i.grant_id),c("Version",i.version),d();return}if(e==="rename"){(!t.id||!t.name)&&u("Workspace ID and name required",{hint:"Usage: domani workspace rename --id <id> --name <name>",code:"validation_error",json:t.json});let i=await me(`/api/workspaces/${encodeURIComponent(t.id)}`,{method:"PATCH",body:JSON.stringify({name:t.name})},t,"Renaming workspace");if(t.json)return k(i,t.fields);d(),C("Workspace Renamed"),c("ID",i.id),c("Name",i.name),d();return}if(e==="invite"){(!t.id||!t.email)&&u("Workspace ID and email required",{hint:"Usage: domani workspace invite --id <id> --email person@example.com",code:"validation_error",json:t.json});let i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/invitations`,{method:"POST",body:JSON.stringify({email:t.email,role:t.role,mailbox_ids:t.mailboxes?.split(",").map(s=>s.trim()).filter(Boolean),mailbox_role:t.mailboxRole})},t,"Sending invitation");if(t.json)return k(i,t.fields);d(),C("Invitation Sent"),c("Email",i.email),c("Role",i.role),c("Expires",i.expires_at),d();return}if(e==="accept"){t.token||u("Invitation token required",{hint:"Usage: domani workspace accept --token <token>",code:"validation_error",json:t.json});let i=await me("/api/workspaces/invitations/accept",{method:"POST",body:JSON.stringify({token:t.token})},t,"Accepting invitation");if(t.json)return k(i,t.fields);d(),C("Workspace Joined"),c("Workspace",i.workspace_name),c("Role",i.role),d();return}if(e==="revoke-invite"){(!t.id||!t.invitationId)&&u("Workspace ID and invitation ID required",{hint:"Usage: domani workspace revoke-invite --id <id> --invitation-id <id>",code:"validation_error",json:t.json});let i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/invitations/${encodeURIComponent(t.invitationId)}`,{method:"DELETE"},t,"Revoking invitation");if(t.json)return k(i,t.fields);d(),C("Invitation Revoked"),c("Invitation",i.invitation_id),d();return}if(e==="member-role"){(!t.id||!t.membershipId||!t.role)&&u("Workspace ID, membership ID, and role required",{hint:"Usage: domani workspace member-role --id <id> --membership-id <id> --role admin|member",code:"validation_error",json:t.json});let i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/members/${encodeURIComponent(t.membershipId)}`,{method:"PATCH",body:JSON.stringify({role:t.role})},t,"Updating member role");if(t.json)return k(i,t.fields);d(),C("Member Updated"),c("Membership",i.id),c("Role",i.role),d();return}if(e==="remove-member"){(!t.id||!t.membershipId)&&u("Workspace ID and membership ID required",{hint:"Usage: domani workspace remove-member --id <id> --membership-id <id>",code:"validation_error",json:t.json});let i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/members/${encodeURIComponent(t.membershipId)}`,{method:"DELETE"},t,"Removing member and revoking access");if(t.json)return k(i,t.fields);d(),C("Member Removed"),c("Membership",i.membership_id),d();return}if(e==="leave"){t.id||u("Workspace ID required",{hint:"Usage: domani workspace leave --id <id>",code:"validation_error",json:t.json});let i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/members/me`,{method:"DELETE"},t,"Leaving workspace and revoking access");if(t.json)return k(i,t.fields);d(),C("Workspace Left"),c("Workspace",i.workspace_id),d();return}if(e==="transfer"){(!t.id||!t.membershipId)&&u("Workspace ID and target membership ID required",{hint:"Usage: domani workspace transfer --id <workspace-id> --membership-id <membership-id>",code:"validation_error",json:t.json});let i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/ownership-transfer`,{method:"POST",body:JSON.stringify({membership_id:t.membershipId})},t,"Requesting ownership transfer");if(t.json)return k(i,t.fields);d(),C("Ownership Transfer Requested"),c("To",i.to_email),c("Expires",i.expires_at),c("Billing",i.billing),d();return}if(e==="accept-ownership"){t.token||u("Ownership transfer token required",{hint:"Usage: domani workspace accept-ownership --token <token>",code:"validation_error",json:t.json});let i=await me("/api/workspaces/ownership-transfers/accept",{method:"POST",body:JSON.stringify({token:t.token})},t,"Accepting ownership");if(t.json)return k(i,t.fields);d(),C("Ownership Transferred"),c("Workspace",i.workspace_id),c("Domains",i.domains_transferred),c("Mailboxes",i.mailboxes_transferred),c("Previous owner",i.previous_owner_role),d();return}if(e==="revoke-transfer"){(!t.id||!t.transferId)&&u("Workspace ID and transfer ID required",{hint:"Usage: domani workspace revoke-transfer --id <workspace-id> --transfer-id <transfer-id>",code:"validation_error",json:t.json});let i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/ownership-transfer/${encodeURIComponent(t.transferId)}`,{method:"DELETE"},t,"Revoking ownership transfer");if(t.json)return k(i,t.fields);d(),C("Ownership Transfer Revoked"),c("Transfer",i.transfer_id),d();return}if(e==="adopt-mailbox"){(!t.id||!t.mailboxId)&&u("Workspace ID and mailbox ID required",{hint:"Usage: domani workspace adopt-mailbox --id <workspace-id> --mailbox-id <mailbox-id>",code:"validation_error",json:t.json});let i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/mailboxes`,{method:"POST",body:JSON.stringify({mailbox_id:t.mailboxId})},t,"Adopting mailbox boundary");if(t.json)return k(i,t.fields);d(),C(i.adopted?"Mailbox Boundary Adopted":"Already in Workspace"),c("Address",i.address),c("Mailboxes",i.mailbox_ids?.length??1),d();return}if(e==="grant"){(!t.id||!t.mailboxId||!t.membershipId||!t.role)&&u("Workspace, mailbox, membership, and role required",{hint:"Usage: domani workspace grant --id <id> --mailbox-id <id> --membership-id <id> --role viewer|responder|manager",code:"validation_error",json:t.json});let i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/mailboxes/${encodeURIComponent(t.mailboxId)}/grants`,{method:"PUT",body:JSON.stringify({membership_id:t.membershipId,role:t.role})},t,"Granting mailbox access");if(t.json)return k(i,t.fields);d(),C("Mailbox Access Granted"),c("Membership",i.membership_id),c("Mailbox",i.mailbox_id),c("Role",i.role),d();return}if(e==="revoke-grant"){(!t.id||!t.mailboxId||!t.membershipId)&&u("Workspace, mailbox, and membership required",{hint:"Usage: domani workspace revoke-grant --id <id> --mailbox-id <id> --membership-id <id>",code:"validation_error",json:t.json});let i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/mailboxes/${encodeURIComponent(t.mailboxId)}/grants`,{method:"DELETE",body:JSON.stringify({membership_id:t.membershipId})},t,"Revoking mailbox access");if(t.json)return k(i,t.fields);d(),C("Mailbox Access Revoked"),c("Membership",i.membership_id),c("Mailbox",i.mailbox_id),d();return}if(e==="checkout"){(!t.id||!t.plan)&&u("Workspace ID and plan required",{hint:"Usage: domani workspace checkout --id <id> --plan mail_team",code:"validation_error",json:t.json});let i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/billing/checkout`,{method:"POST",body:JSON.stringify({plan:t.plan})},t,"Creating secure checkout");if(t.json)return k(i,t.fields);d(),C("Workspace Checkout"),c("Plan",i.plan),c("URL",i.url),d(),i.url&&t.open!==!1&&(console.log(` ${xn.default.dim("Opening browser")} ${y.arrow} ${$.url(i.url)}`),We(i.url));return}if(e==="cancel"){t.id||u("Workspace ID required",{hint:"Usage: domani workspace cancel --id <id>",code:"validation_error",json:t.json});let i=await me(`/api/workspaces/${encodeURIComponent(t.id)}/billing/cancel`,{method:"POST"},t,"Scheduling cancellation");if(t.json)return k(i,t.fields);d(),C("Cancellation Scheduled"),c("Message",i.message),i.cancel_at&&c("Cancels",i.cancel_at),d();return}u(`Unknown action: ${e}`,{hint:"Actions: list, create, show, access, group, collection, offer, accept-offer, revoke-access, rename, invite, accept, revoke-invite, member-role, remove-member, leave, transfer, accept-ownership, revoke-transfer, adopt-mailbox, grant, revoke-grant, checkout, cancel",code:"validation_error",json:t.json,fields:t.fields})}var Qo=U(require("node:readline"),1);mt();function lc(e){return(Array.isArray(e)?e:[e]).filter(i=>!!i&&typeof i=="object")}function jn(e,t,i,s){return{jsonrpc:"2.0",id:e,error:{code:t,message:i,...s?{data:s}:{}}}}function pi(e,t,i,s){let n=lc(e).filter(r=>Object.prototype.hasOwnProperty.call(r,"id")).map(r=>jn(r.id??null,t,i,s));if(n.length!==0)return Array.isArray(e)?n:n[0]}function dc(e){let t=[];for(let i of e.split(/\r?\n/)){if(!i.startsWith("data:"))continue;let s=i.slice(5).trim();if(!(!s||s==="[DONE]"))try{t.push(JSON.parse(s))}catch{}}return t}async function cc(e,t={}){let i=t.fetchImpl??fetch,s=t.getAuthToken?t.getAuthToken():Me(),n=(t.apiUrl??qe()).replace(/\/$/,""),r={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};s&&(r.Authorization=`Bearer ${s}`);let o=()=>i(`${n}/mcp`,{method:"POST",headers:r,body:JSON.stringify(e)}),a;try{a=await o()}catch(f){let g=f instanceof Error?f.message:"Unknown network error",b=pi(e,-32002,"Domani MCP is unreachable",{code:"MCP_NETWORK_ERROR",hint:`Check your connection and that ${n} is reachable.`,detail:g});return b===void 0?[]:[b]}if(a.status===401){let f=t.refreshAuthToken?t.refreshAuthToken():t.getAuthToken?void 0:Me({refreshKeychain:!0});if(f&&f!==s){await a.body?.cancel(),s=f,r.Authorization=`Bearer ${s}`;try{a=await o()}catch(g){let b=g instanceof Error?g.message:"Unknown network error",w=pi(e,-32002,"Domani MCP is unreachable",{code:"MCP_NETWORK_ERROR",hint:`Check your connection and that ${n} is reachable.`,detail:b});return w===void 0?[]:[w]}}}if(a.status===202||a.status===204)return[];let l=await a.text();if(a.status===401){let f=pi(e,-32001,"Domani authentication required",{code:"AUTH_REQUIRED",hint:"Run `npx -y domani-cli@latest login`, approve access in the browser, then retry. Never paste an API key into chat.",fix_command:"npx -y domani-cli@latest login"});return f===void 0?[]:[f]}if(!a.ok){let f=pi(e,-32e3,`Domani MCP request failed (${a.status})`,{code:"MCP_HTTP_ERROR",hint:"Retry once. If the error persists, check https://domani.run/status."});return f===void 0?[]:[f]}if(!l.trim())return[];if((a.headers.get("content-type")??"").includes("text/event-stream"))return dc(l);try{return[JSON.parse(l)]}catch{let f=pi(e,-32700,"Domani MCP returned invalid JSON",{code:"MCP_INVALID_RESPONSE"});return f===void 0?[]:[f]}}async function ea(e={}){let t=e.stderr??process.stderr,i=Qo.default.createInterface({input:process.stdin,crlfDelay:1/0}),s=new Set;e.verbose&&t.write(`domani MCP bridge ready
206
+ `);for await(let n of i){if(!n.trim())continue;let r=(async()=>{let o;try{o=JSON.parse(n)}catch{process.stdout.write(`${JSON.stringify(jn(null,-32700,"Parse error"))}
207
207
  `);return}let a=await cc(o,e);for(let l of a)process.stdout.write(`${JSON.stringify(l)}
208
208
  `)})().catch(o=>{if(e.verbose){let a=o instanceof Error?o.message:String(o);t.write(`domani MCP bridge internal error: ${a}
209
- `)}process.stdout.write(`${JSON.stringify(xn(null,-32603,"Domani MCP bridge internal error"))}
210
- `)});s.add(r),r.then(()=>s.delete(r))}await Promise.all(s)}process.stdin.setMaxListeners(50);var H=new qn;H.name("domani").description(`Domain names for developers and AI agents - ${Lt}`).version(_e).option("--api-url <url>","Override API base URL").configureOutput({outputError:(e,t)=>{let i=e.replace(/^error:\s*/i,"").trimEnd();if(t(`${at.default.red("\u2717")} ${i}
209
+ `)}process.stdout.write(`${JSON.stringify(jn(null,-32603,"Domani MCP bridge internal error"))}
210
+ `)});s.add(r),r.then(()=>s.delete(r))}await Promise.all(s)}process.stdin.setMaxListeners(50);var H=new qn;H.name("domani").description(`Domain names for developers and AI agents - ${Lt}`).version(ke).option("--api-url <url>","Override API base URL").configureOutput({outputError:(e,t)=>{let i=e.replace(/^error:\s*/i,"").trimEnd();if(t(`${at.default.red("\u2717")} ${i}
211
211
  `),/unknown option|missing required|expected argument/i.test(i)){let s=process.argv[2],n=s&&!s.startsWith("-")?`domani ${s} --help`:"domani --help";t(`${at.default.dim(` Run \`${n}\` to see available options.`)}
212
- `)}}}).hook("preAction",async(e,t)=>{let i=e.opts();i.apiUrl&&Yn(i.apiUrl),process.stdout.isTTY||t.options.some(r=>r.long==="--json")&&t.setOptionValue("json",!0),["login","logout","search","suggest","tlds","whois","schema","update","uninstall","mcp"].includes(t.name())||await Mr()});H.command("login").description(`Log in to ${Lt} (opens browser)`).option("--json","Output as JSON (returns auth_url for non-interactive approval)").option("--no-open","Don't open browser (print URL instead)").option("--scopes <scopes>","Request a comma-separated, least-privilege scope set").option("--label <label>","Human-readable label shown on the approval screen").option("--expires-in <seconds>","Delegated credential lifetime in seconds (3600-31536000)").option("--surface <surface>","Attribute onboarding: cli, mcp, plugin, skill, or api","cli").addHelpText("after",`
212
+ `)}}}).hook("preAction",async(e,t)=>{let i=e.opts();i.apiUrl&&Yn(i.apiUrl),process.stdout.isTTY||t.options.some(r=>r.long==="--json")&&t.setOptionValue("json",!0),["login","logout","search","suggest","tlds","whois","schema","update","uninstall","mcp"].includes(t.name())||await Mr()});H.command("login").description(`Log in to ${Lt} (opens browser)`).option("--json","Output as JSON (returns auth_url for non-interactive approval)").option("--no-open","Don't open browser (print URL instead)").option("--scopes <scopes>","Request a comma-separated, least-privilege scope set").option("--mailboxes <addresses>","Confine the credential to these comma-separated mailbox addresses").option("--label <label>","Human-readable label shown on the approval screen").option("--expires-in <seconds>","Delegated credential lifetime in seconds (3600-31536000)").option("--surface <surface>","Attribute onboarding: cli, mcp, plugin, skill, or api","cli").addHelpText("after",`
213
213
  Examples:
214
214
  domani login # interactive login (opens browser)
215
215
  domani login --scopes domains:read,search --label "Project agent" --expires-in 86400
216
+ domani login --scopes email:read,email:write --mailboxes support@acme.com --label "Support agent"
216
217
  domani login --surface mcp # authenticate an MCP integration
217
218
  domani login --surface plugin # authenticate the Domani agent plugin
218
219
  domani login --json # non-interactive (returns auth_url)
@@ -325,7 +326,7 @@ Examples:
325
326
  Examples:
326
327
  domani contact # view current contact info
327
328
  domani contact set --first-name John --last-name Doe --address1 "123 Main St" \\
328
- --city "San Francisco" --state CA --postal-code 94102 --country US --phone +1.5551234567 --email john@example.com`).option("--first-name <name>","First name (for set)").option("--last-name <name>","Last name (for set)").option("--org-name <name>","Organization name (for set, optional)").option("--address1 <addr>","Address line 1 (for set)").option("--address2 <addr>","Address line 2 (for set, optional)").option("--city <city>","City (for set)").option("--state <state>","State/Province (for set)").option("--postal-code <code>","Postal/ZIP code (for set)").option("--country <code>","Country code ISO 3166-1 alpha-2 (for set)").option("--phone <phone>","Phone +CC.NUMBER (for set)").option("--email <email>","Contact email (for set)").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(jo);H.command("parking [domain] [action] [value]").description("Manage parking page (enable/disable/price)").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
329
+ --city "San Francisco" --state CA --postal-code 94102 --country US --phone +1.5551234567 --email john@example.com`).option("--first-name <name>","First name (for set)").option("--last-name <name>","Last name (for set)").option("--org-name <name>","Organization name (for set, optional)").option("--address1 <addr>","Address line 1 (for set)").option("--address2 <addr>","Address line 2 (for set, optional)").option("--city <city>","City (for set)").option("--state <state>","State/Province (for set)").option("--postal-code <code>","Postal/ZIP code (for set)").option("--country <code>","Country code ISO 3166-1 alpha-2 (for set)").option("--phone <phone>","Phone +CC.NUMBER (for set)").option("--email <email>","Contact email (for set)").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(xo);H.command("parking [domain] [action] [value]").description("Manage parking page (enable/disable/price)").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
329
330
  Examples:
330
331
  domani parking myapp.dev # view parking status
331
332
  domani parking myapp.dev enable # enable parking page
@@ -356,8 +357,8 @@ Examples:
356
357
  domani broker request dream.com --max-budget 5000
357
358
  domani broker # list your requests
358
359
  domani broker status brq_abc123
359
- domani broker cancel brq_abc123`).action((e,t,i)=>Do(e,t,i));H.command("notifications").alias("notifs").description("View notifications or mark all as read").option("--read","Mark all notifications as read").option("--unread","Show only unread notifications").option("--limit <n>","Limit results").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(No);H.command("send [arg2]").description("Send an email - shortcut for: domani email send").option("--from <email>","Sender address user@domain").option("--to <email>","Recipient email address").option("--cc <emails>","CC recipients, comma-separated").option("--bcc <emails>","BCC recipients, comma-separated").option("--subject <s>","Email subject").option("--title <s>","Email subject (alias for --subject)").option("--text <t>","Email body text").option("--body <t>","Email body text (alias for --text)").option("--in-reply-to <message-id>","Message-ID of email being replied to").option("--references <message-ids>","Space-separated Message-ID chain").option("--domain <domain>","Domain name").option("--slug <slug>","Mailbox slug").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action((e,t)=>li("send",e,t));H.command("inbox [arg2]").description("View email inbox - shortcut for: domani email inbox").option("--from <email>","Sender address user@domain").option("--domain <domain>","Domain name").option("--slug <slug>","Mailbox slug").option("--direction <dir>","Filter messages: in or out").option("--limit <n>","Limit results").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action((e,t)=>li("inbox",e,t));H.command("schema [command]").description("Show command schemas for AI agent integration").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(Ko);H.command("update").description("Update domani CLI to the latest version").option("--json","Output as JSON (check version without updating)").action(Wo);H.command("uninstall").description("Remove domani CLI and config from this machine").action(Bo);(async()=>{let e=Qn();await H.parseAsync();let t=await e;t?.forced?(console.error(`
360
- ${at.default.red("!")} CLI v${_e} is no longer supported. Run ${at.default.bold("domani update")} to upgrade to v${t.update}
360
+ domani broker cancel brq_abc123`).action((e,t,i)=>Do(e,t,i));H.command("notifications").alias("notifs").description("View notifications or mark all as read").option("--read","Mark all notifications as read").option("--unread","Show only unread notifications").option("--limit <n>","Limit results").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(No);H.command("send [arg2]").description("Send an email - shortcut for: domani email send").option("--from <email>","Sender address user@domain").option("--to <email>","Recipient email address").option("--cc <emails>","CC recipients, comma-separated").option("--bcc <emails>","BCC recipients, comma-separated").option("--subject <s>","Email subject").option("--title <s>","Email subject (alias for --subject)").option("--text <t>","Email body text").option("--body <t>","Email body text (alias for --text)").option("--in-reply-to <message-id>","Message-ID of email being replied to").option("--references <message-ids>","Space-separated Message-ID chain").option("--domain <domain>","Domain name").option("--slug <slug>","Mailbox slug").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action((e,t)=>li("send",e,t));H.command("inbox [arg2]").description("View email inbox - shortcut for: domani email inbox").option("--from <email>","Sender address user@domain").option("--domain <domain>","Domain name").option("--slug <slug>","Mailbox slug").option("--direction <dir>","Filter messages: in or out").option("--limit <n>","Limit results").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action((e,t)=>li("inbox",e,t));H.command("schema [command]").description("Show command schemas for AI agent integration").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(Ko);H.command("update").description("Update domani CLI to the latest version").option("--json","Output as JSON (check version without updating)").option("--yes","Perform the update even in JSON/non-interactive mode").action(Wo);H.command("uninstall").description("Remove domani CLI and config from this machine").action(Bo);(async()=>{let e=Qn();await H.parseAsync();let t=await e,i=process.stdout.isTTY?"domani update":"domani update --yes";t?.forced?(console.error(`
361
+ ${at.default.red("!")} CLI v${ke} is no longer supported. Run ${at.default.bold(i)} to upgrade to v${t.update}
361
362
  `),process.exit(1)):t?.update&&console.error(`
362
- ${at.default.yellow("!")} Update available: ${at.default.dim(_e)} ${at.default.dim("\u2192")} ${at.default.green(t.update)} Run ${at.default.bold("domani update")}
363
+ ${at.default.yellow("!")} Update available: ${at.default.dim(ke)} ${at.default.dim("\u2192")} ${at.default.green(t.update)} Run ${at.default.bold(i)}
363
364
  `)})();