domani-cli 0.4.42 → 0.4.45

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 (3) hide show
  1. package/README.md +5 -3
  2. package/dist/domani.cjs +140 -137
  3. package/package.json +1 -1
package/dist/domani.cjs CHANGED
@@ -1,124 +1,124 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Yo=Object.create;var Qi=Object.defineProperty;var zo=Object.getOwnPropertyDescriptor;var Xo=Object.getOwnPropertyNames;var Zo=Object.getPrototypeOf,Qo=Object.prototype.hasOwnProperty;var Ee=(e,t)=>()=>(e&&(t=e(e=0)),t);var lt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ft=(e,t)=>{for(var i in t)Qi(e,i,{get:t[i],enumerable:!0})},ea=(e,t,i,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Xo(t))!Qo.call(e,n)&&n!==i&&Qi(e,n,{get:()=>t[n],enumerable:!(s=zo(t,n))||s.enumerable});return e};var U=(e,t,i)=>(i=e!=null?Yo(Zo(e)):{},ea(t||!e||!e.__esModule?Qi(i,"default",{value:e,enumerable:!0}):i,e));var zt=lt(ts=>{var fi=class extends Error{constructor(t,i,s){super(s),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=i,this.exitCode=t,this.nestedError=void 0}},es=class extends fi{constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};ts.CommanderError=fi;ts.InvalidArgumentError=es});var pi=lt(ss=>{var{InvalidArgumentError:ta}=zt(),is=class{constructor(t,i){switch(this.description=i||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,t[0]){case"<":this.required=!0,this._name=t.slice(1,-1);break;case"[":this.required=!1,this._name=t.slice(1,-1);break;default:this.required=!0,this._name=t;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(t,i){return i===this.defaultValue||!Array.isArray(i)?[t]:i.concat(t)}default(t,i){return this.defaultValue=t,this.defaultValueDescription=i,this}argParser(t){return this.parseArg=t,this}choices(t){return this.argChoices=t.slice(),this.parseArg=(i,s)=>{if(!this.argChoices.includes(i))throw new ta(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(i,s):i},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function ia(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}ss.Argument=is;ss.humanReadableArgName=ia});var os=lt(rs=>{var{humanReadableArgName:sa}=pi(),ns=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(t){this.helpWidth=this.helpWidth??t.helpWidth??80}visibleCommands(t){let i=t.commands.filter(n=>!n._hidden),s=t._getHelpCommand();return s&&!s._hidden&&i.push(s),this.sortSubcommands&&i.sort((n,r)=>n.name().localeCompare(r.name())),i}compareOptions(t,i){let s=n=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return s(t).localeCompare(s(i))}visibleOptions(t){let i=t.options.filter(n=>!n.hidden),s=t._getHelpOption();if(s&&!s.hidden){let n=s.short&&t._findOption(s.short),r=s.long&&t._findOption(s.long);!n&&!r?i.push(s):s.long&&!r?i.push(t.createOption(s.long,s.description)):s.short&&!n&&i.push(t.createOption(s.short,s.description))}return this.sortOptions&&i.sort(this.compareOptions),i}visibleGlobalOptions(t){if(!this.showGlobalOptions)return[];let i=[];for(let s=t.parent;s;s=s.parent){let n=s.options.filter(r=>!r.hidden);i.push(...n)}return this.sortOptions&&i.sort(this.compareOptions),i}visibleArguments(t){return t._argsDescription&&t.registeredArguments.forEach(i=>{i.description=i.description||t._argsDescription[i.name()]||""}),t.registeredArguments.find(i=>i.description)?t.registeredArguments:[]}subcommandTerm(t){let i=t.registeredArguments.map(s=>sa(s)).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(i?" "+i:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,i){return i.visibleCommands(t).reduce((s,n)=>Math.max(s,this.displayWidth(i.styleSubcommandTerm(i.subcommandTerm(n)))),0)}longestOptionTermLength(t,i){return i.visibleOptions(t).reduce((s,n)=>Math.max(s,this.displayWidth(i.styleOptionTerm(i.optionTerm(n)))),0)}longestGlobalOptionTermLength(t,i){return i.visibleGlobalOptions(t).reduce((s,n)=>Math.max(s,this.displayWidth(i.styleOptionTerm(i.optionTerm(n)))),0)}longestArgumentTermLength(t,i){return i.visibleArguments(t).reduce((s,n)=>Math.max(s,this.displayWidth(i.styleArgumentTerm(i.argumentTerm(n)))),0)}commandUsage(t){let i=t._name;t._aliases[0]&&(i=i+"|"+t._aliases[0]);let s="";for(let n=t.parent;n;n=n.parent)s=n.name()+" "+s;return s+i+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){let i=[];return t.argChoices&&i.push(`choices: ${t.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),t.defaultValue!==void 0&&(t.required||t.optional||t.isBoolean()&&typeof t.defaultValue=="boolean")&&i.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),t.presetArg!==void 0&&t.optional&&i.push(`preset: ${JSON.stringify(t.presetArg)}`),t.envVar!==void 0&&i.push(`env: ${t.envVar}`),i.length>0?`${t.description} (${i.join(", ")})`:t.description}argumentDescription(t){let i=[];if(t.argChoices&&i.push(`choices: ${t.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),t.defaultValue!==void 0&&i.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),i.length>0){let s=`(${i.join(", ")})`;return t.description?`${t.description} ${s}`:s}return t.description}formatHelp(t,i){let s=i.padWidth(t,i),n=i.helpWidth??80;function r(g,y){return i.formatItem(g,s,y,i)}let o=[`${i.styleTitle("Usage:")} ${i.styleUsage(i.commandUsage(t))}`,""],a=i.commandDescription(t);a.length>0&&(o=o.concat([i.boxWrap(i.styleCommandDescription(a),n),""]));let l=i.visibleArguments(t).map(g=>r(i.styleArgumentTerm(i.argumentTerm(g)),i.styleArgumentDescription(i.argumentDescription(g))));l.length>0&&(o=o.concat([i.styleTitle("Arguments:"),...l,""]));let u=i.visibleOptions(t).map(g=>r(i.styleOptionTerm(i.optionTerm(g)),i.styleOptionDescription(i.optionDescription(g))));if(u.length>0&&(o=o.concat([i.styleTitle("Options:"),...u,""])),i.showGlobalOptions){let g=i.visibleGlobalOptions(t).map(y=>r(i.styleOptionTerm(i.optionTerm(y)),i.styleOptionDescription(i.optionDescription(y))));g.length>0&&(o=o.concat([i.styleTitle("Global Options:"),...g,""]))}let m=i.visibleCommands(t).map(g=>r(i.styleSubcommandTerm(i.subcommandTerm(g)),i.styleSubcommandDescription(i.subcommandDescription(g))));return m.length>0&&(o=o.concat([i.styleTitle("Commands:"),...m,""])),o.join(`
3
- `)}displayWidth(t){return _n(t).length}styleTitle(t){return t}styleUsage(t){return t.split(" ").map(i=>i==="[options]"?this.styleOptionText(i):i==="[command]"?this.styleSubcommandText(i):i[0]==="["||i[0]==="<"?this.styleArgumentText(i):this.styleCommandText(i)).join(" ")}styleCommandDescription(t){return this.styleDescriptionText(t)}styleOptionDescription(t){return this.styleDescriptionText(t)}styleSubcommandDescription(t){return this.styleDescriptionText(t)}styleArgumentDescription(t){return this.styleDescriptionText(t)}styleDescriptionText(t){return t}styleOptionTerm(t){return this.styleOptionText(t)}styleSubcommandTerm(t){return t.split(" ").map(i=>i==="[options]"?this.styleOptionText(i):i[0]==="["||i[0]==="<"?this.styleArgumentText(i):this.styleSubcommandText(i)).join(" ")}styleArgumentTerm(t){return this.styleArgumentText(t)}styleOptionText(t){return t}styleArgumentText(t){return t}styleSubcommandText(t){return t}styleCommandText(t){return t}padWidth(t,i){return Math.max(i.longestOptionTermLength(t,i),i.longestGlobalOptionTermLength(t,i),i.longestSubcommandTermLength(t,i),i.longestArgumentTermLength(t,i))}preformatted(t){return/\n[^\S\r\n]/.test(t)}formatItem(t,i,s,n){let o=" ".repeat(2);if(!s)return o+t;let a=t.padEnd(i+t.length-n.displayWidth(t)),l=2,m=(this.helpWidth??80)-i-l-2,g;return m<this.minWidthToWrap||n.preformatted(s)?g=s:g=n.boxWrap(s,m).replace(/\n/g,`
2
+ "use strict";var ea=Object.create;var ts=Object.defineProperty;var ta=Object.getOwnPropertyDescriptor;var ia=Object.getOwnPropertyNames;var sa=Object.getPrototypeOf,na=Object.prototype.hasOwnProperty;var Ie=(e,t)=>()=>(e&&(t=e(e=0)),t);var lt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Ft=(e,t)=>{for(var i in t)ts(e,i,{get:t[i],enumerable:!0})},ra=(e,t,i,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of ia(t))!na.call(e,n)&&n!==i&&ts(e,n,{get:()=>t[n],enumerable:!(s=ta(t,n))||s.enumerable});return e};var U=(e,t,i)=>(i=e!=null?ea(sa(e)):{},ra(t||!e||!e.__esModule?ts(i,"default",{value:e,enumerable:!0}):i,e));var Yt=lt(ss=>{var hi=class extends Error{constructor(t,i,s){super(s),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=i,this.exitCode=t,this.nestedError=void 0}},is=class extends hi{constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};ss.CommanderError=hi;ss.InvalidArgumentError=is});var gi=lt(rs=>{var{InvalidArgumentError:oa}=Yt(),ns=class{constructor(t,i){switch(this.description=i||"",this.variadic=!1,this.parseArg=void 0,this.defaultValue=void 0,this.defaultValueDescription=void 0,this.argChoices=void 0,t[0]){case"<":this.required=!0,this._name=t.slice(1,-1);break;case"[":this.required=!1,this._name=t.slice(1,-1);break;default:this.required=!0,this._name=t;break}this._name.length>3&&this._name.slice(-3)==="..."&&(this.variadic=!0,this._name=this._name.slice(0,-3))}name(){return this._name}_concatValue(t,i){return i===this.defaultValue||!Array.isArray(i)?[t]:i.concat(t)}default(t,i){return this.defaultValue=t,this.defaultValueDescription=i,this}argParser(t){return this.parseArg=t,this}choices(t){return this.argChoices=t.slice(),this.parseArg=(i,s)=>{if(!this.argChoices.includes(i))throw new oa(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(i,s):i},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function aa(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}rs.Argument=ns;rs.humanReadableArgName=aa});var ls=lt(as=>{var{humanReadableArgName:la}=gi(),os=class{constructor(){this.helpWidth=void 0,this.minWidthToWrap=40,this.sortSubcommands=!1,this.sortOptions=!1,this.showGlobalOptions=!1}prepareContext(t){this.helpWidth=this.helpWidth??t.helpWidth??80}visibleCommands(t){let i=t.commands.filter(n=>!n._hidden),s=t._getHelpCommand();return s&&!s._hidden&&i.push(s),this.sortSubcommands&&i.sort((n,r)=>n.name().localeCompare(r.name())),i}compareOptions(t,i){let s=n=>n.short?n.short.replace(/^-/,""):n.long.replace(/^--/,"");return s(t).localeCompare(s(i))}visibleOptions(t){let i=t.options.filter(n=>!n.hidden),s=t._getHelpOption();if(s&&!s.hidden){let n=s.short&&t._findOption(s.short),r=s.long&&t._findOption(s.long);!n&&!r?i.push(s):s.long&&!r?i.push(t.createOption(s.long,s.description)):s.short&&!n&&i.push(t.createOption(s.short,s.description))}return this.sortOptions&&i.sort(this.compareOptions),i}visibleGlobalOptions(t){if(!this.showGlobalOptions)return[];let i=[];for(let s=t.parent;s;s=s.parent){let n=s.options.filter(r=>!r.hidden);i.push(...n)}return this.sortOptions&&i.sort(this.compareOptions),i}visibleArguments(t){return t._argsDescription&&t.registeredArguments.forEach(i=>{i.description=i.description||t._argsDescription[i.name()]||""}),t.registeredArguments.find(i=>i.description)?t.registeredArguments:[]}subcommandTerm(t){let i=t.registeredArguments.map(s=>la(s)).join(" ");return t._name+(t._aliases[0]?"|"+t._aliases[0]:"")+(t.options.length?" [options]":"")+(i?" "+i:"")}optionTerm(t){return t.flags}argumentTerm(t){return t.name()}longestSubcommandTermLength(t,i){return i.visibleCommands(t).reduce((s,n)=>Math.max(s,this.displayWidth(i.styleSubcommandTerm(i.subcommandTerm(n)))),0)}longestOptionTermLength(t,i){return i.visibleOptions(t).reduce((s,n)=>Math.max(s,this.displayWidth(i.styleOptionTerm(i.optionTerm(n)))),0)}longestGlobalOptionTermLength(t,i){return i.visibleGlobalOptions(t).reduce((s,n)=>Math.max(s,this.displayWidth(i.styleOptionTerm(i.optionTerm(n)))),0)}longestArgumentTermLength(t,i){return i.visibleArguments(t).reduce((s,n)=>Math.max(s,this.displayWidth(i.styleArgumentTerm(i.argumentTerm(n)))),0)}commandUsage(t){let i=t._name;t._aliases[0]&&(i=i+"|"+t._aliases[0]);let s="";for(let n=t.parent;n;n=n.parent)s=n.name()+" "+s;return s+i+" "+t.usage()}commandDescription(t){return t.description()}subcommandDescription(t){return t.summary()||t.description()}optionDescription(t){let i=[];return t.argChoices&&i.push(`choices: ${t.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),t.defaultValue!==void 0&&(t.required||t.optional||t.isBoolean()&&typeof t.defaultValue=="boolean")&&i.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),t.presetArg!==void 0&&t.optional&&i.push(`preset: ${JSON.stringify(t.presetArg)}`),t.envVar!==void 0&&i.push(`env: ${t.envVar}`),i.length>0?`${t.description} (${i.join(", ")})`:t.description}argumentDescription(t){let i=[];if(t.argChoices&&i.push(`choices: ${t.argChoices.map(s=>JSON.stringify(s)).join(", ")}`),t.defaultValue!==void 0&&i.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),i.length>0){let s=`(${i.join(", ")})`;return t.description?`${t.description} ${s}`:s}return t.description}formatHelp(t,i){let s=i.padWidth(t,i),n=i.helpWidth??80;function r(g,y){return i.formatItem(g,s,y,i)}let o=[`${i.styleTitle("Usage:")} ${i.styleUsage(i.commandUsage(t))}`,""],a=i.commandDescription(t);a.length>0&&(o=o.concat([i.boxWrap(i.styleCommandDescription(a),n),""]));let l=i.visibleArguments(t).map(g=>r(i.styleArgumentTerm(i.argumentTerm(g)),i.styleArgumentDescription(i.argumentDescription(g))));l.length>0&&(o=o.concat([i.styleTitle("Arguments:"),...l,""]));let m=i.visibleOptions(t).map(g=>r(i.styleOptionTerm(i.optionTerm(g)),i.styleOptionDescription(i.optionDescription(g))));if(m.length>0&&(o=o.concat([i.styleTitle("Options:"),...m,""])),i.showGlobalOptions){let g=i.visibleGlobalOptions(t).map(y=>r(i.styleOptionTerm(i.optionTerm(y)),i.styleOptionDescription(i.optionDescription(y))));g.length>0&&(o=o.concat([i.styleTitle("Global Options:"),...g,""]))}let f=i.visibleCommands(t).map(g=>r(i.styleSubcommandTerm(i.subcommandTerm(g)),i.styleSubcommandDescription(i.subcommandDescription(g))));return f.length>0&&(o=o.concat([i.styleTitle("Commands:"),...f,""])),o.join(`
3
+ `)}displayWidth(t){return Sn(t).length}styleTitle(t){return t}styleUsage(t){return t.split(" ").map(i=>i==="[options]"?this.styleOptionText(i):i==="[command]"?this.styleSubcommandText(i):i[0]==="["||i[0]==="<"?this.styleArgumentText(i):this.styleCommandText(i)).join(" ")}styleCommandDescription(t){return this.styleDescriptionText(t)}styleOptionDescription(t){return this.styleDescriptionText(t)}styleSubcommandDescription(t){return this.styleDescriptionText(t)}styleArgumentDescription(t){return this.styleDescriptionText(t)}styleDescriptionText(t){return t}styleOptionTerm(t){return this.styleOptionText(t)}styleSubcommandTerm(t){return t.split(" ").map(i=>i==="[options]"?this.styleOptionText(i):i[0]==="["||i[0]==="<"?this.styleArgumentText(i):this.styleSubcommandText(i)).join(" ")}styleArgumentTerm(t){return this.styleArgumentText(t)}styleOptionText(t){return t}styleArgumentText(t){return t}styleSubcommandText(t){return t}styleCommandText(t){return t}padWidth(t,i){return Math.max(i.longestOptionTermLength(t,i),i.longestGlobalOptionTermLength(t,i),i.longestSubcommandTermLength(t,i),i.longestArgumentTermLength(t,i))}preformatted(t){return/\n[^\S\r\n]/.test(t)}formatItem(t,i,s,n){let o=" ".repeat(2);if(!s)return o+t;let a=t.padEnd(i+t.length-n.displayWidth(t)),l=2,f=(this.helpWidth??80)-i-l-2,g;return f<this.minWidthToWrap||n.preformatted(s)?g=s:g=n.boxWrap(s,f).replace(/\n/g,`
4
4
  `+" ".repeat(i+l)),o+a+" ".repeat(l)+g.replace(/\n/g,`
5
- ${o}`)}boxWrap(t,i){if(i<this.minWidthToWrap)return t;let s=t.split(/\r\n|\n/),n=/[\s]*[^\s]+/g,r=[];return s.forEach(o=>{let a=o.match(n);if(a===null){r.push("");return}let l=[a.shift()],u=this.displayWidth(l[0]);a.forEach(m=>{let g=this.displayWidth(m);if(u+g<=i){l.push(m),u+=g;return}r.push(l.join(""));let y=m.trimStart();l=[y],u=this.displayWidth(y)}),r.push(l.join(""))}),r.join(`
6
- `)}};function _n(e){let t=/\x1b\[\d*(;\d*)*m/g;return e.replace(t,"")}rs.Help=ns;rs.stripColor=_n});var cs=lt(ds=>{var{InvalidArgumentError:na}=zt(),as=class{constructor(t,i){this.flags=t,this.description=i||"",this.required=t.includes("<"),this.optional=t.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(t),this.mandatory=!1;let s=ra(t);this.short=s.shortFlag,this.long=s.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(t,i){return this.defaultValue=t,this.defaultValueDescription=i,this}preset(t){return this.presetArg=t,this}conflicts(t){return this.conflictsWith=this.conflictsWith.concat(t),this}implies(t){let i=t;return typeof t=="string"&&(i={[t]:!0}),this.implied=Object.assign(this.implied||{},i),this}env(t){return this.envVar=t,this}argParser(t){return this.parseArg=t,this}makeOptionMandatory(t=!0){return this.mandatory=!!t,this}hideHelp(t=!0){return this.hidden=!!t,this}_concatValue(t,i){return i===this.defaultValue||!Array.isArray(i)?[t]:i.concat(t)}choices(t){return this.argChoices=t.slice(),this.parseArg=(i,s)=>{if(!this.argChoices.includes(i))throw new na(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(i,s):i},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?xn(this.name().replace(/^no-/,"")):xn(this.name())}is(t){return this.short===t||this.long===t}isBoolean(){return!this.required&&!this.optional&&!this.negate}},ls=class{constructor(t){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,t.forEach(i=>{i.negate?this.negativeOptions.set(i.attributeName(),i):this.positiveOptions.set(i.attributeName(),i)}),this.negativeOptions.forEach((i,s)=>{this.positiveOptions.has(s)&&this.dualOptions.add(s)})}valueFromOption(t,i){let s=i.attributeName();if(!this.dualOptions.has(s))return!0;let n=this.negativeOptions.get(s).presetArg,r=n!==void 0?n:!1;return i.negate===(r===t)}};function xn(e){return e.split("-").reduce((t,i)=>t+i[0].toUpperCase()+i.slice(1))}function ra(e){let t,i,s=/^-[^-]$/,n=/^--[^-]/,r=e.split(/[ |,]+/).concat("guard");if(s.test(r[0])&&(t=r.shift()),n.test(r[0])&&(i=r.shift()),!t&&s.test(r[0])&&(t=r.shift()),!t&&n.test(r[0])&&(t=i,i=r.shift()),r[0].startsWith("-")){let o=r[0],a=`option creation failed due to '${o}' in option flags '${e}'`;throw/^-[^-][^-]/.test(o)?new Error(`${a}
5
+ ${o}`)}boxWrap(t,i){if(i<this.minWidthToWrap)return t;let s=t.split(/\r\n|\n/),n=/[\s]*[^\s]+/g,r=[];return s.forEach(o=>{let a=o.match(n);if(a===null){r.push("");return}let l=[a.shift()],m=this.displayWidth(l[0]);a.forEach(f=>{let g=this.displayWidth(f);if(m+g<=i){l.push(f),m+=g;return}r.push(l.join(""));let y=f.trimStart();l=[y],m=this.displayWidth(y)}),r.push(l.join(""))}),r.join(`
6
+ `)}};function Sn(e){let t=/\x1b\[\d*(;\d*)*m/g;return e.replace(t,"")}as.Help=os;as.stripColor=Sn});var ms=lt(us=>{var{InvalidArgumentError:da}=Yt(),ds=class{constructor(t,i){this.flags=t,this.description=i||"",this.required=t.includes("<"),this.optional=t.includes("["),this.variadic=/\w\.\.\.[>\]]$/.test(t),this.mandatory=!1;let s=ca(t);this.short=s.shortFlag,this.long=s.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}default(t,i){return this.defaultValue=t,this.defaultValueDescription=i,this}preset(t){return this.presetArg=t,this}conflicts(t){return this.conflictsWith=this.conflictsWith.concat(t),this}implies(t){let i=t;return typeof t=="string"&&(i={[t]:!0}),this.implied=Object.assign(this.implied||{},i),this}env(t){return this.envVar=t,this}argParser(t){return this.parseArg=t,this}makeOptionMandatory(t=!0){return this.mandatory=!!t,this}hideHelp(t=!0){return this.hidden=!!t,this}_concatValue(t,i){return i===this.defaultValue||!Array.isArray(i)?[t]:i.concat(t)}choices(t){return this.argChoices=t.slice(),this.parseArg=(i,s)=>{if(!this.argChoices.includes(i))throw new da(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(i,s):i},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?Cn(this.name().replace(/^no-/,"")):Cn(this.name())}is(t){return this.short===t||this.long===t}isBoolean(){return!this.required&&!this.optional&&!this.negate}},cs=class{constructor(t){this.positiveOptions=new Map,this.negativeOptions=new Map,this.dualOptions=new Set,t.forEach(i=>{i.negate?this.negativeOptions.set(i.attributeName(),i):this.positiveOptions.set(i.attributeName(),i)}),this.negativeOptions.forEach((i,s)=>{this.positiveOptions.has(s)&&this.dualOptions.add(s)})}valueFromOption(t,i){let s=i.attributeName();if(!this.dualOptions.has(s))return!0;let n=this.negativeOptions.get(s).presetArg,r=n!==void 0?n:!1;return i.negate===(r===t)}};function Cn(e){return e.split("-").reduce((t,i)=>t+i[0].toUpperCase()+i.slice(1))}function ca(e){let t,i,s=/^-[^-]$/,n=/^--[^-]/,r=e.split(/[ |,]+/).concat("guard");if(s.test(r[0])&&(t=r.shift()),n.test(r[0])&&(i=r.shift()),!t&&s.test(r[0])&&(t=r.shift()),!t&&n.test(r[0])&&(t=i,i=r.shift()),r[0].startsWith("-")){let o=r[0],a=`option creation failed due to '${o}' in option flags '${e}'`;throw/^-[^-][^-]/.test(o)?new Error(`${a}
7
7
  - a short flag is a single dash and a single character
8
8
  - either use a single dash and a single character (for a short flag)
9
9
  - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):s.test(o)?new Error(`${a}
10
10
  - too many short flags`):n.test(o)?new Error(`${a}
11
11
  - too many long flags`):new Error(`${a}
12
- - unrecognised flag format`)}if(t===void 0&&i===void 0)throw new Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:i}}ds.Option=as;ds.DualOptions=ls});var Sn=lt(jn=>{function oa(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let i=[];for(let s=0;s<=e.length;s++)i[s]=[s];for(let s=0;s<=t.length;s++)i[0][s]=s;for(let s=1;s<=t.length;s++)for(let n=1;n<=e.length;n++){let r=1;e[n-1]===t[s-1]?r=0:r=1,i[n][s]=Math.min(i[n-1][s]+1,i[n][s-1]+1,i[n-1][s-1]+r),n>1&&s>1&&e[n-1]===t[s-2]&&e[n-2]===t[s-1]&&(i[n][s]=Math.min(i[n][s],i[n-2][s-2]+1))}return i[e.length][t.length]}function aa(e,t){if(!t||t.length===0)return"";t=Array.from(new Set(t));let i=e.startsWith("--");i&&(e=e.slice(2),t=t.map(o=>o.slice(2)));let s=[],n=3,r=.4;return t.forEach(o=>{if(o.length<=1)return;let a=oa(e,o),l=Math.max(e.length,o.length);(l-a)/l>r&&(a<n?(n=a,s=[o]):a===n&&s.push(o))}),s.sort((o,a)=>o.localeCompare(a)),i&&(s=s.map(o=>`--${o}`)),s.length>1?`
12
+ - unrecognised flag format`)}if(t===void 0&&i===void 0)throw new Error(`option creation failed due to no flags found in '${e}'.`);return{shortFlag:t,longFlag:i}}us.Option=ds;us.DualOptions=cs});var In=lt(On=>{function ua(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let i=[];for(let s=0;s<=e.length;s++)i[s]=[s];for(let s=0;s<=t.length;s++)i[0][s]=s;for(let s=1;s<=t.length;s++)for(let n=1;n<=e.length;n++){let r=1;e[n-1]===t[s-1]?r=0:r=1,i[n][s]=Math.min(i[n-1][s]+1,i[n][s-1]+1,i[n-1][s-1]+r),n>1&&s>1&&e[n-1]===t[s-2]&&e[n-2]===t[s-1]&&(i[n][s]=Math.min(i[n][s],i[n-2][s-2]+1))}return i[e.length][t.length]}function ma(e,t){if(!t||t.length===0)return"";t=Array.from(new Set(t));let i=e.startsWith("--");i&&(e=e.slice(2),t=t.map(o=>o.slice(2)));let s=[],n=3,r=.4;return t.forEach(o=>{if(o.length<=1)return;let a=ua(e,o),l=Math.max(e.length,o.length);(l-a)/l>r&&(a<n?(n=a,s=[o]):a===n&&s.push(o))}),s.sort((o,a)=>o.localeCompare(a)),i&&(s=s.map(o=>`--${o}`)),s.length>1?`
13
13
  (Did you mean one of ${s.join(", ")}?)`:s.length===1?`
14
- (Did you mean ${s[0]}?)`:""}jn.suggestSimilar=aa});var Rn=lt(hs=>{var la=require("node:events").EventEmitter,us=require("node:child_process"),dt=require("node:path"),hi=require("node:fs"),ne=require("node:process"),{Argument:da,humanReadableArgName:ca}=pi(),{CommanderError:ms}=zt(),{Help:ua,stripColor:ma}=os(),{Option:Cn,DualOptions:fa}=cs(),{suggestSimilar:On}=Sn(),fs=class e extends la{constructor(t){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=t||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:i=>ne.stdout.write(i),writeErr:i=>ne.stderr.write(i),outputError:(i,s)=>s(i),getOutHelpWidth:()=>ne.stdout.isTTY?ne.stdout.columns:void 0,getErrHelpWidth:()=>ne.stderr.isTTY?ne.stderr.columns:void 0,getOutHasColors:()=>ps()??(ne.stdout.isTTY&&ne.stdout.hasColors?.()),getErrHasColors:()=>ps()??(ne.stderr.isTTY&&ne.stderr.hasColors?.()),stripColor:i=>ma(i)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(t){return this._outputConfiguration=t._outputConfiguration,this._helpOption=t._helpOption,this._helpCommand=t._helpCommand,this._helpConfiguration=t._helpConfiguration,this._exitCallback=t._exitCallback,this._storeOptionsAsProperties=t._storeOptionsAsProperties,this._combineFlagAndOptionalValue=t._combineFlagAndOptionalValue,this._allowExcessArguments=t._allowExcessArguments,this._enablePositionalOptions=t._enablePositionalOptions,this._showHelpAfterError=t._showHelpAfterError,this._showSuggestionAfterError=t._showSuggestionAfterError,this}_getCommandAndAncestors(){let t=[];for(let i=this;i;i=i.parent)t.push(i);return t}command(t,i,s){let n=i,r=s;typeof n=="object"&&n!==null&&(r=n,n=null),r=r||{};let[,o,a]=t.match(/([^ ]+) *(.*)/),l=this.createCommand(o);return n&&(l.description(n),l._executableHandler=!0),r.isDefault&&(this._defaultCommandName=l._name),l._hidden=!!(r.noHelp||r.hidden),l._executableFile=r.executableFile||null,a&&l.arguments(a),this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),n?this:l}createCommand(t){return new e(t)}createHelp(){return Object.assign(new ua,this.configureHelp())}configureHelp(t){return t===void 0?this._helpConfiguration:(this._helpConfiguration=t,this)}configureOutput(t){return t===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,t),this)}showHelpAfterError(t=!0){return typeof t!="string"&&(t=!!t),this._showHelpAfterError=t,this}showSuggestionAfterError(t=!0){return this._showSuggestionAfterError=!!t,this}addCommand(t,i){if(!t._name)throw new Error(`Command passed to .addCommand() must have a name
15
- - specify the name in Command constructor or using .name()`);return i=i||{},i.isDefault&&(this._defaultCommandName=t._name),(i.noHelp||i.hidden)&&(t._hidden=!0),this._registerCommand(t),t.parent=this,t._checkForBrokenPassThrough(),this}createArgument(t,i){return new da(t,i)}argument(t,i,s,n){let r=this.createArgument(t,i);return typeof s=="function"?r.default(n).argParser(s):r.default(s),this.addArgument(r),this}arguments(t){return t.trim().split(/ +/).forEach(i=>{this.argument(i)}),this}addArgument(t){let i=this.registeredArguments.slice(-1)[0];if(i&&i.variadic)throw new Error(`only the last argument can be variadic '${i.name()}'`);if(t.required&&t.defaultValue!==void 0&&t.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${t.name()}'`);return this.registeredArguments.push(t),this}helpCommand(t,i){if(typeof t=="boolean")return this._addImplicitHelpCommand=t,this;t=t??"help [command]";let[,s,n]=t.match(/([^ ]+) *(.*)/),r=i??"display help for command",o=this.createCommand(s);return o.helpOption(!1),n&&o.arguments(n),r&&o.description(r),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(t,i){return typeof t!="object"?(this.helpCommand(t,i),this):(this._addImplicitHelpCommand=!0,this._helpCommand=t,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(t,i){let s=["preSubcommand","preAction","postAction"];if(!s.includes(t))throw new Error(`Unexpected value for event passed to hook : '${t}'.
16
- Expecting one of '${s.join("', '")}'`);return this._lifeCycleHooks[t]?this._lifeCycleHooks[t].push(i):this._lifeCycleHooks[t]=[i],this}exitOverride(t){return t?this._exitCallback=t:this._exitCallback=i=>{if(i.code!=="commander.executeSubCommandAsync")throw i},this}_exit(t,i,s){this._exitCallback&&this._exitCallback(new ms(t,i,s)),ne.exit(t)}action(t){let i=s=>{let n=this.registeredArguments.length,r=s.slice(0,n);return this._storeOptionsAsProperties?r[n]=this:r[n]=this.opts(),r.push(this),t.apply(this,r)};return this._actionHandler=i,this}createOption(t,i){return new Cn(t,i)}_callParseArg(t,i,s,n){try{return t.parseArg(i,s)}catch(r){if(r.code==="commander.invalidArgument"){let o=`${n} ${r.message}`;this.error(o,{exitCode:r.exitCode,code:r.code})}throw r}}_registerOption(t){let i=t.short&&this._findOption(t.short)||t.long&&this._findOption(t.long);if(i){let s=t.long&&this._findOption(t.long)?t.long:t.short;throw new Error(`Cannot add option '${t.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${s}'
17
- - already used by option '${i.flags}'`)}this.options.push(t)}_registerCommand(t){let i=n=>[n.name()].concat(n.aliases()),s=i(t).find(n=>this._findCommand(n));if(s){let n=i(this._findCommand(s)).join("|"),r=i(t).join("|");throw new Error(`cannot add command '${r}' as already have command '${n}'`)}this.commands.push(t)}addOption(t){this._registerOption(t);let i=t.name(),s=t.attributeName();if(t.negate){let r=t.long.replace(/^--no-/,"--");this._findOption(r)||this.setOptionValueWithSource(s,t.defaultValue===void 0?!0:t.defaultValue,"default")}else t.defaultValue!==void 0&&this.setOptionValueWithSource(s,t.defaultValue,"default");let n=(r,o,a)=>{r==null&&t.presetArg!==void 0&&(r=t.presetArg);let l=this.getOptionValue(s);r!==null&&t.parseArg?r=this._callParseArg(t,r,l,o):r!==null&&t.variadic&&(r=t._concatValue(r,l)),r==null&&(t.negate?r=!1:t.isBoolean()||t.optional?r=!0:r=""),this.setOptionValueWithSource(s,r,a)};return this.on("option:"+i,r=>{let o=`error: option '${t.flags}' argument '${r}' is invalid.`;n(r,o,"cli")}),t.envVar&&this.on("optionEnv:"+i,r=>{let o=`error: option '${t.flags}' value '${r}' from env '${t.envVar}' is invalid.`;n(r,o,"env")}),this}_optionEx(t,i,s,n,r){if(typeof i=="object"&&i instanceof Cn)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(i,s);if(o.makeOptionMandatory(!!t.mandatory),typeof n=="function")o.default(r).argParser(n);else if(n instanceof RegExp){let a=n;n=(l,u)=>{let m=a.exec(l);return m?m[0]:u},o.default(r).argParser(n)}else o.default(n);return this.addOption(o)}option(t,i,s,n){return this._optionEx({},t,i,s,n)}requiredOption(t,i,s,n){return this._optionEx({mandatory:!0},t,i,s,n)}combineFlagAndOptionalValue(t=!0){return this._combineFlagAndOptionalValue=!!t,this}allowUnknownOption(t=!0){return this._allowUnknownOption=!!t,this}allowExcessArguments(t=!0){return this._allowExcessArguments=!!t,this}enablePositionalOptions(t=!0){return this._enablePositionalOptions=!!t,this}passThroughOptions(t=!0){return this._passThroughOptions=!!t,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(t=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!t,this}getOptionValue(t){return this._storeOptionsAsProperties?this[t]:this._optionValues[t]}setOptionValue(t,i){return this.setOptionValueWithSource(t,i,void 0)}setOptionValueWithSource(t,i,s){return this._storeOptionsAsProperties?this[t]=i:this._optionValues[t]=i,this._optionValueSources[t]=s,this}getOptionValueSource(t){return this._optionValueSources[t]}getOptionValueSourceWithGlobals(t){let i;return this._getCommandAndAncestors().forEach(s=>{s.getOptionValueSource(t)!==void 0&&(i=s.getOptionValueSource(t))}),i}_prepareUserArgs(t,i){if(t!==void 0&&!Array.isArray(t))throw new Error("first parameter to parse must be array or undefined");if(i=i||{},t===void 0&&i.from===void 0){ne.versions?.electron&&(i.from="electron");let n=ne.execArgv??[];(n.includes("-e")||n.includes("--eval")||n.includes("-p")||n.includes("--print"))&&(i.from="eval")}t===void 0&&(t=ne.argv),this.rawArgs=t.slice();let s;switch(i.from){case void 0:case"node":this._scriptPath=t[1],s=t.slice(2);break;case"electron":ne.defaultApp?(this._scriptPath=t[1],s=t.slice(2)):s=t.slice(1);break;case"user":s=t.slice(0);break;case"eval":s=t.slice(1);break;default:throw new Error(`unexpected parse option { from: '${i.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",s}parse(t,i){this._prepareForParse();let s=this._prepareUserArgs(t,i);return this._parseCommand([],s),this}async parseAsync(t,i){this._prepareForParse();let s=this._prepareUserArgs(t,i);return await this._parseCommand([],s),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
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(hi.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
14
+ (Did you mean ${s[0]}?)`:""}On.suggestSimilar=ma});var Pn=lt(ys=>{var fa=require("node:events").EventEmitter,fs=require("node:child_process"),dt=require("node:path"),yi=require("node:fs"),ne=require("node:process"),{Argument:pa,humanReadableArgName:ha}=gi(),{CommanderError:ps}=Yt(),{Help:ga,stripColor:ya}=ls(),{Option:Rn,DualOptions:ba}=ms(),{suggestSimilar:An}=In(),hs=class e extends fa{constructor(t){super(),this.commands=[],this.options=[],this.parent=null,this._allowUnknownOption=!1,this._allowExcessArguments=!1,this.registeredArguments=[],this._args=this.registeredArguments,this.args=[],this.rawArgs=[],this.processedArgs=[],this._scriptPath=null,this._name=t||"",this._optionValues={},this._optionValueSources={},this._storeOptionsAsProperties=!1,this._actionHandler=null,this._executableHandler=!1,this._executableFile=null,this._executableDir=null,this._defaultCommandName=null,this._exitCallback=null,this._aliases=[],this._combineFlagAndOptionalValue=!0,this._description="",this._summary="",this._argsDescription=void 0,this._enablePositionalOptions=!1,this._passThroughOptions=!1,this._lifeCycleHooks={},this._showHelpAfterError=!1,this._showSuggestionAfterError=!0,this._savedState=null,this._outputConfiguration={writeOut:i=>ne.stdout.write(i),writeErr:i=>ne.stderr.write(i),outputError:(i,s)=>s(i),getOutHelpWidth:()=>ne.stdout.isTTY?ne.stdout.columns:void 0,getErrHelpWidth:()=>ne.stderr.isTTY?ne.stderr.columns:void 0,getOutHasColors:()=>gs()??(ne.stdout.isTTY&&ne.stdout.hasColors?.()),getErrHasColors:()=>gs()??(ne.stderr.isTTY&&ne.stderr.hasColors?.()),stripColor:i=>ya(i)},this._hidden=!1,this._helpOption=void 0,this._addImplicitHelpCommand=void 0,this._helpCommand=void 0,this._helpConfiguration={}}copyInheritedSettings(t){return this._outputConfiguration=t._outputConfiguration,this._helpOption=t._helpOption,this._helpCommand=t._helpCommand,this._helpConfiguration=t._helpConfiguration,this._exitCallback=t._exitCallback,this._storeOptionsAsProperties=t._storeOptionsAsProperties,this._combineFlagAndOptionalValue=t._combineFlagAndOptionalValue,this._allowExcessArguments=t._allowExcessArguments,this._enablePositionalOptions=t._enablePositionalOptions,this._showHelpAfterError=t._showHelpAfterError,this._showSuggestionAfterError=t._showSuggestionAfterError,this}_getCommandAndAncestors(){let t=[];for(let i=this;i;i=i.parent)t.push(i);return t}command(t,i,s){let n=i,r=s;typeof n=="object"&&n!==null&&(r=n,n=null),r=r||{};let[,o,a]=t.match(/([^ ]+) *(.*)/),l=this.createCommand(o);return n&&(l.description(n),l._executableHandler=!0),r.isDefault&&(this._defaultCommandName=l._name),l._hidden=!!(r.noHelp||r.hidden),l._executableFile=r.executableFile||null,a&&l.arguments(a),this._registerCommand(l),l.parent=this,l.copyInheritedSettings(this),n?this:l}createCommand(t){return new e(t)}createHelp(){return Object.assign(new ga,this.configureHelp())}configureHelp(t){return t===void 0?this._helpConfiguration:(this._helpConfiguration=t,this)}configureOutput(t){return t===void 0?this._outputConfiguration:(Object.assign(this._outputConfiguration,t),this)}showHelpAfterError(t=!0){return typeof t!="string"&&(t=!!t),this._showHelpAfterError=t,this}showSuggestionAfterError(t=!0){return this._showSuggestionAfterError=!!t,this}addCommand(t,i){if(!t._name)throw new Error(`Command passed to .addCommand() must have a name
15
+ - specify the name in Command constructor or using .name()`);return i=i||{},i.isDefault&&(this._defaultCommandName=t._name),(i.noHelp||i.hidden)&&(t._hidden=!0),this._registerCommand(t),t.parent=this,t._checkForBrokenPassThrough(),this}createArgument(t,i){return new pa(t,i)}argument(t,i,s,n){let r=this.createArgument(t,i);return typeof s=="function"?r.default(n).argParser(s):r.default(s),this.addArgument(r),this}arguments(t){return t.trim().split(/ +/).forEach(i=>{this.argument(i)}),this}addArgument(t){let i=this.registeredArguments.slice(-1)[0];if(i&&i.variadic)throw new Error(`only the last argument can be variadic '${i.name()}'`);if(t.required&&t.defaultValue!==void 0&&t.parseArg===void 0)throw new Error(`a default value for a required argument is never used: '${t.name()}'`);return this.registeredArguments.push(t),this}helpCommand(t,i){if(typeof t=="boolean")return this._addImplicitHelpCommand=t,this;t=t??"help [command]";let[,s,n]=t.match(/([^ ]+) *(.*)/),r=i??"display help for command",o=this.createCommand(s);return o.helpOption(!1),n&&o.arguments(n),r&&o.description(r),this._addImplicitHelpCommand=!0,this._helpCommand=o,this}addHelpCommand(t,i){return typeof t!="object"?(this.helpCommand(t,i),this):(this._addImplicitHelpCommand=!0,this._helpCommand=t,this)}_getHelpCommand(){return this._addImplicitHelpCommand??(this.commands.length&&!this._actionHandler&&!this._findCommand("help"))?(this._helpCommand===void 0&&this.helpCommand(void 0,void 0),this._helpCommand):null}hook(t,i){let s=["preSubcommand","preAction","postAction"];if(!s.includes(t))throw new Error(`Unexpected value for event passed to hook : '${t}'.
16
+ Expecting one of '${s.join("', '")}'`);return this._lifeCycleHooks[t]?this._lifeCycleHooks[t].push(i):this._lifeCycleHooks[t]=[i],this}exitOverride(t){return t?this._exitCallback=t:this._exitCallback=i=>{if(i.code!=="commander.executeSubCommandAsync")throw i},this}_exit(t,i,s){this._exitCallback&&this._exitCallback(new ps(t,i,s)),ne.exit(t)}action(t){let i=s=>{let n=this.registeredArguments.length,r=s.slice(0,n);return this._storeOptionsAsProperties?r[n]=this:r[n]=this.opts(),r.push(this),t.apply(this,r)};return this._actionHandler=i,this}createOption(t,i){return new Rn(t,i)}_callParseArg(t,i,s,n){try{return t.parseArg(i,s)}catch(r){if(r.code==="commander.invalidArgument"){let o=`${n} ${r.message}`;this.error(o,{exitCode:r.exitCode,code:r.code})}throw r}}_registerOption(t){let i=t.short&&this._findOption(t.short)||t.long&&this._findOption(t.long);if(i){let s=t.long&&this._findOption(t.long)?t.long:t.short;throw new Error(`Cannot add option '${t.flags}'${this._name&&` to command '${this._name}'`} due to conflicting flag '${s}'
17
+ - already used by option '${i.flags}'`)}this.options.push(t)}_registerCommand(t){let i=n=>[n.name()].concat(n.aliases()),s=i(t).find(n=>this._findCommand(n));if(s){let n=i(this._findCommand(s)).join("|"),r=i(t).join("|");throw new Error(`cannot add command '${r}' as already have command '${n}'`)}this.commands.push(t)}addOption(t){this._registerOption(t);let i=t.name(),s=t.attributeName();if(t.negate){let r=t.long.replace(/^--no-/,"--");this._findOption(r)||this.setOptionValueWithSource(s,t.defaultValue===void 0?!0:t.defaultValue,"default")}else t.defaultValue!==void 0&&this.setOptionValueWithSource(s,t.defaultValue,"default");let n=(r,o,a)=>{r==null&&t.presetArg!==void 0&&(r=t.presetArg);let l=this.getOptionValue(s);r!==null&&t.parseArg?r=this._callParseArg(t,r,l,o):r!==null&&t.variadic&&(r=t._concatValue(r,l)),r==null&&(t.negate?r=!1:t.isBoolean()||t.optional?r=!0:r=""),this.setOptionValueWithSource(s,r,a)};return this.on("option:"+i,r=>{let o=`error: option '${t.flags}' argument '${r}' is invalid.`;n(r,o,"cli")}),t.envVar&&this.on("optionEnv:"+i,r=>{let o=`error: option '${t.flags}' value '${r}' from env '${t.envVar}' is invalid.`;n(r,o,"env")}),this}_optionEx(t,i,s,n,r){if(typeof i=="object"&&i instanceof Rn)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(i,s);if(o.makeOptionMandatory(!!t.mandatory),typeof n=="function")o.default(r).argParser(n);else if(n instanceof RegExp){let a=n;n=(l,m)=>{let f=a.exec(l);return f?f[0]:m},o.default(r).argParser(n)}else o.default(n);return this.addOption(o)}option(t,i,s,n){return this._optionEx({},t,i,s,n)}requiredOption(t,i,s,n){return this._optionEx({mandatory:!0},t,i,s,n)}combineFlagAndOptionalValue(t=!0){return this._combineFlagAndOptionalValue=!!t,this}allowUnknownOption(t=!0){return this._allowUnknownOption=!!t,this}allowExcessArguments(t=!0){return this._allowExcessArguments=!!t,this}enablePositionalOptions(t=!0){return this._enablePositionalOptions=!!t,this}passThroughOptions(t=!0){return this._passThroughOptions=!!t,this._checkForBrokenPassThrough(),this}_checkForBrokenPassThrough(){if(this.parent&&this._passThroughOptions&&!this.parent._enablePositionalOptions)throw new Error(`passThroughOptions cannot be used for '${this._name}' without turning on enablePositionalOptions for parent command(s)`)}storeOptionsAsProperties(t=!0){if(this.options.length)throw new Error("call .storeOptionsAsProperties() before adding options");if(Object.keys(this._optionValues).length)throw new Error("call .storeOptionsAsProperties() before setting option values");return this._storeOptionsAsProperties=!!t,this}getOptionValue(t){return this._storeOptionsAsProperties?this[t]:this._optionValues[t]}setOptionValue(t,i){return this.setOptionValueWithSource(t,i,void 0)}setOptionValueWithSource(t,i,s){return this._storeOptionsAsProperties?this[t]=i:this._optionValues[t]=i,this._optionValueSources[t]=s,this}getOptionValueSource(t){return this._optionValueSources[t]}getOptionValueSourceWithGlobals(t){let i;return this._getCommandAndAncestors().forEach(s=>{s.getOptionValueSource(t)!==void 0&&(i=s.getOptionValueSource(t))}),i}_prepareUserArgs(t,i){if(t!==void 0&&!Array.isArray(t))throw new Error("first parameter to parse must be array or undefined");if(i=i||{},t===void 0&&i.from===void 0){ne.versions?.electron&&(i.from="electron");let n=ne.execArgv??[];(n.includes("-e")||n.includes("--eval")||n.includes("-p")||n.includes("--print"))&&(i.from="eval")}t===void 0&&(t=ne.argv),this.rawArgs=t.slice();let s;switch(i.from){case void 0:case"node":this._scriptPath=t[1],s=t.slice(2);break;case"electron":ne.defaultApp?(this._scriptPath=t[1],s=t.slice(2)):s=t.slice(1);break;case"user":s=t.slice(0);break;case"eval":s=t.slice(1);break;default:throw new Error(`unexpected parse option { from: '${i.from}' }`)}return!this._name&&this._scriptPath&&this.nameFromFilename(this._scriptPath),this._name=this._name||"program",s}parse(t,i){this._prepareForParse();let s=this._prepareUserArgs(t,i);return this._parseCommand([],s),this}async parseAsync(t,i){this._prepareForParse();let s=this._prepareUserArgs(t,i);return await this._parseCommand([],s),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
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(yi.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(m,g){let y=dt.resolve(m,g);if(hi.existsSync(y))return y;if(n.includes(dt.extname(g)))return;let w=n.find(v=>hi.existsSync(`${y}${v}`));if(w)return`${y}${w}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=t._executableFile||`${this._name}-${t._name}`,a=this._executableDir||"";if(this._scriptPath){let m;try{m=hi.realpathSync(this._scriptPath)}catch{m=this._scriptPath}a=dt.resolve(dt.dirname(m),a)}if(a){let m=r(a,o);if(!m&&!t._executableFile&&this._scriptPath){let g=dt.basename(this._scriptPath,dt.extname(this._scriptPath));g!==this._name&&(m=r(a,`${g}-${t._name}`))}o=m||o}s=n.includes(dt.extname(o));let l;ne.platform!=="win32"?s?(i.unshift(o),i=In(ne.execArgv).concat(i),l=us.spawn(ne.argv[0],i,{stdio:"inherit"})):l=us.spawn(o,i,{stdio:"inherit"}):(this._checkForMissingExecutable(o,a,t._name),i.unshift(o),i=In(ne.execArgv).concat(i),l=us.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 u=this._exitCallback;l.on("close",m=>{m=m??1,u?u(new ms(m,"commander.executeSubCommandAsync","(close)")):ne.exit(m)}),l.on("error",m=>{if(m.code==="ENOENT")this._checkForMissingExecutable(o,a,t._name);else if(m.code==="EACCES")throw new Error(`'${o}' not executable`);if(!u)ne.exit(1);else{let g=new ms(1,"commander.executeSubCommandAsync","(error)");g.nestedError=m,u(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 u=this._findOption(l);if(u){if(u.required){let m=r.shift();m===void 0&&this.optionMissingArgument(u),this.emit(`option:${u.name()}`,m)}else if(u.optional){let m=null;r.length>0&&!o(r[0])&&(m=r.shift()),this.emit(`option:${u.name()}`,m)}else this.emit(`option:${u.name()}`);a=u.variadic?u:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let u=this._findOption(`-${l[1]}`);if(u){u.required||u.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${u.name()}`,l.slice(2)):(this.emit(`option:${u.name()}`),r.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let u=l.indexOf("="),m=this._findOption(l.slice(0,u));if(m&&(m.required||m.optional)){this.emit(`option:${m.name()}`,l.slice(u+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 y=dt.resolve(f,g);if(yi.existsSync(y))return y;if(n.includes(dt.extname(g)))return;let v=n.find(w=>yi.existsSync(`${y}${w}`));if(v)return`${y}${v}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=t._executableFile||`${this._name}-${t._name}`,a=this._executableDir||"";if(this._scriptPath){let f;try{f=yi.realpathSync(this._scriptPath)}catch{f=this._scriptPath}a=dt.resolve(dt.dirname(f),a)}if(a){let f=r(a,o);if(!f&&!t._executableFile&&this._scriptPath){let g=dt.basename(this._scriptPath,dt.extname(this._scriptPath));g!==this._name&&(f=r(a,`${g}-${t._name}`))}o=f||o}s=n.includes(dt.extname(o));let l;ne.platform!=="win32"?s?(i.unshift(o),i=En(ne.execArgv).concat(i),l=fs.spawn(ne.argv[0],i,{stdio:"inherit"})):l=fs.spawn(o,i,{stdio:"inherit"}):(this._checkForMissingExecutable(o,a,t._name),i.unshift(o),i=En(ne.execArgv).concat(i),l=fs.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 ps(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 ps(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
- `),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 fa(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),u=this.options.find(g=>g.negate&&a===g.attributeName()),m=this.options.find(g=>!g.negate&&a===g.attributeName());return u&&(u.presetArg===void 0&&l===!1||u.presetArg!==void 0&&l===u.presetArg)?u:m||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=On(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=On(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
- `),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=>ca(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=dt.basename(t,dt.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.
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 ba(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
+ `),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=>ha(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=dt.basename(t,dt.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 In(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 ps(){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}hs.Command=fs;hs.useColor=ps});var Dn=lt(Ge=>{var{Argument:An}=pi(),{Command:gs}=Rn(),{CommanderError:pa,InvalidArgumentError:En}=zt(),{Help:ha}=os(),{Option:Pn}=cs();Ge.program=new gs;Ge.createCommand=e=>new gs(e);Ge.createOption=(e,t)=>new Pn(e,t);Ge.createArgument=(e,t)=>new An(e,t);Ge.Command=gs;Ge.Option=Pn;Ge.Argument=An;Ge.Help=ha;Ge.CommanderError=pa;Ge.InvalidArgumentError=En;Ge.InvalidOptionArgumentError=En});var L=lt((kc,ys)=>{var yi=process||{},Un=yi.argv||[],gi=yi.env||{},ga=!(gi.NO_COLOR||Un.includes("--no-color"))&&(!!gi.FORCE_COLOR||Un.includes("--color")||yi.platform==="win32"||(yi.stdout||{}).isTTY&&gi.TERM!=="dumb"||!!gi.CI),ya=(e,t,i=e)=>s=>{let n=""+s,r=n.indexOf(t,e.length);return~r?e+ba(n,t,i,r)+t:e+n+t},ba=(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)},Fn=(e=ga)=>{let t=e?ya:()=>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")}};ys.exports=Fn();ys.exports.createColors=Fn});var qt,Xt,Zt=Ee(()=>{"use strict";qt="domani.run",Xt=`https://${qt}`});function xt(e,t,i){try{let s=(0,qn.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 Mn(){return process.platform==="darwin"?!0:process.platform==="linux"?xt("secret-tool",["--help"]).ok:!1}function Ln(e={}){if(e.refresh&&(Mt=void 0),Mt!==void 0)return Mt??void 0;let t;if(process.platform==="darwin"){let i=xt("security",["find-generic-password","-s",Lt,"-a",Vt,"-w"]);i.ok&&i.stdout&&(t=i.stdout)}else if(process.platform==="linux"){let i=xt("secret-tool",["lookup","service",Lt,"account",Vt]);i.ok&&i.stdout&&(t=i.stdout)}return Mt=t??null,t}function Vn(e){let t=!1;return process.platform==="darwin"?t=xt("security",["add-generic-password","-U","-s",Lt,"-a",Vt,"-w",e]).ok:process.platform==="linux"&&(t=xt("secret-tool",["store","--label=domani CLI token","service",Lt,"account",Vt],e+`
28
- `).ok),t&&(Mt=e),t}function Wn(){process.platform==="darwin"?xt("security",["delete-generic-password","-s",Lt,"-a",Vt]):process.platform==="linux"&&xt("secret-tool",["clear","service",Lt,"account",Vt]),Mt=null}var qn,Lt,Vt,Mt,Jn=Ee(()=>{"use strict";qn=require("child_process"),Lt="domani-cli",Vt="default"});function Gn(e){Bn=e}function ct(){try{let e=bt.default.readFileSync(bs,"utf-8");return JSON.parse(e)}catch{return{}}}function Wt(e){e.token&&Mn()&&Vn(e.token)&&(e={...e,token:void 0,token_in_keychain:!0}),bt.default.mkdirSync(wi,{recursive:!0,mode:448}),bt.default.writeFileSync(bs,JSON.stringify(e,null,2),{mode:384})}function Yn(){Wn();try{bt.default.unlinkSync(bs)}catch{}}function qe(){return Bn||ct().api_url||Xt}function Me(e={}){if(process.env.DOMANI_API_KEY)return process.env.DOMANI_API_KEY;let t=ct();if(t.token)return t.token;if(t.token_in_keychain)return Ln({refresh:e.refreshKeychain})}function wa(){try{let e=bt.default.readFileSync(Kn,"utf-8");return JSON.parse(e)}catch{return null}}function va(e){try{bt.default.mkdirSync(wi,{recursive:!0,mode:448}),bt.default.writeFileSync(Kn,JSON.stringify(e),{mode:384})}catch{}}function bi(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 zn(){let e=wa();if(e&&Date.now()-e.checkedAt<$a)return bi(e.version,_e)>0?{update:e.version,forced:bi(_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(va({version:s.version,min:s.min,checkedAt:Date.now()}),bi(s.version,_e)>0)return{update:s.version,forced:bi(_e,s.min)<0}}catch{}return null}var bt,$i,Hn,wi,bs,Bn,Kn,$a,$s,_e,ut=Ee(()=>{"use strict";bt=U(require("fs"),1),$i=U(require("path"),1),Hn=U(require("os"),1);Zt();Jn();wi=process.env.DOMANI_CONFIG_DIR||$i.default.join(Hn.default.homedir(),".domani"),bs=$i.default.join(wi,"config.json");Kn=$i.default.join(wi,"version-check.json"),$a=1440*60*1e3;$s=process.stdout.isTTY??!1,_e="0.4.42"});var vs=lt((Oc,Xn)=>{"use strict";var ws={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"},ka={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},_a={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?ws.up():"");return e&&(t+=ws.left),t}};Xn.exports={cursor:ws,scroll:ka,erase:_a,beep:"\x07"}});function mt(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?mt(r,t<0?-1:1,i):r}function Ss(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 gs(){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=hs;ys.useColor=gs});var Un=lt(Ge=>{var{Argument:Dn}=gi(),{Command:bs}=Pn(),{CommanderError:$a,InvalidArgumentError:Tn}=Yt(),{Help:va}=ls(),{Option:Nn}=ms();Ge.program=new bs;Ge.createCommand=e=>new bs(e);Ge.createOption=(e,t)=>new Nn(e,t);Ge.createArgument=(e,t)=>new Dn(e,t);Ge.Command=bs;Ge.Option=Nn;Ge.Argument=Dn;Ge.Help=va;Ge.CommanderError=$a;Ge.InvalidArgumentError=Tn;Ge.InvalidOptionArgumentError=Tn});var L=lt((Cc,$s)=>{var $i=process||{},Mn=$i.argv||[],bi=$i.env||{},wa=!(bi.NO_COLOR||Mn.includes("--no-color"))&&(!!bi.FORCE_COLOR||Mn.includes("--color")||$i.platform==="win32"||($i.stdout||{}).isTTY&&bi.TERM!=="dumb"||!!bi.CI),ka=(e,t,i=e)=>s=>{let n=""+s,r=n.indexOf(t,e.length);return~r?e+_a(n,t,i,r)+t:e+n+t},_a=(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=wa)=>{let t=e?ka:()=>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")}};$s.exports=Ln();$s.exports.createColors=Ln});var qt,Xt,Zt=Ie(()=>{"use strict";qt="domani.run",Xt=`https://${qt}`});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 Jn(e={}){if(e.refresh&&(Mt=void 0),Mt!==void 0)return Mt??void 0;let t;if(process.platform==="darwin"){let i=xt("security",["find-generic-password","-s",Lt,"-a",Vt,"-w"]);i.ok&&i.stdout&&(t=i.stdout)}else if(process.platform==="linux"){let i=xt("secret-tool",["lookup","service",Lt,"account",Vt]);i.ok&&i.stdout&&(t=i.stdout)}return Mt=t??null,t}function Hn(e){let t=!1;return process.platform==="darwin"?t=xt("security",["add-generic-password","-U","-s",Lt,"-a",Vt,"-w",e]).ok:process.platform==="linux"&&(t=xt("secret-tool",["store","--label=domani CLI token","service",Lt,"account",Vt],e+`
28
+ `).ok),t&&(Mt=e),t}function Bn(){process.platform==="darwin"?xt("security",["delete-generic-password","-s",Lt,"-a",Vt]):process.platform==="linux"&&xt("secret-tool",["clear","service",Lt,"account",Vt]),Mt=null}var Vn,Lt,Vt,Mt,Gn=Ie(()=>{"use strict";Vn=require("child_process"),Lt="domani-cli",Vt="default"});function Yn(e){zn=e}function ct(){try{let e=bt.default.readFileSync(vs,"utf-8");return JSON.parse(e)}catch{return{}}}function Wt(e){e.token&&Wn()&&Hn(e.token)&&(e={...e,token:void 0,token_in_keychain:!0}),bt.default.mkdirSync(ki,{recursive:!0,mode:448}),bt.default.writeFileSync(vs,JSON.stringify(e,null,2),{mode:384})}function Zn(){Bn();try{bt.default.unlinkSync(vs)}catch{}}function qe(){return zn||ct().api_url||Xt}function Me(e={}){if(process.env.DOMANI_API_KEY)return process.env.DOMANI_API_KEY;let t=ct();if(t.token)return t.token;if(t.token_in_keychain)return Jn({refresh:e.refreshKeychain})}function ja(){try{let e=bt.default.readFileSync(Xn,"utf-8");return JSON.parse(e)}catch{return null}}function Sa(e){try{bt.default.mkdirSync(ki,{recursive:!0,mode:448}),bt.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=ja();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(Sa({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 bt,wi,Kn,ki,vs,zn,Xn,xa,ws,_e,ut=Ie(()=>{"use strict";bt=U(require("fs"),1),wi=U(require("path"),1),Kn=U(require("os"),1);Zt();Gn();ki=process.env.DOMANI_CONFIG_DIR||wi.default.join(Kn.default.homedir(),".domani"),vs=wi.default.join(ki,"config.json");Xn=wi.default.join(ki,"version-check.json"),xa=1440*60*1e3;ws=process.stdout.isTTY??!1,_e="0.4.45"});var _s=lt((Pc,er)=>{"use strict";var ks={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"},Ca={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},Oa={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?ks.up():"");return e&&(t+=ks.left),t}};er.exports={cursor:ks,scroll:Ca,erase:Oa,beep:"\x07"}});function mt(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?mt(r,t<0?-1:1,i):r}function Os(e,t,i){return String(e).normalize().replaceAll(`\r
29
29
  `,`
30
30
  `).split(`
31
- `).map(s=>Ta(s,t,i)).join(`
32
- `)}function or(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 Rs(e,t){if(typeof e=="string")return ce.aliases.get(e)===t;for(let i of e)if(i!==void 0&&Rs(i,t))return!0;return!1}function Ua(e,t){if(e===t)return;let i=e.split(`
31
+ `).map(s=>Ma(s,t,i)).join(`
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 Es(e,t){if(typeof e=="string")return ce.aliases.get(e)===t;for(let i of e)if(i!==void 0&&Es(i,t))return!0;return!1}function Va(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===Cs}function xi(e,t){let i=e;i.isTTY&&i.setRawMode(t)}function ar({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 js.ReadStream&&e.isTTY&&e.setRawMode(!0);let r=(o,{name:a,sequence:l})=>{let u=String(o);if(Rs([u,a,l],"cancel")){s&&t.write(Ie.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(Ie.cursor.hide),e.once("keypress",r),()=>{e.off("keypress",r),s&&t.write(Ie.cursor.show),e instanceof js.ReadStream&&e.isTTY&&!Fa&&e.setRawMode(!1),n.terminal=!1,n.close()}}function nt(e,t,i,s=i){let n=St(e??jt.stdout);return Ss(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===Is}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=vt.createInterface({input:e,output:t,prompt:"",tabSize:1});vt.emitKeypressEvents(e,n),e instanceof Cs.ReadStream&&e.isTTY&&e.setRawMode(!0);let r=(o,{name:a,sequence:l})=>{let m=String(o);if(Es([m,a,l],"cancel")){s&&t.write(Re.cursor.show),process.exit(0);return}if(!i)return;vt.moveCursor(t,a==="return"?0:-1,a==="return"?-1:0,()=>{vt.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 Cs.ReadStream&&e.isTTY&&!Wa&&e.setRawMode(!1),n.terminal=!1,n.close()}}function nt(e,t,i,s=i){let n=St(e??jt.stdout);return Os(t,n-i.length,{hard:!0,trim:!1}).split(`
35
35
  `).map((r,o)=>`${o===0?s:i}${r}`).join(`
36
- `)}function qa(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 Ma(e,t){return(t.label??String(t.value)).toLowerCase().includes(e.toLowerCase())}function La(e,t){if(t)return e?t:t[0]}var $t,jt,wt,tr,Ie,js,xa,ja,Sa,ks,vi,ki,_s,_i,Ca,Oa,ir,Ia,Qt,Ai,sr,Ra,Os,nr,Aa,rr,Is,Zn,Ea,Qn,er,Pa,xs,Da,Ta,Na,ce,Fa,Cs,St,As,st,ei,ji,Si,Ci,lr,Oi,Ii,Ri,Es=Ee(()=>{$t=U(L(),1),jt=require("node:process"),wt=U(require("node:readline"),1),tr=U(require("node:readline"),1),Ie=U(vs(),1),js=require("node:tty");xa=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,ja=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Sa=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,ks=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,vi=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,ki=/\t{1,1000}/y,_s=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"),_i=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Ca=new RegExp("\\p{M}+","gu"),Oa={limit:1/0,ellipsis:""},ir=(e,t={},i={})=>{let s=t.limit??1/0,n=t.ellipsis??"",r=t?.ellipsisWidth??(n?ir(n,Oa,i).width:0),o=i.ansiWidth??0,a=i.controlWidth??0,l=i.tabWidth??8,u=i.ambiguousWidth??1,m=i.emojiWidth??2,g=i.fullWidthWidth??2,y=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 T=e.slice(V,ee)||e.slice(v,h);x=0;for(let Z of T.replaceAll(Ca,"")){let Y=Z.codePointAt(0)||0;if(ja(Y)?E=g:Sa(Y)?E=w:u!==y&&xa(Y)?E=u:E=y,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(_i.lastIndex=h,_i.test(e)){if(x=_i.lastIndex-h,E=x*y,P+E>M&&(R=Math.min(R,h+Math.floor((M-P)/y))),P+E>s){O=!0;break}P+=E,V=v,ee=h,h=v=_i.lastIndex;continue}if(ks.lastIndex=h,ks.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=ks.lastIndex;continue}if(vi.lastIndex=h,vi.test(e)){if(x=vi.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=vi.lastIndex;continue}if(ki.lastIndex=h,ki.test(e)){if(x=ki.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=ki.lastIndex;continue}if(_s.lastIndex=h,_s.test(e)){if(P+m>M&&(R=Math.min(R,h)),P+m>s){O=!0;break}P+=m,V=v,ee=h,h=v=_s.lastIndex;continue}h+=1}return{width:O?M:P,index:O?R:_,truncated:O,ellipsed:O&&s>=r}},Ia={limit:1/0,ellipsis:"",ellipsisWidth:0},Qt=(e,t={})=>ir(e,Ia,t).width,Ai="\x1B",sr="\x9B",Ra=39,Os="\x07",nr="[",Aa="]",rr="m",Is=`${Aa}8;;`,Zn=new RegExp(`(?:\\${nr}(?<code>\\d+)m|\\${Is}(?<uri>.*)${Os})`,"y"),Ea=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},Qn=e=>`${Ai}${nr}${e}${rr}`,er=e=>`${Ai}${Is}${e}${Os}`,Pa=e=>e.map(t=>Qt(t)),xs=(e,t,i)=>{let s=t[Symbol.iterator](),n=!1,r=!1,o=e.at(-1),a=o===void 0?0:Qt(o),l=s.next(),u=s.next(),m=0;for(;!l.done;){let g=l.value,y=Qt(g);a+y<=i?e[e.length-1]+=g:(e.push(g),a=0),(g===Ai||g===sr)&&(n=!0,r=t.startsWith(Is,m+1)),n?r?g===Os&&(n=!1,r=!1):g===rr&&(n=!1):(a+=y,a===i&&!u.done&&(e.push(""),a=0)),l=u,u=s.next(),m+=g.length}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop())},Da=e=>{let t=e.split(" "),i=t.length;for(;i>0&&!(Qt(t[i-1])>0);)i--;return i===t.length?e:t.slice(0,i).join(" ")+t.slice(i).join("")},Ta=(e,t,i={})=>{if(i.trim!==!1&&e.trim()==="")return"";let s="",n,r,o=e.split(" "),a=Pa(o),l=[""];for(let[v,h]of o.entries()){i.trim!==!1&&(l[l.length-1]=(l.at(-1)??"").trimStart());let _=Qt(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(""),xs(l,h,t);continue}if(_+a[v]>t&&_>0&&a[v]>0){if(i.wordWrap===!1&&_<t){xs(l,h,t);continue}l.push("")}if(_+a[v]>t&&i.wordWrap===!1){xs(l,h,t);continue}l[l.length-1]+=h}i.trim!==!1&&(l=l.map(v=>Da(v)));let u=l.join(`
37
- `),m=u[Symbol.iterator](),g=m.next(),y=m.next(),w=0;for(;!g.done;){let v=g.value,h=y.value;if(s+=v,v===Ai||v===sr){Zn.lastIndex=w+1;let x=Zn.exec(u)?.groups;if(x?.code!==void 0){let O=Number.parseFloat(x.code);n=O===Ra?void 0:O}else x?.uri!==void 0&&(r=x.uri.length===0?void 0:x.uri)}let _=n?Ea(n):void 0;h===`
38
- `?(r&&(s+=er("")),n&&_&&(s+=Qn(_))):v===`
39
- `&&(n&&_&&(s+=Qn(n)),r&&(s+=er(r))),w+=v.length,g=y,y=m.next()}return s};Na=["up","down","left","right","space","enter","cancel"],ce={actions:new Set(Na),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0};Fa=globalThis.process.platform.startsWith("win"),Cs=Symbol("clack:cancel");St=e=>"columns"in e&&typeof e.columns=="number"?e.columns:80,As=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(Cs);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=tr.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),xi(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(Ie.cursor.show),this.output.off("resize",this.render),xi(this.input,!1),t(this.value)}),this.once("cancel",()=>{this.output.write(Ie.cursor.show),this.output.off("resize",this.render),xi(this.input,!1),t(Cs)})})}_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")}Rs([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
- `),xi(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let t=Ss(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
41
- `).length-1;this.output.write(Ie.cursor.move(-999,t*-1))}render(){let t=Ss(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(t!==this._prevFrame){if(this.state==="initial")this.output.write(Ie.cursor.hide);else{let i=Ua(this._prevFrame,t),s=As(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(Ie.cursor.move(0,o-r)),this.output.write(Ie.erase.lines(1));let a=t.split(`
42
- `);this.output.write(a[o]),this._prevFrame=t,this.output.write(Ie.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(Ie.cursor.move(0,l))}this.output.write(Ie.erase.down());let a=t.split(`
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 Ha(e,t){return(t.label??String(t.value)).toLowerCase().includes(e.toLowerCase())}function Ba(e,t){if(t)return e?t:t[0]}var $t,jt,vt,nr,Re,Cs,Ia,Ra,Aa,xs,_i,xi,js,ji,Ea,Pa,rr,Da,Qt,Pi,or,Ta,Rs,ar,Na,lr,As,tr,Ua,ir,sr,Fa,Ss,qa,Ma,La,ce,Wa,Is,St,Ps,st,ei,Ci,Oi,Ii,ur,Ri,Ai,Ei,Ds=Ie(()=>{$t=U(L(),1),jt=require("node:process"),vt=U(require("node:readline"),1),nr=U(require("node:readline"),1),Re=U(_s(),1),Cs=require("node:tty");Ia=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,Ra=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Aa=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,xi=/\t{1,1000}/y,js=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,Ea=new RegExp("\\p{M}+","gu"),Pa={limit:1/0,ellipsis:""},rr=(e,t={},i={})=>{let s=t.limit??1/0,n=t.ellipsis??"",r=t?.ellipsisWidth??(n?rr(n,Pa,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,y=i.regularWidth??1,v=i.wideWidth??2,w=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>w){let N=e.slice(V,ee)||e.slice(w,h);x=0;for(let Z of N.replaceAll(Ea,"")){let z=Z.codePointAt(0)||0;if(Ra(z)?E=g:Aa(z)?E=v:m!==y&&Ia(z)?E=m:E=y,P+E>M&&(R=Math.min(R,Math.max(V,w)+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*y,P+E>M&&(R=Math.min(R,h+Math.floor((M-P)/y))),P+E>s){O=!0;break}P+=E,V=w,ee=h,h=w=ji.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(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=w,ee=h,h=w=_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=w,ee=h,h=w=xi.lastIndex;continue}if(js.lastIndex=h,js.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=js.lastIndex;continue}h+=1}return{width:O?M:P,index:O?R:_,truncated:O,ellipsed:O&&s>=r}},Da={limit:1/0,ellipsis:"",ellipsisWidth:0},Qt=(e,t={})=>rr(e,Da,t).width,Pi="\x1B",or="\x9B",Ta=39,Rs="\x07",ar="[",Na="]",lr="m",As=`${Na}8;;`,tr=new RegExp(`(?:\\${ar}(?<code>\\d+)m|\\${As}(?<uri>.*)${Rs})`,"y"),Ua=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}${As}${e}${Rs}`,Fa=e=>e.map(t=>Qt(t)),Ss=(e,t,i)=>{let s=t[Symbol.iterator](),n=!1,r=!1,o=e.at(-1),a=o===void 0?0:Qt(o),l=s.next(),m=s.next(),f=0;for(;!l.done;){let g=l.value,y=Qt(g);a+y<=i?e[e.length-1]+=g:(e.push(g),a=0),(g===Pi||g===or)&&(n=!0,r=t.startsWith(As,f+1)),n?r?g===Rs&&(n=!1,r=!1):g===lr&&(n=!1):(a+=y,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())},qa=e=>{let t=e.split(" "),i=t.length;for(;i>0&&!(Qt(t[i-1])>0);)i--;return i===t.length?e:t.slice(0,i).join(" ")+t.slice(i).join("")},Ma=(e,t,i={})=>{if(i.trim!==!1&&e.trim()==="")return"";let s="",n,r,o=e.split(" "),a=Fa(o),l=[""];for(let[w,h]of o.entries()){i.trim!==!1&&(l[l.length-1]=(l.at(-1)??"").trimStart());let _=Qt(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 x=t-_,O=1+Math.floor((a[w]-x-1)/t);Math.floor((a[w]-1)/t)<O&&l.push(""),Ss(l,h,t);continue}if(_+a[w]>t&&_>0&&a[w]>0){if(i.wordWrap===!1&&_<t){Ss(l,h,t);continue}l.push("")}if(_+a[w]>t&&i.wordWrap===!1){Ss(l,h,t);continue}l[l.length-1]+=h}i.trim!==!1&&(l=l.map(w=>qa(w)));let m=l.join(`
37
+ `),f=m[Symbol.iterator](),g=f.next(),y=f.next(),v=0;for(;!g.done;){let w=g.value,h=y.value;if(s+=w,w===Pi||w===or){tr.lastIndex=v+1;let x=tr.exec(m)?.groups;if(x?.code!==void 0){let O=Number.parseFloat(x.code);n=O===Ta?void 0:O}else x?.uri!==void 0&&(r=x.uri.length===0?void 0:x.uri)}let _=n?Ua(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=y,y=f.next()}return s};La=["up","down","left","right","space","enter","cancel"],ce={actions:new Set(La),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0};Wa=globalThis.process.platform.startsWith("win"),Is=Symbol("clack:cancel");St=e=>"columns"in e&&typeof e.columns=="number"?e.columns:80,Ps=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(Is);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(Is)})})}_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")}Es([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
+ `),Si(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let t=Os(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
41
+ `).length-1;this.output.write(Re.cursor.move(-999,t*-1))}render(){let t=Os(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=Va(this._prevFrame,t),s=Ps(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
+ `);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(Ie.erase.down())}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t}}};ei=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 $t.default.inverse($t.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}${$t.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??Ma;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=mt(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=La(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=qa(this.focusedValue,this.filteredOptions);this.#e=mt(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())}}},ji=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(Ie.cursor.move(0,-1)),this.value=i,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}},Si=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}})}},Ci=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?mt(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=mt(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=mt(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}},lr=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}${$t.default.inverse($t.default.hidden("_"))}`;let t=this.masked,i=t.slice(0,this.cursor),s=t.slice(this.cursor);return`${i}${$t.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)})}},Oi=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?mt(s,1,this.options):s,this.changeValue(),this.on("cursor",n=>{switch(n){case"left":case"up":this.cursor=mt(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=mt(this.cursor,1,this.options);break}this.changeValue()})}},Ii=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"))})}},Ri=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}${$t.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 zs={};Ft(zs,{S_BAR:()=>A,S_BAR_END:()=>ke,S_BAR_END_RIGHT:()=>$r,S_BAR_H:()=>qi,S_BAR_START:()=>qs,S_BAR_START_RIGHT:()=>br,S_CHECKBOX_ACTIVE:()=>Fi,S_CHECKBOX_INACTIVE:()=>Ht,S_CHECKBOX_SELECTED:()=>Ot,S_CONNECT_LEFT:()=>vr,S_CORNER_BOTTOM_LEFT:()=>Vs,S_CORNER_BOTTOM_RIGHT:()=>Ls,S_CORNER_TOP_LEFT:()=>kr,S_CORNER_TOP_RIGHT:()=>Ms,S_ERROR:()=>Bs,S_INFO:()=>Ws,S_PASSWORD_MASK:()=>wr,S_RADIO_ACTIVE:()=>si,S_RADIO_INACTIVE:()=>Rt,S_STEP_ACTIVE:()=>yr,S_STEP_CANCEL:()=>Us,S_STEP_ERROR:()=>Fs,S_STEP_SUBMIT:()=>At,S_SUCCESS:()=>Js,S_WARN:()=>Hs,autocomplete:()=>Or,autocompleteMultiselect:()=>sl,box:()=>al,cancel:()=>cl,confirm:()=>Ke,group:()=>ll,groupMultiselect:()=>dl,intro:()=>ul,isCI:()=>Ns,isCancel:()=>le,isTTY:()=>gr,limitOptions:()=>Gt,log:()=>Ve,multiselect:()=>fl,note:()=>gl,outro:()=>ml,password:()=>yl,path:()=>bl,progress:()=>wl,select:()=>Ze,selectKey:()=>vl,settings:()=>ce,spinner:()=>ni,stream:()=>Ct,symbol:()=>Xe,symbolBar:()=>Gs,taskLog:()=>xl,tasks:()=>kl,text:()=>Re,unicode:()=>Ui,unicodeOr:()=>oe,updateSettings:()=>or});function Va(){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 Bt(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}}};ei=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 $t.default.inverse($t.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}${$t.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??Ha;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=mt(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=Ba(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=mt(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?mt(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=mt(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=mt(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}${$t.default.inverse($t.default.hidden("_"))}`;let t=this.masked,i=t.slice(0,this.cursor),s=t.slice(this.cursor);return`${i}${$t.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?mt(s,1,this.options):s,this.changeValue(),this.on("cursor",n=>{switch(n){case"left":case"up":this.cursor=mt(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=mt(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}${$t.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 Zs={};Ft(Zs,{S_BAR:()=>A,S_BAR_END:()=>ke,S_BAR_END_RIGHT:()=>kr,S_BAR_H:()=>Li,S_BAR_START:()=>Ls,S_BAR_START_RIGHT:()=>wr,S_CHECKBOX_ACTIVE:()=>Mi,S_CHECKBOX_INACTIVE:()=>Ht,S_CHECKBOX_SELECTED:()=>Ot,S_CONNECT_LEFT:()=>xr,S_CORNER_BOTTOM_LEFT:()=>Js,S_CORNER_BOTTOM_RIGHT:()=>Ws,S_CORNER_TOP_LEFT:()=>jr,S_CORNER_TOP_RIGHT:()=>Vs,S_ERROR:()=>Ks,S_INFO:()=>Hs,S_PASSWORD_MASK:()=>_r,S_RADIO_ACTIVE:()=>si,S_RADIO_INACTIVE:()=>Rt,S_STEP_ACTIVE:()=>vr,S_STEP_CANCEL:()=>qs,S_STEP_ERROR:()=>Ms,S_STEP_SUBMIT:()=>At,S_SUCCESS:()=>Bs,S_WARN:()=>Gs,autocomplete:()=>Ar,autocompleteMultiselect:()=>ll,box:()=>ml,cancel:()=>hl,confirm:()=>Ke,group:()=>fl,groupMultiselect:()=>pl,intro:()=>gl,isCI:()=>Fs,isCancel:()=>le,isTTY:()=>$r,limitOptions:()=>Gt,log:()=>Ve,multiselect:()=>bl,note:()=>wl,outro:()=>yl,password:()=>kl,path:()=>_l,progress:()=>jl,select:()=>Ze,selectKey:()=>Sl,settings:()=>ce,spinner:()=>ni,stream:()=>Ct,symbol:()=>Xe,symbolBar:()=>zs,taskLog:()=>Il,tasks:()=>Cl,text:()=>Ae,unicode:()=>qi,unicodeOr:()=>oe,updateSettings:()=>dr});function Ga(){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 Bt(e,t,i){return String(e).normalize().replaceAll(`\r
45
45
  `,`
46
46
  `).split(`
47
- `).map(s=>el(s,t,i)).join(`
48
- `)}function mr(e){return e.label??String(e.value??"")}function Cr(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 il(e,t){let i=[];for(let s of t)e.includes(s.value)&&i.push(s);return i}function fr(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 wl({style:e="heavy",max:t=100,size:i=40,...s}={}){let n=ni(s),r=0,o="",a=Math.max(1,t),l=Math.max(1,i),u=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}},m=(w,v)=>{let h=Math.floor(r/a*l);return`${u(w)(pr[e].repeat(h))}${p.default.dim(pr[e].repeat(l-h))} ${v}`},g=(w="")=>{o=w,n.start(m("initial",w))},y=(w=1,v)=>{r=Math.min(a,w+r),n.message(m("active",v??o)),o=v??o};return{start:g,stop:n.stop,cancel:n.cancel,error:n.error,clear:n.clear,advance:y,isCancelled:n.isCancelled,message:w=>y(0,w)}}var p,Le,It,ii,Jt,Ni,Ui,Ns,gr,oe,yr,Us,Fs,At,qs,A,ke,br,$r,si,Rt,Fi,Ot,Ht,wr,qi,Ms,vr,Ls,Vs,kr,Ws,Js,Hs,Bs,Xe,Gs,Wa,Ja,Ha,Ps,Ei,Pi,Ds,Di,Ba,Ga,_r,Ka,Pe,Mi,xr,Ya,Ks,jr,za,Sr,Ys,dr,Xa,cr,ur,Za,Ts,Qa,el,tl,Gt,Or,sl,nl,rl,ol,al,Ke,ll,dl,Ve,cl,ul,ml,ti,fl,pl,hl,gl,yl,bl,$l,ni,pr,Ti,Ze,vl,hr,Ct,kl,_l,xl,Re,De=Ee(()=>{Es();Es();p=U(L(),1),Le=U(require("node:process"),1),It=require("node:fs"),ii=require("node:path"),Jt=U(vs(),1),Ni=require("node:util");Ui=Va(),Ns=()=>process.env.CI==="true",gr=e=>e.isTTY===!0,oe=(e,t)=>Ui?e:t,yr=oe("\u25C6","*"),Us=oe("\u25A0","x"),Fs=oe("\u25B2","x"),At=oe("\u25C7","o"),qs=oe("\u250C","T"),A=oe("\u2502","|"),ke=oe("\u2514","\u2014"),br=oe("\u2510","T"),$r=oe("\u2518","\u2014"),si=oe("\u25CF",">"),Rt=oe("\u25CB"," "),Fi=oe("\u25FB","[\u2022]"),Ot=oe("\u25FC","[+]"),Ht=oe("\u25FB","[ ]"),wr=oe("\u25AA","\u2022"),qi=oe("\u2500","-"),Ms=oe("\u256E","+"),vr=oe("\u251C","+"),Ls=oe("\u256F","+"),Vs=oe("\u2570","+"),kr=oe("\u256D","+"),Ws=oe("\u25CF","\u2022"),Js=oe("\u25C6","*"),Hs=oe("\u25B2","!"),Bs=oe("\u25A0","x"),Xe=e=>{switch(e){case"initial":case"active":return p.default.cyan(yr);case"cancel":return p.default.red(Us);case"error":return p.default.yellow(Fs);case"submit":return p.default.green(At)}},Gs=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)}},Wa=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,Ja=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Ha=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,Ps=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,Ei=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Pi=/\t{1,1000}/y,Ds=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"),Di=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Ba=new RegExp("\\p{M}+","gu"),Ga={limit:1/0,ellipsis:""},_r=(e,t={},i={})=>{let s=t.limit??1/0,n=t.ellipsis??"",r=t?.ellipsisWidth??(n?_r(n,Ga,i).width:0),o=i.ansiWidth??0,a=i.controlWidth??0,l=i.tabWidth??8,u=i.ambiguousWidth??1,m=i.emojiWidth??2,g=i.fullWidthWidth??2,y=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 T=e.slice(V,ee)||e.slice(v,h);x=0;for(let Z of T.replaceAll(Ba,"")){let Y=Z.codePointAt(0)||0;if(Ja(Y)?E=g:Ha(Y)?E=w:u!==y&&Wa(Y)?E=u:E=y,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(Di.lastIndex=h,Di.test(e)){if(x=Di.lastIndex-h,E=x*y,P+E>M&&(R=Math.min(R,h+Math.floor((M-P)/y))),P+E>s){O=!0;break}P+=E,V=v,ee=h,h=v=Di.lastIndex;continue}if(Ps.lastIndex=h,Ps.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=Ps.lastIndex;continue}if(Ei.lastIndex=h,Ei.test(e)){if(x=Ei.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=Ei.lastIndex;continue}if(Pi.lastIndex=h,Pi.test(e)){if(x=Pi.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=Pi.lastIndex;continue}if(Ds.lastIndex=h,Ds.test(e)){if(P+m>M&&(R=Math.min(R,h)),P+m>s){O=!0;break}P+=m,V=v,ee=h,h=v=Ds.lastIndex;continue}h+=1}return{width:O?M:P,index:O?R:_,truncated:O,ellipsed:O&&s>=r}},Ka={limit:1/0,ellipsis:"",ellipsisWidth:0},Pe=(e,t={})=>_r(e,Ka,t).width,Mi="\x1B",xr="\x9B",Ya=39,Ks="\x07",jr="[",za="]",Sr="m",Ys=`${za}8;;`,dr=new RegExp(`(?:\\${jr}(?<code>\\d+)m|\\${Ys}(?<uri>.*)${Ks})`,"y"),Xa=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},cr=e=>`${Mi}${jr}${e}${Sr}`,ur=e=>`${Mi}${Ys}${e}${Ks}`,Za=e=>e.map(t=>Pe(t)),Ts=(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(),u=s.next(),m=0;for(;!l.done;){let g=l.value,y=Pe(g);a+y<=i?e[e.length-1]+=g:(e.push(g),a=0),(g===Mi||g===xr)&&(n=!0,r=t.startsWith(Ys,m+1)),n?r?g===Ks&&(n=!1,r=!1):g===Sr&&(n=!1):(a+=y,a===i&&!u.done&&(e.push(""),a=0)),l=u,u=s.next(),m+=g.length}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop())},Qa=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("")},el=(e,t,i={})=>{if(i.trim!==!1&&e.trim()==="")return"";let s="",n,r,o=e.split(" "),a=Za(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(""),Ts(l,h,t);continue}if(_+a[v]>t&&_>0&&a[v]>0){if(i.wordWrap===!1&&_<t){Ts(l,h,t);continue}l.push("")}if(_+a[v]>t&&i.wordWrap===!1){Ts(l,h,t);continue}l[l.length-1]+=h}i.trim!==!1&&(l=l.map(v=>Qa(v)));let u=l.join(`
49
- `),m=u[Symbol.iterator](),g=m.next(),y=m.next(),w=0;for(;!g.done;){let v=g.value,h=y.value;if(s+=v,v===Mi||v===xr){dr.lastIndex=w+1;let x=dr.exec(u)?.groups;if(x?.code!==void 0){let O=Number.parseFloat(x.code);n=O===Ya?void 0:O}else x?.uri!==void 0&&(r=x.uri.length===0?void 0:x.uri)}let _=n?Xa(n):void 0;h===`
50
- `?(r&&(s+=ur("")),n&&_&&(s+=cr(_))):v===`
51
- `&&(n&&_&&(s+=cr(n)),r&&(s+=ur(r))),w+=v.length,g=y,y=m.next()}return s};tl=(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}},Gt=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,u=As(n),m=p.default.dim("..."),g=e.maxItems??Number.POSITIVE_INFINITY,y=Math.max(u-a,0),w=Math.max(Math.min(g,y),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=Bt(s(i[P],P===t),l,{hard:!0,trim:!1}).split(`
52
- `);O.push(E),R+=E.length}if(R>y){let P=0,E=0,T=R,Z=t-M,Y=(F,ie)=>tl(O,T,F,ie,y);h?({lineCount:T,removals:P}=Y(0,Z),T>y&&({lineCount:T,removals:E}=Y(Z+1,O.length))):({lineCount:T,removals:E}=Y(Z+1,O.length),T>y&&({lineCount:T,removals:P}=Y(0,Z))),P>0&&(h=!0,O.splice(0,P)),E>0&&(_=!0,O.splice(O.length-E,E))}let ee=[];h&&ee.push(m);for(let P of O)for(let E of P)ee.push(E);return _&&ee.push(m),ee};Or=e=>new ei({options:e.options,initialValue:e.initialValue?[e.initialValue]:void 0,initialUserInput:e.initialUserInput,filter:e.filter??((t,i)=>Cr(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)}`,`${Xe(this.state)} ${e.message}`]:[`${Xe(this.state)} ${e.message}`],s=this.userInput,n=this.options,r=e.placeholder,o=s===""&&r!==void 0,a=(l,u)=>{let m=mr(l),g=l.hint&&l.value===this.focusedValue?p.default.dim(` (${l.hint})`):"";switch(u){case"active":return`${p.default.green(si)} ${m}${g}`;case"inactive":return`${p.default.dim(Rt)} ${p.default.dim(m)}`;case"disabled":return`${p.default.gray(Rt)} ${p.default.strikethrough(p.default.gray(m))}`}};switch(this.state){case"submit":{let l=il(this.selectedValues,n),u=l.length>0?` ${p.default.dim(l.map(mr).join(", "))}`:"",m=t?p.default.gray(A):"";return`${i.join(`
47
+ `).map(s=>rl(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 al(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 jl({style:e="heavy",max:t=100,size:i=40,...s}={}){let n=ni(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)(yr[e].repeat(h))}${p.default.dim(yr[e].repeat(l-h))} ${w}`},g=(v="")=>{o=v,n.start(f("initial",v))},y=(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:y,isCancelled:n.isCancelled,message:v=>y(0,v)}}var p,Le,It,ii,Jt,Fi,qi,Fs,$r,oe,vr,qs,Ms,At,Ls,A,ke,wr,kr,si,Rt,Mi,Ot,Ht,_r,Li,Vs,xr,Ws,Js,jr,Hs,Bs,Gs,Ks,Xe,zs,Ka,za,Ya,Ts,Di,Ti,Ns,Ni,Xa,Za,Sr,Qa,Pe,Vi,Cr,el,Ys,Or,tl,Ir,Xs,mr,il,fr,pr,sl,Us,nl,rl,ol,Gt,Ar,ll,dl,cl,ul,ml,Ke,fl,pl,Ve,hl,gl,yl,ti,bl,$l,vl,wl,kl,_l,xl,ni,yr,Ui,Ze,Sl,br,Ct,Cl,Ol,Il,Ae,De=Ie(()=>{Ds();Ds();p=U(L(),1),Le=U(require("node:process"),1),It=require("node:fs"),ii=require("node:path"),Jt=U(_s(),1),Fi=require("node:util");qi=Ga(),Fs=()=>process.env.CI==="true",$r=e=>e.isTTY===!0,oe=(e,t)=>qi?e:t,vr=oe("\u25C6","*"),qs=oe("\u25A0","x"),Ms=oe("\u25B2","x"),At=oe("\u25C7","o"),Ls=oe("\u250C","T"),A=oe("\u2502","|"),ke=oe("\u2514","\u2014"),wr=oe("\u2510","T"),kr=oe("\u2518","\u2014"),si=oe("\u25CF",">"),Rt=oe("\u25CB"," "),Mi=oe("\u25FB","[\u2022]"),Ot=oe("\u25FC","[+]"),Ht=oe("\u25FB","[ ]"),_r=oe("\u25AA","\u2022"),Li=oe("\u2500","-"),Vs=oe("\u256E","+"),xr=oe("\u251C","+"),Ws=oe("\u256F","+"),Js=oe("\u2570","+"),jr=oe("\u256D","+"),Hs=oe("\u25CF","\u2022"),Bs=oe("\u25C6","*"),Gs=oe("\u25B2","!"),Ks=oe("\u25A0","x"),Xe=e=>{switch(e){case"initial":case"active":return p.default.cyan(vr);case"cancel":return p.default.red(qs);case"error":return p.default.yellow(Ms);case"submit":return p.default.green(At)}},zs=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)}},Ka=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,za=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Ya=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,Ts=/[\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,Ns=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,Xa=new RegExp("\\p{M}+","gu"),Za={limit:1/0,ellipsis:""},Sr=(e,t={},i={})=>{let s=t.limit??1/0,n=t.ellipsis??"",r=t?.ellipsisWidth??(n?Sr(n,Za,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,y=i.regularWidth??1,v=i.wideWidth??2,w=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>w){let N=e.slice(V,ee)||e.slice(w,h);x=0;for(let Z of N.replaceAll(Xa,"")){let z=Z.codePointAt(0)||0;if(za(z)?E=g:Ya(z)?E=v:m!==y&&Ka(z)?E=m:E=y,P+E>M&&(R=Math.min(R,Math.max(V,w)+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*y,P+E>M&&(R=Math.min(R,h+Math.floor((M-P)/y))),P+E>s){O=!0;break}P+=E,V=w,ee=h,h=w=Ni.lastIndex;continue}if(Ts.lastIndex=h,Ts.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=Ts.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=w,ee=h,h=w=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=w,ee=h,h=w=Ti.lastIndex;continue}if(Ns.lastIndex=h,Ns.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=Ns.lastIndex;continue}h+=1}return{width:O?M:P,index:O?R:_,truncated:O,ellipsed:O&&s>=r}},Qa={limit:1/0,ellipsis:"",ellipsisWidth:0},Pe=(e,t={})=>Sr(e,Qa,t).width,Vi="\x1B",Cr="\x9B",el=39,Ys="\x07",Or="[",tl="]",Ir="m",Xs=`${tl}8;;`,mr=new RegExp(`(?:\\${Or}(?<code>\\d+)m|\\${Xs}(?<uri>.*)${Ys})`,"y"),il=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}${Xs}${e}${Ys}`,sl=e=>e.map(t=>Pe(t)),Us=(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,y=Pe(g);a+y<=i?e[e.length-1]+=g:(e.push(g),a=0),(g===Vi||g===Cr)&&(n=!0,r=t.startsWith(Xs,f+1)),n?r?g===Ys&&(n=!1,r=!1):g===Ir&&(n=!1):(a+=y,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())},nl=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("")},rl=(e,t,i={})=>{if(i.trim!==!1&&e.trim()==="")return"";let s="",n,r,o=e.split(" "),a=sl(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 x=t-_,O=1+Math.floor((a[w]-x-1)/t);Math.floor((a[w]-1)/t)<O&&l.push(""),Us(l,h,t);continue}if(_+a[w]>t&&_>0&&a[w]>0){if(i.wordWrap===!1&&_<t){Us(l,h,t);continue}l.push("")}if(_+a[w]>t&&i.wordWrap===!1){Us(l,h,t);continue}l[l.length-1]+=h}i.trim!==!1&&(l=l.map(w=>nl(w)));let m=l.join(`
49
+ `),f=m[Symbol.iterator](),g=f.next(),y=f.next(),v=0;for(;!g.done;){let w=g.value,h=y.value;if(s+=w,w===Vi||w===Cr){mr.lastIndex=v+1;let x=mr.exec(m)?.groups;if(x?.code!==void 0){let O=Number.parseFloat(x.code);n=O===el?void 0:O}else x?.uri!==void 0&&(r=x.uri.length===0?void 0:x.uri)}let _=n?il(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=y,y=f.next()}return s};ol=(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}},Gt=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=Ps(n),f=p.default.dim("..."),g=e.maxItems??Number.POSITIVE_INFINITY,y=Math.max(m-a,0),v=Math.max(Math.min(g,y),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,x=Math.min(w+v,i.length),O=[],R=0;h&&R++,_&&R++;let M=w+(h?1:0),V=x-(_?1:0);for(let P=M;P<V;P++){let E=Bt(s(i[P],P===t),l,{hard:!0,trim:!1}).split(`
52
+ `);O.push(E),R+=E.length}if(R>y){let P=0,E=0,N=R,Z=t-M,z=(F,ie)=>ol(O,N,F,ie,y);h?({lineCount:N,removals:P}=z(0,Z),N>y&&({lineCount:N,removals:E}=z(Z+1,O.length))):({lineCount:N,removals:E}=z(Z+1,O.length),N>y&&({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 ei({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)}`,`${Xe(this.state)} ${e.message}`]:[`${Xe(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(si)} ${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=al(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
- ${m}${u}`}case"cancel":{let l=s?` ${p.default.strikethrough(p.default.dim(s))}`:"",u=t?p.default.gray(A):"";return`${i.join(`
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
- ${u}${l}`}default:{let l=this.state==="error"?p.default.yellow:p.default.cyan,u=t?`${l(A)} `:"",m=t?l(ke):"",g="";if(this.isNavigating||o){let O=o?r:s;g=O!==""?` ${p.default.dim(O)}`:""}else g=` ${this.userInputWithCursor}`;let y=this.filteredOptions.length!==n.length?p.default.dim(` (${this.filteredOptions.length} match${this.filteredOptions.length===1?"":"es"})`):"",w=this.filteredOptions.length===0&&s?[`${u}${p.default.yellow("No matches found")}`]:[],v=this.state==="error"?[`${u}${p.default.yellow(this.error)}`]:[];t&&i.push(`${u.trimEnd()}`),i.push(`${u}${p.default.dim("Search:")}${g}${y}`,...w,...v);let h=[`${p.default.dim("\u2191/\u2193")} to select`,`${p.default.dim("Enter:")} confirm`,`${p.default.dim("Type:")} to search`],_=[`${u}${h.join(" \u2022 ")}`,m],x=this.filteredOptions.length===0?[]:Gt({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=>`${u}${O}`),..._].join(`
57
- `)}}}}).prompt(),sl=e=>{let t=(s,n,r,o)=>{let a=r.includes(s.value),l=s.label??String(s.value??""),u=s.hint&&o!==void 0&&s.value===o?p.default.dim(` (${s.hint})`):"",m=a?p.default.green(Ot):p.default.dim(Ht);return s.disabled?`${p.default.gray(Ht)} ${p.default.strikethrough(p.default.gray(l))}`:n?`${m} ${l}${u}`:`${m} ${p.default.dim(l)}`},i=new ei({options:e.options,multiple:!0,filter:e.filter??((s,n)=>Cr(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)}
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 y=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}${y}`,...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],x=this.filteredOptions.length===0?[]:Gt({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
+ `)}}}}).prompt(),ll=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(Ht);return s.disabled?`${p.default.gray(Ht)} ${p.default.strikethrough(p.default.gray(l))}`:n?`${f} ${l}${m}`:`${f} ${p.default.dim(l)}`},i=new ei({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
  ${Xe(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,u=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 m=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`],y=this.filteredOptions.length===0&&n?[`${m(A)} ${p.default.yellow("No matches found")}`]:[],w=this.state==="error"?[`${m(A)} ${p.default.yellow(this.error)}`]:[],v=[...`${s}${m(A)}`.split(`
60
- `),`${m(A)} ${p.default.dim("Search:")} ${a}${u}`,...y,...w],h=[`${m(A)} ${g.join(" \u2022 ")}`,`${m(ke)}`],_=Gt({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=>`${m(A)} ${x}`),...h].join(`
61
- `)}}}});return i.prompt()},nl=[kr,Ms,Vs,Ls],rl=[qs,br,ke,$r];ol=e=>e,al=(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),u=i?.withGuide??ce.withGuide?`${A} `:"",m=i?.formatBorder??ol,g=(i?.rounded?nl:rl).map(m),y=m(qi),w=m(A),v=Pe(u),h=Pe(t),_=n-v,x=Math.floor(n*l)-v;if(i?.width==="auto"){let T=e.split(`
62
- `),Z=h+o*2;for(let F of T){let ie=Pe(F)+a*2;ie>Z&&(Z=ie)}let Y=Z+r;Y<x&&(x=Y)}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]=fr(Pe(M),O,o,i?.titleAlign),P=Bt(e,O-a*2,{hard:!0,trim:!1});s.write(`${u}${g[0]}${y.repeat(V)}${M}${y.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`],y=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}`,...y,...v],h=[`${f(A)} ${g.join(" \u2022 ")}`,`${f(ke)}`],_=Gt({cursor:this.cursor,options:this.filteredOptions,style:(x,O)=>t(x,O,this.selectedValues,this.focusedValue),maxItems:e.maxItems,output:e.output,rowPadding:w.length+h.length});return[...w,..._.map(x=>`${f(A)} ${x}`),...h].join(`
61
+ `)}}}});return i.prompt()},dl=[jr,Vs,Js,Ws],cl=[Ls,wr,ke,kr];ul=e=>e,ml=(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??ul,g=(i?.rounded?dl:cl).map(f),y=f(Li),v=f(A),w=Pe(m),h=Pe(t),_=n-w,x=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<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=Bt(e,O-a*2,{hard:!0,trim:!1});s.write(`${m}${g[0]}${y.repeat(V)}${M}${y.repeat(ee)}${g[1]}
63
63
  `);let E=P.split(`
64
- `);for(let T of E){let[Z,Y]=fr(Pe(T),O,a,i?.contentAlign);s.write(`${u}${w}${" ".repeat(Z)}${T}${" ".repeat(Y)}${w}
65
- `)}s.write(`${u}${g[2]}${y.repeat(O)}${g[3]}
66
- `)},Ke=e=>{let t=e.active??"Yes",i=e.inactive??"No";return new ji({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)}
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}
65
+ `)}s.write(`${m}${g[2]}${y.repeat(O)}${g[3]}
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
  `:""}${Xe(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
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(si)} ${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(si)} ${i}`}
72
72
  ${a}
73
- `}}}}).prompt()},ll=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},dl=e=>{let{selectableGroups:t=!0,groupSpacing:i=0}=e,s=(r,o,a=[])=>{let l=r.label??String(r.value),u=typeof r.group=="string",m=u&&(a[a.indexOf(r)+1]??{group:!0}),g=u&&m&&m.group===!0,y=u?t?`${g?ke:A} `:" ":"",w="";if(i>0&&!u){let h=`
74
- ${p.default.cyan(A)}`;w=`${h.repeat(i-1)}${h} `}if(o==="active")return`${w}${p.default.dim(y)}${p.default.cyan(Fi)} ${l}${r.hint?` ${p.default.dim(`(${r.hint})`)}`:""}`;if(o==="group-active")return`${w}${y}${p.default.cyan(Fi)} ${p.default.dim(l)}`;if(o==="group-active-selected")return`${w}${y}${p.default.green(Ot)} ${p.default.dim(l)}`;if(o==="selected"){let h=u||t?p.default.green(Ot):"";return`${w}${p.default.dim(y)}${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(y)}${p.default.green(Ot)} ${l}${r.hint?` ${p.default.dim(`(${r.hint})`)}`:""}`;if(o==="submitted")return`${p.default.dim(l)}`;let v=u||t?p.default.dim(Ht):"";return`${w}${p.default.dim(y)}${v} ${p.default.dim(l)}`},n=e.required??!0;return new Si({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()},fl=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},pl=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,y=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(y)}${p.default.cyan(Mi)} ${l}${r.hint?` ${p.default.dim(`(${r.hint})`)}`:""}`;if(o==="group-active")return`${v}${y}${p.default.cyan(Mi)} ${p.default.dim(l)}`;if(o==="group-active-selected")return`${v}${y}${p.default.green(Ot)} ${p.default.dim(l)}`;if(o==="selected"){let h=m||t?p.default.green(Ot):"";return`${v}${p.default.dim(y)}${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(y)}${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(Ht):"";return`${v}${p.default.dim(y)}${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.
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
  ${Xe(this.state)} ${e.message}
77
- `,o=this.value??[];switch(this.state){case"submit":{let a=this.options.filter(({value:u})=>o.includes(u)).map(u=>s(u,"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}
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,u)=>u===0?`${p.default.yellow(ke)} ${p.default.yellow(l)}`:` ${l}`).join(`
80
- `);return`${r}${p.default.yellow(A)} ${this.options.map((l,u,m)=>{let g=o.includes(l.value)||l.group===!0&&this.isGroupSelected(`${l.value}`),y=u===this.cursor;return!y&&typeof l.group=="string"&&this.options[this.cursor].value===l.group?s(l,g?"group-active-selected":"group-active",m):y&&g?s(l,"active-selected",m):g?s(l,"selected",m):s(l,y?"active":"inactive",m)}).join(`
79
+ `).map((l,m)=>m===0?`${p.default.yellow(ke)} ${p.default.yellow(l)}`:` ${l}`).join(`
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}`),y=m===this.cursor;return!y&&typeof l.group=="string"&&this.options[this.cursor].value===l.group?s(l,g?"group-active-selected":"group-active",f):y&&g?s(l,"active-selected",f):g?s(l,"selected",f):s(l,y?"active":"inactive",f)}).join(`
81
81
  ${p.default.yellow(A)} `)}
82
82
  ${a}
83
- `}default:{let a=this.options.map((u,m,g)=>{let y=o.includes(u.value)||u.group===!0&&this.isGroupSelected(`${u.value}`),w=m===this.cursor,v=!w&&typeof u.group=="string"&&this.options[this.cursor].value===u.group,h="";return v?h=s(u,y?"group-active-selected":"group-active",g):w&&y?h=s(u,"active-selected",g):y?h=s(u,"selected",g):h=s(u,w?"active":"inactive",g),`${m!==0&&!h.startsWith(`
83
+ `}default:{let a=this.options.map((m,f,g)=>{let y=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,y?"group-active-selected":"group-active",g):v&&y?h=s(m,"active-selected",g):y?h=s(m,"selected",g):h=s(m,v?"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
87
  ${p.default.cyan(ke)}
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:"",u=a?`${t} `:"",m=a?`${i} `:"";for(let y=0;y<n;y++)o.push(l);let g=Array.isArray(e)?e:e.split(`
89
- `);if(g.length>0){let[y,...w]=g;y.length>0?o.push(`${u}${y}`):o.push(a?t:"");for(let v of w)v.length>0?o.push(`${m}${v}`):o.push(a?i:"")}s.write(`${o.join(`
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 y=0;y<n;y++)o.push(l);let g=Array.isArray(e)?e:e.split(`
89
+ `);if(g.length>0){let[y,...v]=g;y.length>0?o.push(`${m}${y}`):o.push(a?t:"");for(let w of v)w.length>0?o.push(`${f}${w}`):o.push(a?i:"")}s.write(`${o.join(`
90
90
  `)}
91
- `)},info:(e,t)=>{Ve.message(e,{...t,symbol:p.default.blue(Ws)})},success:(e,t)=>{Ve.message(e,{...t,symbol:p.default.green(Js)})},step:(e,t)=>{Ve.message(e,{...t,symbol:p.default.green(At)})},warn:(e,t)=>{Ve.message(e,{...t,symbol:p.default.yellow(Hs)})},warning:(e,t)=>{Ve.warn(e,t)},error:(e,t)=>{Ve.message(e,{...t,symbol:p.default.red(Bs)})}},cl=(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(Hs)})},success:(e,t)=>{Ve.message(e,{...t,symbol:p.default.green(Bs)})},step:(e,t)=>{Ve.message(e,{...t,symbol:p.default.green(At)})},warn:(e,t)=>{Ve.message(e,{...t,symbol:p.default.yellow(Gs)})},warning:(e,t)=>{Ve.warn(e,t)},error:(e,t)=>{Ve.message(e,{...t,symbol:p.default.red(Ks)})}},hl=(e="",t)=>{(t?.output??process.stdout).write(`${p.default.gray(ke)} ${p.default.red(e)}
92
92
 
93
- `)},ul=(e="",t)=>{(t?.output??process.stdout).write(`${p.default.gray(qs)} ${e}
94
- `)},ml=(e="",t)=>{(t?.output??process.stdout).write(`${p.default.gray(A)}
93
+ `)},gl=(e="",t)=>{(t?.output??process.stdout).write(`${p.default.gray(Ls)} ${e}
94
+ `)},yl=(e="",t)=>{(t?.output??process.stdout).write(`${p.default.gray(A)}
95
95
  ${p.default.gray(ke)} ${e}
96
96
 
97
97
  `)},ti=(e,t)=>e.split(`
98
98
  `).map(i=>t(i)).join(`
99
- `),fl=e=>{let t=(s,n)=>{let r=s.label??String(s.value);return n==="disabled"?`${p.default.gray(Ht)} ${ti(r,o=>p.default.strikethrough(p.default.gray(o)))}${s.hint?` ${p.default.dim(`(${s.hint??"disabled"})`)}`:""}`:n==="active"?`${p.default.cyan(Fi)} ${r}${s.hint?` ${p.default.dim(`(${s.hint})`)}`:""}`:n==="selected"?`${p.default.green(Ot)} ${ti(r,p.default.dim)}${s.hint?` ${p.default.dim(`(${s.hint})`)}`:""}`:n==="cancelled"?`${ti(r,o=>p.default.strikethrough(p.default.dim(o)))}`:n==="active-selected"?`${p.default.green(Ot)} ${r}${s.hint?` ${p.default.dim(`(${s.hint})`)}`:""}`:n==="submitted"?`${ti(r,p.default.dim)}`:`${p.default.dim(Ht)} ${ti(r,p.default.dim)}`},i=e.required??!0;return new Ci({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:i,cursorAt:e.cursorAt,validate(s){if(i&&(s===void 0||s.length===0))return`Please select at least one option.
100
- ${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 s=nt(e.output,e.message,`${Gs(this.state)} `,`${Xe(this.state)} `),n=`${p.default.gray(A)}
99
+ `),bl=e=>{let t=(s,n)=>{let r=s.label??String(s.value);return n==="disabled"?`${p.default.gray(Ht)} ${ti(r,o=>p.default.strikethrough(p.default.gray(o)))}${s.hint?` ${p.default.dim(`(${s.hint??"disabled"})`)}`:""}`:n==="active"?`${p.default.cyan(Mi)} ${r}${s.hint?` ${p.default.dim(`(${s.hint})`)}`:""}`:n==="selected"?`${p.default.green(Ot)} ${ti(r,p.default.dim)}${s.hint?` ${p.default.dim(`(${s.hint})`)}`:""}`:n==="cancelled"?`${ti(r,o=>p.default.strikethrough(p.default.dim(o)))}`:n==="active-selected"?`${p.default.green(Ot)} ${r}${s.hint?` ${p.default.dim(`(${s.hint})`)}`:""}`:n==="submitted"?`${ti(r,p.default.dim)}`:`${p.default.dim(Ht)} ${ti(r,p.default.dim)}`},i=e.required??!0;return new Ii({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:i,cursorAt:e.cursorAt,validate(s){if(i&&(s===void 0||s.length===0))return`Please select at least one option.
100
+ ${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 s=nt(e.output,e.message,`${zs(this.state)} `,`${Xe(this.state)} `),n=`${p.default.gray(A)}
101
101
  ${s}
102
- `,r=this.value??[],o=(a,l)=>{if(a.disabled)return t(a,"disabled");let u=r.includes(a.value);return l&&u?t(a,"active-selected"):u?t(a,"selected"):t(a,l?"active":"inactive")};switch(this.state){case"submit":{let a=this.options.filter(({value:u})=>r.includes(u)).map(u=>t(u,"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:u})=>r.includes(u)).map(u=>t(u,"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}
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
104
  `).map((g,y)=>y===0?`${p.default.yellow(ke)} ${p.default.yellow(g)}`:` ${g}`).join(`
105
- `),u=n.split(`
106
- `).length,m=l.split(`
107
- `).length+1;return`${n}${a}${Gt({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:a.length,rowPadding:u+m,style:o}).join(`
105
+ `),m=n.split(`
106
+ `).length,f=l.split(`
107
+ `).length+1;return`${n}${a}${Gt({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:a.length,rowPadding:m+f,style:o}).join(`
108
108
  ${a}`)}
109
109
  ${l}
110
110
  `}default:{let a=`${p.default.cyan(A)} `,l=n.split(`
111
111
  `).length;return`${n}${a}${Gt({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
113
  ${p.default.cyan(ke)}
114
- `}}}}).prompt()},pl=e=>p.default.dim(e),hl=(e,t,i)=>{let s={hard:!0,trim:!1},n=Bt(e,t,s).split(`
115
- `),r=n.reduce((l,u)=>Math.max(Pe(u),l),0),o=n.map(i).reduce((l,u)=>Math.max(Pe(u),l),0),a=t-(o-r);return Bt(e,a,s)},gl=(e="",t="",i)=>{let s=i?.output??Le.default.stdout,n=i?.withGuide??ce.withGuide,r=i?.format??pl,o=["",...hl(e,St(s)-6,r).split(`
116
- `).map(r),""],a=Pe(t),l=Math.max(o.reduce((y,w)=>{let v=Pe(w);return v>y?v:y},0),a)+2,u=o.map(y=>`${p.default.gray(A)} ${y}${" ".repeat(l-Pe(y))}${p.default.gray(A)}`).join(`
117
- `),m=n?`${p.default.gray(A)}
118
- `:"",g=n?vr:Vs;s.write(`${m}${p.default.green(At)} ${p.default.reset(t)} ${p.default.gray(qi.repeat(Math.max(l-a-1,1))+Ms)}
119
- ${u}
120
- ${p.default.gray(g+qi.repeat(l+2)+Ls)}
121
- `)},yl=e=>new lr({validate:e.validate,mask:e.mask??wr,signal:e.signal,input:e.input,output:e.output,render(){let t=e.withGuide??ce.withGuide,i=`${t?`${p.default.gray(A)}
114
+ `}}}}).prompt()},$l=e=>p.default.dim(e),vl=(e,t,i)=>{let s={hard:!0,trim:!1},n=Bt(e,t,s).split(`
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 Bt(e,a,s)},wl=(e="",t="",i)=>{let s=i?.output??Le.default.stdout,n=i?.withGuide??ce.withGuide,r=i?.format??$l,o=["",...vl(e,St(s)-6,r).split(`
116
+ `).map(r),""],a=Pe(t),l=Math.max(o.reduce((y,v)=>{let w=Pe(v);return w>y?w:y},0),a)+2,m=o.map(y=>`${p.default.gray(A)} ${y}${" ".repeat(l-Pe(y))}${p.default.gray(A)}`).join(`
117
+ `),f=n?`${p.default.gray(A)}
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))+Vs)}
119
+ ${m}
120
+ ${p.default.gray(g+Li.repeat(l+2)+Ws)}
121
+ `)},kl=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
  `:""}${Xe(this.state)} ${e.message}
123
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()}
124
124
  ${r}${a}
@@ -126,47 +126,47 @@ ${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
127
  ${p.default.gray(A)}`:""}`}default:{let r=t?`${p.default.cyan(A)} `:"",o=t?p.default.cyan(ke):"";return`${i}${r}${s}
128
128
  ${o}
129
- `}}}}).prompt(),bl=e=>{let t=e.validate;return Or({...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,ii.dirname)(i):s=(0,ii.dirname)(i),(0,It.readdirSync)(s).map(n=>{let r=(0,ii.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[]}}})},$l=p.default.magenta,ni=({indicator:e="dots",onCancel:t,output:i=process.stdout,cancelMessage:s,errorMessage:n,frames:r=Ui?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:o=Ui?80:120,signal:a,...l}={})=>{let u=Ns(),m,g,y=!1,w=!1,v="",h,_=performance.now(),x=St(i),O=l?.styleFrame??$l,R=q=>{let z=q>1?n??ce.messages.error:s??ce.messages.cancel;w=q===1,y&&(ie(z,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;u&&i.write(`
129
+ `}}}}).prompt(),_l=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,ii.dirname)(i):s=(0,ii.dirname)(i),(0,It.readdirSync)(s).map(n=>{let r=(0,ii.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,ni=({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=Fs(),f,g,y=!1,v=!1,w="",h,_=performance.now(),x=St(i),O=l?.styleFrame??xl,R=q=>{let Y=q>1?n??ce.messages.error:s??ce.messages.cancel;v=q===1,y&&(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
130
  `);let q=Bt(h,x,{hard:!0,trim:!1}).split(`
131
- `);q.length>1&&i.write(Jt.cursor.up(q.length-1)),i.write(Jt.cursor.to(0)),i.write(Jt.erase.down())},T=q=>q.replace(/\.+$/,""),Z=q=>{let z=(performance.now()-q)/1e3,Q=Math.floor(z/60),G=Math.floor(z%60);return Q>0?`[${Q}m ${G}s]`:`[${G}s]`},Y=l.withGuide??ce.withGuide,F=(q="")=>{y=!0,m=ar({output:i}),v=T(q),_=performance.now(),Y&&i.write(`${p.default.gray(A)}
132
- `);let z=0,Q=0;ee(),g=setInterval(()=>{if(u&&v===h)return;E(),h=v;let G=O(r[z]),Oe;if(u)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=Bt(Oe,x,{hard:!0,trim:!1});i.write(Be),z=z+1<r.length?z+1:0,Q=Q<4?Q+.125:0},o)},ie=(q="",z=0,Q=!1)=>{if(!y)return;y=!1,clearInterval(g),E();let G=z===0?p.default.green(At):z===1?p.default.red(Us):p.default.red(Fs);v=q??v,Q||(e==="timer"?i.write(`${G} ${v} ${Z(_)}
133
- `):i.write(`${G} ${v}
134
- `)),P(),m()};return{start:F,stop:(q="")=>ie(q,0),message:(q="")=>{v=T(q??v)},cancel:(q="")=>ie(q,1),error:(q="")=>ie(q,2),clear:()=>ie("",0,!0),get isCancelled(){return w}}},pr={light:oe("\u2500","-"),heavy:oe("\u2501","="),block:oe("\u2588","#")};Ti=(e,t)=>e.includes(`
131
+ `);q.length>1&&i.write(Jt.cursor.up(q.length-1)),i.write(Jt.cursor.to(0)),i.write(Jt.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="")=>{y=!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=Bt(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(!y)return;y=!1,clearInterval(g),E();let G=Y===0?p.default.green(At):Y===1?p.default.red(qs):p.default.red(Ms);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}}},yr={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
- `):t(e),Ze=e=>{let t=(i,s)=>{let n=i.label??String(i.value);switch(s){case"disabled":return`${p.default.gray(Rt)} ${Ti(n,p.default.gray)}${i.hint?` ${p.default.dim(`(${i.hint??"disabled"})`)}`:""}`;case"selected":return`${Ti(n,p.default.dim)}`;case"active":return`${p.default.green(si)} ${n}${i.hint?` ${p.default.dim(`(${i.hint})`)}`:""}`;case"cancelled":return`${Ti(n,r=>p.default.strikethrough(p.default.dim(r)))}`;default:return`${p.default.dim(Rt)} ${Ti(n,p.default.dim)}`}};return new Oi({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let i=e.withGuide??ce.withGuide,s=`${Xe(this.state)} `,n=`${Gs(this.state)} `,r=nt(e.output,e.message,n,s),o=`${i?`${p.default.gray(A)}
137
+ `):t(e),Ze=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(si)} ${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=`${Xe(this.state)} `,n=`${zs(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):"",u=o.split(`
141
- `).length,m=i?2:1;return`${o}${a}${Gt({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:a.length,rowPadding:u+m,style:(g,y)=>t(g,g.disabled?"disabled":y?"active":"inactive")}).join(`
140
+ ${p.default.gray(A)}`:""}`}default:{let a=i?`${p.default.cyan(A)} `:"",l=i?p.default.cyan(ke):"",m=o.split(`
141
+ `).length,f=i?2:1;return`${o}${a}${Gt({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:a.length,rowPadding:m+f,style:(g,y)=>t(g,g.disabled?"disabled":y?"active":"inactive")}).join(`
142
142
  ${a}`)}
143
143
  ${l}
144
- `}}}}).prompt()},vl=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 Ii({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)}
144
+ `}}}}).prompt()},Sl=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
  `:""}${Xe(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
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(`
148
148
  `);return`${s}${o}
149
149
  ${r}
150
- `}}}}).prompt()},hr=`${p.default.gray(A)} `,Ct={message:async(e,{symbol:t=p.default.gray(A)}={})=>{process.stdout.write(`${p.default.gray(A)}
150
+ `}}}}).prompt()},br=`${p.default.gray(A)} `,Ct={message:async(e,{symbol:t=p.default.gray(A)}={})=>{process.stdout.write(`${p.default.gray(A)}
151
151
  ${t} `);let i=3;for await(let s of e){s=s.replace(/\n/g,`
152
- ${hr}`),s.includes(`
153
- `)&&(i=3+(0,Ni.stripVTControlCharacters)(s.slice(s.lastIndexOf(`
154
- `))).length);let n=(0,Ni.stripVTControlCharacters)(s).length;i+n<process.stdout.columns?(i+=n,process.stdout.write(s)):(process.stdout.write(`
155
- ${hr}${s.trimStart()}`),i=3+(0,Ni.stripVTControlCharacters)(s.trimStart()).length)}process.stdout.write(`
156
- `)},info:e=>Ct.message(e,{symbol:p.default.blue(Ws)}),success:e=>Ct.message(e,{symbol:p.default.green(Js)}),step:e=>Ct.message(e,{symbol:p.default.green(At)}),warn:e=>Ct.message(e,{symbol:p.default.yellow(Hs)}),warning:e=>Ct.warn(e),error:e=>Ct.message(e,{symbol:p.default.red(Bs)})},kl=async(e,t)=>{for(let i of e){if(i.enabled===!1)continue;let s=ni(t);s.start(i.title);let n=await i.task(s.message);s.stop(n||i.title)}},_l=e=>e.replace(/\x1b\[(?:\d+;)*\d*[ABCDEFGHfJKSTsu]|\x1b\[(s|u)/g,""),xl=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=!Ns()&&gr(t);t.write(`${s}
152
+ ${br}`),s.includes(`
153
+ `)&&(i=3+(0,Fi.stripVTControlCharacters)(s.slice(s.lastIndexOf(`
154
+ `))).length);let n=(0,Fi.stripVTControlCharacters)(s).length;i+n<process.stdout.columns?(i+=n,process.stdout.write(s)):(process.stdout.write(`
155
+ ${br}${s.trimStart()}`),i=3+(0,Fi.stripVTControlCharacters)(s.trimStart()).length)}process.stdout.write(`
156
+ `)},info:e=>Ct.message(e,{symbol:p.default.blue(Hs)}),success:e=>Ct.message(e,{symbol:p.default.green(Bs)}),step:e=>Ct.message(e,{symbol:p.default.green(At)}),warn:e=>Ct.message(e,{symbol:p.default.yellow(Gs)}),warning:e=>Ct.warn(e),error:e=>Ct.message(e,{symbol:p.default.red(Ks)})},Cl=async(e,t)=>{for(let i of e){if(i.enabled===!1)continue;let s=ni(t);s.start(i.title);let n=await i.task(s.message);s.stop(n||i.title)}},Ol=e=>e.replace(/\x1b\[(?:\d+;)*\d*[ABCDEFGHfJKSTsu]|\x1b\[(s|u)/g,""),Il=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=!Fs()&&$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:""}],u=!1,m=_=>{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+=`
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
161
  `).reduce((P,E)=>E===""?P+1:P+Math.ceil((E.length+r)/i),0);x+=ee}x>0&&(x+=1,t.write(Jt.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:x??n})},y=()=>{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(m(!1),(O?.raw!==!0||!u)&&_.value!==""&&(_.value+=`
165
- `),_.value+=_l(x),u=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})},y=()=>{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)}},v=(_,x,O)=>{if(f(!1),(O?.raw!==!0||!m)&&_.value!==""&&(_.value+=`
165
+ `),_.value+=Ol(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&&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)=>{m(!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){m(!0),Ve.error(_,{output:t,secondarySymbol:s,spacing:1}),x?.showLog!==!1&&y(),l.splice(1,l.length-1),l[0].value="",l[0].full=""},success(_,x){m(!0),Ve.success(_,{output:t,secondarySymbol:s,spacing:1}),x?.showLog===!0&&y(),l.splice(1,l.length-1),l[0].value="",l[0].full=""}}},Re=e=>new Ri({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&&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=(_,x)=>{f(!1),_.result=x,a&&w()};return{message(_,x){v(l[0],_,x)},group(_){let x={header:_,value:"",full:""};return l.push(x),{message(O,R){v(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&&y(),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&&y(),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
  `:""}${Xe(this.state)} `}${e.message}
171
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()}
172
172
  ${a}${n}
@@ -174,94 +174,94 @@ ${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
175
  ${a}`:""}`}default:{let o=t?`${p.default.cyan(A)} `:"",a=t?p.default.cyan(ke):"";return`${i}${o}${n}
176
176
  ${a}
177
- `}}}}).prompt()});function jl(e){return!!(e.json||!xe)}function C(e,t=50){console.log(),console.log(` ${H.default.bold(e)}`),console.log(` ${H.default.dim("\u2500".repeat(t))}`)}function c(e,t,i=2){let s=" ".repeat(i);console.log(`${s}${H.default.dim(e.padEnd(16))} ${t}`)}function d(){console.log()}function Ye(e){console.log(` ${H.default.dim(e)}`)}function I(e,t){console.log(` ${H.default.dim(e)} ${H.default.cyan(t)}`)}function Er(e){return e.split(/(https?:\/\/[^\s]+)/g).map(i=>/^https?:\/\//.test(i)?`\x1B]8;;${i}\x1B\\${H.default.underline(H.default.cyan(i))}\x1B]8;;\x1B\\`:H.default.dim(i)).join("")}function Zs(e,t){console.error(` ${$.error} ${H.default.red(e)}`),t&&console.error(` ${Er(t)}`)}function S(e=!0){return e?ni():Sl}function Pr(e){return e.replace(Cl,"")}function Li(e,t){let i=Pr(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((u,m)=>Math.max(u,Pr(m[a]||"").length),0);return Math.max(o.length,l)+2}),n=e.map((o,a)=>H.default.dim(o.padEnd(s[a]))).join(" "),r=s.map(o=>H.default.dim("\u2500".repeat(o))).join(" ");console.log(` ${n}`),console.log(` ${r}`);for(let o of t){let a=o.map((l,u)=>Li(l,s[u])).join(" ");console.log(` ${a}`)}}function Ol(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Xs(e){if(Array.isArray(e))return e.map(Xs);if(e&&typeof e=="object"&&!(e instanceof Date)){let t={};for(let[i,s]of Object.entries(e))t[Ol(i)]=Xs(s);return t}return e}function k(e,t){let i=Xs(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=>Ir(r,s));console.log(JSON.stringify(n,null,2))}else console.log(JSON.stringify(i&&typeof i=="object"?Ir(i,s):i,null,2))}function Ir(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||jl(e))}function B(e,t,i,s){if(i){k({dry_run:!0,action:e,...t},s);return}console.log(),console.log(` ${H.default.yellow("\u25B8 DRY RUN")} ${H.default.dim("- no changes made")}`),console.log(` ${H.default.dim("Action:")} ${H.default.bold(e)}`);for(let[n,r]of Object.entries(t))r!=null&&(Array.isArray(r)?console.log(` ${H.default.dim(n+":")} ${r.map(String).join(", ")}`):console.log(typeof r=="object"?` ${H.default.dim(n+":")} ${JSON.stringify(r)}`:` ${H.default.dim(n+":")} ${String(r)}`));console.log()}function Rl(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 f(e,t){let i=e||`Request failed${t?.status?` (${t.status})`:""}`,s=t?.code||Rl(i,t?.status,t?.fixUrl),n=t?.fixCommand||Il[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 Zs(i,t?.hint),n?console.error(` ${H.default.dim("Or run:")} ${H.default.cyan(n)}`):t?.fixUrl&&console.error(` ${Er(`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,Ar.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 y=" "+e.map((h,_)=>H.default.dim(h.padEnd(i[_]))).join(" "),w=" "+i.map(h=>H.default.dim("\u2500".repeat(h))).join(" "),v=[y,w];for(let h of t){let _=h.status==="done"?h.icon??$.success:H.default.cyan(Rr[r%Rr.length]),x=h.cells.map((O,R)=>Li(O,i[R])).join(" ");v.push(` ${_} ${x}`)}return v}let u=!1,m=()=>process.stdout.write("\x1B[?25h");function g(){let y=l();if(u&&n){process.stdout.write(`\x1B[${a}A`);for(let w of y)process.stdout.write(`\x1B[2K${w}
178
- `)}else{for(let w of y)console.log(w);u=!0}}return{start(){n&&(process.stdout.write("\x1B[?25l"),process.on("exit",m)),g(),n&&(o=setInterval(()=>{r++,g()},80))},markDone(y,w){t[y].status="done",w!==void 0&&(t[y].icon=w),n&&g()},stop(){o&&clearInterval(o);for(let y of t)y.status="done";g(),n&&(process.stdout.write("\x1B[?25h"),process.removeListener("exit",m))}}}var H,Ar,xe,$,b,Sl,Cl,Il,Rr,W=Ee(()=>{"use strict";H=U(L(),1),Ar=require("child_process");De();xe=process.stdout.isTTY??!1;$={success:H.default.green("\u2713"),error:H.default.red("\u2717"),warning:H.default.yellow("!"),info:H.default.cyan("\u25CF"),arrow:H.default.dim("\u2192"),dot:H.default.dim("\xB7"),dash:H.default.dim("\u2500")},b={domain:e=>H.default.bold(H.default.white(e)),price:e=>H.default.green(`$${e}`),label:e=>H.default.dim(e),value:e=>H.default.white(e),dim:e=>H.default.dim(e),bold:e=>H.default.bold(e),success:e=>H.default.green(e),error:e=>H.default.red(e),warn:e=>H.default.yellow(e),cyan:e=>H.default.cyan(e),url:e=>`\x1B]8;;${e}\x1B\\${H.default.underline(H.default.cyan(e))}\x1B]8;;\x1B\\`};Sl={start:()=>{},stop:()=>{},message:()=>{}};Cl=/\x1b\]8;;[^\x1b]*\x1b\\|\x1b\[[0-9;]*m/g;Il={auth_required:"domani login",payment_required:"domani card add",contact_required:"domani contact set"};Rr=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"]});async function Dr(){if(en)return;let e=process.argv.includes("--json")||!$s,t=qe(),i=Me();try{if((await(await fetch(`${t}/api/me`,{headers:{Authorization:`Bearer ${i}`}})).json()).plan==="pro"){en=!0;return}}catch{}e&&(console.log(JSON.stringify({error:"Pro plan required",code:"upgrade_required",hint:"Upgrade at https://domani.run/settings",fix_command:"domani upgrade"},null,2)),process.exit(1)),d(),console.log(` ${be.default.dim("This feature requires")} ${be.default.bold("Pro")} ${be.default.dim("($9/month).")}`),console.log(` ${be.default.dim("Opening billing page")} ${$.arrow} ${be.default.cyan("domani.run/settings")}`),We(`${t.replace("http://localhost:3000","https://domani.run")}/settings`),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{if((await(await fetch(`${t}/api/me`,{headers:{Authorization:`Bearer ${i}`}})).json()).plan==="pro"){en=!0,s.stop(`${$.success} Upgraded to Pro! Continuing...`),d();return}}catch{}}s.stop("Timed out"),console.error(` ${be.default.red("\u2717")} No upgrade detected. Visit ${be.default.cyan("domani.run/settings")} to upgrade.`),process.exit(1)}async function Tr(){if(Qs||Me()){Qs=!0;return}(process.argv.includes("--json")||!$s)&&(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(` ${be.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(` ${be.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(` ${be.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(` ${be.default.red("\u2717")} Invalid response from server.`),process.exit(1)}i.stop(`${$.success} Auth code ready`),d(),console.log(` ${be.default.dim("Verification code:")} ${be.default.bold(be.default.cyan(n))}`),console.log(` ${be.default.dim("Opening browser")} ${$.arrow} ${b.url(r)}`),We(r),d(),i.start("Waiting for browser approval");for(let o=0;o<120;o++){await new Promise(u=>setTimeout(u,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"){Wt({...ct(),token:l.token,email:l.email,api_url:t}),Qs=!0,i.stop(`${$.success} Logged in as ${be.default.bold(l.email)}`),d();return}}i.stop("Timed out"),console.error(` ${be.default.red("\u2717")} No approval received. Run ${be.default.cyan("domani login")} to try again.`),process.exit(1)}var be,Qs,en,tn=Ee(()=>{"use strict";be=U(L(),1);ut();W();Qs=!1,en=!1});function Fr(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/${_e}`,...t.headers}});if(!i){let o=await r.clone().text();try{if(JSON.parse(o).code==="UPGRADE_REQUIRED")return await Dr(),j(e,t,!0)}catch{}}return Fr(r)}async function ye(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 Fr(n)}var X=Ee(()=>{"use strict";ut();tn()});function kt(){return{ok:!0}}function ft(e,t,i){return{ok:!1,error:{message:e,code:t,hint:i}}}function Lr(e){return El.test(e)?ft("Input contains control characters","invalid_input","Remove non-printable characters from the input"):kt()}function Fl(e){return Pl.test(e)?ft("Input contains path traversal","invalid_input","Domain names cannot contain '../' or '..\\'"):kt()}function ql(e){return Dl.test(e)?ft("Input contains query string or fragment","invalid_input","Remove '?' or '#' from the domain name"):kt()}function Ml(e){return Tl.test(e)?ft("Input contains percent-encoded characters","invalid_input","Use plain text, not URL-encoded values (e.g. 'example.com' not 'example%2Ecom')"):kt()}function Vr(e){if(!e)return ft("Domain name is required","validation_error");if(e.length>Mr)return ft(`Domain name too long (${e.length} chars, max ${Mr})`,"validation_error");for(let t of[Lr,Fl,ql,Ml]){let i=t(e);if(!i.ok)return i}return Nl.test(e)?kt():ft(`Invalid domain name: ${e}`,"validation_error","Domain names can only contain letters, digits, hyphens, and dots")}function Ll(e){if(!e)return ft("TLD is required","validation_error");let t=Lr(e);return t.ok?Ul.test(e)?kt():ft(`Invalid TLD: ${e}`,"validation_error","TLDs contain only letters (e.g. 'com', '.dev', 'ai')"):t}function Vl(e){for(let t of e){let i=Vr(t);if(!i.ok)return i}return kt()}function Wl(e){for(let t of e){let i=Ll(t);if(!i.ok)return i}return kt()}function K(e,t){let i=Vr(e);i.ok||f(i.error.message,{code:i.error.code,hint:i.error.hint,json:t?.json,fields:t?.fields})}function Wr(e,t){let i=Vl(e);i.ok||f(i.error.message,{code:i.error.code,hint:i.error.hint,json:t?.json,fields:t?.fields})}function Vi(e,t){let i=Wl(e);i.ok||f(i.error.message,{code:i.error.code,hint:i.error.hint,json:t?.json,fields:t?.fields})}var El,Pl,Dl,Tl,Nl,Ul,Mr,pe=Ee(()=>{"use strict";W();El=/[\x00-\x08\x0b\x0c\x0e-\x1f]/,Pl=/\.\.[/\\]/,Dl=/[?#]/,Tl=/%[0-9a-fA-F]{2}/,Nl=/^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?)*\.?$/,Ul=/^\.?[a-zA-Z]{2,63}$/,Mr=253});async function fe(){xe||f("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"),Zs(i.error,i.hint),process.exit(1));let s=i.domains||[];s.length===0&&(e.stop("No domains"),d(),console.log(` ${nn.default.dim("No domains yet.")} Use: ${nn.default.cyan("domani buy <domain>")}`),d(),process.exit(0)),e.stop(`${s.length} domain(s)`);let n=await Ze({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 nn,ze=Ee(()=>{"use strict";X();De();nn=U(L(),1);W()});var Hr={};Ft(Hr,{connect:()=>rn});async function rn(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 ${b.domain(e)}`);let r=await j(`/api/domains/${encodeURIComponent(e)}/connect`),o=await r.json();if(r.ok||(n.stop("Failed"),f(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&&f("No providers available",{code:"not_found",json:i.json,fields:i.fields});let l=await Ze({message:"Choose a provider",options:a});le(l)&&process.exit(0);let[u,m]=l.split(":"),y=(o.providers?.[u]||[]).find(h=>h.name===m),w;if(y&&y.methods.length>1){let h=await Ze({message:"Choose a method",options:y.methods.map(_=>({value:_.name,label:_.name,hint:_.default?"default":void 0}))});le(h)&&process.exit(0),w=h}let v;if(u==="hosting"&&y?.requires_target){y.notes?.setup&&Ye(y.notes.setup);let h=await Re({message:"Target hostname or IP"});le(h)&&process.exit(0),v=h.trim()}return Jr(e,{target:v,provider:m,method:w,dryRun:i.dryRun,json:!1})}if(i.list){let n=S(!i.json);n.start(`Loading providers for ${b.domain(e)}`);let r=await j(`/api/domains/${encodeURIComponent(e)}/connect`),o=await r.json();if(r.ok||(n.stop("Failed"),f(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 ${b.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 u of l){let m=u.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(u.name.padEnd(20))} ${m}`)}}}d();return}return Jr(e,i)}async function Jr(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 ${b.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"),f(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?`${$.success} DNS instructions for ${ue.default.cyan(r.provider)}`:`${$.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 ${b.domain(r.domain)}`:`Connected ${b.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((m,g)=>ue.default.dim(m.padEnd(a[g]))).join(" "),u=a.map(m=>ue.default.dim("\u2500".repeat(m))).join(" ");console.log(` ${l}`),console.log(` ${u}`);for(let m of r.records){let g=m.record,y=m.status!=="already_set";process.stdout.isTTY&&y&&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)=>Li(x,a[O])).join(" "),h=m.status==="already_set"?ue.default.dim("\u2713"):m.status==="updated"?ue.default.yellow("\u21BA"):m.status==="pending"?ue.default.yellow("\u2192"):$.success,_=m.status==="already_set"?ue.default.dim(" already set"):m.status==="updated"?ue.default.dim(" updated"):m.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:")} ${b.url(r.docs)}`),d()}var ue,on=Ee(()=>{"use strict";X();ue=U(L(),1);De();W();pe();ze()});var Zr={};Ft(Zr,{email:()=>oi,parseRecipients:()=>Wi,recipientField:()=>Ji});function Bl(e){return[N.default.yellow(e.type),e.name,N.default.cyan(e.value)+(e.priority?N.default.dim(` pri=${e.priority}`):"")]}function an(e){return Hl[e]||e}function Wi(e){return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function Ji(e){if(e.length!==0)return e.length===1?e[0]:e}function Gl(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 Qe(e){return e.domain?(K(e.domain,e),e.domain):fe()}async function oi(e,t,i){if(e&&e.includes(".")&&!Jl.includes(e))return i.check?Gr(e,!!i.json,i.fields):t?Kr(e,t,!!i.json,i.fields):zr(e,!!i.json,i.fields);if(Gl(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 Br(i);case"list":return Br(i);case"inbox":return dd(i);case"folders":return cd(i);case"archive":case"trash":case"restore":case"read":case"unread":case"star":case"unstar":return ud(e,i);case"setup":return sd(i);case"status":return nd(i);case"remove":return rd(i);case"create":return od(i);case"delete":return ad(i);case"send":return ld(i);case"webhook":return md(i);case"forward":return fd(i);case"work":return Zl(i);case"triage":return Ql(i);case"note":return ed(i);case"notes":return td(i);case"activity":return id(i);case"changes":return Xl(i);case"coordination":return Kl(i);case"presence":return Yl(i);case"release-presence":return zl(i);case"check":return Gr(i.domain||await fe(),!!i.json,i.fields);case"connect":return Kr(i.domain||await fe(),t||void 0,!!i.json,i.fields);default:f(`Unknown action: ${e}`,{hint:"Actions: list, inbox, folders, archive, trash, restore, read, unread, star, unstar, create, delete, send, forward, webhook, work, triage, notes, note, activity, changes, coordination, presence, release-presence, setup, status, check, connect",code:"validation_error",json:i.json,fields:i.fields})}}function ln(e){let t=e.mailboxIds?.split(",").map(i=>i.trim()).filter(Boolean)[0];return(!t||!e.threadKey)&&f("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 Kl(e){let{mailboxId:t,threadKey:i}=ln(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||f(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 Yl(e){let{mailboxId:t,threadKey:i}=ln(e);e.clientId||f("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)||f("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||f(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 zl(e){let{mailboxId:t,threadKey:i}=ln(e);e.clientId||f("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||f(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 Xl(e){let t=e.mailboxIds?.split(",").map(r=>r.trim()).filter(Boolean)[0];t||f("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||f(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),Ye("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(` ${N.default.dim("No changes since this cursor.")}`),c("Next cursor",n.next_cursor),n.has_more&&Ye("More changes are available; call again with the next cursor.")}async function Zl(e){let t=(e.mailboxIds||"").split(",").map(r=>r.trim()).filter(Boolean);t.length||f("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||f(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(` ${N.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&&Ye("This is a bounded snapshot. Increase --limit or use the API scan_limit when you need a wider queue.")}async function Ql(e){(!e.mailboxIds||!e.threadKey)&&f("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||f(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 ed(e){(!e.conversationId||!e.note)&&f("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||f(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(`${$.success} Private note added`)}async function td(e){e.conversationId||f("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||f(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(` ${N.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 id(e){e.conversationId||f("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||f(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(` ${N.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 sd(e){let t=await Qe(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 ${b.domain(t)}`);let s=await j(`/api/domains/${encodeURIComponent(t)}/email/setup`,{method:"POST"}),n=await s.json();if(s.ok||(i.stop("Failed"),f(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields})),i.stop(`${$.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 ${b.domain(t)}`);let r=n.records.map(o=>[N.default.yellow(o.type),o.name,o.value.length>40?o.value.slice(0,40)+"...":o.value,o.status==="verified"||o.status==="created"?N.default.green(o.status):N.default.yellow(o.status)]);se(["Type","Name","Value","Status"],r,[8,28,44,12])}d(),n.hint&&Ye(n.hint),I("Check status:",`domani email status --domain ${t}`),d()}async function nd(e){let t=await Qe(e),i=S(!e.json);i.start(`Checking email status for ${b.domain(t)}`);let s=await j(`/api/domains/${encodeURIComponent(t)}/email/status`),n=await s.json();if(s.ok||(i.stop("Failed"),f(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields})),i.stop(`${$.success} Status loaded`),e.json){k(n,e.fields);return}if(C(`Email ${b.domain(t)}`),c("Enabled",n.enabled?N.default.green("yes"):N.default.dim("no")),n.enabled&&(c("Verified",n.verified?N.default.green("yes"):N.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(` ${N.default.yellow("!")} Add these DNS records to verify:`);for(let r of n.records)console.log(` ${N.default.yellow(r.type)} ${r.name} ${N.default.dim("\u2192")} ${r.value.length>50?r.value.slice(0,50)+"...":r.value}`);d()}}async function rd(e){let t=await Qe(e);if(e.dryRun)return B("email_remove",{domain:t},e.json,e.fields);let i=S(!e.json);i.start(`Removing email from ${b.domain(t)}`);let s=await j(`/api/domains/${encodeURIComponent(t)}/email/setup`,{method:"DELETE"}),n=await s.json();if(s.ok||(i.stop("Failed"),f(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields})),i.stop(`${$.success} Email disabled`),e.json){k(n,e.fields);return}n.mailboxes_deleted>0&&console.log(` ${N.default.dim(`${n.mailboxes_deleted} mailbox(es) deleted.`)}`),d()}async function Br(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"),f(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields}));let r=n.mailboxes||[];if(t.stop(`${$.success} ${r.length} mailbox(es)`),e.json){k(n,e.fields);return}if(r.length===0){d(),console.log(` ${N.default.dim("No mailboxes.")}`),d(),I("Create one:","domani email create hello@example.com"),d();return}d(),C("Mailboxes");let o=r.map(a=>[N.default.cyan(a.address),String(a.message_count),a.webhook_url?b.url(a.webhook_url):N.default.dim("-"),N.default.dim(new Date(a.created_at).toLocaleDateString())]);se(["Address","Messages","Webhook","Created"],o,[32,10,36,14]),d()}async function od(e){let t=await Qe(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 u=await Re({message:`Email handle for @${t}:`,placeholder:"hello"});le(u)&&process.exit(0),i=u}i||f("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 u=o.txt_record,m=o.email_records||[],g=[{type:"TXT",name:u?.name||"@",value:u?.value||"",note:"ownership proof"},...m];d(),console.log(" Add these records at your DNS provider:"),d();for(let x of g){let O=x.priority!==void 0?` ${N.default.dim(`priority: ${x.priority}`)}`:"",R=x.note?` ${N.default.dim(`(${x.note})`)}`:"";console.log(` ${N.default.yellow(x.type)} ${N.default.bold(x.name)}${O}${R}`),console.log(` ${N.default.dim("\u2192")} ${N.default.cyan(x.value)}`),d()}Ye("DNS propagation typically takes 5\u201330 minutes. Checking automatically..."),d();let y=g.map(x=>({cells:[N.default.yellow(x.type),x.name,x.note?N.default.dim(`(${x.note})`):""],status:"pending"})),w=Dt(["Type","Name",""],y,[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(),f(o.error||o.message,{hint:o.hint,status:r.status,json:e.json,fields:e.fields}));r.status===202&&(w.stop(),f("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"),f(o.error||o.message,{hint:o.hint,status:r.status,json:e.json,fields:e.fields})),n.stop(`${$.success} ${N.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:",`${Xt}/inbox?address=${encodeURIComponent(o.address)}`)):(I("Check propagation:",`domani email status --domain ${t}`),I("Web inbox:",`${Xt}/inbox?address=${encodeURIComponent(o.address)}`)),d()}async function ad(e){let t=await Qe(e);if(e.slug||f("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"),f(r.error||r.message,{hint:r.hint,status:n.status,json:e.json,fields:e.fields})),i.stop(`${$.success} Mailbox deleted`),e.json){k(r,e.fields);return}console.log(` ${N.default.dim(`${r.address} and all messages deleted.`)}`),d()}async function ld(e){let t=await Qe(e);if(e.slug||f("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||f("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:Ji(Wi(e.to))},n=Ji(Wi(e.cc)),r=Ji(Wi(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 m=l.code==="MONTHLY_LIMIT_EXCEEDED"?`Run ${N.default.cyan("domani upgrade")} to switch to Pro (10,000 emails/month).`:l.hint;f(l.error||l.message,{hint:m,status:a.status,json:e.json,fields:e.fields})}let u=Array.isArray(l.to)?l.to.join(", "):l.to;if(i.stop(`${$.success} Sent to ${N.default.cyan(u)}`),e.json){k(l,e.fields);return}}async function dd(e){let t=await Qe(e);e.slug||f("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"),f(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(`${$.success} ${l.length} message(s)`),k(a,e.fields);return}if(l.length===0){n.stop(`${N.default.dim("No messages")}`);return}let u=l.length>1?"s":"";n.stop(`${$.success} ${N.default.cyan(`${e.slug}@${t}`)} ${N.default.dim("\xB7 "+l.length+" message"+u)}`);for(let m of l){let g=m.direction==="in"?N.default.green("in "):N.default.dim("out"),y=m.direction==="in"?m.from:m.to,w=m.subject||"(no subject)",v=N.default.dim(new Date(m.created_at).toLocaleString()),h=w;if(m.text){let _=m.text.replace(/\s+/g," ").trim(),x=_.length>60?_.slice(0,60)+"\u2026":_;h=`${w} ${N.default.dim("- "+x)}`}console.log(` ${g} ${y.padEnd(30)} ${h} ${v}`)}a.next_cursor&&console.log(` ${N.default.dim("\u2026 more available, use --limit to paginate")}`)}async function cd(e){let t=await Qe(e);e.slug||f("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||f(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 ud(e,t){let i=await Qe(t);t.slug||f("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(m=>m.trim()).filter(Boolean);s.length||f("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,Yr.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&&f(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(m=>m.ok).length,u=(a.results||[]).length-l;console.log(`${$.success} ${l} updated${u?N.default.yellow(`, ${u} 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 md(e){let t=await Qe(e);e.slug||f("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);if(e.dryRun)return B("email_webhook",{address:i,webhook_url:e.url||null},e.json,e.fields);let n=S(!e.json);if(e.url){n.start(`Setting webhook for ${i}`);let r=await j(`/api/emails/${s}/webhook`,{method:"PUT",body:JSON.stringify({url:e.url})}),o=await r.json();if(r.ok||(n.stop("Failed"),f(o.error||o.message,{hint:o.hint,status:r.status,json:e.json,fields:e.fields})),n.stop(`${$.success} Webhook set`),e.json){k(o,e.fields);return}C(`Mailbox ${o.address}`),c("Webhook",b.url(o.webhook_url)),c("Signing secret",N.default.dim(o.signing_secret)),d()}else{n.start(`Removing webhook for ${i}`);let r=await j(`/api/emails/${s}/webhook`,{method:"DELETE"}),o=await r.json();if(r.ok||(n.stop("Failed"),f(o.error||o.message,{hint:o.hint,status:r.status,json:e.json,fields:e.fields})),n.stop(`${$.success} Webhook removed`),e.json){k(o,e.fields);return}C(`Mailbox ${o.address}`),c("Webhook",N.default.dim("none")),d()}}async function fd(e){let t=await Qe(e);if(e.slug||f("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"),f(o.error||o.message,{hint:o.hint,status:r.status,json:e.json,fields:e.fields})),i.stop(`${$.success} Forward ${s?"set":"removed"}`),e.json){k(o,e.fields);return}C(`Mailbox ${o.address}`),c("Forward to",o.forward_to?N.default.cyan(o.forward_to):N.default.dim("none")),d()}async function Gr(e,t,i){let s=S(!t);s.start(`Checking email health for ${b.domain(e)}`);let n=await j(`/api/domains/${encodeURIComponent(e)}/email/check`),r=await n.json();if(n.ok||(s.stop("Failed"),f(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 ${b.domain(r.domain)}`),r.provider?c("Provider",N.default.cyan(an(r.provider))):c("Provider",N.default.dim("unknown")),r.mx.configured?c("MX",`${$.success} ${N.default.green("propagated")} ${N.default.dim(`(${r.mx.records.length} record${r.mx.records.length!==1?"s":""})`)}`):c("MX",`${$.error} ${N.default.red("not configured")}`),r.spf.configured?c("SPF",`${$.success} ${N.default.green(r.spf.value)}`):c("SPF",`${$.error} ${N.default.red("missing")}`),r.dmarc.configured){let o=r.dmarc.value.length>50?r.dmarc.value.slice(0,50)+"...":r.dmarc.value;c("DMARC",`${$.success} ${N.default.green(o)}`)}else c("DMARC",`${$.error} ${N.default.red("missing")}`);r.dkim.configured?c("DKIM",`${$.success} ${N.default.green("found")} ${N.default.dim(`(${r.dkim.selectors.join(", ")})`)}`):c("DKIM",`${$.warning} ${N.default.yellow("not found")}`),d(),r.mx.configured?(!r.spf.configured||!r.dmarc.configured)&&(Ye("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 Kr(e,t,i,s){return t?Xr(e,t,i,s):zr(e,i,s)}async function zr(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"),f(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&&f("No email providers available",{code:"not_found",json:t,fields:i});let a=await Ze({message:"Choose an email provider",options:o.map(l=>({value:l.name,label:an(l.name)}))});return le(a)&&process.exit(0),Xr(e,a,t,i)}async function Xr(e,t,i,s){if(i){let u=await j(`/api/domains/${encodeURIComponent(e)}/connect`,{method:"POST",body:JSON.stringify({target:t})}),m=await u.json();u.ok||f(m.error||m.message,{hint:m.hint,status:u.status,json:i,fields:s}),k(m,s);return}let n=await j(`/api/domains/${encodeURIComponent(e)}/connect?provider=${encodeURIComponent(t)}`);if(!n.ok){let u=await n.json();f(u.error||u.message,{hint:u.hint,status:n.status,json:i,fields:s})}let r=await n.json(),o=r.preview?.records??[],a=r.preview?.provider??t,l=an(a);if(C(`Email ${b.domain(e)}`),c("Provider",N.default.cyan(l)),o.length){d(),console.log(` ${N.default.bold("DNS Records")}`);let u=[8,24,40],m=Dt(["Type","Name","Value"],o.map(x=>({cells:Bl(x),status:"pending"})),u);m.start();let g=await j(`/api/domains/${encodeURIComponent(e)}/connect`,{method:"POST",body:JSON.stringify({target:t})}),y=await g.json();g.ok||(m.stop(),d(),f(y.error||y.message,{hint:y.hint,status:g.status,json:i,fields:s}));let w=y.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),m.markDone(x);await Pt(80),m.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(` ${$.success} ${N.default.green(`Email configured - ${_}`)}`)}else{let u=S(!0);u.start("Setting DNS records");let m=await j(`/api/domains/${encodeURIComponent(e)}/connect`,{method:"POST",body:JSON.stringify({target:t})}),g=await m.json();m.ok||(u.stop("Failed"),f(g.error||g.message,{hint:g.hint,status:m.status,json:i,fields:s})),u.stop(`${$.success} Email configured via ${N.default.cyan(l)}`)}d(),I("Verify propagation:",`domani email ${e} --check`),d()}var N,Yr,Jl,Hl,dn=Ee(()=>{"use strict";X();Zt();N=U(L(),1);De();W();pe();ze();Yr=require("node:crypto"),Jl=["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"],Hl={"google-workspace":"Google Workspace",fastmail:"Fastmail",proton:"Proton Mail"}});var Qr={};Ft(Qr,{dns:()=>un});async function un(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,u=r?.value||n;if(!t||t==="get"){let m=S(!o);m.start(`Loading DNS for ${b.domain(e)}`);let g=await j(`/api/domains/${encodeURIComponent(e)}/dns`),y=await g.json();if(g.ok||(m.stop("Failed"),f(y.error||y.message,{hint:y.hint,status:g.status,json:o,fields:r?.fields})),m.stop(`${y.records.length} record(s)`),o){k(y,r?.fields);return}if(y.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 ${b.domain(e)}`,w.reduce((h,_)=>h+_,0)+w.length-1);let v=y.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||!u)&&f("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:u,ttl:3600}},o,r?.fields);let m=S(!o);m.start(`Setting ${je.default.yellow(a.toUpperCase())} record`);let g=await j(`/api/domains/${encodeURIComponent(e)}/dns`),y=await g.json(),v=(g.ok?y.records:[]).filter(x=>!(x.type===a.toUpperCase()&&x.name===l));v.push({type:a.toUpperCase(),name:l,value:u,ttl:3600});let h=await j(`/api/domains/${encodeURIComponent(e)}/dns`,{method:"PUT",body:JSON.stringify({records:v})}),_=await h.json();h.ok||(m.stop("Failed"),f(_.error||_.message,{hint:_.hint,status:h.status,json:o,fields:r?.fields})),m.stop(`${$.success} ${je.default.yellow(a.toUpperCase())} ${l} ${$.arrow} ${je.default.cyan(u)}`),o?k(_,r?.fields):(d(),I("Check propagation:",`domani status ${e}`),d());return}if(t==="delete"){if((!a||!l)&&f("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 m=S(!o);m.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"}),y=await g.json();g.ok||(m.stop("Failed"),f(y.error||y.message,{hint:y.hint,status:g.status,json:o,fields:r?.fields})),m.stop(`${$.success} Deleted ${je.default.yellow(a.toUpperCase())} ${l}`),o?k(y,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 m=S(!o);m.start(`Capturing DNS snapshot for ${b.domain(e)}`);let g=await j(`/api/domains/${encodeURIComponent(e)}/dns/snapshot`,{method:"POST"}),y=await g.json();g.ok||(m.stop("Failed"),f(y.error||y.message,{hint:y.hint,status:g.status,json:o,fields:r?.fields}));let w=y.records?.length??0;if(m.stop(`${$.success} Captured ${w} record(s)`),o){k(y,r?.fields);return}let v=`${e}.dns.json`,h=(0,cn.resolve)(process.cwd(),v);(0,Hi.writeFileSync)(h,JSON.stringify(y,null,2)+`
179
- `),C("DNS Snapshot"),c("Domain",b.domain(y.domain)),c("Records",String(w)),c("Subdomains",String(y.subdomains?.length??0)),c("Sources",(y.sources||[]).join(", ")||"none"),c("Captured",y.capturedAt||y.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 m=S(!o),g;if(r?.file){let v=(0,cn.resolve)(process.cwd(),r.file);v.startsWith(process.cwd())||f("File path must be within the current directory",{hint:`Got: ${r.file}`,code:"validation_error",json:o,fields:r?.fields});try{let h=(0,Hi.readFileSync)(v,"utf-8"),_=JSON.parse(h);g=JSON.stringify({snapshot:_}),m.start(`Restoring DNS for ${b.domain(e)} from ${je.default.cyan(r.file)}`)}catch(h){f(`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 m.start(`Restoring DNS for ${b.domain(e)} from server backup`);let y=await j(`/api/domains/${encodeURIComponent(e)}/dns/restore`,{method:"POST",...g?{body:g}:{}}),w=await y.json();if(y.ok||(m.stop("Failed"),f(w.error||w.message,{hint:w.hint,status:y.status,json:o,fields:r?.fields})),m.stop(`${$.success} Restored DNS`),o){k(w,r?.fields);return}if(C("DNS Restored"),c("Domain",b.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}f(`Unknown action: ${t}`,{hint:"Use 'get', 'set', 'delete', 'snapshot', or 'restore'.",code:"validation_error",json:o,fields:r?.fields})}var je,Hi,cn,mn=Ee(()=>{"use strict";X();je=U(L(),1);W();pe();ze();Hi=require("node:fs"),cn=require("node:path")});var eo={};Ft(eo,{status:()=>fn});function pd(e){return[et.default.yellow(e.type),e.name,et.default.cyan(e.value)+(e.priority?et.default.dim(` pri=${e.priority}`):"")]}function hd(e){if(C(`Status ${b.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 fn(e,t){if(e||(e=await fe()),K(e,t),t.json){let g=await j(`/api/domains/${encodeURIComponent(e)}/status`),y=await g.json();g.ok||f(y.error||y.message,{hint:y.hint,status:g.status,json:t.json,fields:t.fields}),k(y,t.fields);return}let i=S(!0);i.start(`Checking ${b.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"),f("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();f(g.error||g.message,{hint:g.hint,status:s.status,json:t.json,fields:t.fields})}catch{f(`Server error (${s.status})`,{status:s.status,json:t.json,fields:t.fields})}}let n=s.body;n||(i.stop("Failed"),f("Empty response"));let r=new TextDecoder,o="",a=null,l=[],u=!1,m="";try{for await(let g of n){o+=r.decode(g,{stream:!0});let y=o.split(`
180
- `);o=y.pop()??"";for(let w of y)if(w.startsWith("event: "))m=w.slice(7);else if(w.startsWith("data: ")){let v=JSON.parse(w.slice(6));if(m==="info"&&(i.stop("Status retrieved"),u=!0,hd(v)),m==="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:pd(_),status:"pending"})),h),a.start()}else d(),c("DNS",et.default.dim("no records")),I("Auto-configure DNS:",`domani connect ${e}`);if(m==="propagation"&&a){let{index:h,propagated:_}=v,x=_?$.success:`${$.warning}`;a.markDone(h,x)}m==="done"&&a&&a.stop(),m==="error"&&(u||i.stop("Failed"),a&&a.stop(),f(v.message||"Status check failed"))}}}catch{u||i.stop("Failed"),a&&a.stop(),f("Connection lost",{hint:"The status check was interrupted. Try again.",code:"connection_lost",json:t.json,fields:t.fields})}u||i.stop("Done"),d()}var et,pn=Ee(()=>{"use strict";X();et=U(L(),1);W();pe();ze()});var ai={};Ft(ai,{buy:()=>gn});async function hn(e){let t=await Ze({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(()=>(on(),Hr));await i(e,void 0,{})}else if(t==="email"){let i=await Re({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(()=>(dn(),Zr));await s("create",void 0,{domain:e,slug:i})}else if(t==="dns"){let{dns:i}=await Promise.resolve().then(()=>(mn(),Qr));await i(e)}else if(t==="status"){let{status:i}=await Promise.resolve().then(()=>(pn(),eo));await i(e,{})}}async function gd(e,t){K(e,t);let i;if(t.preChecked)i={available:!0,...t.preChecked};else{let m=S(!t.json);m.start(`Checking ${b.domain(e)}`);let g=await j(`/api/domains/search?q=${encodeURIComponent(e)}`);i=await g.json(),g.ok||(m.stop("Search failed"),f(i.error,{hint:i.hint,status:g.status,json:t.json,fields:t.fields})),i.available||(m.stop(`${$.error} ${b.domain(e)} is not available`),f(`${e} is not available`,{code:"not_available",json:t.json,fields:t.fields})),m.stop(`${$.success} ${b.domain(e)} ${$.dot} available ${$.dot} ${b.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 m=await Ke({message:`Purchase ${Te.default.bold(e)} for ${b.price(i.price)}/yr?`});if(!m||typeof m=="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 m=await n.json().catch(()=>({}));f(m.error||m.message,{hint:m.hint,fixUrl:m.setup_url||m.payment_options?.card?.setup_url,status:n.status,json:t.json,fields:t.fields})}let r={},o=new TextDecoder,a="",l="";for await(let m of n.body){a+=o.decode(m,{stream:!0});let g=a.split(`
181
- `);a=g.pop()??"";for(let y of g)if(y.startsWith("event: "))l=y.slice(7).trim();else if(y.startsWith("data: ")){let w=JSON.parse(y.slice(6));l==="checking"?s.message(`Checking ${b.domain(w.domain)}`):l==="payment"?s.message(`Charging ${b.price(w.total)}`):l==="registering"?s.message(`Registering ${b.domain(w.domain)}`):l==="registered"?r=w:l==="error"&&(s.stop("Purchase failed"),f(w.error,{hint:w.hint,fixUrl:w.setup_url,status:n.status,json:t.json,fields:t.fields}))}}let u=r.expires?Te.default.dim(` \xB7 expires ${new Date(r.expires).toLocaleDateString()}`):"";if(s.stop(`${$.success} ${b.domain(r.domain)} is yours!${u}`),t.json){k(r,t.fields);return}xe?await hn(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 yd(e,t){Wr(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(`${$.error} None of the ${e.length} domains are available`),process.exit(1));let a=r.reduce((h,_)=>h+(_.price||0),0);if(s.stop(`${$.success} ${r.length}/${e.length} available ${$.dot} ${b.price(a.toFixed(2))} total`),o.length>0)for(let h of o)console.log(` ${$.error} ${b.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 ${b.price(a.toFixed(2))}?`});if(!h||typeof h=="symbol"){console.log(` ${Te.default.dim("Cancelled.")}`);return}}d();let l=r.map(h=>({cells:[b.domain(h.domain),h.price?`${b.price(h.price.toFixed(2))}/yr`:""],status:"pending"})),u=Dt(["Domain","Price"],l,[30,12],!i);u.start();let g=await(await j("/api/domains/buy",{method:"POST",body:JSON.stringify({domains:r.map(h=>h.domain)})})).json(),y=new Set((g.results||[]).map(h=>h.domain));for(let h=0;h<r.length;h++){let _=r[h].domain.toLowerCase().trim();y.has(_)?u.markDone(h,$.success):u.markDone(h,$.error)}if(u.stop(),i){k(g,t.fields);return}d();let w=g.summary?.succeeded??0,v=g.summary?.failed??0;if(w>0&&console.log(` ${$.success} ${Te.default.green(`${w} domain${w>1?"s":""} registered`)}`),v>0){console.log(` ${$.error} ${Te.default.red(`${v} failed`)}`);for(let h of g.errors||[])console.log(` ${Te.default.dim("\u2500")} ${b.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 hn(h[0]);else{let _=await Ze({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 hn(_)):d()}}else w>0&&(I("Connect to a service:","domani connect <domain>"),I("Set up email:","domani email setup <domain>"),d())}async function gn(e,t){let i=e.filter(Boolean);if(i.length===0){xe||f("Missing required argument: domain(s)",{hint:"Usage: domani buy <domain> [domain2 ...]",code:"missing_argument",json:t.json});let s=await Re({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?gd(i[0],t):yd(i,t)}var Te,Kt=Ee(()=>{"use strict";X();De();Te=U(L(),1);W();pe()});var Tn=U(Dn(),1),{program:uc,createCommand:mc,createArgument:fc,createOption:pc,CommanderError:hc,InvalidArgumentError:gc,InvalidOptionArgumentError:yc,Command:Nn,Argument:bc,Option:$c,Help:wc}=Tn.default;var ot=U(L(),1);ut();tn();W();Zt();ut();var vt=U(L(),1);W();function Al(e){let t=e.scopes?.split(",").map(n=>n.trim()).filter(Boolean),i=!!(t?.length||e.label||e.expiresIn),s=e.expiresIn===void 0?void 0:Number(e.expiresIn);if(s!==void 0&&(!Number.isInteger(s)||s<3600||s>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}:{},...s!==void 0?{expires_in:s}:{}}}}async function Nr(e){let t=qe(),i=S(!e.json),s;try{s=Al(e)}catch(w){f(w instanceof Error?w.message:"Invalid login options",{code:"invalid_expires_in",json:e.json})}let{body:n,delegated:r}=s,o=ct(),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 ${vt.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();f(w.error||w.message||`Server error (${l.status})`,{hint:w.hint,code:"login_failed",json:e.json})}catch{f(`Could not reach ${t}. Check your connection and try again.`,{code:"network_error",json:e.json})}}let{code:u,auth_url:m,expires_in:g}=await l.json();if(i.stop("Auth code received"),e.json){k({status:"awaiting_approval",code:u,auth_url:m,expires_in:g});return}d(),console.log(` ${vt.default.dim("Verification code:")} ${vt.default.bold(vt.default.cyan(u))}`),e.open!==!1?(console.log(` ${vt.default.dim("Opening browser")} ${$.arrow} ${b.url(m)}`),We(m)):console.log(` ${vt.default.dim("Open this URL to approve:")} ${b.url(m)}`),d(),i.start("Waiting for approval");let y=120;for(let w=0;w<y;w++){await new Promise(_=>setTimeout(_,5e3));let v=await fetch(`${t}/api/auth/cli/poll?code=${u}`);!v.ok&&v.status!==202&&(i.stop("Login failed"),f(`Server error (${v.status})`,{code:"login_failed"}));let h=await v.json();if(h.status==="complete"){Wt({...ct(),token:h.token,email:h.email,api_url:t}),i.stop(`Logged in as ${vt.default.bold(h.email)}`),d(),I("Get started:","domani search"),d();return}h.error&&(i.stop("Login failed"),f(h.error||h.message,{hint:h.hint,code:"login_failed"}))}i.stop("Login timed out"),f("No approval received within 10 minutes",{hint:"Run 'domani login' to try again",code:"timeout"})}ut();var sn=U(L(),1);W();async function Ur(e){let t=ct();if(!t.token){e.json?k({status:"not_logged_in"}):console.log(` ${sn.default.dim("Not logged in.")}`);return}let{api_url:i}=t;Yn(),i&&Wt({api_url:i}),e.json?k({status:"logged_out",email:t.email||null}):console.log(` ${$.success} Logged out${t.email?` ${sn.default.dim(`(${t.email})`)}`:""}`)}X();var ri=U(L(),1);W();async function qr(e){let[t,i]=await Promise.all([j("/api/me"),j("/api/me/activation")]),s=await t.json();t.ok||f(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",ri.default.bold(s.email)),c("Payment",s.has_payment_method?`${$.success} ${ri.default.green("active")}`:`${$.error} ${ri.default.dim("none")}`),c("Domains",String(s.domain_count)),c("API tokens",String(s.token_count)),c("Referral code",s.referral_code||ri.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 D=U(L(),1);W();pe();var Je=10,Yt=200,Bi=["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"],Gi=null;async function to(){if(Gi)return Gi;try{let e=await ye("/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(Bi),n=new Set(i),r=[...Bi.filter(o=>n.has(o)),...i.filter(o=>!s.has(o))];return Gi=r,r}}}catch{}return Gi=Bi,Bi}async function bd(e,t,i,s,n){let r=[],o=[],a=Je,l=0,u=!0,m=0,g=0,y=!1,w=!1,v=null,h="",_=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],x=0,O=setInterval(()=>{w||!u||(x=(x+1)%_.length,E())},80);function R(){m>0&&(process.stdout.write(`\x1B[${m}A\x1B[0J`),m=0)}function M(){if(u)return[];let q=Je+g*Je;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=[],z=V(),Q=!u&&z.length===0&&o.length>0,G=Q?o.slice(0,P):z,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(`${D.default.dim("\u2502")} ${D.default.dim("\u2715")} ${D.default.dim(ae.domain.padEnd(Oe))} ${D.default.dim("taken")}`);else{let ve=de===l,at=ve?D.default.green("\u25CF"):D.default.dim("\u25CB"),te=ae.domain.padEnd(Oe),it=ve?D.default.bold(D.default.cyan(te)):te,yt=ae.for_sale?D.default.cyan(`$${ae.for_sale.price} (for sale)`):D.default.dim(`$${ae.price}/yr`);q.push(`${D.default.dim("\u2502")} ${at} ${it} ${yt}`)}}if(Q&&o.length>P&&q.push(`${D.default.dim("\u2502")} ${D.default.dim(`\u2026 and ${o.length-P} more taken`)}`),u){let de=h?D.default.dim(`checking ${h}\u2026`):D.default.dim("searching\u2026");q.push(`${D.default.dim("\u2502")} ${D.default.cyan(_[x])} ${de}`)}else{let de=Je+g*Je;s&&de>=n.length&&q.push(`${D.default.dim("\u2502")} ${D.default.dim(`All ${Math.min(de,n.length)} TLDs searched`)}`);for(let ve=0;ve<Be.length;ve++){let it=V().length+ve===l?D.default.green("\u25CF"):D.default.dim("\u25CB"),yt=Be[ve]==="more"?D.default.dim("More \u2192"):Be[ve]==="new"?D.default.dim("New search \u2192"):D.default.dim("Skip");q.push(`${D.default.dim("\u2502")} ${it} ${yt}`)}q.push(D.default.dim("\u2514"))}process.stdout.write(q.join(`
177
+ `}}}}).prompt()});function Rl(e){return!!(e.json||!xe)}function C(e,t=50){console.log(),console.log(` ${H.default.bold(e)}`),console.log(` ${H.default.dim("\u2500".repeat(t))}`)}function c(e,t,i=2){let s=" ".repeat(i);console.log(`${s}${H.default.dim(e.padEnd(16))} ${t}`)}function d(){console.log()}function ze(e){console.log(` ${H.default.dim(e)}`)}function I(e,t){console.log(` ${H.default.dim(e)} ${H.default.cyan(t)}`)}function Tr(e){return e.split(/(https?:\/\/[^\s]+)/g).map(i=>/^https?:\/\//.test(i)?`\x1B]8;;${i}\x1B\\${H.default.underline(H.default.cyan(i))}\x1B]8;;\x1B\\`:H.default.dim(i)).join("")}function en(e,t){console.error(` ${$.error} ${H.default.red(e)}`),t&&console.error(` ${Tr(t)}`)}function S(e=!0){return e?ni():Al}function Nr(e){return e.replace(El,"")}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)=>H.default.dim(o.padEnd(s[a]))).join(" "),r=s.map(o=>H.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 Pl(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Qs(e){if(Array.isArray(e))return e.map(Qs);if(e&&typeof e=="object"&&!(e instanceof Date)){let t={};for(let[i,s]of Object.entries(e))t[Pl(i)]=Qs(s);return t}return e}function k(e,t){let i=Qs(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||Rl(e))}function B(e,t,i,s){if(i){k({dry_run:!0,action:e,...t},s);return}console.log(),console.log(` ${H.default.yellow("\u25B8 DRY RUN")} ${H.default.dim("- no changes made")}`),console.log(` ${H.default.dim("Action:")} ${H.default.bold(e)}`);for(let[n,r]of Object.entries(t))r!=null&&(Array.isArray(r)?console.log(` ${H.default.dim(n+":")} ${r.map(String).join(", ")}`):console.log(typeof r=="object"?` ${H.default.dim(n+":")} ${JSON.stringify(r)}`:` ${H.default.dim(n+":")} ${String(r)}`));console.log()}function Tl(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||Tl(i,t?.status,t?.fixUrl),n=t?.fixCommand||Dl[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 en(i,t?.hint),n?console.error(` ${H.default.dim("Or run:")} ${H.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 y=" "+e.map((h,_)=>H.default.dim(h.padEnd(i[_]))).join(" "),v=" "+i.map(h=>H.default.dim("\u2500".repeat(h))).join(" "),w=[y,v];for(let h of t){let _=h.status==="done"?h.icon??$.success:H.default.cyan(Pr[r%Pr.length]),x=h.cells.map((O,R)=>Wi(O,i[R])).join(" ");w.push(` ${_} ${x}`)}return w}let m=!1,f=()=>process.stdout.write("\x1B[?25h");function g(){let y=l();if(m&&n){process.stdout.write(`\x1B[${a}A`);for(let v of y)process.stdout.write(`\x1B[2K${v}
178
+ `)}else{for(let v of y)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(y,v){t[y].status="done",v!==void 0&&(t[y].icon=v),n&&g()},stop(){o&&clearInterval(o);for(let y of t)y.status="done";g(),n&&(process.stdout.write("\x1B[?25h"),process.removeListener("exit",f))}}}var H,Dr,xe,$,b,Al,El,Dl,Pr,W=Ie(()=>{"use strict";H=U(L(),1),Dr=require("child_process");De();xe=process.stdout.isTTY??!1;$={success:H.default.green("\u2713"),error:H.default.red("\u2717"),warning:H.default.yellow("!"),info:H.default.cyan("\u25CF"),arrow:H.default.dim("\u2192"),dot:H.default.dim("\xB7"),dash:H.default.dim("\u2500")},b={domain:e=>H.default.bold(H.default.white(e)),price:e=>H.default.green(`$${e}`),label:e=>H.default.dim(e),value:e=>H.default.white(e),dim:e=>H.default.dim(e),bold:e=>H.default.bold(e),success:e=>H.default.green(e),error:e=>H.default.red(e),warn:e=>H.default.yellow(e),cyan:e=>H.default.cyan(e),url:e=>`\x1B]8;;${e}\x1B\\${H.default.underline(H.default.cyan(e))}\x1B]8;;\x1B\\`};Al={start:()=>{},stop:()=>{},message:()=>{}};El=/\x1b\]8;;[^\x1b]*\x1b\\|\x1b\[[0-9;]*m/g;Dl={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(sn)return;let e=process.argv.includes("--json")||!ws,t=qe(),i=Me();try{let r=await(await fetch(`${t}/api/me`,{headers:{Authorization:`Bearer ${i}`}})).json();if(Fr(r)){sn=!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(` ${be.default.dim("This feature requires a")} ${be.default.bold("paid plan")} ${be.default.dim("(including an active Mailzero workspace plan or legacy Pro subscription).")}`),console.log(` ${be.default.dim("Opening pricing page")} ${$.arrow} ${be.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)){sn=!0,s.stop(`${$.success} Paid plan active! Continuing...`),d();return}}catch{}}s.stop("Timed out"),console.error(` ${be.default.red("\u2717")} No upgrade detected. Visit ${be.default.cyan("domani.run/settings")} to upgrade.`),process.exit(1)}async function Mr(){if(tn||Me()){tn=!0;return}(process.argv.includes("--json")||!ws)&&(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(` ${be.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(` ${be.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(` ${be.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(` ${be.default.red("\u2717")} Invalid response from server.`),process.exit(1)}i.stop(`${$.success} Auth code ready`),d(),console.log(` ${be.default.dim("Verification code:")} ${be.default.bold(be.default.cyan(n))}`),console.log(` ${be.default.dim("Opening browser")} ${$.arrow} ${b.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"){Wt({...ct(),token:l.token,email:l.email,api_url:t}),tn=!0,i.stop(`${$.success} Logged in as ${be.default.bold(l.email)}`),d();return}}i.stop("Timed out"),console.error(` ${be.default.red("\u2717")} No approval received. Run ${be.default.cyan("domani login")} to try again.`),process.exit(1)}var be,tn,sn,nn=Ie(()=>{"use strict";be=U(L(),1);ut();W();tn=!1,sn=!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/${_e}`,...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 ye(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";ut();nn()});function kt(){return{ok:!0}}function ft(e,t,i){return{ok:!1,error:{message:e,code:t,hint:i}}}function Br(e){return Ul.test(e)?ft("Input contains control characters","invalid_input","Remove non-printable characters from the input"):kt()}function Wl(e){return Fl.test(e)?ft("Input contains path traversal","invalid_input","Domain names cannot contain '../' or '..\\'"):kt()}function Jl(e){return ql.test(e)?ft("Input contains query string or fragment","invalid_input","Remove '?' or '#' from the domain name"):kt()}function Hl(e){return Ml.test(e)?ft("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 ft("Domain name is required","validation_error");if(e.length>Hr)return ft(`Domain name too long (${e.length} chars, max ${Hr})`,"validation_error");for(let t of[Br,Wl,Jl,Hl]){let i=t(e);if(!i.ok)return i}return Ll.test(e)?kt():ft(`Invalid domain name: ${e}`,"validation_error","Domain names can only contain letters, digits, hyphens, and dots")}function Bl(e){if(!e)return ft("TLD is required","validation_error");let t=Br(e);return t.ok?Vl.test(e)?kt():ft(`Invalid TLD: ${e}`,"validation_error","TLDs contain only letters (e.g. 'com', '.dev', 'ai')"):t}function Gl(e){for(let t of e){let i=Gr(t);if(!i.ok)return i}return kt()}function Kl(e){for(let t of e){let i=Bl(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=Gl(e);i.ok||u(i.error.message,{code:i.error.code,hint:i.error.hint,json:t?.json,fields:t?.fields})}function Ji(e,t){let i=Kl(e);i.ok||u(i.error.message,{code:i.error.code,hint:i.error.hint,json:t?.json,fields:t?.fields})}var Ul,Fl,ql,Ml,Ll,Vl,Hr,he=Ie(()=>{"use strict";W();Ul=/[\x00-\x08\x0b\x0c\x0e-\x1f]/,Fl=/\.\.[/\\]/,ql=/[?#]/,Ml=/%[0-9a-fA-F]{2}/,Ll=/^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?)*\.?$/,Vl=/^\.?[a-zA-Z]{2,63}$/,Hr=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"),en(i.error,i.hint),process.exit(1));let s=i.domains||[];s.length===0&&(e.stop("No domains"),d(),console.log(` ${on.default.dim("No domains yet.")} Use: ${on.default.cyan("domani buy <domain>")}`),d(),process.exit(0)),e.stop(`${s.length} domain(s)`);let n=await Ze({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 on,Ye=Ie(()=>{"use strict";X();De();on=U(L(),1);W()});var Yr={};Ft(Yr,{connect:()=>an});async function an(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 ${b.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 Ze({message:"Choose a provider",options:a});le(l)&&process.exit(0);let[m,f]=l.split(":"),y=(o.providers?.[m]||[]).find(h=>h.name===f),v;if(y&&y.methods.length>1){let h=await Ze({message:"Choose a method",options:y.methods.map(_=>({value:_.name,label:_.name,hint:_.default?"default":void 0}))});le(h)&&process.exit(0),v=h}let w;if(m==="hosting"&&y?.requires_target){y.notes?.setup&&ze(y.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 ${b.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 ${b.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 ${b.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?`${$.success} DNS instructions for ${ue.default.cyan(r.provider)}`:`${$.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 ${b.domain(r.domain)}`:`Connected ${b.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,y=f.status!=="already_set";process.stdout.isTTY&&y&&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((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"):$.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:")} ${b.url(r.docs)}`),d()}var ue,ln=Ie(()=>{"use strict";X();ue=U(L(),1);De();W();he();Ye()});function oi(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 ai(e){return e?Object.keys(e):[]}var dn=Ie(()=>{"use strict"});var so={};Ft(so,{email:()=>li,parseRecipients:()=>Hi,recipientField:()=>Bi});function Xl(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 Yl[e]||e}function Hi(e){return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function Bi(e){if(e.length!==0)return e.length===1?e[0]:e}function Zl(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 Qe(e){return e.domain?(K(e.domain,e),e.domain):fe()}async function li(e,t,i){if(e&&e.includes(".")&&!zl.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(Zl(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 pd(i);case"folders":return hd(i);case"archive":case"trash":case"restore":case"read":case"unread":case"star":case"unstar":return gd(e,i);case"setup":return ld(i);case"status":return dd(i);case"remove":return cd(i);case"create":return ud(i);case"delete":return md(i);case"send":return fd(i);case"webhook":return yd(i);case"forward":return bd(i);case"work":return sd(i);case"triage":return nd(i);case"note":return rd(i);case"notes":return od(i);case"activity":return ad(i);case"changes":return id(i);case"coordination":return Ql(i);case"presence":return ed(i);case"release-presence":return td(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, 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 Ql(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 ed(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 td(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 id(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 sd(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 nd(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 rd(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(`${$.success} Private note added`)}async function od(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 ad(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 ld(e){let t=await Qe(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 ${b.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(`${$.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 ${b.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 dd(e){let t=await Qe(e),i=S(!e.json);i.start(`Checking email status for ${b.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(`${$.success} Status loaded`),e.json){k(n,e.fields);return}if(C(`Email ${b.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 cd(e){let t=await Qe(e);if(e.dryRun)return B("email_remove",{domain:t},e.json,e.fields);let i=S(!e.json);i.start(`Removing email from ${b.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(`${$.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(`${$.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?b.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 ud(e){let t=await Qe(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 y=g.map(x=>({cells:[D.default.yellow(x.type),x.name,x.note?D.default.dim(`(${x.note})`):""],status:"pending"})),v=Dt(["Type","Name",""],y,[6,24,16]);v.start();let w=0;for(;r.status===202&&w<60;)await Pt(15e3),w++,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&&(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=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&&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(`${$.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:",`${Xt}/inbox?address=${encodeURIComponent(o.address)}`)):(I("Check propagation:",`domani email status --domain ${t}`),I("Web inbox:",`${Xt}/inbox?address=${encodeURIComponent(o.address)}`)),d()}async function md(e){let t=await Qe(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(`${$.success} Mailbox deleted`),e.json){k(r,e.fields);return}console.log(` ${D.default.dim(`${r.address} and all messages deleted.`)}`),d()}async function fd(e){let t=await Qe(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:Bi(Hi(e.to))},n=Bi(Hi(e.cc)),r=Bi(Hi(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(`${$.success} Sent to ${D.default.cyan(m)}`),e.json){k(l,e.fields);return}}async function pd(e){let t=await Qe(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(`${$.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(`${$.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"),y=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(),x=_.length>60?_.slice(0,60)+"\u2026":_;h=`${v} ${D.default.dim("- "+x)}`}console.log(` ${g} ${y.padEnd(30)} ${h} ${w}`)}a.next_cursor&&console.log(` ${D.default.dim("\u2026 more available, use --limit to paginate")}`)}async function hd(e){let t=await Qe(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 gd(e,t){let i=await Qe(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(`${$.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 yd(e){let t=await Qe(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=oi(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:ai(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(`${$.success} Webhook set`),e.json){k(a,e.fields);return}C(`Mailbox ${a.address}`),c("Webhook",b.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(`${$.success} Webhook removed`),e.json){k(a,e.fields);return}C(`Mailbox ${a.address}`),c("Webhook",D.default.dim("none")),d()}}async function bd(e){let t=await Qe(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(`${$.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 ${b.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 ${b.domain(r.domain)}`),r.provider?c("Provider",D.default.cyan(cn(r.provider))):c("Provider",D.default.dim("unknown")),r.mx.configured?c("MX",`${$.success} ${D.default.green("propagated")} ${D.default.dim(`(${r.mx.records.length} record${r.mx.records.length!==1?"s":""})`)}`):c("MX",`${$.error} ${D.default.red("not configured")}`),r.spf.configured?c("SPF",`${$.success} ${D.default.green(r.spf.value)}`):c("SPF",`${$.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",`${$.success} ${D.default.green(o)}`)}else c("DMARC",`${$.error} ${D.default.red("missing")}`);r.dkim.configured?c("DKIM",`${$.success} ${D.default.green("found")} ${D.default.dim(`(${r.dkim.selectors.join(", ")})`)}`):c("DKIM",`${$.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 Ze({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 ${b.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:Xl(x),status:"pending"})),m);f.start();let g=await j(`/api/domains/${encodeURIComponent(e)}/connect`,{method:"POST",body:JSON.stringify({target:t})}),y=await g.json();g.ok||(f.stop(),d(),u(y.error||y.message,{hint:y.hint,status:g.status,json:i,fields:s}));let v=y.records||[];for(let x=0;x<o.length;x++)v.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 w=v.filter(x=>x.status==="created"||x.status==="updated").length,h=v.filter(x=>x.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(` ${$.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(`${$.success} Email configured via ${D.default.cyan(l)}`)}d(),I("Verify propagation:",`domani email ${e} --check`),d()}var D,eo,zl,Yl,mn=Ie(()=>{"use strict";X();Zt();D=U(L(),1);De();W();he();Ye();eo=require("node:crypto");dn();zl=["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"],Yl={"google-workspace":"Google Workspace",fastmail:"Fastmail",proton:"Proton Mail"}});var no={};Ft(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 ${b.domain(e)}`);let g=await j(`/api/domains/${encodeURIComponent(e)}/dns`),y=await g.json();if(g.ok||(f.stop("Failed"),u(y.error||y.message,{hint:y.hint,status:g.status,json:o,fields:r?.fields})),f.stop(`${y.records.length} record(s)`),o){k(y,r?.fields);return}if(y.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 v=[8,24,40,8];C(`DNS ${b.domain(e)}`,v.reduce((h,_)=>h+_,0)+v.length-1);let w=y.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"],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 ${je.default.yellow(a.toUpperCase())} record`);let g=await j(`/api/domains/${encodeURIComponent(e)}/dns`),y=await g.json(),w=(g.ok?y.records:[]).filter(x=>!(x.type===a.toUpperCase()&&x.name===l));w.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:w})}),_=await h.json();h.ok||(f.stop("Failed"),u(_.error||_.message,{hint:_.hint,status:h.status,json:o,fields:r?.fields})),f.stop(`${$.success} ${je.default.yellow(a.toUpperCase())} ${l} ${$.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"}),y=await g.json();g.ok||(f.stop("Failed"),u(y.error||y.message,{hint:y.hint,status:g.status,json:o,fields:r?.fields})),f.stop(`${$.success} Deleted ${je.default.yellow(a.toUpperCase())} ${l}`),o?k(y,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 ${b.domain(e)}`);let g=await j(`/api/domains/${encodeURIComponent(e)}/dns/snapshot`,{method:"POST"}),y=await g.json();g.ok||(f.stop("Failed"),u(y.error||y.message,{hint:y.hint,status:g.status,json:o,fields:r?.fields}));let v=y.records?.length??0;if(f.stop(`${$.success} Captured ${v} record(s)`),o){k(y,r?.fields);return}let w=`${e}.dns.json`,h=(0,fn.resolve)(process.cwd(),w);(0,Gi.writeFileSync)(h,JSON.stringify(y,null,2)+`
179
+ `),C("DNS Snapshot"),c("Domain",b.domain(y.domain)),c("Records",String(v)),c("Subdomains",String(y.subdomains?.length??0)),c("Sources",(y.sources||[]).join(", ")||"none"),c("Captured",y.capturedAt||y.captured_at||"now"),c("Saved to",je.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,Gi.readFileSync)(w,"utf-8"),_=JSON.parse(h);g=JSON.stringify({snapshot:_}),f.start(`Restoring DNS for ${b.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 ${b.domain(e)} from server backup`);let y=await j(`/api/domains/${encodeURIComponent(e)}/dns/restore`,{method:"POST",...g?{body:g}:{}}),v=await y.json();if(y.ok||(f.stop("Failed"),u(v.error||v.message,{hint:v.hint,status:y.status,json:o,fields:r?.fields})),f.stop(`${$.success} Restored DNS`),o){k(v,r?.fields);return}if(C("DNS Restored"),c("Domain",b.domain(v.domain)),c("Applied",je.default.green(String(v.applied??0))),c("Skipped",je.default.dim(String(v.skipped??0))),v.errors?.length>0){c("Errors",je.default.red(String(v.errors.length)));for(let w of v.errors)console.log(` ${je.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 je,Gi,fn,hn=Ie(()=>{"use strict";X();je=U(L(),1);W();he();Ye();Gi=require("node:fs"),fn=require("node:path")});var ro={};Ft(ro,{status:()=>gn});function $d(e){return[et.default.yellow(e.type),e.name,et.default.cyan(e.value)+(e.priority?et.default.dim(` pri=${e.priority}`):"")]}function vd(e){if(C(`Status ${b.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`),y=await g.json();g.ok||u(y.error||y.message,{hint:y.hint,status:g.status,json:t.json,fields:t.fields}),k(y,t.fields);return}let i=S(!0);i.start(`Checking ${b.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 y=o.split(`
180
+ `);o=y.pop()??"";for(let v of y)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,vd(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:$d(_),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,x=_?$.success:`${$.warning}`;a.markDone(h,x)}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,yn=Ie(()=>{"use strict";X();et=U(L(),1);W();he();Ye()});var di={};Ft(di,{buy:()=>$n});async function bn(e){let t=await Ze({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(()=>(ln(),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(()=>(yn(),ro));await i(e,{})}}async function wd(e,t){K(e,t);let i;if(t.preChecked)i={available:!0,...t.preChecked};else{let f=S(!t.json);f.start(`Checking ${b.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(`${$.error} ${b.domain(e)} is not available`),u(`${e} is not available`,{code:"not_available",json:t.json,fields:t.fields})),f.stop(`${$.success} ${b.domain(e)} ${$.dot} available ${$.dot} ${b.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 ${b.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 y of g)if(y.startsWith("event: "))l=y.slice(7).trim();else if(y.startsWith("data: ")){let v=JSON.parse(y.slice(6));l==="checking"?s.message(`Checking ${b.domain(v.domain)}`):l==="payment"?s.message(`Charging ${b.price(v.total)}`):l==="registering"?s.message(`Registering ${b.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(`${$.success} ${b.domain(r.domain)} is yours!${m}`),t.json){k(r,t.fields);return}xe?await bn(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 kd(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(`${$.error} None of the ${e.length} domains are available`),process.exit(1));let a=r.reduce((h,_)=>h+(_.price||0),0);if(s.stop(`${$.success} ${r.length}/${e.length} available ${$.dot} ${b.price(a.toFixed(2))} total`),o.length>0)for(let h of o)console.log(` ${$.error} ${b.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 ${b.price(a.toFixed(2))}?`});if(!h||typeof h=="symbol"){console.log(` ${Te.default.dim("Cancelled.")}`);return}}d();let l=r.map(h=>({cells:[b.domain(h.domain),h.price?`${b.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(),y=new Set((g.results||[]).map(h=>h.domain));for(let h=0;h<r.length;h++){let _=r[h].domain.toLowerCase().trim();y.has(_)?m.markDone(h,$.success):m.markDone(h,$.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(` ${$.success} ${Te.default.green(`${v} domain${v>1?"s":""} registered`)}`),w>0){console.log(` ${$.error} ${Te.default.red(`${w} failed`)}`);for(let h of g.errors||[])console.log(` ${Te.default.dim("\u2500")} ${b.domain(h.domain)}: ${Te.default.dim(h.error)}${h.hint?` ${Te.default.dim(`(${h.hint})`)}`:""}`)}if(d(),v>0&&xe){let h=(g.results||[]).filter(_=>_.success).map(_=>_.domain);if(h.length===1)await bn(h[0]);else{let _=await Ze({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 bn(_)):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){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?wd(i[0],t):kd(i,t)}var Te,Kt=Ie(()=>{"use strict";X();De();Te=U(L(),1);W();he()});var Fn=U(Un(),1),{program:gc,createCommand:yc,createArgument:bc,createOption:$c,CommanderError:vc,InvalidArgumentError:wc,InvalidOptionArgumentError:kc,Command:qn,Argument:_c,Option:xc,Help:jc}=Fn.default;var ot=U(L(),1);ut();nn();W();Zt();ut();var wt=U(L(),1);W();function Nl(e){let t=e.scopes?.split(",").map(n=>n.trim()).filter(Boolean),i=!!(t?.length||e.label||e.expiresIn),s=e.expiresIn===void 0?void 0:Number(e.expiresIn);if(s!==void 0&&(!Number.isInteger(s)||s<3600||s>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}:{},...s!==void 0?{expires_in:s}:{}}}}async function Lr(e){let t=qe(),i=S(!e.json),s;try{s=Nl(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=ct(),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 ${wt.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(` ${wt.default.dim("Verification code:")} ${wt.default.bold(wt.default.cyan(m))}`),e.open!==!1?(console.log(` ${wt.default.dim("Opening browser")} ${$.arrow} ${b.url(f)}`),We(f)):console.log(` ${wt.default.dim("Open this URL to approve:")} ${b.url(f)}`),d(),i.start("Waiting for approval");let y=120;for(let v=0;v<y;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"){Wt({...ct(),token:h.token,email:h.email,api_url:t}),i.stop(`Logged in as ${wt.default.bold(h.email)}`),d(),I("Get started:","domani search"),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"})}ut();var rn=U(L(),1);W();async function Vr(e){let t=ct();if(!t.token){e.json?k({status:"not_logged_in"}):console.log(` ${rn.default.dim("Not logged in.")}`);return}let{api_url:i}=t;Zn(),i&&Wt({api_url:i}),e.json?k({status:"logged_out",email:t.email||null}):console.log(` ${$.success} Logged out${t.email?` ${rn.default.dim(`(${t.email})`)}`:""}`)}X();var ri=U(L(),1);W();async function Jr(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",ri.default.bold(s.email)),c("Payment",s.has_payment_method?`${$.success} ${ri.default.green("active")}`:`${$.error} ${ri.default.dim("none")}`),c("Domains",String(s.domain_count)),c("API tokens",String(s.token_count)),c("Referral code",s.referral_code||ri.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 Je=10,zt=200,Ki=["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"],zi=null;async function oo(){if(zi)return zi;try{let e=await ye("/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(Ki),n=new Set(i),r=[...Ki.filter(o=>n.has(o)),...i.filter(o=>!s.has(o))];return zi=r,r}}}catch{}return zi=Ki,Ki}async function _d(e,t,i,s,n){let r=[],o=[],a=Je,l=0,m=!0,f=0,g=0,y=!1,v=!1,w=null,h="",_=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],x=0,O=setInterval(()=>{v||!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=Je+g*Je;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,at=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")} ${at} ${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=Je+g*Je;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
- `),m=q.length}process.stdout.write(`${D.default.cyan("\u25C6")} Register a domain?
184
- `),process.stdout.write("\x1B[?25l"),process.stdin.setRawMode(!0),process.stdin.resume();let T=q=>{let z=q.toString();if(z==="\x1B[A")l=Math.max(0,l-1),E();else if(z==="\x1B[B")l=Math.min(ee(),l+1),E();else if(z==="\r"){let Q=V();if(u&&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+=Je,r.length<a?y=!0:(l=Math.min(l,ee()),E())):(Oe==="new"&&(v="__new__"),w=!0)}}else(z===""||z==="\x1B")&&(w=!0)};process.stdin.on("data",T),E();async function Z(q){let z=new TextDecoder,Q="",G="";for await(let Oe of q){if(w)break;Q+=z.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"),f(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 ve=r.findIndex(at=>at.price>ae.price);ve===-1?r.push(ae):(r.splice(ve,0,ae),ve<=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"){u=!1,l=Math.min(l,ee());let ve=Je+g*Je;r.length<a&&s&&ve<n.length&&(y=!0),y||E()}}}u=!1}for(await Z(e);!w;)if(await new Promise(q=>{let z=setInterval(()=>{(w||y)&&(clearInterval(z),q())},16)}),y&&!w){y=!1;let q=Je+g*Je,z=n.slice(q,q+Je);g++,u=!0,l=Math.min(l,Math.max(0,r.length-1)),E();let Q=new URLSearchParams;Q.set("domains",z.map(G=>`${t}.${G}`).join(","));try{let G=await ye(`/api/domains/search?${Q}`,{headers:{Accept:"text/event-stream"}});G.ok&&G.body?await Z(G.body):(u=!1,E())}catch{u=!1,E()}}clearInterval(O),process.stdin.removeListener("data",T),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.pause(),process.stdout.write("\x1B[?25h"),R();let Y=v==="__new__",F=Y?null:v,ie=F?r.find(q=>q.domain===F)??null:null;return F?process.stdout.write(`${D.default.dim("\u25C7")} Register a domain?
186
- ${D.default.dim("\u2502")} ${D.default.bold(D.default.cyan(F))}
187
- ${D.default.dim("\u2514")}
188
- `):process.stdout.write(`${D.default.dim("\u2514")}
189
- `),{chosen:F,chosenResult:ie,searchAgain:Y,allTaken:r.length===0&&o.length>0,expanded:g>0}}async function io(e,t,i){if(!e){xe||f("Missing required argument: domain",{hint:"Usage: domani search <domain> [tlds...]",code:"missing_argument",json:i.json});let T=await Re({message:"Search for a domain",placeholder:"e.g. myapp or myapp.dev"});(le(T)||!T)&&process.exit(0),e=T}let s=t.map(T=>T.replace(/^\./,"")),n=i.tlds?.split(",").map(T=>T.trim())||[],r=[...new Set([...s,...n])];if(r.length>0&&Vi(r,i),K(e,i),e.includes(".")&&r.length===0){let T=S(!i.json);T.start(`Checking ${b.domain(e)}`);let[Z,Y]=await Promise.all([ye(`/api/domains/search?q=${encodeURIComponent(e)}`),ye(`/api/domains/${encodeURIComponent(e)}/og`).catch(()=>null)]),F=await Z.json();if(Z.ok||(T.stop("Search failed"),f(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(T.stop(`${$.success} ${b.domain(F.domain)} ${$.dot} available ${$.dot} ${b.price(F.price)}/yr`),xe&&!i.json){let{buy:ie}=await Promise.resolve().then(()=>(Kt(),ai));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(T.stop(`${$.info} ${b.domain(F.domain)} ${$.dot} ${D.default.cyan("for sale")} ${$.dot} ${b.price(F.for_sale.price)}`),xe&&!i.json){let{buy:ie}=await Promise.resolve().then(()=>(Kt(),ai));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)T.stop(`${D.default.dim("?")} ${b.domain(F.domain)} ${$.dot} ${D.default.dim("lookup failed")}`);else{let ie;try{if(Y?.ok){let z=await Y.json();z?.title&&(ie=z.title)}}catch{}let q=ie?` ${$.dot} ${D.default.dim(`"${ie}"`)}`:"";T.stop(`${$.error} ${b.domain(F.domain)} ${$.dot} ${D.default.red("taken")}${q}`)}return}let o=e.split(".")[0];if(xe&&!i.json&&r.length>0){let T=new URLSearchParams;T.set("domains",r.map(te=>`${o}.${te}`).join(",")),i.maxPrice&&T.set("max_price",i.maxPrice);let Z=await ye(`/api/domains/search?${T}`,{headers:{Accept:"text/event-stream"}});if(!Z.ok||!Z.body){f("Search failed",{json:i.json});return}let Y=[],F=new TextDecoder,ie="",q="",z=S(!0);z.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"&&Y.push(JSON.parse(yt.slice(6)))}z.stop("");let Q=Math.max(...r.map(te=>`${o}.${te}`.length))+2,G=Y.filter(te=>te.available),Oe=Y.filter(te=>!te.available&&!te.error),Be=Y.filter(te=>!te.available&&te.for_sale);for(let te of[...G,...Be,...Oe.filter(it=>!it.for_sale)])te.available?console.log(` ${D.default.green("\u2713")} ${D.default.bold(D.default.white(te.domain.padEnd(Q)))} ${D.default.green(b.price(te.price)+"/yr")}`):te.for_sale?console.log(` ${D.default.cyan("$")} ${D.default.bold(D.default.white(te.domain.padEnd(Q)))} ${D.default.cyan(b.price(te.for_sale.price))} ${D.default.dim("(for sale)")}`):console.log(` ${D.default.dim("\u2717")} ${D.default.dim(te.domain.padEnd(Q))} ${D.default.dim("taken")}`);if(G.length===0){console.log(` ${D.default.dim("No domains available")}`),d();return}let{buy:de}=await Promise.resolve().then(()=>(Kt(),ai));if(G.length===1){await de([G[0].domain],{preChecked:{price:G[0].price,currency:G[0].currency}});return}let{select:ae,isCancel:ve}=await Promise.resolve().then(()=>(De(),zs)),at=await ae({message:"Register one?",options:[...G.map(te=>({value:te.domain,label:b.domain(te.domain),hint:b.price(te.price)+"/yr"})),{value:"__skip__",label:"Skip"}]});if(!ve(at)&&at!=="__skip__"){d();let te=G.find(it=>it.domain===at);await de([at],{preChecked:te?{price:te.price,currency:te.currency}:void 0})}else d();return}if(xe&&!i.json){let T=await to();for(i.expand&&T.length>Yt&&console.error(D.default.dim(` (--expand: checking the first ${Yt} of ${T.length} TLDs - server limit per request)`));;){let Z=i.expand?T.slice(0,Yt):T.slice(0,Je),Y=new URLSearchParams;Y.set("domains",Z.map(ae=>`${o}.${ae}`).join(",")),i.maxPrice&&Y.set("max_price",i.maxPrice);let F=S(!0);F.start(`Searching available domains for ${D.default.bold(o)}`);let ie=await ye(`/api/domains/search?${Y}`,{headers:{Accept:"text/event-stream"}});if(!ie.ok||!ie.body){F.stop("Search failed");break}F.stop("");let q=!i.expand,{chosen:z,chosenResult:Q,searchAgain:G}=await bd(ie.body,o,i.all??!1,q,T);if(z){d();let{buy:ae}=await Promise.resolve().then(()=>(Kt(),ai)),ve=Q?{price:Q.price,currency:Q.currency}:void 0;await ae([z],{preChecked:ve});return}if(!G)break;let{text:Oe,isCancel:Be}=await Promise.resolve().then(()=>(De(),zs)),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 to(),u=r.length>0?r:i.expand?l.slice(0,Yt):l.slice(0,Je);i.expand&&r.length===0&&l.length>Yt&&console.error(`(--expand: checking the first ${Yt} of ${l.length} TLDs - server limit per request; use --tlds to target others)`);let m=u.map(T=>`${a}.${T}`),g=new URLSearchParams;g.set("domains",m.join(",")),i.maxPrice&&g.set("max_price",i.maxPrice);let y=S(!i.json);y.start(`Searching available domains for ${D.default.bold(a)}`);let w=await ye(`/api/domains/search?${g}`,{headers:{Accept:"text/event-stream"}});if(!w.ok){y.stop("Search failed");try{let T=await w.json();f(T.error||T.message||`Server error (${w.status})`,{hint:T.hint,status:w.status,json:i.json,fields:i.fields})}catch{f(`Server error (${w.status})`,{status:w.status,json:i.json,fields:i.fields})}}let v=w.body;v||(y.stop("Search failed"),f("Empty response",{code:"error",json:i.json,fields:i.fields}));let h=[],_=!1,x=0,O=i.all??!1;function R(){_||(_=!0,y.stop(`Checking TLDs for ${D.default.bold(a)}`),d())}function M(T){R(),T.available?console.log(` ${$.success} ${b.domain(T.domain).padEnd(37)} ${b.price(T.price)}${D.default.dim("/yr")}`):T.for_sale?console.log(` ${$.info} ${b.domain(T.domain).padEnd(37)} ${D.default.cyan(b.price(T.for_sale.price))} ${D.default.dim("(for sale)")}`):T.error||console.log(` ${$.error} ${D.default.dim(T.domain.padEnd(38))} ${D.default.red("taken")}`)}function V(){_||y.message(`Checking TLDs for ${D.default.bold(a)} ${D.default.dim(`(${x} checked)`)}`)}let ee=new TextDecoder,P="",E="";for await(let T of v){P+=ee.decode(T,{stream:!0});let Z=P.split(`
191
- `);P=Z.pop()??"";for(let Y of Z)if(Y.startsWith("event: "))E=Y.slice(7);else if(Y.startsWith("data: ")){let F=JSON.parse(Y.slice(6));if(E==="error")y.stop("Search failed"),f(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(` ${D.default.dim("\u2500".repeat(50))}`);let ie=F.total-F.available,q=F.total>=5&&ie/F.total>=.5,z=`Checked ${F.total} TLDs \xB7 ${F.available} available${q?" \xB7 popular name":""}`;console.log(` ${D.default.dim(z)}`),F.available===0&&!i.expand&&r.length===0&&(d(),I("Try more TLDs:",`domani search ${a} --expand`))}}}d()}Kt();X();var li=U(L(),1);W();pe();async function so(e,t){K(e,t);let i={domain:e};if(t.slug&&(i.slug=t.slug),t.name&&(i.name=t.name),t.webhook&&(i.webhook_url=t.webhook),t.years&&(i.years=Number(t.years)),t.paymentMethod&&(i.payment_method=t.paymentMethod),t.dryRun){B("POST /api/agents/provision",i,t.json,t.fields);return}let s=S(!t.json);s.start(`Provisioning ${b.domain(e)}`);let n=await j("/api/agents/provision",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)}),r=await n.json();if(n.ok||(s.stop("Provisioning failed"),f(r.error||"Provisioning failed",{hint:r.hint,status:n.status,json:t.json,fields:t.fields})),s.stop(`${b.domain(e)} is ready`),t.json){k(r,t.fields);return}if(d(),C("Agent identity"),c("Domain",`${r.domain} (${r.domain_status})`),c("Mailbox",r.mailbox?li.default.green(r.mailbox.address):li.default.yellow("pending DNS")),c("Webhook",r.webhook?r.webhook.url:li.default.dim("none")),r.webhook?.secret&&c("Signing secret",r.webhook.secret),r.warnings?.length){d();for(let o of r.warnings)Ye(li.default.yellow(o))}if(r.next_steps?.length){d(),C("Next");for(let o of r.next_steps)Ye(o)}d()}X();var pt=U(L(),1);W();async function no(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"),f(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(` ${pt.default.dim("No domains yet.")} Use: ${pt.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"?pt.default.green:o.status==="pending"?pt.default.yellow:pt.default.red,u=o.autoRenew?pt.default.green("on"):pt.default.dim("off");return[b.domain(o.domain),l(o.status),u,pt.default.dim(a)]});se(["Domain","Status","Auto-renew","Expires"],r,n),d()}mn();X();var Tt=U(L(),1);W();async function ro(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 ye(`/api/tlds?${t}`),n=await s.json();if(s.ok||(i.stop("Failed"),f(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(` ${Tt.default.dim("No TLDs match your filters.")}`),d();return}C("TLD Pricing");let o=r.map(a=>[Tt.default.bold(`.${a.tld}`),b.price(a.registration.toFixed(2))+Tt.default.dim("/yr"),Tt.default.dim("renew ")+b.price(a.renewal.toFixed(2))+Tt.default.dim("/yr")]);se(["TLD","Register","Renewal"],o,[22,16,20]),d(),console.log(` ${Tt.default.dim(`${n.total} TLDs total`)}`),d()}X();var Se=U(L(),1);W();pe();async function oo(e,t){K(e,t);let i=S(!t.json);i.start(`Looking up ${b.domain(e)}`);let[s,n]=await Promise.all([ye(`/api/domains/whois?q=${encodeURIComponent(e)}`),ye(`/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"),f(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 ${b.domain(r.domain)}`),!r.registered){c("Status",`${$.success} ${Se.default.green("not registered")}`),d(),I("Register it:",`domani buy ${r.domain}`),d();return}if(c("Status",`${$.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,u=l<30?Se.default.red:l<90?Se.default.yellow:Se.default.green;c("Days left",u(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",b.url(a.email)),a.country&&c("Country",a.country)):r.redacted&&c("Contact",Se.default.dim("redacted (WHOIS privacy)")),d()}X();De();var ht=U(L(),1);W();pe();async function ao(e,t){if(!e){xe||f("Missing required argument: prompt",{hint:'Usage: domani suggest "describe your project"',code:"missing_argument",json:t.json});let h=await Re({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&&Vi(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 ye(`/api/domains/suggest?${i}`,{signal:AbortSignal.timeout(_)})}catch{h.stop("Failed"),f("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"),f(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 ye(`/api/domains/suggest?${i}`,{headers:{Accept:"text/event-stream"},signal:AbortSignal.timeout(n)})}catch{s.stop("Failed"),f("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();f(h.error||h.message||`Server error (${r.status})`,{hint:h.hint,status:r.status})}catch{f(`Server error (${r.status})`,{status:r.status})}}let o=r.body;o||(s.stop("Failed"),f("Empty response"));let a=[],l=[],u=!1,m=0;function g(){u||(u=!0,s.stop("Finding available domains"),d())}let y=new TextDecoder,w="",v="";for await(let h of o){w+=y.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")m++,O.available?a.push(O):l.push(O),u||s.message(`Finding available domains ${ht.default.dim(`(${m} checked, ${a.length} available)`)}`);else if(v==="iteration")u||s.message(`Finding available domains ${ht.default.dim(`(round ${O.n})`)}`);else if(v==="done"){g();for(let R of a){let M=R.reason?` ${ht.default.dim(R.reason)}`:"";console.log(` ${$.success} ${b.domain(R.domain).padEnd(37)} ${b.price(R.price)}${ht.default.dim("/yr")}${M}`)}for(let R of l)console.log(` ${$.error} ${ht.default.dim(R.domain.padEnd(38))} ${ht.default.red("taken")}`);console.log(` ${ht.default.dim("\u2500".repeat(50))}`),console.log(` ${ht.default.dim(`Found ${O.total} available \xB7 checked ${O.checked} \xB7 ${O.iterations} round${O.iterations>1?"s":""}`)}`)}else v==="error"&&(u||s.stop("Failed"),f(O.message))}catch{}}a.length===0&&l.length===0&&(u||s.stop("No results"),f("Could not find available domains for this prompt.")),d(),a.length>0&&(I("Register one:",`domani buy ${a[0].domain}`),d())}on();pn();X();De();var Nt=U(L(),1);W();pe();Zt();async function lo(e,t){K(e,t);let i=S(!t.json);i.start(`Planning safe adoption for ${b.domain(e)}`);let s=await j(`/api/domains/adoption-plan?domain=${encodeURIComponent(e)}`),n=await s.json();if(s.ok||(i.stop("Check failed"),f(n.error,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),n.options?.transfer?.eligible||(i.stop(`${$.error} Not eligible`),f(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(`${$.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?Nt.default.yellow("Enabled, DS will be verified"):"Not enabled"),c("DNS migration","Not requested"),d();let a=n.options.transfer.price!=null?` for ${b.price(n.options.transfer.price.toFixed(2))}`:"",l=await Ke({message:`Transfer ${Nt.default.bold(e)} to ${qt}${a}? Nameservers stay unchanged and 1 year is included.`});if(!l||typeof l=="symbol"){console.log(` ${Nt.default.dim("Cancelled.")}`);return}}if(!t.authCode){(t.json||!process.stdout.isTTY)&&f("--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 Re({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 ${b.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"),f(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(`${$.success} Transfer initiated`),t.json){k(o,t.fields);return}C("Transfer Initiated"),c("Domain",b.domain(o.domain)),c("Status",Nt.default.yellow(o.status||"pending")),o.price&&c("Price",b.price(o.price)+Nt.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(` ${Nt.default.dim(o.hint)}`)),d(),I("Check transfer progress:",`domani status ${o.domain}`),d()}X();var Ki=U(L(),1);W();pe();async function co(e,t){K(e,t);let i=S(!t.json);i.start(`Inspecting ${b.domain(e)}`);let s=await j(`/api/domains/adoption-plan?domain=${encodeURIComponent(e)}`),n=await s.json();if(s.ok||(i.stop("Inspection failed"),f(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),i.stop(`${$.success} Adoption plan ready`),t.json){k(n,t.fields);return}if(C(`Adopt ${b.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?Ki.default.yellow("Enabled"):"Not enabled"),c("Account",n.account_state),c("Recommended",Ki.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(` ${Ki.default.yellow("!")} ${r}`);d()}X();De();var Yi=U(L(),1);W();pe();ze();async function uo(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)&&f("--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 ${Yi.default.bold(e)} for ${i} year${i>1?"s":""}? You will be charged.`});if(!o||typeof o=="symbol"){console.log(` ${Yi.default.dim("Cancelled.")}`);return}}let s=S(!t.json);s.start(`Renewing ${b.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"),f(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(`${$.success} Domain renewed`),t.json){k(r,t.fields);return}C("Renewal Complete"),c("Domain",b.domain(r.domain)),c("Years",String(r.renewed_years)),c("New expiry",new Date(r.new_expiry).toLocaleDateString()),r.price&&c("Price",b.price(r.price)+Yi.default.dim(` ${r.currency||"USD"}`)),r.payment_method&&c("Payment",r.payment_method),d(),I("Verify renewal:",`domani status ${r.domain}`),d()}X();var rt=U(L(),1);W();pe();async function mo(e,t){e||f("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 ${b.domain(e)}`:`Initiating import for ${b.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"),f(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(`${$.success} ${b.domain(e)} imported!`),C("Domain Imported"),c("Domain",b.domain(r.domain)),c("Status",rt.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(`${$.success} Verification record ready`),C("Import Domain"),c("Domain",b.domain(r.domain)),c("Status",rt.default.yellow("pending verification")),d(),console.log(" Add this TXT record at your DNS provider:"),d(),console.log(` ${rt.default.dim("Type:")} ${rt.default.bold("TXT")}`),console.log(` ${rt.default.dim("Name:")} ${rt.default.bold(r.txt_record?.name||"@")}`),console.log(` ${rt.default.dim("Value:")} ${rt.default.bold(r.txt_record?.value||`domani-verify=${r.token}`)}`),d(),console.log(` ${rt.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())}dn();ut();W();function fo(e){let t=Me();if(t||(d(),f("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 po(e,t){switch(e){case void 0:case"list":return $d(t.json,t.fields);case"create":return wd(t);case"revoke":return vd(t);default:f(`Unknown action: ${e}`,{hint:"Actions: list, create, revoke",code:"validation_error",json:t.json,fields:t.fields})}}async function $d(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"),f(n.error||n.message,{hint:n.hint,status:s.status,json:e,fields:t})),i.stop(`${$.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 wd(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)&&f("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"),f(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields})),i.stop(`${$.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 vd(e){e.tokenId||f("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"),f(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),t.stop(`${$.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();pe();ze();async function ho(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 kd(e,t.json,t.fields);let r={};if(i){let u=yn(t.autoRenew);u===null&&f("--auto-renew must be on or off",{code:"validation_error",json:t.json,fields:t.fields}),r.auto_renew=u}if(s){let u=yn(t.whoisPrivacy);u===null&&f("--whois-privacy must be on or off",{code:"validation_error",json:t.json,fields:t.fields}),r.whois_privacy=u}if(n){let u=yn(t.securityLock);u===null&&f("--security-lock must be on or off",{code:"validation_error",json:t.json,fields:t.fields}),r.security_lock=u}if(t.dryRun)return B("settings_update",{domain:e,...r},t.json,t.fields);let o=S(!t.json);o.start(`Updating ${b.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"),f(l.error||l.message,{hint:l.hint,status:a.status,json:t.json,fields:t.fields})),o.stop(`${$.success} Settings updated`),t.json){k(l,t.fields);return}C("Settings Updated"),c("Domain",b.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 kd(e,t,i){let s=S(!t);s.start(`Loading ${b.domain(e)}`);let n=await j(`/api/domains/${encodeURIComponent(e)}`),r=await n.json();if(n.ok||(s.stop("Failed"),f(r.error||r.message,{hint:r.hint,status:n.status,json:t,fields:i})),s.stop(`${$.success} ${b.domain(e)}`),t){k(r,i);return}C("Domain Settings"),c("Domain",b.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 yn(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 Ut=U(L(),1);W();pe();ze();async function go(e,t){e||(e=await fe()),K(e,t);let i=S(!t.json);i.start(`Getting auth code for ${b.domain(e)}`);let s=await j(`/api/domains/${encodeURIComponent(e)}/auth-code`),n=await s.json();if(s.ok||(i.stop("Failed"),f(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),i.stop(`${$.success} Auth code retrieved`),t.json){k(n,t.fields);return}if(C("Auth Code"),c("Domain",b.domain(n.domain)),c("Auth code",Ut.default.bold(Ut.default.green(n.auth_code))),n.was_unlocked&&c("",Ut.default.yellow("Domain was automatically unlocked to allow transfer.")),n.hint&&(d(),console.log(` ${Ut.default.dim(n.hint)}`)),n.next_steps?.length){d();for(let r of n.next_steps)console.log(` ${Ut.default.dim("\u2192")} ${Ut.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 gt=U(L(),1);W();pe();ze();var _d={none:gt.default.dim,pending:gt.default.yellow,approved:gt.default.yellow,completed:gt.default.green,rejected:gt.default.red,expired:gt.default.red};async function yo(e,t){e||(e=await fe()),K(e,t);let i=S(!t.json);i.start(`Checking transfer status for ${b.domain(e)}`);let s=await j(`/api/domains/${encodeURIComponent(e)}/transfer-away`),n=await s.json();if(s.ok||(i.stop("Failed"),f(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),i.stop(`${$.success} ${b.domain(e)}`),t.json){k(n,t.fields);return}C("Transfer Away Status"),c("Domain",b.domain(n.domain));let r=_d[n.status]||gt.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(` ${gt.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 zi=U(L(),1);W();async function bo(e,t){return e==="set"?jd(t):xd(t)}async function xd(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"),f(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),t.stop(`${$.success} Contact info`),e.json){k(s,e.fields);return}if(C("Contact Info"),!s.has_contact){console.log(` ${$.warning} ${zi.default.yellow("No contact info set.")} Run ${zi.default.bold("domani contact set")} to add.`),d(),console.log(` ${zi.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 jd(e){let t={},i=e.firstName||e.lastName||e.address1;if(!xe&&!i&&f("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"},u=a.filter(m=>!e[m]);u.length>0&&f(`Missing required flags: ${u.map(m=>`--${m.replace(/[A-Z]/g,g=>`-${g.toLowerCase()}`)}`).join(", ")}`,{code:"missing_argument",json:e.json});for(let[m,g]of Object.entries(l)){let y=e[m];y&&(t[g]=y)}}else{let a=await j("/api/me/contact"),u=(a.ok?await a.json():null)?.contact,m=[{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 m){let y=u?.[g.key]||"",w=await Re({message:g.message,placeholder:g.placeholder,defaultValue:y,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"),f(r.error||r.message,{hint:r.hint,status:n.status,json:e.json,fields:e.fields})),s.stop(`${$.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 Ae=U(L(),1);W();pe();ze();async function vo(e,t,i,s){if(e||(e=await fe()),K(e,s),!t)return Sd(e,s.json,s.fields);switch(t){case"enable":case"on":return s.dryRun?B("parking_enable",{domain:e},s.json,s.fields):$o(e,!0,s.json,s.fields);case"disable":case"off":return s.dryRun?B("parking_disable",{domain:e},s.json,s.fields):$o(e,!1,s.json,s.fields);case"price":{i||f("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)&&f("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):wo(e,n,s.json,s.fields)}case"unprice":case"unlist":return s.dryRun?B("parking_unlist",{domain:e},s.json,s.fields):wo(e,null,s.json,s.fields);default:f(`Unknown action: ${t}`,{hint:"Actions: enable, disable, price <amount>, unprice",code:"validation_error",json:s.json,fields:s.fields})}}async function Sd(e,t,i){let s=S(!t);s.start(`Loading ${b.domain(e)}`);let n=await j(`/api/domains/${encodeURIComponent(e)}`),r=await n.json();if(n.ok||(s.stop("Failed"),f(r.error||r.message,{hint:r.hint,status:n.status,json:t,fields:i})),s.stop(`${$.success} ${b.domain(e)}`),t){k({domain:r.domain,parking_enabled:r.parking_enabled,listing_price:r.listing_price},i);return}C("Parking"),c("Domain",b.domain(r.domain)),c("Parking",r.parking_enabled?Ae.default.green("enabled"):Ae.default.dim("disabled")),c("Listing",r.listing_price?`${b.price(r.listing_price)} ${Ae.default.dim("(for sale)")}`:Ae.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 $o(e,t,i,s){let n=S(!i);n.start(`${t?"Enabling":"Disabling"} parking for ${b.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(`${$.warning} DNS records will be replaced`),i){k(o,s);return}console.log(`
195
- ${Ae.default.yellow("Enabling parking will replace these DNS records:")}`);for(let a of o.existing_dns||[])console.log(` ${Ae.default.dim(a.type)} ${a.name} ${Ae.default.dim("\u2192")} ${a.value}`);console.log(`
196
- ${Ae.default.dim("Run again with --confirm to proceed (not implemented yet).")}`),console.log(` ${Ae.default.dim("Or use the dashboard to confirm.")}`),d();return}if(r.ok||(n.stop("Failed"),f(o.error||o.message,{hint:o.hint,status:r.status,json:i,fields:s})),n.stop(`${$.success} Parking ${t?"enabled":"disabled"}`),i){k(o,s);return}C("Parking Updated"),c("Domain",b.domain(o.domain)),c("Parking",o.parking_enabled?Ae.default.green("enabled"):Ae.default.dim("disabled")),o.hint&&c("",Ae.default.dim(o.hint)),d()}async function wo(e,t,i,s){let n=S(!i);n.start(t!==null?`Setting price for ${b.domain(e)} to ${b.price(t)}`:`Removing listing for ${b.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"),f(o.error||o.message,{hint:o.hint,status:r.status,json:i,fields:s})),n.stop(`${$.success} ${t!==null?"Price set":"Listing removed"}`),i){k(o,s);return}C("Listing Updated"),c("Domain",b.domain(o.domain)),c("Listing",o.listing_price?`${b.price(o.listing_price)} ${Ae.default.dim("(for sale)")}`:Ae.default.dim("not listed")),o.hint&&c("",Ae.default.dim(o.hint)),d()}X();var He=U(L(),1);W();pe();ze();var Cd=" \u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588";function Od(e){let t=Math.max(...e,1);return e.map(i=>Cd[Math.min(Math.round(i/t*8),8)]).join("")}async function ko(e,t){e||(e=await fe()),K(e,t);let i=S(!t.json);i.start(`Loading analytics for ${b.domain(e)}`);let s=await j(`/api/domains/${encodeURIComponent(e)}/analytics`),n=await s.json();if(s.ok||(i.stop("Failed"),f(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: ${b.domain(e)}`),c("Views (7d)",He.default.cyan(n.views_7d.toLocaleString())),c("Views (30d)",He.default.cyan(n.views_30d.toLocaleString())),c("Inquiries",He.default.cyan(String(n.inquiries_30d))),c("Conversion",n.conversion_rate>0?He.default.green(`${n.conversion_rate}%`):He.default.dim("0%")),n.daily_views&&n.daily_views.length>0){let r=n.daily_views.map(u=>u.views),o=Od(r),a=n.daily_views[0].date.slice(5),l=n.daily_views[n.daily_views.length-1].date.slice(5);d(),console.log(` ${He.default.dim(a)} ${He.default.cyan(o)} ${He.default.dim(l)}`)}if(n.recent_inquiries&&n.recent_inquiries.length>0){d(),console.log(` ${He.default.bold("Recent Inquiries")}`);let r=n.recent_inquiries.map(o=>[He.default.dim(o.email),o.offer?b.price(o.offer):He.default.dim("-"),He.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 ge=U(L(),1);W();async function _o(e,t){switch(e){case void 0:case"list":return Rd(t.json,t.fields);case"create":return Ad(t);case"update":return Ed(t);case"delete":return Pd(t);case"deliveries":return Dd(t);case"replay":return Id(t);case"events":return Td(t.json,t.fields);default:f(`Unknown action: ${e}`,{hint:"Actions: list, create, update, delete, deliveries, replay, events",code:"validation_error",json:t.json,fields:t.fields})}}async function Id(e){(!e.webhookId||!e.deliveryId||!e.idempotencyKey)&&f("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"),f(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),t.stop(`${$.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 Rd(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"),f(n.error||n.message,{hint:n.hint,status:s.status,json:e,fields:t})),i.stop(`${$.success} ${n.webhooks.length} webhook(s)`),e){k(n,t);return}if(n.webhooks.length===0){d(),console.log(` ${ge.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=>[ge.default.dim(o.id),b.url(o.url),o.events.length<=3?o.events.join(", "):`${o.events.length} events`,o.active?ge.default.green("active"):ge.default.dim("paused")]);se(["ID","URL","Events","Status"],r,[28,40,24,10]),d()}async function Ad(e){e.url||f("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||f("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(r=>r.trim());if(e.dryRun)return B("webhook_create",{url:e.url,events:t},e.json,e.fields);let i=S(!e.json);i.start("Creating webhook");let s=await j("/api/webhooks",{method:"POST",body:JSON.stringify({url:e.url,events:t})}),n=await s.json();if(s.ok||(i.stop("Failed"),f(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields})),i.stop(`${$.success} Webhook created`),e.json){k(n,e.fields);return}d(),C("Webhook Created"),c("ID",n.id),c("URL",b.url(n.url)),c("Events",n.events.join(", ")),c("Status",ge.default.green("active")),d(),console.log(` ${ge.default.yellow("!")} ${ge.default.bold("Secret:")} ${n.secret}`),console.log(` ${ge.default.dim("Save this secret - it won't be shown again.")}`),console.log(` ${ge.default.dim("Use it to verify payloads with HMAC-SHA256.")}`),d()}async function Ed(e){e.webhookId||f("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={};if(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"),e.dryRun)return B("webhook_update",{webhook_id:e.webhookId,...t},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"),f(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields})),i.stop(`${$.success} Webhook updated`),e.json){k(n,e.fields);return}C("Webhook Updated"),c("ID",n.id),c("URL",b.url(n.url)),c("Events",n.events.join(", ")),c("Status",n.active?ge.default.green("active"):ge.default.dim("paused")),d()}async function Pd(e){if(e.webhookId||f("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"),f(s.error||s.message,{hint:s.hint,status:i.status,json:e.json,fields:e.fields})),t.stop(`${$.success} Webhook deleted`),e.json){k(s,e.fields);return}console.log(` ${ge.default.dim("Pending deliveries have been cancelled.")}`),d()}async function Dd(e){e.webhookId||f("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"),f(n.error||n.message,{hint:n.hint,status:s.status,json:e.json,fields:e.fields})),i.stop(`${$.success} ${n.deliveries.length} delivery(ies)`),e.json){k(n,e.fields);return}if(n.deliveries.length===0){d(),console.log(` ${ge.default.dim("No deliveries yet.")}`),d();return}d(),C("Deliveries");let r=n.deliveries.map(o=>{let a=o.status==="delivered"?ge.default.green("delivered"):o.status==="failed"?ge.default.red("failed"):ge.default.yellow("pending");return[o.event_type,a,o.http_status?String(o.http_status):ge.default.dim("-"),String(o.attempts),ge.default.dim(new Date(o.created_at).toLocaleString())]});se(["Event","Status","HTTP","Tries","Date"],r,[22,12,6,6,22]),d()}async function Td(e,t){let i=S(!e);i.start("Loading event types");let s=await ye("/api/webhooks/events"),n=await s.json();if(s.ok||(i.stop("Failed"),f(n.error||n.message,{hint:n.hint,status:s.status,json:e,fields:t})),i.stop(`${$.success} ${n.events.length} event type(s)`),e){k(n,t);return}d(),C("Webhook Event Types");let r=n.events.map(o=>[ge.default.cyan(o.type),ge.default.dim(o.description)]);se(["Event","Description"],r,[24,50]),d()}X();var $e=U(L(),1);W();pe();async function xo(e,t){if(e||f("Domain is required",{hint:`Usage: domani sell <domain> --price <amount>
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+=Je,r.length<a?y=!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(at=>at.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=Je+g*Je;r.length<a&&s&&we<n.length&&(y=!0),y||E()}}}m=!1}for(await Z(e);!v;)if(await new Promise(q=>{let Y=setInterval(()=>{(v||y)&&(clearInterval(Y),q())},16)}),y&&!v){y=!1;let q=Je+g*Je,Y=n.slice(q,q+Je);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 ye(`/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?
186
+ ${T.default.dim("\u2502")} ${T.default.bold(T.default.cyan(F))}
187
+ ${T.default.dim("\u2514")}
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){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&&Ji(r,i),K(e,i),e.includes(".")&&r.length===0){let N=S(!i.json);N.start(`Checking ${b.domain(e)}`);let[Z,z]=await Promise.all([ye(`/api/domains/search?q=${encodeURIComponent(e)}`),ye(`/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(`${$.success} ${b.domain(F.domain)} ${$.dot} available ${$.dot} ${b.price(F.price)}/yr`),xe&&!i.json){let{buy:ie}=await Promise.resolve().then(()=>(Kt(),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(`${$.info} ${b.domain(F.domain)} ${$.dot} ${T.default.cyan("for sale")} ${$.dot} ${b.price(F.for_sale.price)}`),xe&&!i.json){let{buy:ie}=await Promise.resolve().then(()=>(Kt(),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("?")} ${b.domain(F.domain)} ${$.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?` ${$.dot} ${T.default.dim(`"${ie}"`)}`:"";N.stop(`${$.error} ${b.domain(F.domain)} ${$.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 ye(`/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(b.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(b.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(()=>(Kt(),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(),Zs)),at=await ae({message:"Register one?",options:[...G.map(te=>({value:te.domain,label:b.domain(te.domain),hint:b.price(te.price)+"/yr"})),{value:"__skip__",label:"Skip"}]});if(!we(at)&&at!=="__skip__"){d();let te=G.find(it=>it.domain===at);await de([at],{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>zt&&console.error(T.default.dim(` (--expand: checking the first ${zt} of ${N.length} TLDs - server limit per request)`));;){let Z=i.expand?N.slice(0,zt):N.slice(0,Je),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 ye(`/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 _d(ie.body,o,i.all??!1,q,N);if(Y){d();let{buy:ae}=await Promise.resolve().then(()=>(Kt(),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(),Zs)),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,zt):l.slice(0,Je);i.expand&&r.length===0&&l.length>zt&&console.error(`(--expand: checking the first ${zt} 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 y=S(!i.json);y.start(`Searching available domains for ${T.default.bold(a)}`);let v=await ye(`/api/domains/search?${g}`,{headers:{Accept:"text/event-stream"}});if(!v.ok){y.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||(y.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,y.stop(`Checking TLDs for ${T.default.bold(a)}`),d())}function M(N){R(),N.available?console.log(` ${$.success} ${b.domain(N.domain).padEnd(37)} ${b.price(N.price)}${T.default.dim("/yr")}`):N.for_sale?console.log(` ${$.info} ${b.domain(N.domain).padEnd(37)} ${T.default.cyan(b.price(N.for_sale.price))} ${T.default.dim("(for sale)")}`):N.error||console.log(` ${$.error} ${T.default.dim(N.domain.padEnd(38))} ${T.default.red("taken")}`)}function V(){_||y.message(`Checking TLDs for ${T.default.bold(a)} ${T.default.dim(`(${x} 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")y.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()}Kt();X();var ci=U(L(),1);W();he();async function lo(e,t){K(e,t);let i={domain:e};if(t.slug&&(i.slug=t.slug),t.name&&(i.name=t.name),t.webhook&&(i.webhook_url=t.webhook),t.years&&(i.years=Number(t.years)),t.paymentMethod&&(i.payment_method=t.paymentMethod),t.dryRun){B("POST /api/agents/provision",i,t.json,t.fields);return}let s=S(!t.json);s.start(`Provisioning ${b.domain(e)}`);let n=await j("/api/agents/provision",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)}),r=await n.json();if(n.ok||(s.stop("Provisioning failed"),u(r.error||"Provisioning failed",{hint:r.hint,status:n.status,json:t.json,fields:t.fields})),s.stop(`${b.domain(e)} is ready`),t.json){k(r,t.fields);return}if(d(),C("Agent identity"),c("Domain",`${r.domain} (${r.domain_status})`),c("Mailbox",r.mailbox?ci.default.green(r.mailbox.address):ci.default.yellow("pending DNS")),c("Webhook",r.webhook?r.webhook.url:ci.default.dim("none")),r.webhook?.secret&&c("Signing secret",r.webhook.secret),r.warnings?.length){d();for(let o of r.warnings)ze(ci.default.yellow(o))}if(r.next_steps?.length){d(),C("Next");for(let o of r.next_steps)ze(o)}d()}X();var pt=U(L(),1);W();async function co(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(` ${pt.default.dim("No domains yet.")} Use: ${pt.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"?pt.default.green:o.status==="pending"?pt.default.yellow:pt.default.red,m=o.autoRenew?pt.default.green("on"):pt.default.dim("off");return[b.domain(o.domain),l(o.status),m,pt.default.dim(a)]});se(["Domain","Status","Auto-renew","Expires"],r,n),d()}hn();X();var Tt=U(L(),1);W();async function uo(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 ye(`/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(` ${Tt.default.dim("No TLDs match your filters.")}`),d();return}C("TLD Pricing");let o=r.map(a=>[Tt.default.bold(`.${a.tld}`),b.price(a.registration.toFixed(2))+Tt.default.dim("/yr"),Tt.default.dim("renew ")+b.price(a.renewal.toFixed(2))+Tt.default.dim("/yr")]);se(["TLD","Register","Renewal"],o,[22,16,20]),d(),console.log(` ${Tt.default.dim(`${n.total} TLDs total`)}`),d()}X();var Se=U(L(),1);W();he();async function mo(e,t){K(e,t);let i=S(!t.json);i.start(`Looking up ${b.domain(e)}`);let[s,n]=await Promise.all([ye(`/api/domains/whois?q=${encodeURIComponent(e)}`),ye(`/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 ${b.domain(r.domain)}`),!r.registered){c("Status",`${$.success} ${Se.default.green("not registered")}`),d(),I("Register it:",`domani buy ${r.domain}`),d();return}if(c("Status",`${$.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",b.url(a.email)),a.country&&c("Country",a.country)):r.redacted&&c("Contact",Se.default.dim("redacted (WHOIS privacy)")),d()}X();De();var ht=U(L(),1);W();he();async function fo(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&&Ji(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 ye(`/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 ye(`/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 y=new TextDecoder,v="",w="";for await(let h of o){v+=y.decode(h,{stream:!0});let _=v.split(`
192
+ `);v=_.pop()??"";for(let x of _)if(x.startsWith("event: "))w=x.slice(7);else if(x.startsWith("data: "))try{let O=JSON.parse(x.slice(6));if(w==="result")f++,O.available?a.push(O):l.push(O),m||s.message(`Finding available domains ${ht.default.dim(`(${f} checked, ${a.length} available)`)}`);else if(w==="iteration")m||s.message(`Finding available domains ${ht.default.dim(`(round ${O.n})`)}`);else if(w==="done"){g();for(let R of a){let M=R.reason?` ${ht.default.dim(R.reason)}`:"";console.log(` ${$.success} ${b.domain(R.domain).padEnd(37)} ${b.price(R.price)}${ht.default.dim("/yr")}${M}`)}for(let R of l)console.log(` ${$.error} ${ht.default.dim(R.domain.padEnd(38))} ${ht.default.red("taken")}`);console.log(` ${ht.default.dim("\u2500".repeat(50))}`),console.log(` ${ht.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())}ln();yn();X();De();var Nt=U(L(),1);W();he();Zt();async function po(e,t){K(e,t);let i=S(!t.json);i.start(`Planning safe adoption for ${b.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(`${$.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(`${$.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?Nt.default.yellow("Enabled, DS will be verified"):"Not enabled"),c("DNS migration","Not requested"),d();let a=n.options.transfer.price!=null?` for ${b.price(n.options.transfer.price.toFixed(2))}`:"",l=await Ke({message:`Transfer ${Nt.default.bold(e)} to ${qt}${a}? Nameservers stay unchanged and 1 year is included.`});if(!l||typeof l=="symbol"){console.log(` ${Nt.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 ${b.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(`${$.success} Transfer initiated`),t.json){k(o,t.fields);return}C("Transfer Initiated"),c("Domain",b.domain(o.domain)),c("Status",Nt.default.yellow(o.status||"pending")),o.price&&c("Price",b.price(o.price)+Nt.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(` ${Nt.default.dim(o.hint)}`)),d(),I("Check transfer progress:",`domani status ${o.domain}`),d()}X();var Yi=U(L(),1);W();he();async function ho(e,t){K(e,t);let i=S(!t.json);i.start(`Inspecting ${b.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(`${$.success} Adoption plan ready`),t.json){k(n,t.fields);return}if(C(`Adopt ${b.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?Yi.default.yellow("Enabled"):"Not enabled"),c("Account",n.account_state),c("Recommended",Yi.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(` ${Yi.default.yellow("!")} ${r}`);d()}X();De();var Xi=U(L(),1);W();he();Ye();async function go(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 ${Xi.default.bold(e)} for ${i} year${i>1?"s":""}? You will be charged.`});if(!o||typeof o=="symbol"){console.log(` ${Xi.default.dim("Cancelled.")}`);return}}let s=S(!t.json);s.start(`Renewing ${b.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(`${$.success} Domain renewed`),t.json){k(r,t.fields);return}C("Renewal Complete"),c("Domain",b.domain(r.domain)),c("Years",String(r.renewed_years)),c("New expiry",new Date(r.new_expiry).toLocaleDateString()),r.price&&c("Price",b.price(r.price)+Xi.default.dim(` ${r.currency||"USD"}`)),r.payment_method&&c("Payment",r.payment_method),d(),I("Verify renewal:",`domani status ${r.domain}`),d()}X();var rt=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 ${b.domain(e)}`:`Initiating import for ${b.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(`${$.success} ${b.domain(e)} imported!`),C("Domain Imported"),c("Domain",b.domain(r.domain)),c("Status",rt.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(`${$.success} Verification record ready`),C("Import Domain"),c("Domain",b.domain(r.domain)),c("Status",rt.default.yellow("pending verification")),d(),console.log(" Add this TXT record at your DNS provider:"),d(),console.log(` ${rt.default.dim("Type:")} ${rt.default.bold("TXT")}`),console.log(` ${rt.default.dim("Name:")} ${rt.default.bold(r.txt_record?.name||"@")}`),console.log(` ${rt.default.dim("Value:")} ${rt.default.bold(r.txt_record?.value||`domani-verify=${r.token}`)}`),d(),console.log(` ${rt.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();ut();W();function bo(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 $o(e,t){switch(e){case void 0:case"list":return xd(t.json,t.fields);case"create":return jd(t);case"revoke":return Sd(t);default:u(`Unknown action: ${e}`,{hint:"Actions: list, create, revoke",code:"validation_error",json:t.json,fields:t.fields})}}async function xd(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(`${$.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 jd(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(`${$.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 Sd(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(`${$.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 vo(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 Cd(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 ${b.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(`${$.success} Settings updated`),t.json){k(l,t.fields);return}C("Settings Updated"),c("Domain",b.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 Cd(e,t,i){let s=S(!t);s.start(`Loading ${b.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(`${$.success} ${b.domain(e)}`),t){k(r,i);return}C("Domain Settings"),c("Domain",b.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 Ut=U(L(),1);W();he();Ye();async function wo(e,t){e||(e=await fe()),K(e,t);let i=S(!t.json);i.start(`Getting auth code for ${b.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(`${$.success} Auth code retrieved`),t.json){k(n,t.fields);return}if(C("Auth Code"),c("Domain",b.domain(n.domain)),c("Auth code",Ut.default.bold(Ut.default.green(n.auth_code))),n.was_unlocked&&c("",Ut.default.yellow("Domain was automatically unlocked to allow transfer.")),n.hint&&(d(),console.log(` ${Ut.default.dim(n.hint)}`)),n.next_steps?.length){d();for(let r of n.next_steps)console.log(` ${Ut.default.dim("\u2192")} ${Ut.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 gt=U(L(),1);W();he();Ye();var Od={none:gt.default.dim,pending:gt.default.yellow,approved:gt.default.yellow,completed:gt.default.green,rejected:gt.default.red,expired:gt.default.red};async function ko(e,t){e||(e=await fe()),K(e,t);let i=S(!t.json);i.start(`Checking transfer status for ${b.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(`${$.success} ${b.domain(e)}`),t.json){k(n,t.fields);return}C("Transfer Away Status"),c("Domain",b.domain(n.domain));let r=Od[n.status]||gt.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(` ${gt.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 Zi=U(L(),1);W();async function _o(e,t){return e==="set"?Rd(t):Id(t)}async function Id(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(`${$.success} Contact info`),e.json){k(s,e.fields);return}if(C("Contact Info"),!s.has_contact){console.log(` ${$.warning} ${Zi.default.yellow("No contact info set.")} Run ${Zi.default.bold("domani contact set")} to add.`),d(),console.log(` ${Zi.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 Rd(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 y=e[f];y&&(t[g]=y)}}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 y=m?.[g.key]||"",v=await Ae({message:g.message,placeholder:g.placeholder,defaultValue:y,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 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(`${$.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 So(e,t,i,s){if(e||(e=await fe()),K(e,s),!t)return Ad(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):jo(e,n,s.json,s.fields)}case"unprice":case"unlist":return s.dryRun?B("parking_unlist",{domain:e},s.json,s.fields):jo(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 Ad(e,t,i){let s=S(!t);s.start(`Loading ${b.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(`${$.success} ${b.domain(e)}`),t){k({domain:r.domain,parking_enabled:r.parking_enabled,listing_price:r.listing_price},i);return}C("Parking"),c("Domain",b.domain(r.domain)),c("Parking",r.parking_enabled?Ee.default.green("enabled"):Ee.default.dim("disabled")),c("Listing",r.listing_price?`${b.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 ${b.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(`${$.warning} DNS records will be replaced`),i){k(o,s);return}console.log(`
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(`${$.success} Parking ${t?"enabled":"disabled"}`),i){k(o,s);return}C("Parking Updated"),c("Domain",b.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 jo(e,t,i,s){let n=S(!i);n.start(t!==null?`Setting price for ${b.domain(e)} to ${b.price(t)}`:`Removing listing for ${b.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(`${$.success} ${t!==null?"Price set":"Listing removed"}`),i){k(o,s);return}C("Listing Updated"),c("Domain",b.domain(o.domain)),c("Listing",o.listing_price?`${b.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 He=U(L(),1);W();he();Ye();var Ed=" \u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588";function Pd(e){let t=Math.max(...e,1);return e.map(i=>Ed[Math.min(Math.round(i/t*8),8)]).join("")}async function Co(e,t){e||(e=await fe()),K(e,t);let i=S(!t.json);i.start(`Loading analytics for ${b.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: ${b.domain(e)}`),c("Views (7d)",He.default.cyan(n.views_7d.toLocaleString())),c("Views (30d)",He.default.cyan(n.views_30d.toLocaleString())),c("Inquiries",He.default.cyan(String(n.inquiries_30d))),c("Conversion",n.conversion_rate>0?He.default.green(`${n.conversion_rate}%`):He.default.dim("0%")),n.daily_views&&n.daily_views.length>0){let r=n.daily_views.map(m=>m.views),o=Pd(r),a=n.daily_views[0].date.slice(5),l=n.daily_views[n.daily_views.length-1].date.slice(5);d(),console.log(` ${He.default.dim(a)} ${He.default.cyan(o)} ${He.default.dim(l)}`)}if(n.recent_inquiries&&n.recent_inquiries.length>0){d(),console.log(` ${He.default.bold("Recent Inquiries")}`);let r=n.recent_inquiries.map(o=>[He.default.dim(o.email),o.offer?b.price(o.offer):He.default.dim("-"),He.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();dn();async function Oo(e,t){switch(e){case void 0:case"list":return Td(t.json,t.fields);case"create":return Nd(t);case"update":return Ud(t);case"delete":return Fd(t);case"deliveries":return qd(t);case"replay":return Dd(t);case"events":return Md(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 Dd(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(`${$.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 Td(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(`${$.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),b.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 Nd(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=oi(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:ai(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(`${$.success} Webhook created`),e.json){k(r,e.fields);return}d(),C("Webhook Created"),c("ID",r.id),c("URL",b.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 Ud(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=oi(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:ai(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(`${$.success} Webhook updated`),e.json){k(n,e.fields);return}C("Webhook Updated"),c("ID",n.id),c("URL",b.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 Fd(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(`${$.success} Webhook deleted`),e.json){k(s,e.fields);return}console.log(` ${pe.default.dim("Pending deliveries have been cancelled.")}`),d()}async function qd(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(`${$.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 Md(e,t){let i=S(!e);i.start("Loading event types");let s=await ye("/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(`${$.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 Io(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
- domani sell <domain> --cancel`,code:"validation_error",json:t.json,fields:t.fields}),K(e,t),t.status)return Fd(e,t);if(t.verify)return Ud(e,t);if(t.cancel)return qd(e,t);if(t.transferCode)return Md(e,t.transferCode,t);if(t.price)return Nd(e,t);f("No action specified",{hint:`Usage: domani sell <domain> --price <amount>
200
+ domani sell <domain> --cancel`,code:"validation_error",json:t.json,fields:t.fields}),K(e,t),t.status)return Wd(e,t);if(t.verify)return Vd(e,t);if(t.cancel)return Jd(e,t);if(t.transferCode)return Hd(e,t.transferCode,t);if(t.price)return Ld(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 Nd(e,t){let i=parseFloat(t.price);(isNaN(i)||i<=0)&&f("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 ${b.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"),f(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(`${$.success} Listed for sale`),C("Sell Domain"),c("Domain",b.domain(o.listing?.domain||e)),c("Price",b.price(i)),c("Status",$e.default.green("active")),d(),console.log(` ${$e.default.dim("Your listing is live on the marketplace.")}`),d()):(s.stop(`${$.success} Verification record ready`),C("Sell Domain"),c("Domain",b.domain(o.listing?.domain||e)),c("Price",b.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 Ud(e,t){let i=S(!t.json);i.start(`Verifying ownership of ${b.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"),f(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(`${$.success} ${b.domain(e)} is now listed for sale!`),C("Domain Listed"),c("Domain",b.domain(n.domain||e)),c("Status",$e.default.green(n.status||"active")),n.price&&c("Price",b.price(n.price)),d(),I("Check listing status:",`domani sell ${e} --status`),I("View your deals:","domani deals"),d()}async function Fd(e,t){let i=S(!t.json);i.start(`Checking listing status for ${b.domain(e)}`);let s=await j(`/api/domains/sell/status?domain=${encodeURIComponent(e)}`),n=await s.json();if(s.ok||(i.stop("Failed"),f(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),i.stop(`${$.success} Listing status loaded`),t.json){k(n,t.fields);return}let r=n.listing;if(C("Listing Status"),c("Domain",b.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",b.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 qd(e,t){let i=S(!t.json);i.start(`Removing ${b.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"),f(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(`${$.success} ${b.domain(e)} removed from sale`),d()}async function Md(e,t,i){let s=S(!i.json);s.start(`Looking up active deal for ${b.domain(e)}`);let n=await j(`/api/deals?role=seller&domain=${encodeURIComponent(e)}&status=active`),r=await n.json();n.ok||(s.stop("Failed"),f(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"),f(`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 u=await j(`/api/deals/${encodeURIComponent(l)}`,{method:"PATCH",body:JSON.stringify({auth_code:t})}),m=await u.json();if(u.ok||(s.stop("Failed"),f(m.error||m.message,{hint:m.hint,status:u.status,json:i.json,fields:i.fields})),i.json){s.stop(""),k(m,i.fields);return}s.stop(`${$.success} Transfer code submitted for ${b.domain(e)}`),C("Transfer Code Submitted"),c("Domain",b.domain(e)),c("Deal",$e.default.dim(l)),c("Status",$e.default.green(m.status||"code_submitted")),d(),I("Track the deal:",`domani deals ${l}`),d()}X();var we=U(L(),1);W();async function jo(e,t){return e?Vd(e,t):Ld(t)}async function Ld(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"),f(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(`${$.success} ${o.length} deal(s)`),e.json){k(r,e.fields);return}if(o.length===0){d(),console.log(` ${we.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 u=l.status==="completed"?we.default.green:l.status==="active"?we.default.cyan:l.status==="cancelled"?we.default.red:we.default.yellow;return[b.domain(l.domain),b.price(l.price),u(l.status),we.default.dim(l.role||"-"),we.default.dim(new Date(l.created_at).toLocaleDateString())]});se(["Domain","Price","Status","Role","Created"],a,[28,12,14,10,14]),d()}async function Vd(e,t){let i=S(!t.json);i.start(`Loading deal ${we.default.dim(e)}`);let s=await j(`/api/deals/${encodeURIComponent(e)}`),n=await s.json();if(s.ok||(i.stop("Failed"),f(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),i.stop(`${$.success} Deal loaded`),t.json){k(n,t.fields);return}let r=n.deal||n;C("Deal Details"),c("ID",we.default.dim(r.id)),c("Domain",b.domain(r.domain)),c("Price",b.price(r.price));let o=r.status==="completed"?we.default.green:r.status==="active"?we.default.cyan:r.status==="cancelled"?we.default.red:we.default.yellow;c("Status",o(r.status)),r.role&&c("Your Role",r.role),r.buyer&&c("Buyer",we.default.dim(r.buyer)),r.seller&&c("Seller",we.default.dim(r.seller)),r.created_at&&c("Created",we.default.dim(new Date(r.created_at).toLocaleDateString())),r.updated_at&&c("Updated",we.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 u=we.default.dim(new Date(l.created_at).toLocaleString()),m=l.status==="completed"?$.success:l.status==="expired"||l.status==="refunded"?$.error:$.info;console.log(` ${m} ${u} ${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();pe();async function Oo(e,t,i){switch(e){case void 0:case"list":case"ls":return Wd(i);case"request":case"acquire":case"new":return So(t,i);case"status":case"get":return Co(t,i);case"cancel":case"rm":return Jd(t,i);default:return e.includes(".")?So(e,i):Co(e,i)}}async function So(e,t){e||f("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 ${b.domain(e)}`);let s={domain:e};if(t.maxBudget){let a=Number(t.maxBudget);(!Number.isFinite(a)||a<=0)&&f("--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"),f(r.error||r.message,{hint:r.hint,status:n.status,json:t.json,fields:t.fields}));let o=r.request||r;if(i.stop(`${$.success} Acquisition requested`),t.json)return k(r,t.fields);C("Broker request"),c("Domain",b.domain(o.domain)),c("Status",bn(o.status)),o.max_budget!=null&&c("Max budget",b.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 Wd(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"),f(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(`${$.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=>[b.domain(o.domain),bn(o.status),o.max_budget!=null?b.price(o.max_budget):Ue.default.dim("-"),Ue.default.dim(o.id)])),d()}async function Co(e,t){e||f("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"),f(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields}));let r=n.request||n;if(i.stop(`${$.success} ${b.domain(r.domain)}`),t.json)return k(n,t.fields);C("Broker request"),c("Domain",b.domain(r.domain)),c("Status",bn(r.status)),r.max_budget!=null&&c("Max budget",b.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 Jd(e,t){e||f("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"),f(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),i.stop(`${$.success} Request cancelled`),t.json)return k(n,t.fields);d()}function bn(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 he=U(L(),1);W();async function Ro(e){return e.read?Bd(e):Hd(e)}async function Hd(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"),f(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(u=>!u.read).length;if(t.stop(`${$.success} ${o.length} notification(s)${a>0?` ${$.dot} ${he.default.yellow(`${a} unread`)}`:""}`),e.json){k(r,e.fields);return}if(o.length===0){d(),console.log(` ${he.default.dim("No notifications.")}`),d();return}d(),C("Notifications");let l=o.map(u=>{let m=u.read?he.default.dim($.dot):he.default.cyan($.info),g=Gd(u.type),y=u.read?he.default.dim(u.title):he.default.white(u.title),w=u.body?u.read?he.default.dim(Io(u.body,40)):he.default.dim(Io(u.body,40)):he.default.dim("-"),v=he.default.dim(new Date(u.created_at).toLocaleDateString());return[m,g,y,w,v]});se(["","Type","Title","Body","Date"],l,[3,16,28,42,14]),d(),a>0&&(console.log(` ${he.default.dim("Mark all as read:")} ${he.default.cyan("domani notifications --read")}`),d())}async function Bd(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"),f(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(`${$.success} ${n} notification(s) marked as read`),d()}function Gd(e){let t={deal:he.default.cyan,sale:he.default.green,purchase:he.default.green,transfer:he.default.yellow,expiry:he.default.red,security:he.default.red,billing:he.default.yellow,email:he.default.blue},i=e.split(".")[0].split("_")[0];return(t[i]||he.default.dim)(e)}function Io(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}X();var _t=U(L(),1);W();async function Ao(e){let t=e.limit?Number(e.limit):20,i=await j(`/api/billing/invoices?limit=${t}`),s=await i.json();if(i.ok||f(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(` ${$.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 di=U(L(),1);W();async function Eo(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"),f(s.error||s.message,{hint:s.hint,status:i.status,json:e?.json})),s.url||(t.stop("Failed"),f("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(` ${di.default.dim("Opening browser")} ${$.arrow} ${b.url(s.url)}`),d(),We(s.url),console.log(` ${$.info} ${di.default.dim("Complete payment setup in your browser.")}`),console.log(` ${di.default.dim(" After setup, you can purchase domains with")} ${di.default.cyan("domani buy")}`),d()}X();var $n=U(L(),1);W();async function Po(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_PRO"?f("You're already on the Pro plan.",{json:e?.json}):f(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(` ${$n.default.dim("Opening browser")} ${$.arrow} ${b.url(s.url)}`),d(),We(s.url),console.log(` ${$.info} ${$n.default.dim("Complete your Pro upgrade in the browser.")}`),d()}X();var wn=U(L(),1);W();async function Do(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_PRO"?f("You're not on the Pro plan.",{json:e?.json}):f(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(` ${$.success} ${wn.default.dim("Subscription cancelled.")} Access continues until ${wn.default.cyan(n)}.`),d()}X();var tt=U(L(),1);W();pe();ze();async function To(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 Yd(e,s,i);return}await Kd(e,i)}async function Kd(e,t){let i=S(!t.json);i.start(`Fetching nameservers for ${b.domain(e)}`);let s=await j(`/api/domains/${encodeURIComponent(e)}/nameservers`),n=await s.json();if(s.ok||(i.stop("Failed"),f(n.error||n.message,{hint:n.hint,status:s.status,json:t.json,fields:t.fields})),i.stop(`Nameservers for ${b.domain(e)}`),t.json){k(n,t.fields);return}if(d(),n.nameservers.length===0)console.log(` ${$.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(` ${$.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 Yd(e,t,i){let s=S(!i.json);if(i.reset){s.start(`Fetching default nameservers for ${b.domain(e)}`);let o=await j(`/api/domains/${encodeURIComponent(e)}/nameservers`),a=await o.json();o.ok||(s.stop("Failed"),f(a.error,{hint:a.hint,status:o.status,json:i.json,fields:i.fields})),a.default_nameservers?.length||(s.stop("No defaults"),f("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&&f("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 ${b.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"),f(r.error||r.message,{hint:r.hint,status:n.status,json:i.json,fields:i.fields})),s.stop(`${$.success} Nameservers updated`),i.json){k(r,i.fields);return}d();for(let o of r.nameservers)console.log(` ${$.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 No=require("crypto"),Xi=U(require("fs"),1);ut();var ci=U(L(),1);W();function zd(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 Uo(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"),f("Could not check for updates"));let n=await s.json(),r=n.version,o=n.sha256;if(zd(r,_e)<=0){t.stop(`${$.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: ${ci.default.cyan(_e)} ${$.arrow} ${ci.default.green(r)}`);let a=S();a.start("Downloading update");let l=`${i}/cli/domani.js`,u=await fetch(l);u.ok||(a.stop("Download failed"),f(`Failed to download from ${l}`));let m=await u.text();o&&(0,No.createHash)("sha256").update(m).digest("hex")!==o&&(a.stop("Integrity check failed"),f("Downloaded file does not match expected hash - update aborted"));let g=process.argv[1];g||(a.stop("Failed"),f("Could not determine binary path"));let y=Xi.default.realpathSync(g),w=y+".tmp";Xi.default.writeFileSync(w,m,{mode:493}),Xi.default.renameSync(w,y),a.stop(`${$.success} Updated to v${r}`),d(),console.log(` ${ci.default.dim("Restart your terminal or run")} domani --version ${ci.default.dim("to verify")}`),d()}catch(s){f(`Update failed: ${s instanceof Error?s.message:String(s)}`)}}var Zi=U(require("fs"),1),Fo=U(require("path"),1),qo=U(require("os"),1);De();var ui=U(L(),1);W();async function Mo(){let e=process.argv[1],t=e?Zi.default.realpathSync(e):null,i=Fo.default.join(qo.default.homedir(),".domani");if(d(),console.log(` ${ui.default.bold("This will remove:")}`),t&&console.log(` ${$.dot} CLI binary: ${ui.default.dim(t)}`),console.log(` ${$.dot} Config dir: ${ui.default.dim(i)}`),d(),await Ke({message:"Uninstall domani?"})!==!0){console.log(` ${ui.default.dim("Cancelled.")}`);return}Zi.default.rmSync(i,{recursive:!0,force:!0}),t&&Zi.default.unlinkSync(t),d(),console.log(` ${$.success} domani uninstalled.`),d()}X();var re=U(L(),1);W();async function Vo(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 ye(n),a=await o.json();if(o.ok||(r.stop("Failed"),f(a.error||a.message,{hint:a.hint,status:o.status,json:i,fields:s})),r.stop("Schema loaded"),i){k(a,s);return}e?Zd(e,a):Xd(a.commands)}function Xd(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 Zd(e,t){if(C(`domani ${e}`),console.log(` ${t.description}`),d(),console.log(` ${b.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")}`),Qd(t.api))Lo(t.api);else for(let[i,s]of Object.entries(t.api))console.log(` ${re.default.bold(re.default.yellow(i))}`),Lo(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 Qd(e){return typeof e=="object"&&e!==null&&"method"in e&&"path"in e}function Lo(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 Wo(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"),f(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}`,u=n.charAt(0).toUpperCase()+n.slice(1);t.stop("Payment method loaded"),C("Payment method"),c("Card",`${Fe.default.bold(u)} \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 Jo(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"),f(s.error||s.message,{hint:s.hint,status:i.status,json:e?.json})),s.url||(t.stop("Failed"),f("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")} ${$.arrow} ${b.url(s.url)}`),d(),We(s.url),console.log(` ${$.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 Ho(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"),f(s.error||s.message,{hint:s.hint,status:i.status,json:e?.json})),t.stop(`${$.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 vn=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"),f(o.error||o.message,{hint:o.hint,status:r.status,json:i.json,fields:i.fields})),n.stop(`${$.success} Done`),o}async function Bo(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(` ${vn.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||f("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||f("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||f("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)&&f("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))&&f("Invalid --subject",{hint:"Use human:<id>, agent:<id>, service:<id>, token:<id>, or group:<id>",json:t.json}),(!r||!["mailbox","collection"].includes(n))&&f("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)&&f("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||f(`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)&&f("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)&&f("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||f("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)&&f("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)&&f("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)&&f("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||f("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)&&f("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)&&f("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)&&f("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||f("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)&&f("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||f("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)&&f("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)&&f("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)&&f("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)&&f("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)&&f("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(` ${vn.default.dim("Opening browser")} ${$.arrow} ${b.url(i.url)}`),We(i.url));return}if(e==="cancel"){t.id||f("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}f(`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 Go=U(require("node:readline"),1);ut();function ec(e){return(Array.isArray(e)?e:[e]).filter(i=>!!i&&typeof i=="object")}function kn(e,t,i,s){return{jsonrpc:"2.0",id:e,error:{code:t,message:i,...s?{data:s}:{}}}}function mi(e,t,i,s){let n=ec(e).filter(r=>Object.prototype.hasOwnProperty.call(r,"id")).map(r=>kn(r.id??null,t,i,s));if(n.length!==0)return Array.isArray(e)?n:n[0]}function tc(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 ic(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(m){let g=m instanceof Error?m.message:"Unknown network error",y=mi(e,-32002,"Domani MCP is unreachable",{code:"MCP_NETWORK_ERROR",hint:`Check your connection and that ${n} is reachable.`,detail:g});return y===void 0?[]:[y]}if(a.status===401){let m=t.refreshAuthToken?t.refreshAuthToken():t.getAuthToken?void 0:Me({refreshKeychain:!0});if(m&&m!==s){await a.body?.cancel(),s=m,r.Authorization=`Bearer ${s}`;try{a=await o()}catch(g){let y=g instanceof Error?g.message:"Unknown network error",w=mi(e,-32002,"Domani MCP is unreachable",{code:"MCP_NETWORK_ERROR",hint:`Check your connection and that ${n} is reachable.`,detail:y});return w===void 0?[]:[w]}}}if(a.status===202||a.status===204)return[];let l=await a.text();if(a.status===401){let m=mi(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 m===void 0?[]:[m]}if(!a.ok){let m=mi(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 m===void 0?[]:[m]}if(!l.trim())return[];if((a.headers.get("content-type")??"").includes("text/event-stream"))return tc(l);try{return[JSON.parse(l)]}catch{let m=mi(e,-32700,"Domani MCP returned invalid JSON",{code:"MCP_INVALID_RESPONSE"});return m===void 0?[]:[m]}}async function Ko(e={}){let t=e.stderr??process.stderr,i=Go.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(kn(null,-32700,"Parse error"))}
207
- `);return}let a=await ic(o,e);for(let l of a)process.stdout.write(`${JSON.stringify(l)}
204
+ domani sell <domain> --transfer-code <code>`,code:"validation_error",json:t.json,fields:t.fields})}async function Ld(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 ${b.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(`${$.success} Listed for sale`),C("Sell Domain"),c("Domain",b.domain(o.listing?.domain||e)),c("Price",b.price(i)),c("Status",$e.default.green("active")),d(),console.log(` ${$e.default.dim("Your listing is live on the marketplace.")}`),d()):(s.stop(`${$.success} Verification record ready`),C("Sell Domain"),c("Domain",b.domain(o.listing?.domain||e)),c("Price",b.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 Vd(e,t){let i=S(!t.json);i.start(`Verifying ownership of ${b.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(`${$.success} ${b.domain(e)} is now listed for sale!`),C("Domain Listed"),c("Domain",b.domain(n.domain||e)),c("Status",$e.default.green(n.status||"active")),n.price&&c("Price",b.price(n.price)),d(),I("Check listing status:",`domani sell ${e} --status`),I("View your deals:","domani deals"),d()}async function Wd(e,t){let i=S(!t.json);i.start(`Checking listing status for ${b.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(`${$.success} Listing status loaded`),t.json){k(n,t.fields);return}let r=n.listing;if(C("Listing Status"),c("Domain",b.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",b.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 Jd(e,t){let i=S(!t.json);i.start(`Removing ${b.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(`${$.success} ${b.domain(e)} removed from sale`),d()}async function Hd(e,t,i){let s=S(!i.json);s.start(`Looking up active deal for ${b.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(`${$.success} Transfer code submitted for ${b.domain(e)}`),C("Transfer Code Submitted"),c("Domain",b.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 Ro(e,t){return e?Gd(e,t):Bd(t)}async function Bd(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(`${$.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[b.domain(l.domain),b.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 Gd(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(`${$.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",b.domain(r.domain)),c("Price",b.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"?$.success:l.status==="expired"||l.status==="refunded"?$.error:$.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 Po(e,t,i){switch(e){case void 0:case"list":case"ls":return Kd(i);case"request":case"acquire":case"new":return Ao(t,i);case"status":case"get":return Eo(t,i);case"cancel":case"rm":return zd(t,i);default:return e.includes(".")?Ao(e,i):Eo(e,i)}}async function Ao(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 ${b.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(`${$.success} Acquisition requested`),t.json)return k(r,t.fields);C("Broker request"),c("Domain",b.domain(o.domain)),c("Status",wn(o.status)),o.max_budget!=null&&c("Max budget",b.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 Kd(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(`${$.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=>[b.domain(o.domain),wn(o.status),o.max_budget!=null?b.price(o.max_budget):Ue.default.dim("-"),Ue.default.dim(o.id)])),d()}async function Eo(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(`${$.success} ${b.domain(r.domain)}`),t.json)return k(n,t.fields);C("Broker request"),c("Domain",b.domain(r.domain)),c("Status",wn(r.status)),r.max_budget!=null&&c("Max budget",b.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(`${$.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 To(e){return e.read?Xd(e):Yd(e)}async function Yd(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(`${$.success} ${o.length} notification(s)${a>0?` ${$.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($.dot):ge.default.cyan($.info),g=Zd(m.type),y=m.read?ge.default.dim(m.title):ge.default.white(m.title),v=m.body?m.read?ge.default.dim(Do(m.body,40)):ge.default.dim(Do(m.body,40)):ge.default.dim("-"),w=ge.default.dim(new Date(m.created_at).toLocaleDateString());return[f,g,y,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 Xd(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(`${$.success} ${n} notification(s) marked as read`),d()}function Zd(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 Do(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}X();var _t=U(L(),1);W();async function No(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(` ${$.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 Uo(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")} ${$.arrow} ${b.url(s.url)}`),d(),We(s.url),console.log(` ${$.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 Fo(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")} ${$.arrow} ${b.url(s.url)}`),d(),We(s.url),console.log(` ${$.info} ${kn.default.dim("Complete your plan upgrade in the browser.")}`),d()}X();var _n=U(L(),1);W();async function qo(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(` ${$.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 Mo(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 ec(e,s,i);return}await Qd(e,i)}async function Qd(e,t){let i=S(!t.json);i.start(`Fetching nameservers for ${b.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 ${b.domain(e)}`),t.json){k(n,t.fields);return}if(d(),n.nameservers.length===0)console.log(` ${$.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(` ${$.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 ec(e,t,i){let s=S(!i.json);if(i.reset){s.start(`Fetching default nameservers for ${b.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 ${b.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(`${$.success} Nameservers updated`),i.json){k(r,i.fields);return}d();for(let o of r.nameservers)console.log(` ${$.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 Lo=require("crypto"),Qi=U(require("fs"),1);ut();var mi=U(L(),1);W();function tc(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 Vo(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(tc(r,_e)<=0){t.stop(`${$.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)} ${$.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,Lo.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 y=Qi.default.realpathSync(g),v=y+".tmp";Qi.default.writeFileSync(v,f,{mode:493}),Qi.default.renameSync(v,y),a.stop(`${$.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 es=U(require("fs"),1),Wo=U(require("path"),1),Jo=U(require("os"),1);De();var fi=U(L(),1);W();async function Ho(){let e=process.argv[1],t=e?es.default.realpathSync(e):null,i=Wo.default.join(Jo.default.homedir(),".domani");if(d(),console.log(` ${fi.default.bold("This will remove:")}`),t&&console.log(` ${$.dot} CLI binary: ${fi.default.dim(t)}`),console.log(` ${$.dot} Config dir: ${fi.default.dim(i)}`),d(),await Ke({message:"Uninstall domani?"})!==!0){console.log(` ${fi.default.dim("Cancelled.")}`);return}es.default.rmSync(i,{recursive:!0,force:!0}),t&&es.default.unlinkSync(t),d(),console.log(` ${$.success} domani uninstalled.`),d()}X();var re=U(L(),1);W();async function Go(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 ye(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?sc(e,a):ic(a.commands)}function ic(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 sc(e,t){if(C(`domani ${e}`),console.log(` ${t.description}`),d(),console.log(` ${b.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")}`),nc(t.api))Bo(t.api);else for(let[i,s]of Object.entries(t.api))console.log(` ${re.default.bold(re.default.yellow(i))}`),Bo(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 nc(e){return typeof e=="object"&&e!==null&&"method"in e&&"path"in e}function Bo(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 Ko(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 zo(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")} ${$.arrow} ${b.url(s.url)}`),d(),We(s.url),console.log(` ${$.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 Yo(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(`${$.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(`${$.success} Done`),o}async function Xo(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")} ${$.arrow} ${b.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 Zo=U(require("node:readline"),1);ut();function rc(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=rc(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 oc(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 ac(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",y=pi(e,-32002,"Domani MCP is unreachable",{code:"MCP_NETWORK_ERROR",hint:`Check your connection and that ${n} is reachable.`,detail:g});return y===void 0?[]:[y]}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 y=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:y});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 oc(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 Qo(e={}){let t=e.stderr??process.stderr,i=Zo.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
+ `);return}let a=await ac(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(kn(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 J=new Nn;J.name("domani").description(`Domain names for developers and AI agents - ${qt}`).version(_e).option("--api-url <url>","Override API base URL").configureOutput({outputError:(e,t)=>{let i=e.replace(/^error:\s*/i,"").trimEnd();if(t(`${ot.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 J=new qn;J.name("domani").description(`Domain names for developers and AI agents - ${qt}`).version(_e).option("--api-url <url>","Override API base URL").configureOutput({outputError:(e,t)=>{let i=e.replace(/^error:\s*/i,"").trimEnd();if(t(`${ot.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(`${ot.default.dim(` Run \`${n}\` to see available options.`)}
212
- `)}}}).hook("preAction",async(e,t)=>{let i=e.opts();i.apiUrl&&Gn(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 Tr()});J.command("login").description(`Log in to ${qt} (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)").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()});J.command("login").description(`Log in to ${qt} (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)").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
216
  domani login --json # non-interactive (returns auth_url)
217
217
  domani login --no-open # print login URL without opening browser
218
- DOMANI_API_KEY=domani_sk_xxx domani list # skip login, use env var`).action(Nr);J.command("logout").description("Clear saved credentials").option("--yes","Skip confirmation").option("--json","Output as JSON").action(Ur);J.command("me").description("Show account info").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
218
+ DOMANI_API_KEY=domani_sk_xxx domani list # skip login, use env var`).action(Lr);J.command("logout").description("Clear saved credentials").option("--yes","Skip confirmation").option("--json","Output as JSON").action(Vr);J.command("me").description("Show account info").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
219
219
  Examples:
220
220
  domani me # show account overview
221
221
  domani me --json # machine-readable account info
222
- domani me --json --fields email,plan # just email and plan`).action(qr);J.command("invoices").description("List payment invoices").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").option("--limit <n>","Max invoices to show (default 20)").action(Ao);J.command("card [action]").description("Manage payment methods (list, add, remove)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").option("--yes","Skip confirmation prompt (for remove)").action(async(e,t)=>{if(!e||e==="list")return Wo(t);if(e==="add")return Jo(t);if(e==="remove")return Ho(t);f(`Unknown action: ${e}`,{hint:"Use: domani card list, domani card add, or domani card remove"})});J.command("upgrade").description("Upgrade to Pro: 10,000 emails/month, unlimited mailboxes, API/MCP/CLI access").option("--json","Output as JSON (returns checkout URL)").action(Po);J.command("cancel").description("Cancel Pro subscription (access continues until end of billing period)").option("--json","Output as JSON").action(Do);J.command("billing",{hidden:!0}).option("--json","Output as JSON (returns checkout URL)").action(Eo);J.command("token").description("Print your API key (masked on a terminal; --reveal for the full key)").option("--json","Output as JSON").option("--reveal","Print the full key even on an interactive terminal").action(fo);J.command("mcp [action]").description("Run the secure local MCP bridge (stdio)").option("--verbose","Write bridge lifecycle messages to stderr").addHelpText("after",`
222
+ domani me --json --fields email,plan # just email and plan`).action(Jr);J.command("invoices").description("List payment invoices").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").option("--limit <n>","Max invoices to show (default 20)").action(No);J.command("card [action]").description("Manage payment methods (list, add, remove)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").option("--yes","Skip confirmation prompt (for remove)").action(async(e,t)=>{if(!e||e==="list")return Ko(t);if(e==="add")return zo(t);if(e==="remove")return Yo(t);u(`Unknown action: ${e}`,{hint:"Use: domani card list, domani card add, or domani card remove"})});J.command("upgrade").description("Upgrade to Agent ($19/month)").option("--json","Output as JSON (returns checkout URL)").action(Fo);J.command("cancel").description("Cancel your paid subscription (access continues until end of billing period)").option("--json","Output as JSON").action(qo);J.command("billing",{hidden:!0}).option("--json","Output as JSON (returns checkout URL)").action(Uo);J.command("token").description("Print your API key (masked on a terminal; --reveal for the full key)").option("--json","Output as JSON").option("--reveal","Print the full key even on an interactive terminal").action(bo);J.command("mcp [action]").description("Run the secure local MCP bridge (stdio)").option("--verbose","Write bridge lifecycle messages to stderr").addHelpText("after",`
223
223
  Examples:
224
224
  domani login # authenticate once in your browser
225
225
  domani mcp serve # stdio bridge for agent plugins
226
226
 
227
227
  The bridge reads the API token from the OS keychain. It never prints the token
228
- or places it in an MCP/plugin configuration file.`).action(async(e,t)=>{if(e&&e!=="serve"){f(`Unknown action: ${e}`,{hint:"Use: domani mcp serve"});return}await Ko({verbose:t.verbose})});J.command("tokens [action]").description("Manage API tokens (list/create/revoke)").option("--name <name>","Token name (for create)").option("--scopes <scopes>","Comma-separated permission scopes (for create)").option("--expires-in <seconds>","Token lifetime in seconds (for create, min 3600)").option("--agent-identity <id>","Bind this token to an owned agent identity").option("--token-id <id>","Token ID (for revoke)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
228
+ or places it in an MCP/plugin configuration file.`).action(async(e,t)=>{if(e&&e!=="serve"){u(`Unknown action: ${e}`,{hint:"Use: domani mcp serve"});return}await Qo({verbose:t.verbose})});J.command("tokens [action]").description("Manage API tokens (list/create/revoke)").option("--name <name>","Token name (for create)").option("--scopes <scopes>","Comma-separated permission scopes (for create)").option("--expires-in <seconds>","Token lifetime in seconds (for create, min 3600)").option("--agent-identity <id>","Bind this token to an owned agent identity").option("--token-id <id>","Token ID (for revoke)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
229
229
  Examples:
230
230
  domani tokens list # list all tokens
231
231
  domani tokens create --name "CI" --scopes "domains:read,search"
232
232
  domani tokens create --name "Support agent" --agent-identity agent_abc123
233
- domani tokens revoke --token-id tok_abc123`).action(po);J.command("search [domain] [tlds...]").description("Check availability - domani search myapp .io .fm .xyz").option("--tlds <tlds>","Comma-separated TLDs (e.g. com,io,dev)").option("--max-price <price>","Maximum price filter").option("--all","Show taken domains too").option("--expand","Check 30+ TLDs including creative/exotic extensions").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
233
+ domani tokens revoke --token-id tok_abc123`).action($o);J.command("search [domain] [tlds...]").description("Check availability - domani search myapp .io .fm .xyz").option("--tlds <tlds>","Comma-separated TLDs (e.g. com,io,dev)").option("--max-price <price>","Maximum price filter").option("--all","Show taken domains too").option("--expand","Check 30+ TLDs including creative/exotic extensions").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
234
234
  Examples:
235
235
  domani search myapp # check popular TLDs
236
236
  domani search myapp .io .fm .xyz # specific TLDs
237
237
  domani search myapp --expand # check 30+ TLDs
238
238
  domani search myapp --max-price 20 # only affordable options
239
- domani search myapp --json # machine-readable output`).action(io);J.command("tlds").description("List all TLDs with pricing").option("--max-price <price>","Maximum registration price").option("--min-price <price>","Minimum registration price").option("--sort <field>","Sort by: price, tld, renewal (default: tld)").option("--search <term>","Filter TLDs by name").option("--limit <n>","Limit results").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(ro);J.command("whois <domain>").description("WHOIS/RDAP lookup for any domain").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(oo);J.command("suggest [prompt]").description("AI-powered domain name suggestions").option("--count <n>","Number of suggestions (1-20, default 10)").option("--tlds <tlds>","Preferred TLDs, comma-separated (e.g. com,dev,ai)").option("--style <style>","Name style: single, creative, short, brandable, keyword").option("--lang <lang>","Language inspiration: japanese, spanish, french, italian, latin, nordic, arabic, sanskrit").option("--timeout <seconds>","Request timeout in seconds (default: 60)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
239
+ domani search myapp --json # machine-readable output`).action(ao);J.command("tlds").description("List all TLDs with pricing").option("--max-price <price>","Maximum registration price").option("--min-price <price>","Minimum registration price").option("--sort <field>","Sort by: price, tld, renewal (default: tld)").option("--search <term>","Filter TLDs by name").option("--limit <n>","Limit results").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(uo);J.command("whois <domain>").description("WHOIS/RDAP lookup for any domain").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(mo);J.command("suggest [prompt]").description("AI-powered domain name suggestions").option("--count <n>","Number of suggestions (1-20, default 10)").option("--tlds <tlds>","Preferred TLDs, comma-separated (e.g. com,dev,ai)").option("--style <style>","Name style: single, creative, short, brandable, keyword").option("--lang <lang>","Language inspiration: japanese, spanish, french, italian, latin, nordic, arabic, sanskrit").option("--timeout <seconds>","Request timeout in seconds (default: 60)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
240
240
  Examples:
241
241
  domani suggest "cat sitting marketplace"
242
242
  domani suggest "AI code editor" --style creative --tlds ai,dev
243
- domani suggest "meditation app" --lang japanese --count 5`).action(ao);J.command("buy [domains...]").description("Purchase one or more domains").option("--yes","Skip confirmation prompt").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",`
243
+ domani suggest "meditation app" --lang japanese --count 5`).action(fo);J.command("buy [domains...]").description("Purchase one or more domains").option("--yes","Skip confirmation prompt").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",`
244
244
  Examples:
245
245
  domani buy myapp.dev # buy one domain
246
246
  domani buy myapp.dev myapp.com myapp.ai # buy multiple
247
247
  domani buy myapp.dev --dry-run # preview without buying
248
248
  domani buy myapp.dev --yes # skip confirmation
249
- domani buy myapp.dev --json # machine-readable output`).action(gn);J.command("provision <domain>").description("Give an agent a full identity: domain + mailbox + webhook in one call").option("--slug <slug>","Mailbox local part (e.g. 'hi' for hi@domain). Default 'hi'").option("--name <name>","Display name for outbound email").option("--webhook <url>","HTTPS URL to receive inbound email + domain events").option("--years <n>","Registration years (1-10, default 1)").option("--payment-method <method>","card, usdc, or balance").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",`
249
+ domani buy myapp.dev --json # machine-readable output`).action($n);J.command("provision <domain>").description("Give an agent a full identity: domain + mailbox + webhook in one call").option("--slug <slug>","Mailbox local part (e.g. 'hi' for hi@domain). Default 'hi'").option("--name <name>","Display name for outbound email").option("--webhook <url>","HTTPS URL to receive inbound email + domain events").option("--years <n>","Registration years (1-10, default 1)").option("--payment-method <method>","card, usdc, or balance").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",`
250
250
  Examples:
251
251
  domani provision myagent.run # domain + hi@ mailbox
252
252
  domani provision myagent.run --slug hey --name "My Agent" # custom mailbox
253
253
  domani provision myagent.run --webhook https://me.dev/inbox # + inbound webhook
254
- domani provision myagent.run --dry-run # preview`).action(so);J.command("adopt <domain>").description("Inspect an existing domain and plan the safest connection or transfer").option("--json","Output the complete machine-readable plan as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
254
+ domani provision myagent.run --dry-run # preview`).action(lo);J.command("adopt <domain>").description("Inspect an existing domain and plan the safest connection or transfer").option("--json","Output the complete machine-readable plan as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
255
255
  Examples:
256
256
  domani adopt myapp.com
257
- domani adopt myapp.com --json`).action(co);J.command("transfer <domain>").description("Transfer a domain from another registrar").option("--auth-code <code>","EPP/auth code from current registrar").option("--yes","Skip confirmation prompt").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",`
257
+ domani adopt myapp.com --json`).action(ho);J.command("transfer <domain>").description("Transfer a domain from another registrar").option("--auth-code <code>","EPP/auth code from current registrar").option("--yes","Skip confirmation prompt").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",`
258
258
  Examples:
259
259
  domani transfer myapp.com --auth-code ABC123XYZ
260
260
  domani transfer myapp.com --auth-code ABC123XYZ --dry-run
261
- domani transfer myapp.com --auth-code ABC123XYZ --yes`).action(lo);J.command("renew [domain]").description("Renew a domain").option("--years <n>","Number of years (1-10, default: 1)").option("--yes","Skip confirmation prompt").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(uo);J.command("import <domain>").description("Import a domain you own at another registrar").option("--verify","Verify DNS ownership and complete import").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
261
+ domani transfer myapp.com --auth-code ABC123XYZ --yes`).action(po);J.command("renew [domain]").description("Renew a domain").option("--years <n>","Number of years (1-10, default: 1)").option("--yes","Skip confirmation prompt").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(go);J.command("import <domain>").description("Import a domain you own at another registrar").option("--verify","Verify DNS ownership and complete import").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
262
262
  Examples:
263
263
  domani import myapp.com # start import (shows TXT record to add)
264
- domani import myapp.com --verify # verify TXT record and complete import`).action(mo);J.command("sell <domain>").description("List a domain for sale (verify ownership via TXT record)").option("--price <amount>","Sale price in USD").option("--verify","Verify DNS ownership and activate listing").option("--transfer-code <code>","Submit transfer/auth code for an active deal").option("--cancel","Remove domain from sale").option("--status","Check listing status").option("--description <text>","Listing description").option("--yes","Skip confirmation").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
264
+ domani import myapp.com --verify # verify TXT record and complete import`).action(yo);J.command("sell <domain>").description("List a domain for sale (verify ownership via TXT record)").option("--price <amount>","Sale price in USD").option("--verify","Verify DNS ownership and activate listing").option("--transfer-code <code>","Submit transfer/auth code for an active deal").option("--cancel","Remove domain from sale").option("--status","Check listing status").option("--description <text>","Listing description").option("--yes","Skip confirmation").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
265
265
  Examples:
266
266
  domani sell myapp.dev --price 5000 # list for $5,000
267
267
  domani sell myapp.dev --price 5000 --description "Great brand name"
@@ -269,16 +269,16 @@ Examples:
269
269
  domani sell external.com --verify # verify TXT record
270
270
  domani sell myapp.dev --status # check listing status
271
271
  domani sell myapp.dev --cancel # remove from sale
272
- domani sell myapp.dev --transfer-code ABC123 # provide EPP code for a deal`).action(xo);J.command("list").alias("domains").description("List your domains").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
272
+ domani sell myapp.dev --transfer-code ABC123 # provide EPP code for a deal`).action(Io);J.command("list").alias("domains").description("List your domains").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
273
273
  Examples:
274
274
  domani list # list all domains
275
275
  domani domains # alias for list
276
- domani list --json --fields domain,expires_at`).action(no);J.command("status [domain]").description("Check domain health (DNS, SSL, email, expiry)").option("--timeout <seconds>","Request timeout in seconds (default: 30)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(fn);J.command("connect [domain] [target]").description("Connect domain to a hosting/email provider").option("--provider <name>","Provider name (e.g. vercel, google-workspace)").option("--method <name>","Connection method (e.g. cname-only)").option("--list","List available providers").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",`
276
+ domani list --json --fields domain,expires_at`).action(co);J.command("status [domain]").description("Check domain health (DNS, SSL, email, expiry)").option("--timeout <seconds>","Request timeout in seconds (default: 30)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(gn);J.command("connect [domain] [target]").description("Connect domain to a hosting/email provider").option("--provider <name>","Provider name (e.g. vercel, google-workspace)").option("--method <name>","Connection method (e.g. cname-only)").option("--list","List available providers").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",`
277
277
  Examples:
278
278
  domani connect --list # list providers
279
279
  domani connect myapp.dev vercel # connect to Vercel
280
280
  domani connect myapp.dev --provider google-workspace # connect Google Workspace
281
- domani connect myapp.dev vercel --dry-run # preview DNS changes`).action(rn);J.command("email [action] [arg2]").description("Manage email: inbox lifecycle, mailboxes, send, forwarding, webhooks and setup").addHelpText("after",`
281
+ domani connect myapp.dev vercel --dry-run # preview DNS changes`).action(an);J.command("email [action] [arg2]").description("Manage email: inbox lifecycle, mailboxes, send, forwarding, webhooks and setup").addHelpText("after",`
282
282
  Examples:
283
283
  domani email list # list all mailboxes
284
284
  domani email create --domain myapp.dev --slug hi # create hi@myapp.dev
@@ -286,9 +286,10 @@ Examples:
286
286
  domani email folders hi@myapp.dev # folder counts
287
287
  domani email archive hi@myapp.dev --message-ids m1,m2
288
288
  domani email send --from hi@myapp.dev --to bob@x.com --subject "Hello" --text "Hi Bob"
289
+ domani email webhook hi@myapp.dev --url https://example.com/hook --authorization-env CURSOR_AUTH
289
290
  domani email setup myapp.dev # setup email for domain
290
291
  domani email status myapp.dev # check email DNS health
291
- domani email delete --domain myapp.dev --slug hi # delete mailbox`).option("--domain <domain>","Domain name").option("--slug <slug>","Mailbox slug (local part before @)").option("--from <email>","Sender address user@domain (alternative to --domain + --slug)").option("--to <email>","Recipient email address (for send)").option("--cc <emails>","CC recipients, comma-separated (for send)").option("--bcc <emails>","BCC recipients, comma-separated (for send)").option("--subject <s>","Email subject (for send)").option("--title <s>","Email subject (alias for --subject)").option("--text <t>","Email body text (for send)").option("--body <t>","Email body text (alias for --text)").option("--in-reply-to <message-id>","Message-ID of email being replied to (for threading)").option("--references <message-ids>","Space-separated Message-ID chain (for threading)").option("--url <url>","Webhook URL (for webhook)").option("--forward-to <email>","Email address to forward inbound emails to (for forward)").option("--direction <dir>","Filter messages: in or out").option("--folder <folder>","System folder: inbox, archive, sent, spam, trash").option("--view <view>","Virtual view: starred or all").option("--message-ids <ids>","Comma-separated message IDs for lifecycle actions").option("--mailbox-ids <ids>","Comma-separated mailbox IDs for shared inbox work").option("--workspace <id>","Create the mailbox inside this workspace (owner-only)").option("--thread-key <key>","Stable email thread key").option("--thread-aliases <keys>","Comma-separated legacy thread keys returned by the inbox").option("--status <status>","Workflow status: open, waiting, or closed").option("--assigned <filter>","Assignment filter: mine, unassigned, or all").option("--assignee-type <type>","Assignee type: member, token, or agent").option("--assignee-id <id>","Assignee ID").option("--conversation-id <id>","Conversation state ID").option("--note <text>","Private note text").option("--if-version <number>","Conversation version for compare-and-set updates").option("--idempotency-key <key>","Stable retry key for mailbox lifecycle actions").option("--client-id <id>","Stable opaque ID for this app installation or agent process").option("--lease-id <id>","Compose lease returned by a presence heartbeat").option("--mode <mode>","Presence mode: viewing or composing").option("--no-acquire-lease","Advertise composing presence without acquiring the primary lease").option("--limit <n>","Limit results").option("--cursor <cursor>","Opaque pagination or synchronization cursor").option("--check","Verify email DNS health (MX, SPF, DKIM, DMARC)").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(oi);J.command("workspace [action]").description("Manage shared workspaces, members, and mailbox access").option("--id <id>","Workspace ID").option("--name <name>","Workspace name").option("--email <email>","Collaborator email").option("--role <role>","Workspace role: admin or member").option("--mailboxes <ids>","Comma-separated mailbox IDs").option("--mailbox-role <role>","Mailbox role: viewer, responder, or manager").option("--token <token>","Invitation token").option("--membership-id <id>","Target workspace membership ID").option("--invitation-id <id>","Pending workspace invitation ID").option("--transfer-id <id>","Pending ownership transfer ID").option("--mailbox-id <id>","Mailbox ID to adopt into the workspace").option("--subject <type:id>","Access subject: human:id, agent:id, token:id, service:id, or group:id").option("--resource <type:id>","Access resource: mailbox:id or collection:id").option("--profile <profile>","Access profile: viewer, responder, manager, draft_only, or mail_client").option("--principals <principals>","Comma-separated group principals as type:id").option("--group-id <id>","Existing access group ID to replace").option("--collection-id <id>","Existing mailbox collection ID to replace").option("--grant-id <id>","Canonical access grant ID").option("--apply","Apply an access plan; the default is dry-run").option("--expected-version <n>","Expected grant version for conflict-safe reconciliation").option("--ownership-disposition <mode>","Offer ownership: unchanged or claim").option("--creator-disposition <mode>","After ownership claim: stay, stay_admin, or leave").option("--billing-disposition <mode>","Billing after offer: unchanged, sponsor, or transfer").option("--plan <plan>","Mailzero plan: mail_solo, mail_team, or mail_business").option("--no-open","Do not open checkout in a browser").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
292
+ domani email delete --domain myapp.dev --slug hi # delete mailbox`).option("--domain <domain>","Domain name").option("--slug <slug>","Mailbox slug (local part before @)").option("--from <email>","Sender address user@domain (alternative to --domain + --slug)").option("--to <email>","Recipient email address (for send)").option("--cc <emails>","CC recipients, comma-separated (for send)").option("--bcc <emails>","BCC recipients, comma-separated (for send)").option("--subject <s>","Email subject (for send)").option("--title <s>","Email subject (alias for --subject)").option("--text <t>","Email body text (for send)").option("--body <t>","Email body text (alias for --text)").option("--in-reply-to <message-id>","Message-ID of email being replied to (for threading)").option("--references <message-ids>","Space-separated Message-ID chain (for threading)").option("--url <url>","Webhook URL (for webhook)").option("--authorization-env <name>","Read the webhook Authorization value from this environment variable").option("--api-key-env <name>","Read the webhook X-API-Key value from this environment variable").option("--clear-headers","Clear custom webhook auth headers (requires --url)").option("--forward-to <email>","Email address to forward inbound emails to (for forward)").option("--direction <dir>","Filter messages: in or out").option("--folder <folder>","System folder: inbox, archive, sent, spam, trash").option("--view <view>","Virtual view: starred or all").option("--message-ids <ids>","Comma-separated message IDs for lifecycle actions").option("--mailbox-ids <ids>","Comma-separated mailbox IDs for shared inbox work").option("--workspace <id>","Create the mailbox inside this workspace (owner-only)").option("--thread-key <key>","Stable email thread key").option("--thread-aliases <keys>","Comma-separated legacy thread keys returned by the inbox").option("--status <status>","Workflow status: open, waiting, or closed").option("--assigned <filter>","Assignment filter: mine, unassigned, or all").option("--assignee-type <type>","Assignee type: member, token, or agent").option("--assignee-id <id>","Assignee ID").option("--conversation-id <id>","Conversation state ID").option("--note <text>","Private note text").option("--if-version <number>","Conversation version for compare-and-set updates").option("--idempotency-key <key>","Stable retry key for mailbox lifecycle actions").option("--client-id <id>","Stable opaque ID for this app installation or agent process").option("--lease-id <id>","Compose lease returned by a presence heartbeat").option("--mode <mode>","Presence mode: viewing or composing").option("--no-acquire-lease","Advertise composing presence without acquiring the primary lease").option("--limit <n>","Limit results").option("--cursor <cursor>","Opaque pagination or synchronization cursor").option("--check","Verify email DNS health (MX, SPF, DKIM, DMARC)").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(li);J.command("workspace [action]").description("Manage shared workspaces, members, and mailbox access").option("--id <id>","Workspace ID").option("--name <name>","Workspace name").option("--email <email>","Collaborator email").option("--role <role>","Workspace role: admin or member").option("--mailboxes <ids>","Comma-separated mailbox IDs").option("--mailbox-role <role>","Mailbox role: viewer, responder, or manager").option("--token <token>","Invitation token").option("--membership-id <id>","Target workspace membership ID").option("--invitation-id <id>","Pending workspace invitation ID").option("--transfer-id <id>","Pending ownership transfer ID").option("--mailbox-id <id>","Mailbox ID to adopt into the workspace").option("--subject <type:id>","Access subject: human:id, agent:id, token:id, service:id, or group:id").option("--resource <type:id>","Access resource: mailbox:id or collection:id").option("--profile <profile>","Access profile: viewer, responder, manager, draft_only, or mail_client").option("--principals <principals>","Comma-separated group principals as type:id").option("--group-id <id>","Existing access group ID to replace").option("--collection-id <id>","Existing mailbox collection ID to replace").option("--grant-id <id>","Canonical access grant ID").option("--apply","Apply an access plan; the default is dry-run").option("--expected-version <n>","Expected grant version for conflict-safe reconciliation").option("--ownership-disposition <mode>","Offer ownership: unchanged or claim").option("--creator-disposition <mode>","After ownership claim: stay, stay_admin, or leave").option("--billing-disposition <mode>","Billing after offer: unchanged, sponsor, or transfer").option("--plan <plan>","Mailzero plan: mail_solo, mail_team, or mail_business").option("--no-open","Do not open checkout in a browser").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
292
293
  Examples:
293
294
  domani workspace list
294
295
  domani workspace create --name Acme
@@ -305,41 +306,43 @@ Examples:
305
306
  domani workspace transfer --id ws_123 --membership-id mem_123
306
307
  domani workspace accept-ownership --token <ownership-token>
307
308
  domani workspace adopt-mailbox --id ws_123 --mailbox-id mb_123
308
- domani workspace checkout --id ws_123 --plan mail_team`).action(Bo);J.command("dns [domain] [action] [type] [name] [value]").description("Manage DNS records (get/set/delete/snapshot/restore)").option("--type <type>","Record type: A, AAAA, CNAME, MX, TXT, NS, SRV").option("--name <name>","Record name (e.g. www, @, _dmarc)").option("--value <value>","Record value").option("--file <path>","Snapshot file path (for restore)").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",`
309
+ domani workspace checkout --id ws_123 --plan mail_team`).action(Xo);J.command("dns [domain] [action] [type] [name] [value]").description("Manage DNS records (get/set/delete/snapshot/restore)").option("--type <type>","Record type: A, AAAA, CNAME, MX, TXT, NS, SRV").option("--name <name>","Record name (e.g. www, @, _dmarc)").option("--value <value>","Record value").option("--file <path>","Snapshot file path (for restore)").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",`
309
310
  Examples:
310
311
  domani dns myapp.dev get # list all records
311
312
  domani dns myapp.dev set --type A --name @ --value 76.76.21.21 # add A record
312
313
  domani dns myapp.dev set --type CNAME --name www --value cname.vercel-dns.com
313
314
  domani dns myapp.dev delete --type A --name @
314
315
  domani dns myapp.dev snapshot # export DNS as JSON
315
- domani dns myapp.dev restore --file dns-backup.json # restore from snapshot`).action(un);J.command("nameservers [domain] [ns...]").alias("ns").description("Get or set nameservers (--reset for defaults)").option("--set <ns>","Comma-separated nameservers to set").option("--reset","Reset to registrar default nameservers").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(To);J.command("settings [domain]").description("View or update domain settings (auto-renew, WHOIS privacy, security lock)").option("--auto-renew <on|off>","Enable or disable auto-renew").option("--whois-privacy <on|off>","Enable or disable WHOIS privacy").option("--security-lock <on|off>","Lock or unlock domain transfers").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",`
316
+ domani dns myapp.dev restore --file dns-backup.json # restore from snapshot`).action(pn);J.command("nameservers [domain] [ns...]").alias("ns").description("Get or set nameservers (--reset for defaults)").option("--set <ns>","Comma-separated nameservers to set").option("--reset","Reset to registrar default nameservers").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(Mo);J.command("settings [domain]").description("View or update domain settings (auto-renew, WHOIS privacy, security lock)").option("--auto-renew <on|off>","Enable or disable auto-renew").option("--whois-privacy <on|off>","Enable or disable WHOIS privacy").option("--security-lock <on|off>","Lock or unlock domain transfers").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",`
316
317
  Examples:
317
318
  domani settings myapp.dev # view current settings
318
319
  domani settings myapp.dev --auto-renew on # enable auto-renew
319
320
  domani settings myapp.dev --whois-privacy on # enable WHOIS privacy
320
- domani settings myapp.dev --security-lock off # unlock for transfer`).action(ho);J.command("auth-code [domain]").description("Get EPP auth code to transfer domain to another registrar").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(go);J.command("transfer-away [domain]").description("Check status of an outbound domain transfer").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(yo);J.command("contact [action]").description("View or set WHOIS contact info (required for purchases)").addHelpText("after",`
321
+ domani settings myapp.dev --security-lock off # unlock for transfer`).action(vo);J.command("auth-code [domain]").description("Get EPP auth code to transfer domain to another registrar").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(wo);J.command("transfer-away [domain]").description("Check status of an outbound domain transfer").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(ko);J.command("contact [action]").description("View or set WHOIS contact info (required for purchases)").addHelpText("after",`
321
322
  Examples:
322
323
  domani contact # view current contact info
323
324
  domani contact set --first-name John --last-name Doe --address1 "123 Main St" \\
324
- --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(bo);J.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",`
325
+ --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(_o);J.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",`
325
326
  Examples:
326
327
  domani parking myapp.dev # view parking status
327
328
  domani parking myapp.dev enable # enable parking page
328
329
  domani parking myapp.dev disable # disable parking page
329
- domani parking myapp.dev price 500 # set for-sale price to $500`).action(vo);J.command("analytics [domain]").alias("stats").description("View parking analytics (views, inquiries, conversion)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(ko);J.command("webhooks [action]").alias("webhook").description("Manage webhook endpoints (list/create/update/delete/deliveries/replay/events)").addHelpText("after",`
330
+ domani parking myapp.dev price 500 # set for-sale price to $500`).action(So);J.command("analytics [domain]").alias("stats").description("View parking analytics (views, inquiries, conversion)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(Co);J.command("webhooks [action]").alias("webhook").description("Manage webhook endpoints (list/create/update/delete/deliveries/replay/events)").addHelpText("after",`
330
331
  Examples:
331
332
  domani webhooks list
332
333
  domani webhooks create --url https://example.com/hook --events domain.purchased,domain.expiring
334
+ domani webhooks create --url https://example.com/hook --events email.received --authorization-env CURSOR_AUTH
333
335
  domani webhooks update --webhook-id wh_abc --active off
336
+ domani webhooks update --webhook-id wh_abc --clear-headers
334
337
  domani webhooks delete --webhook-id wh_abc
335
338
  domani webhooks deliveries --webhook-id wh_abc
336
339
  domani webhooks replay --webhook-id wh_abc --delivery-id del_abc --idempotency-key incident-2026-07-25
337
- domani webhooks events # list available event types`).option("--url <url>","Webhook HTTPS URL").option("--events <events>","Comma-separated event types").option("--webhook-id <id>","Webhook ID (for update/delete/deliveries)").option("--delivery-id <id>","Webhook delivery ID (for replay)").option("--idempotency-key <key>","Stable idempotency key (for replay)").option("--active <on|off>","Enable or disable webhook").option("--limit <n>","Limit deliveries returned").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(_o);J.command("deals [id]").description("List marketplace deals or view deal details").option("--role <role>","Filter by role: buyer or seller").option("--status <status>","Filter by status: active, completed, or all").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
340
+ domani webhooks events # list available event types`).option("--url <url>","Webhook HTTPS URL").option("--events <events>","Comma-separated event types").option("--webhook-id <id>","Webhook ID (for update/delete/deliveries)").option("--delivery-id <id>","Webhook delivery ID (for replay)").option("--idempotency-key <key>","Stable idempotency key (for replay)").option("--active <on|off>","Enable or disable webhook").option("--authorization-env <name>","Read the webhook Authorization value from this environment variable").option("--api-key-env <name>","Read the webhook X-API-Key value from this environment variable").option("--clear-headers","Clear custom webhook auth headers").option("--limit <n>","Limit deliveries returned").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(Oo);J.command("deals [id]").description("List marketplace deals or view deal details").option("--role <role>","Filter by role: buyer or seller").option("--status <status>","Filter by status: active, completed, or all").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
338
341
  Examples:
339
342
  domani deals # list all your deals
340
343
  domani deals --role seller --status active # your active sales
341
344
  domani deals deal_abc123 # view specific deal
342
- domani deals --json # machine-readable output`).action(jo);J.command("broker [action] [arg]").description("Acquire a taken, unlisted domain (broker sources + negotiates on your behalf)").option("--max-budget <amount>","Your ceiling in USD for a request").option("--status <status>","Filter the list by status").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
345
+ domani deals --json # machine-readable output`).action(Ro);J.command("broker [action] [arg]").description("Acquire a taken, unlisted domain (broker sources + negotiates on your behalf)").option("--max-budget <amount>","Your ceiling in USD for a request").option("--status <status>","Filter the list by status").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
343
346
  Actions:
344
347
  request <domain> ask domani to acquire a taken domain (commission-only)
345
348
  list (default) list your acquisition requests
@@ -350,7 +353,7 @@ Examples:
350
353
  domani broker request dream.com --max-budget 5000
351
354
  domani broker # list your requests
352
355
  domani broker status brq_abc123
353
- domani broker cancel brq_abc123`).action((e,t,i)=>Oo(e,t,i));J.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(Ro);J.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)=>oi("send",e,t));J.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)=>oi("inbox",e,t));J.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(Vo);J.command("update").description("Update domani CLI to the latest version").option("--json","Output as JSON (check version without updating)").action(Uo);J.command("uninstall").description("Remove domani CLI and config from this machine").action(Mo);(async()=>{let e=zn();await J.parseAsync();let t=await e;t?.forced?(console.error(`
356
+ domani broker cancel brq_abc123`).action((e,t,i)=>Po(e,t,i));J.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(To);J.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));J.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));J.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(Go);J.command("update").description("Update domani CLI to the latest version").option("--json","Output as JSON (check version without updating)").action(Vo);J.command("uninstall").description("Remove domani CLI and config from this machine").action(Ho);(async()=>{let e=Qn();await J.parseAsync();let t=await e;t?.forced?(console.error(`
354
357
  ${ot.default.red("!")} CLI v${_e} is no longer supported. Run ${ot.default.bold("domani update")} to upgrade to v${t.update}
355
358
  `),process.exit(1)):t?.update&&console.error(`
356
359
  ${ot.default.yellow("!")} Update available: ${ot.default.dim(_e)} ${ot.default.dim("\u2192")} ${ot.default.green(t.update)} Run ${ot.default.bold("domani update")}