domani-cli 0.4.71 → 0.4.73

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/domani.cjs +211 -206
  2. package/package.json +1 -1
package/dist/domani.cjs CHANGED
@@ -1,226 +1,226 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var Fa=Object.create;var $s=Object.defineProperty;var La=Object.getOwnPropertyDescriptor;var Va=Object.getOwnPropertyNames;var Wa=Object.getPrototypeOf,Ha=Object.prototype.hasOwnProperty;var Te=(e,t)=>()=>(e&&(t=e(e=0)),t);var pt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),zt=(e,t)=>{for(var i in t)$s(e,i,{get:t[i],enumerable:!0})},Ja=(e,t,i,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Va(t))!Ha.call(e,n)&&n!==i&&$s(e,n,{get:()=>t[n],enumerable:!(s=La(t,n))||s.enumerable});return e};var D=(e,t,i)=>(i=e!=null?Fa(Wa(e)):{},Ja(t||!e||!e.__esModule?$s(i,"default",{value:e,enumerable:!0}):i,e));var li=pt(_s=>{var Ii=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}},ks=class extends Ii{constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};_s.CommanderError=Ii;_s.InvalidArgumentError=ks});var Ri=pt(js=>{var{InvalidArgumentError:Ba}=li(),xs=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 Ba(`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 Ga(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}js.Argument=xs;js.humanReadableArgName=Ga});var Os=pt(Cs=>{var{humanReadableArgName:Ka}=Ri(),Ss=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=>Ka(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(h,b){return i.formatItem(h,s,b,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(h=>r(i.styleArgumentTerm(i.argumentTerm(h)),i.styleArgumentDescription(i.argumentDescription(h))));l.length>0&&(o=o.concat([i.styleTitle("Arguments:"),...l,""]));let f=i.visibleOptions(t).map(h=>r(i.styleOptionTerm(i.optionTerm(h)),i.styleOptionDescription(i.optionDescription(h))));if(f.length>0&&(o=o.concat([i.styleTitle("Options:"),...f,""])),i.showGlobalOptions){let h=i.visibleGlobalOptions(t).map(b=>r(i.styleOptionTerm(i.optionTerm(b)),i.styleOptionDescription(i.optionDescription(b))));h.length>0&&(o=o.concat([i.styleTitle("Global Options:"),...h,""]))}let m=i.visibleCommands(t).map(h=>r(i.styleSubcommandTerm(i.subcommandTerm(h)),i.styleSubcommandDescription(i.subcommandDescription(h))));return m.length>0&&(o=o.concat([i.styleTitle("Commands:"),...m,""])),o.join(`
3
- `)}displayWidth(t){return Kn(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,h;return m<this.minWidthToWrap||n.preformatted(s)?h=s:h=n.boxWrap(s,m).replace(/\n/g,`
4
- `+" ".repeat(i+l)),o+a+" ".repeat(l)+h.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()],f=this.displayWidth(l[0]);a.forEach(m=>{let h=this.displayWidth(m);if(f+h<=i){l.push(m),f+=h;return}r.push(l.join(""));let b=m.trimStart();l=[b],f=this.displayWidth(b)}),r.push(l.join(""))}),r.join(`
6
- `)}};function Kn(e){let t=/\x1b\[\d*(;\d*)*m/g;return e.replace(t,"")}Cs.Help=Ss;Cs.stripColor=Kn});var Ts=pt(As=>{var{InvalidArgumentError:za}=li(),Is=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=Ya(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 za(`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?zn(this.name().replace(/^no-/,"")):zn(this.name())}is(t){return this.short===t||this.long===t}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Rs=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 zn(e){return e.split("-").reduce((t,i)=>t+i[0].toUpperCase()+i.slice(1))}function Ya(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}
2
+ "use strict";var od=Object.create;var Dn=Object.defineProperty;var ad=Object.getOwnPropertyDescriptor;var dd=Object.getOwnPropertyNames;var ld=Object.getPrototypeOf,cd=Object.prototype.hasOwnProperty;var Ie=(e,t)=>()=>(e&&(t=e(e=0)),t);var gt=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Qt=(e,t)=>{for(var i in t)Dn(e,i,{get:t[i],enumerable:!0})},ud=(e,t,i,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of dd(t))!cd.call(e,s)&&s!==i&&Dn(e,s,{get:()=>t[s],enumerable:!(n=ad(t,s))||n.enumerable});return e};var U=(e,t,i)=>(i=e!=null?od(ld(e)):{},ud(t||!e||!e.__esModule?Dn(i,"default",{value:e,enumerable:!0}):i,e));var yi=gt(Un=>{var Vi=class extends Error{constructor(t,i,n){super(n),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name,this.code=i,this.exitCode=t,this.nestedError=void 0}},Nn=class extends Vi{constructor(t){super(1,"commander.invalidArgument",t),Error.captureStackTrace(this,this.constructor),this.name=this.constructor.name}};Un.CommanderError=Vi;Un.InvalidArgumentError=Nn});var Wi=gt(Mn=>{var{InvalidArgumentError:md}=yi(),qn=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,n)=>{if(!this.argChoices.includes(i))throw new md(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(i,n):i},this}argRequired(){return this.required=!0,this}argOptional(){return this.required=!1,this}};function fd(e){let t=e.name()+(e.variadic===!0?"...":"");return e.required?"<"+t+">":"["+t+"]"}Mn.Argument=qn;Mn.humanReadableArgName=fd});var Vn=gt(Ln=>{var{humanReadableArgName:pd}=Wi(),Fn=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(s=>!s._hidden),n=t._getHelpCommand();return n&&!n._hidden&&i.push(n),this.sortSubcommands&&i.sort((s,r)=>s.name().localeCompare(r.name())),i}compareOptions(t,i){let n=s=>s.short?s.short.replace(/^-/,""):s.long.replace(/^--/,"");return n(t).localeCompare(n(i))}visibleOptions(t){let i=t.options.filter(s=>!s.hidden),n=t._getHelpOption();if(n&&!n.hidden){let s=n.short&&t._findOption(n.short),r=n.long&&t._findOption(n.long);!s&&!r?i.push(n):n.long&&!r?i.push(t.createOption(n.long,n.description)):n.short&&!s&&i.push(t.createOption(n.short,n.description))}return this.sortOptions&&i.sort(this.compareOptions),i}visibleGlobalOptions(t){if(!this.showGlobalOptions)return[];let i=[];for(let n=t.parent;n;n=n.parent){let s=n.options.filter(r=>!r.hidden);i.push(...s)}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(n=>pd(n)).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((n,s)=>Math.max(n,this.displayWidth(i.styleSubcommandTerm(i.subcommandTerm(s)))),0)}longestOptionTermLength(t,i){return i.visibleOptions(t).reduce((n,s)=>Math.max(n,this.displayWidth(i.styleOptionTerm(i.optionTerm(s)))),0)}longestGlobalOptionTermLength(t,i){return i.visibleGlobalOptions(t).reduce((n,s)=>Math.max(n,this.displayWidth(i.styleOptionTerm(i.optionTerm(s)))),0)}longestArgumentTermLength(t,i){return i.visibleArguments(t).reduce((n,s)=>Math.max(n,this.displayWidth(i.styleArgumentTerm(i.argumentTerm(s)))),0)}commandUsage(t){let i=t._name;t._aliases[0]&&(i=i+"|"+t._aliases[0]);let n="";for(let s=t.parent;s;s=s.parent)n=s.name()+" "+n;return n+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(n=>JSON.stringify(n)).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(n=>JSON.stringify(n)).join(", ")}`),t.defaultValue!==void 0&&i.push(`default: ${t.defaultValueDescription||JSON.stringify(t.defaultValue)}`),i.length>0){let n=`(${i.join(", ")})`;return t.description?`${t.description} ${n}`:n}return t.description}formatHelp(t,i){let n=i.padWidth(t,i),s=i.helpWidth??80;function r(p,y){return i.formatItem(p,n,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),s),""]));let d=i.visibleArguments(t).map(p=>r(i.styleArgumentTerm(i.argumentTerm(p)),i.styleArgumentDescription(i.argumentDescription(p))));d.length>0&&(o=o.concat([i.styleTitle("Arguments:"),...d,""]));let f=i.visibleOptions(t).map(p=>r(i.styleOptionTerm(i.optionTerm(p)),i.styleOptionDescription(i.optionDescription(p))));if(f.length>0&&(o=o.concat([i.styleTitle("Options:"),...f,""])),i.showGlobalOptions){let p=i.visibleGlobalOptions(t).map(y=>r(i.styleOptionTerm(i.optionTerm(y)),i.styleOptionDescription(i.optionDescription(y))));p.length>0&&(o=o.concat([i.styleTitle("Global Options:"),...p,""]))}let m=i.visibleCommands(t).map(p=>r(i.styleSubcommandTerm(i.subcommandTerm(p)),i.styleSubcommandDescription(i.subcommandDescription(p))));return m.length>0&&(o=o.concat([i.styleTitle("Commands:"),...m,""])),o.join(`
3
+ `)}displayWidth(t){return ur(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,n,s){let o=" ".repeat(2);if(!n)return o+t;let a=t.padEnd(i+t.length-s.displayWidth(t)),d=2,m=(this.helpWidth??80)-i-d-2,p;return m<this.minWidthToWrap||s.preformatted(n)?p=n:p=s.boxWrap(n,m).replace(/\n/g,`
4
+ `+" ".repeat(i+d)),o+a+" ".repeat(d)+p.replace(/\n/g,`
5
+ ${o}`)}boxWrap(t,i){if(i<this.minWidthToWrap)return t;let n=t.split(/\r\n|\n/),s=/[\s]*[^\s]+/g,r=[];return n.forEach(o=>{let a=o.match(s);if(a===null){r.push("");return}let d=[a.shift()],f=this.displayWidth(d[0]);a.forEach(m=>{let p=this.displayWidth(m);if(f+p<=i){d.push(m),f+=p;return}r.push(d.join(""));let y=m.trimStart();d=[y],f=this.displayWidth(y)}),r.push(d.join(""))}),r.join(`
6
+ `)}};function ur(e){let t=/\x1b\[\d*(;\d*)*m/g;return e.replace(t,"")}Ln.Help=Fn;Ln.stripColor=ur});var Bn=gt(Jn=>{var{InvalidArgumentError:hd}=yi(),Wn=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 n=gd(t);this.short=n.shortFlag,this.long=n.longFlag,this.negate=!1,this.long&&(this.negate=this.long.startsWith("--no-")),this.defaultValue=void 0,this.defaultValueDescription=void 0,this.presetArg=void 0,this.envVar=void 0,this.parseArg=void 0,this.hidden=!1,this.argChoices=void 0,this.conflictsWith=[],this.implied=void 0}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,n)=>{if(!this.argChoices.includes(i))throw new hd(`Allowed choices are ${this.argChoices.join(", ")}.`);return this.variadic?this._concatValue(i,n):i},this}name(){return this.long?this.long.replace(/^--/,""):this.short.replace(/^-/,"")}attributeName(){return this.negate?mr(this.name().replace(/^no-/,"")):mr(this.name())}is(t){return this.short===t||this.long===t}isBoolean(){return!this.required&&!this.optional&&!this.negate}},Hn=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,n)=>{this.positiveOptions.has(n)&&this.dualOptions.add(n)})}valueFromOption(t,i){let n=i.attributeName();if(!this.dualOptions.has(n))return!0;let s=this.negativeOptions.get(n).presetArg,r=s!==void 0?s:!1;return i.negate===(r===t)}};function mr(e){return e.split("-").reduce((t,i)=>t+i[0].toUpperCase()+i.slice(1))}function gd(e){let t,i,n=/^-[^-]$/,s=/^--[^-]/,r=e.split(/[ |,]+/).concat("guard");if(n.test(r[0])&&(t=r.shift()),s.test(r[0])&&(i=r.shift()),!t&&n.test(r[0])&&(t=r.shift()),!t&&s.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
- - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):s.test(o)?new Error(`${a}
10
- - too many short flags`):n.test(o)?new Error(`${a}
9
+ - or use a double dash for a long option (and can have two, like '--ws, --workspace')`):n.test(o)?new Error(`${a}
10
+ - too many short flags`):s.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}}As.Option=Is;As.DualOptions=Rs});var Xn=pt(Yn=>{function Xa(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 Za(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=Xa(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
- (Did you mean one of ${s.join(", ")}?)`:s.length===1?`
14
- (Did you mean ${s[0]}?)`:""}Yn.suggestSimilar=Za});var tr=pt(Us=>{var Qa=require("node:events").EventEmitter,Es=require("node:child_process"),ht=require("node:path"),Ai=require("node:fs"),oe=require("node:process"),{Argument:el,humanReadableArgName:tl}=Ri(),{CommanderError:Ps}=li(),{Help:il,stripColor:sl}=Os(),{Option:Zn,DualOptions:nl}=Ts(),{suggestSimilar:Qn}=Xn(),Ds=class e extends Qa{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=>oe.stdout.write(i),writeErr:i=>oe.stderr.write(i),outputError:(i,s)=>s(i),getOutHelpWidth:()=>oe.stdout.isTTY?oe.stdout.columns:void 0,getErrHelpWidth:()=>oe.stderr.isTTY?oe.stderr.columns:void 0,getOutHasColors:()=>Ns()??(oe.stdout.isTTY&&oe.stdout.hasColors?.()),getErrHasColors:()=>Ns()??(oe.stderr.isTTY&&oe.stderr.hasColors?.()),stripColor:i=>sl(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 il,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 el(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)),oe.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 Zn(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 Zn)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,f)=>{let m=a.exec(l);return m?m[0]:f},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){oe.versions?.electron&&(i.from="electron");let n=oe.execArgv??[];(n.includes("-e")||n.includes("--eval")||n.includes("-p")||n.includes("--print"))&&(i.from="eval")}t===void 0&&(t=oe.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":oe.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(Ai.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
- - if '${s}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead
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}}Jn.Option=Wn;Jn.DualOptions=Hn});var pr=gt(fr=>{function yd(e,t){if(Math.abs(e.length-t.length)>3)return Math.max(e.length,t.length);let i=[];for(let n=0;n<=e.length;n++)i[n]=[n];for(let n=0;n<=t.length;n++)i[0][n]=n;for(let n=1;n<=t.length;n++)for(let s=1;s<=e.length;s++){let r=1;e[s-1]===t[n-1]?r=0:r=1,i[s][n]=Math.min(i[s-1][n]+1,i[s][n-1]+1,i[s-1][n-1]+r),s>1&&n>1&&e[s-1]===t[n-2]&&e[s-2]===t[n-1]&&(i[s][n]=Math.min(i[s][n],i[s-2][n-2]+1))}return i[e.length][t.length]}function bd(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 n=[],s=3,r=.4;return t.forEach(o=>{if(o.length<=1)return;let a=yd(e,o),d=Math.max(e.length,o.length);(d-a)/d>r&&(a<s?(s=a,n=[o]):a===s&&n.push(o))}),n.sort((o,a)=>o.localeCompare(a)),i&&(n=n.map(o=>`--${o}`)),n.length>1?`
13
+ (Did you mean one of ${n.join(", ")}?)`:n.length===1?`
14
+ (Did you mean ${n[0]}?)`:""}fr.suggestSimilar=bd});var br=gt(Xn=>{var wd=require("node:events").EventEmitter,Gn=require("node:child_process"),yt=require("node:path"),Hi=require("node:fs"),se=require("node:process"),{Argument:vd,humanReadableArgName:$d}=Wi(),{CommanderError:Kn}=yi(),{Help:kd,stripColor:_d}=Vn(),{Option:hr,DualOptions:xd}=Bn(),{suggestSimilar:gr}=pr(),zn=class e extends wd{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=>se.stdout.write(i),writeErr:i=>se.stderr.write(i),outputError:(i,n)=>n(i),getOutHelpWidth:()=>se.stdout.isTTY?se.stdout.columns:void 0,getErrHelpWidth:()=>se.stderr.isTTY?se.stderr.columns:void 0,getOutHasColors:()=>Yn()??(se.stdout.isTTY&&se.stdout.hasColors?.()),getErrHasColors:()=>Yn()??(se.stderr.isTTY&&se.stderr.hasColors?.()),stripColor:i=>_d(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,n){let s=i,r=n;typeof s=="object"&&s!==null&&(r=s,s=null),r=r||{};let[,o,a]=t.match(/([^ ]+) *(.*)/),d=this.createCommand(o);return s&&(d.description(s),d._executableHandler=!0),r.isDefault&&(this._defaultCommandName=d._name),d._hidden=!!(r.noHelp||r.hidden),d._executableFile=r.executableFile||null,a&&d.arguments(a),this._registerCommand(d),d.parent=this,d.copyInheritedSettings(this),s?this:d}createCommand(t){return new e(t)}createHelp(){return Object.assign(new kd,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 vd(t,i)}argument(t,i,n,s){let r=this.createArgument(t,i);return typeof n=="function"?r.default(s).argParser(n):r.default(n),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[,n,s]=t.match(/([^ ]+) *(.*)/),r=i??"display help for command",o=this.createCommand(n);return o.helpOption(!1),s&&o.arguments(s),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 n=["preSubcommand","preAction","postAction"];if(!n.includes(t))throw new Error(`Unexpected value for event passed to hook : '${t}'.
16
+ Expecting one of '${n.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,n){this._exitCallback&&this._exitCallback(new Kn(t,i,n)),se.exit(t)}action(t){let i=n=>{let s=this.registeredArguments.length,r=n.slice(0,s);return this._storeOptionsAsProperties?r[s]=this:r[s]=this.opts(),r.push(this),t.apply(this,r)};return this._actionHandler=i,this}createOption(t,i){return new hr(t,i)}_callParseArg(t,i,n,s){try{return t.parseArg(i,n)}catch(r){if(r.code==="commander.invalidArgument"){let o=`${s} ${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 n=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 '${n}'
17
+ - already used by option '${i.flags}'`)}this.options.push(t)}_registerCommand(t){let i=s=>[s.name()].concat(s.aliases()),n=i(t).find(s=>this._findCommand(s));if(n){let s=i(this._findCommand(n)).join("|"),r=i(t).join("|");throw new Error(`cannot add command '${r}' as already have command '${s}'`)}this.commands.push(t)}addOption(t){this._registerOption(t);let i=t.name(),n=t.attributeName();if(t.negate){let r=t.long.replace(/^--no-/,"--");this._findOption(r)||this.setOptionValueWithSource(n,t.defaultValue===void 0?!0:t.defaultValue,"default")}else t.defaultValue!==void 0&&this.setOptionValueWithSource(n,t.defaultValue,"default");let s=(r,o,a)=>{r==null&&t.presetArg!==void 0&&(r=t.presetArg);let d=this.getOptionValue(n);r!==null&&t.parseArg?r=this._callParseArg(t,r,d,o):r!==null&&t.variadic&&(r=t._concatValue(r,d)),r==null&&(t.negate?r=!1:t.isBoolean()||t.optional?r=!0:r=""),this.setOptionValueWithSource(n,r,a)};return this.on("option:"+i,r=>{let o=`error: option '${t.flags}' argument '${r}' is invalid.`;s(r,o,"cli")}),t.envVar&&this.on("optionEnv:"+i,r=>{let o=`error: option '${t.flags}' value '${r}' from env '${t.envVar}' is invalid.`;s(r,o,"env")}),this}_optionEx(t,i,n,s,r){if(typeof i=="object"&&i instanceof hr)throw new Error("To add an Option object use addOption() instead of option() or requiredOption()");let o=this.createOption(i,n);if(o.makeOptionMandatory(!!t.mandatory),typeof s=="function")o.default(r).argParser(s);else if(s instanceof RegExp){let a=s;s=(d,f)=>{let m=a.exec(d);return m?m[0]:f},o.default(r).argParser(s)}else o.default(s);return this.addOption(o)}option(t,i,n,s){return this._optionEx({},t,i,n,s)}requiredOption(t,i,n,s){return this._optionEx({mandatory:!0},t,i,n,s)}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,n){return this._storeOptionsAsProperties?this[t]=i:this._optionValues[t]=i,this._optionValueSources[t]=n,this}getOptionValueSource(t){return this._optionValueSources[t]}getOptionValueSourceWithGlobals(t){let i;return this._getCommandAndAncestors().forEach(n=>{n.getOptionValueSource(t)!==void 0&&(i=n.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){se.versions?.electron&&(i.from="electron");let s=se.execArgv??[];(s.includes("-e")||s.includes("--eval")||s.includes("-p")||s.includes("--print"))&&(i.from="eval")}t===void 0&&(t=se.argv),this.rawArgs=t.slice();let n;switch(i.from){case void 0:case"node":this._scriptPath=t[1],n=t.slice(2);break;case"electron":se.defaultApp?(this._scriptPath=t[1],n=t.slice(2)):n=t.slice(1);break;case"user":n=t.slice(0);break;case"eval":n=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",n}parse(t,i){this._prepareForParse();let n=this._prepareUserArgs(t,i);return this._parseCommand([],n),this}async parseAsync(t,i){this._prepareForParse();let n=this._prepareUserArgs(t,i);return await this._parseCommand([],n),this}_prepareForParse(){this._savedState===null?this.saveStateBeforeParse():this.restoreStateBeforeParse()}saveStateBeforeParse(){this._savedState={_name:this._name,_optionValues:{...this._optionValues},_optionValueSources:{...this._optionValueSources}}}restoreStateBeforeParse(){if(this._storeOptionsAsProperties)throw new Error(`Can not call parse again when storeOptionsAsProperties is true.
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,n){if(Hi.existsSync(t))return;let s=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
+ - if '${n}' 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,h){let b=ht.resolve(m,h);if(Ai.existsSync(b))return b;if(n.includes(ht.extname(h)))return;let k=n.find($=>Ai.existsSync(`${b}${$}`));if(k)return`${b}${k}`}this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let o=t._executableFile||`${this._name}-${t._name}`,a=this._executableDir||"";if(this._scriptPath){let m;try{m=Ai.realpathSync(this._scriptPath)}catch{m=this._scriptPath}a=ht.resolve(ht.dirname(m),a)}if(a){let m=r(a,o);if(!m&&!t._executableFile&&this._scriptPath){let h=ht.basename(this._scriptPath,ht.extname(this._scriptPath));h!==this._name&&(m=r(a,`${h}-${t._name}`))}o=m||o}s=n.includes(ht.extname(o));let l;oe.platform!=="win32"?s?(i.unshift(o),i=er(oe.execArgv).concat(i),l=Es.spawn(oe.argv[0],i,{stdio:"inherit"})):l=Es.spawn(o,i,{stdio:"inherit"}):(this._checkForMissingExecutable(o,a,t._name),i.unshift(o),i=er(oe.execArgv).concat(i),l=Es.spawn(oe.execPath,i,{stdio:"inherit"})),l.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(h=>{oe.on(h,()=>{l.killed===!1&&l.exitCode===null&&l.kill(h)})});let f=this._exitCallback;l.on("close",m=>{m=m??1,f?f(new Ps(m,"commander.executeSubCommandAsync","(close)")):oe.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(!f)oe.exit(1);else{let h=new Ps(1,"commander.executeSubCommandAsync","(error)");h.nestedError=m,f(h)}}),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 f=this._findOption(l);if(f){if(f.required){let m=r.shift();m===void 0&&this.optionMissingArgument(f),this.emit(`option:${f.name()}`,m)}else if(f.optional){let m=null;r.length>0&&!o(r[0])&&(m=r.shift()),this.emit(`option:${f.name()}`,m)}else this.emit(`option:${f.name()}`);a=f.variadic?f:null;continue}}if(l.length>2&&l[0]==="-"&&l[1]!=="-"){let f=this._findOption(`-${l[1]}`);if(f){f.required||f.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${f.name()}`,l.slice(2)):(this.emit(`option:${f.name()}`),r.unshift(`-${l.slice(2)}`));continue}}if(/^--[^=]+=/.test(l)){let f=l.indexOf("="),m=this._findOption(l.slice(0,f));if(m&&(m.required||m.optional)){this.emit(`option:${m.name()}`,l.slice(f+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
+ - ${s}`;throw new Error(r)}_executeSubCommand(t,i){i=i.slice();let n=!1,s=[".js",".ts",".tsx",".mjs",".cjs"];function r(m,p){let y=yt.resolve(m,p);if(Hi.existsSync(y))return y;if(s.includes(yt.extname(p)))return;let k=s.find(b=>Hi.existsSync(`${y}${b}`));if(k)return`${y}${k}`}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=yt.resolve(yt.dirname(m),a)}if(a){let m=r(a,o);if(!m&&!t._executableFile&&this._scriptPath){let p=yt.basename(this._scriptPath,yt.extname(this._scriptPath));p!==this._name&&(m=r(a,`${p}-${t._name}`))}o=m||o}n=s.includes(yt.extname(o));let d;se.platform!=="win32"?n?(i.unshift(o),i=yr(se.execArgv).concat(i),d=Gn.spawn(se.argv[0],i,{stdio:"inherit"})):d=Gn.spawn(o,i,{stdio:"inherit"}):(this._checkForMissingExecutable(o,a,t._name),i.unshift(o),i=yr(se.execArgv).concat(i),d=Gn.spawn(se.execPath,i,{stdio:"inherit"})),d.killed||["SIGUSR1","SIGUSR2","SIGTERM","SIGINT","SIGHUP"].forEach(p=>{se.on(p,()=>{d.killed===!1&&d.exitCode===null&&d.kill(p)})});let f=this._exitCallback;d.on("close",m=>{m=m??1,f?f(new Kn(m,"commander.executeSubCommandAsync","(close)")):se.exit(m)}),d.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(!f)se.exit(1);else{let p=new Kn(1,"commander.executeSubCommandAsync","(error)");p.nestedError=m,f(p)}}),this.runningCommand=d}_dispatchSubcommand(t,i,n){let s=this._findCommand(t);s||this.help({error:!0}),s._prepareForParse();let r;return r=this._chainOrCallSubCommandHook(r,s,"preSubcommand"),r=this._chainOrCall(r,()=>{if(s._executableHandler)this._executeSubCommand(s,i.concat(n));else return s._parseCommand(i,n)}),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=(n,s,r)=>{let o=s;if(s!==null&&n.parseArg){let a=`error: command-argument value '${s}' is invalid for argument '${n.name()}'.`;o=this._callParseArg(n,s,r,a)}return o};this._checkNumberOfArguments();let i=[];this.registeredArguments.forEach((n,s)=>{let r=n.defaultValue;n.variadic?s<this.args.length?(r=this.args.slice(s),n.parseArg&&(r=r.reduce((o,a)=>t(n,a,o),n.defaultValue))):r===void 0&&(r=[]):s<this.args.length&&(r=this.args[s],n.parseArg&&(r=t(n,r,n.defaultValue))),i[s]=r}),this.processedArgs=i}_chainOrCall(t,i){return t&&t.then&&typeof t.then=="function"?t.then(()=>i()):i()}_chainOrCallHooks(t,i){let n=t,s=[];return this._getCommandAndAncestors().reverse().filter(r=>r._lifeCycleHooks[i]!==void 0).forEach(r=>{r._lifeCycleHooks[i].forEach(o=>{s.push({hookedCommand:r,callback:o})})}),i==="postAction"&&s.reverse(),s.forEach(r=>{n=this._chainOrCall(n,()=>r.callback(r.hookedCommand,this))}),n}_chainOrCallSubCommandHook(t,i,n){let s=t;return this._lifeCycleHooks[n]!==void 0&&this._lifeCycleHooks[n].forEach(r=>{s=this._chainOrCall(s,()=>r(this,i))}),s}_parseCommand(t,i){let n=this.parseOptions(i);if(this._parseOptionsEnv(),this._parseOptionsImplied(),t=t.concat(n.operands),i=n.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(n.unknown),this._checkForMissingMandatoryOptions(),this._checkForConflictingOptions();let s=()=>{n.unknown.length>0&&this.unknownOption(n.unknown[0])},r=`command:${this.name()}`;if(this._actionHandler){s(),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))s(),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():(s(),this._processArguments())}else this.commands.length?(s(),this.help({error:!0})):(s(),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(n=>{let s=n.attributeName();return this.getOptionValue(s)===void 0?!1:this.getOptionValueSource(s)!=="default"});t.filter(n=>n.conflictsWith.length>0).forEach(n=>{let s=t.find(r=>n.conflictsWith.includes(r.attributeName()));s&&this._conflictingOption(n,s)})}_checkForConflictingOptions(){this._getCommandAndAncestors().forEach(t=>{t._checkForConflictingLocalOptions()})}parseOptions(t){let i=[],n=[],s=i,r=t.slice();function o(d){return d.length>1&&d[0]==="-"}let a=null;for(;r.length;){let d=r.shift();if(d==="--"){s===n&&s.push(d),s.push(...r);break}if(a&&!o(d)){this.emit(`option:${a.name()}`,d);continue}if(a=null,o(d)){let f=this._findOption(d);if(f){if(f.required){let m=r.shift();m===void 0&&this.optionMissingArgument(f),this.emit(`option:${f.name()}`,m)}else if(f.optional){let m=null;r.length>0&&!o(r[0])&&(m=r.shift()),this.emit(`option:${f.name()}`,m)}else this.emit(`option:${f.name()}`);a=f.variadic?f:null;continue}}if(d.length>2&&d[0]==="-"&&d[1]!=="-"){let f=this._findOption(`-${d[1]}`);if(f){f.required||f.optional&&this._combineFlagAndOptionalValue?this.emit(`option:${f.name()}`,d.slice(2)):(this.emit(`option:${f.name()}`),r.unshift(`-${d.slice(2)}`));continue}}if(/^--[^=]+=/.test(d)){let f=d.indexOf("="),m=this._findOption(d.slice(0,f));if(m&&(m.required||m.optional)){this.emit(`option:${m.name()}`,d.slice(f+1));continue}}if(o(d)&&(s=n),(this._enablePositionalOptions||this._passThroughOptions)&&i.length===0&&n.length===0){if(this._findCommand(d)){i.push(d),r.length>0&&n.push(...r);break}else if(this._getHelpCommand()&&d===this._getHelpCommand().name()){i.push(d),r.length>0&&i.push(...r);break}else if(this._defaultCommandName){n.push(d),r.length>0&&n.push(...r);break}}if(this._passThroughOptions){s.push(d),r.length>0&&s.push(...r);break}s.push(d)}return{operands:i,unknown:n}}opts(){if(this._storeOptionsAsProperties){let t={},i=this.options.length;for(let n=0;n<i;n++){let s=this.options[n].attributeName();t[s]=s===this._versionOptionName?this._version:this[s]}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 oe.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()}`,oe.env[t.envVar]):this.emit(`optionEnv:${t.name()}`))}})}_parseOptionsImplied(){let t=new nl(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),f=this.options.find(h=>h.negate&&a===h.attributeName()),m=this.options.find(h=>!h.negate&&a===h.attributeName());return f&&(f.presetArg===void 0&&l===!1||f.presetArg!==void 0&&l===f.presetArg)?f: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=Qn(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=Qn(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=>tl(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=ht.basename(t,ht.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(oe.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
- 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 er(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 Ns(){if(oe.env.NO_COLOR||oe.env.FORCE_COLOR==="0"||oe.env.FORCE_COLOR==="false")return!1;if(oe.env.FORCE_COLOR||oe.env.CLICOLOR_FORCE!==void 0)return!0}Us.Command=Ds;Us.useColor=Ns});var rr=pt(Ye=>{var{Argument:ir}=Ri(),{Command:qs}=tr(),{CommanderError:rl,InvalidArgumentError:sr}=li(),{Help:ol}=Os(),{Option:nr}=Ts();Ye.program=new qs;Ye.createCommand=e=>new qs(e);Ye.createOption=(e,t)=>new nr(e,t);Ye.createArgument=(e,t)=>new ir(e,t);Ye.Command=qs;Ye.Option=nr;Ye.Argument=ir;Ye.Help=ol;Ye.CommanderError=rl;Ye.InvalidArgumentError=sr;Ye.InvalidOptionArgumentError=sr});var F=pt((Zu,Ms)=>{var Ei=process||{},lr=Ei.argv||[],Ti=Ei.env||{},al=!(Ti.NO_COLOR||lr.includes("--no-color"))&&(!!Ti.FORCE_COLOR||lr.includes("--color")||Ei.platform==="win32"||(Ei.stdout||{}).isTTY&&Ti.TERM!=="dumb"||!!Ti.CI),ll=(e,t,i=e)=>s=>{let n=""+s,r=n.indexOf(t,e.length);return~r?e+dl(n,t,i,r)+t:e+n+t},dl=(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)},dr=(e=al)=>{let t=e?ll:()=>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")}};Ms.exports=dr();Ms.exports.createColors=dr});var Yt,di,ci=Te(()=>{"use strict";Yt="domani.run",di=`https://${Yt}`});function Tt(e,t,i){try{let s=(0,cr.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 ur(){return process.platform==="darwin"?!0:process.platform==="linux"?Tt("secret-tool",["--help"]).ok:!1}function mr(e={}){if(e.refresh&&(Xt=void 0),Xt!==void 0)return Xt??void 0;let t;if(process.platform==="darwin"){let i=Tt("security",["find-generic-password","-s",Zt,"-a",Qt,"-w"]);i.ok&&i.stdout&&(t=i.stdout)}else if(process.platform==="linux"){let i=Tt("secret-tool",["lookup","service",Zt,"account",Qt]);i.ok&&i.stdout&&(t=i.stdout)}return Xt=t??null,t}function fr(e){let t=!1;return process.platform==="darwin"?t=Tt("security",["add-generic-password","-U","-s",Zt,"-a",Qt,"-w",e]).ok:process.platform==="linux"&&(t=Tt("secret-tool",["store","--label=domani CLI token","service",Zt,"account",Qt],e+`
28
- `).ok),t&&(Xt=e),t}function pr(){process.platform==="darwin"?Tt("security",["delete-generic-password","-s",Zt,"-a",Qt]):process.platform==="linux"&&Tt("secret-tool",["clear","service",Zt,"account",Qt]),Xt=null}var cr,Zt,Qt,Xt,hr=Te(()=>{"use strict";cr=require("child_process"),Zt="domani-cli",Qt="default"});function br(e){yr=e}function gt(){try{let e=jt.default.readFileSync(Fs,"utf-8");return JSON.parse(e)}catch{return{}}}function ei(e){e.token&&ur()&&fr(e.token)&&(e={...e,token:void 0,token_in_keychain:!0}),jt.default.mkdirSync(Ni,{recursive:!0,mode:448}),jt.default.writeFileSync(Fs,JSON.stringify(e,null,2),{mode:384})}function vr(){pr();try{jt.default.unlinkSync(Fs)}catch{}}function We(){return yr||gt().api_url||di}function He(e={}){if(process.env.DOMANI_API_KEY)return process.env.DOMANI_API_KEY;let t=gt();if(t.token)return t.token;if(t.token_in_keychain)return mr({refresh:e.refreshKeychain})}function ul(){try{let e=jt.default.readFileSync(wr,"utf-8");return JSON.parse(e)}catch{return null}}function ml(e){try{jt.default.mkdirSync(Ni,{recursive:!0,mode:448}),jt.default.writeFileSync(wr,JSON.stringify(e),{mode:384})}catch{}}function Pi(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 $r(){let e=ul();if(e&&Date.now()-e.checkedAt<cl)return Pi(e.version,je)>0?{update:e.version,forced:Pi(je,e.min)<0}:null;try{let t=We(),i=await fetch(`${t}/api/cli/version`,{signal:AbortSignal.timeout(3e3)});if(!i.ok)return null;let s=await i.json();if(ml({version:s.version,min:s.min,checkedAt:Date.now()}),Pi(s.version,je)>0)return{update:s.version,forced:Pi(je,s.min)<0}}catch{}return null}var jt,Di,gr,Ni,Fs,yr,wr,cl,Ls,je,yt=Te(()=>{"use strict";jt=D(require("fs"),1),Di=D(require("path"),1),gr=D(require("os"),1);ci();hr();Ni=process.env.DOMANI_CONFIG_DIR||Di.default.join(gr.default.homedir(),".domani"),Fs=Di.default.join(Ni,"config.json");wr=Di.default.join(Ni,"version-check.json"),cl=1440*60*1e3;Ls=process.stdout.isTTY??!1,je="0.4.71"});var Ws=pt((nm,kr)=>{"use strict";var Vs={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"},fl={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},pl={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?Vs.up():"");return e&&(t+=Vs.left),t}};kr.exports={cursor:Vs,scroll:fl,erase:pl,beep:"\x07"}});function bt(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?bt(r,t<0?-1:1,i):r}function Ks(e,t,i){return String(e).normalize().replaceAll(`\r
24
+ `),this.outputHelp({error:!0}));let n=i||{},s=n.exitCode||1,r=n.code||"commander.error";this._exit(s,r,t)}_parseOptionsEnv(){this.options.forEach(t=>{if(t.envVar&&t.envVar in se.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()}`,se.env[t.envVar]):this.emit(`optionEnv:${t.name()}`))}})}_parseOptionsImplied(){let t=new xd(this.options),i=n=>this.getOptionValue(n)!==void 0&&!["default","implied"].includes(this.getOptionValueSource(n));this.options.filter(n=>n.implied!==void 0&&i(n.attributeName())&&t.valueFromOption(this.getOptionValue(n.attributeName()),n)).forEach(n=>{Object.keys(n.implied).filter(s=>!i(s)).forEach(s=>{this.setOptionValueWithSource(s,n.implied[s],"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 n=o=>{let a=o.attributeName(),d=this.getOptionValue(a),f=this.options.find(p=>p.negate&&a===p.attributeName()),m=this.options.find(p=>!p.negate&&a===p.attributeName());return f&&(f.presetArg===void 0&&d===!1||f.presetArg!==void 0&&d===f.presetArg)?f:m||o},s=o=>{let a=n(o),d=a.attributeName();return this.getOptionValueSource(d)==="env"?`environment variable '${a.envVar}'`:`option '${a.flags}'`},r=`error: ${s(t)} cannot be used with ${s(i)}`;this.error(r,{code:"commander.conflictingOption"})}unknownOption(t){if(this._allowUnknownOption)return;let i="";if(t.startsWith("--")&&this._showSuggestionAfterError){let s=[],r=this;do{let o=r.createHelp().visibleOptions(r).filter(a=>a.long).map(a=>a.long);s=s.concat(o),r=r.parent}while(r&&!r._enablePositionalOptions);i=gr(t,s)}let n=`error: unknown option '${t}'${i}`;this.error(n,{code:"commander.unknownOption"})}_excessArguments(t){if(this._allowExcessArguments)return;let i=this.registeredArguments.length,n=i===1?"":"s",r=`error: too many arguments${this.parent?` for '${this.name()}'`:""}. Expected ${i} argument${n} but got ${t.length}.`;this.error(r,{code:"commander.excessArguments"})}unknownCommand(){let t=this.args[0],i="";if(this._showSuggestionAfterError){let s=[];this.createHelp().visibleCommands(this).forEach(r=>{s.push(r.name()),r.alias()&&s.push(r.alias())}),i=gr(t,s)}let n=`error: unknown command '${t}'${i}`;this.error(n,{code:"commander.unknownCommand"})}version(t,i,n){if(t===void 0)return this._version;this._version=t,i=i||"-V, --version",n=n||"output the version number";let s=this.createOption(i,n);return this._versionOptionName=s.attributeName(),this._registerOption(s),this.on("option:"+s.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 n=this.parent?._findCommand(t);if(n){let s=[n.name()].concat(n.aliases()).join("|");throw new Error(`cannot add alias '${t}' to command '${this.name()}' as already have command '${s}'`)}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(n=>$d(n));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=yt.basename(t,yt.extname(t)),this}executableDir(t){return t===void 0?this._executableDir:(this._executableDir=t,this)}helpInformation(t){let i=this.createHelp(),n=this._getOutputContext(t);i.prepareContext({error:n.error,helpWidth:n.helpWidth,outputHasColors:n.hasColors});let s=i.formatHelp(this,i);return n.hasColors?s:this._outputConfiguration.stripColor(s)}_getOutputContext(t){t=t||{};let i=!!t.error,n,s,r;return i?(n=a=>this._outputConfiguration.writeErr(a),s=this._outputConfiguration.getErrHasColors(),r=this._outputConfiguration.getErrHelpWidth()):(n=a=>this._outputConfiguration.writeOut(a),s=this._outputConfiguration.getOutHasColors(),r=this._outputConfiguration.getOutHelpWidth()),{error:i,write:a=>(s||(a=this._outputConfiguration.stripColor(a)),n(a)),hasColors:s,helpWidth:r}}outputHelp(t){let i;typeof t=="function"&&(i=t,t=void 0);let n=this._getOutputContext(t),s={error:n.error,write:n.write,command:this};this._getCommandAndAncestors().reverse().forEach(o=>o.emit("beforeAllHelp",s)),this.emit("beforeHelp",s);let r=this.helpInformation({error:n.error});if(i&&(r=i(r),typeof r!="string"&&!Buffer.isBuffer(r)))throw new Error("outputHelp callback must return a string or a Buffer");n.write(r),this._getHelpOption()?.long&&this.emit(this._getHelpOption().long),this.emit("afterHelp",s),this._getCommandAndAncestors().forEach(o=>o.emit("afterAllHelp",s))}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(se.exitCode??0);i===0&&t&&typeof t!="function"&&t.error&&(i=1),this._exit(i,"commander.help","(outputHelp)")}addHelpText(t,i){let n=["beforeAll","before","after","afterAll"];if(!n.includes(t))throw new Error(`Unexpected value for position to addHelpText.
26
+ Expecting one of '${n.join("', '")}'`);let s=`${t}Help`;return this.on(s,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(s=>i.is(s))&&(this.outputHelp(),this._exit(0,"commander.helpDisplayed","(outputHelp)"))}};function yr(e){return e.map(t=>{if(!t.startsWith("--inspect"))return t;let i,n="127.0.0.1",s="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])?s=r[3]:n=r[3]):(r=t.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/))!==null&&(i=r[1],n=r[3],s=r[4]),i&&s!=="0"?`${i}=${n}:${parseInt(s)+1}`:t})}function Yn(){if(se.env.NO_COLOR||se.env.FORCE_COLOR==="0"||se.env.FORCE_COLOR==="false")return!1;if(se.env.FORCE_COLOR||se.env.CLICOLOR_FORCE!==void 0)return!0}Xn.Command=zn;Xn.useColor=Yn});var kr=gt(Xe=>{var{Argument:wr}=Wi(),{Command:Zn}=br(),{CommanderError:jd,InvalidArgumentError:vr}=yi(),{Help:Sd}=Vn(),{Option:$r}=Bn();Xe.program=new Zn;Xe.createCommand=e=>new Zn(e);Xe.createOption=(e,t)=>new $r(e,t);Xe.createArgument=(e,t)=>new wr(e,t);Xe.Command=Zn;Xe.Option=$r;Xe.Argument=wr;Xe.Help=Sd;Xe.CommanderError=jd;Xe.InvalidArgumentError=vr;Xe.InvalidOptionArgumentError=vr});var M=gt((wm,Qn)=>{var Bi=process||{},jr=Bi.argv||[],Ji=Bi.env||{},Cd=!(Ji.NO_COLOR||jr.includes("--no-color"))&&(!!Ji.FORCE_COLOR||jr.includes("--color")||Bi.platform==="win32"||(Bi.stdout||{}).isTTY&&Ji.TERM!=="dumb"||!!Ji.CI),Od=(e,t,i=e)=>n=>{let s=""+n,r=s.indexOf(t,e.length);return~r?e+Id(s,t,i,r)+t:e+s+t},Id=(e,t,i,n)=>{let s="",r=0;do s+=e.substring(r,n)+i,r=n+t.length,n=e.indexOf(t,r);while(~n);return s+e.substring(r)},Sr=(e=Cd)=>{let t=e?Od:()=>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")}};Qn.exports=Sr();Qn.exports.createColors=Sr});var ei,bi,wi=Ie(()=>{"use strict";ei="domani.run",bi=`https://${ei}`});function Dt(e,t,i){try{let n=(0,Cr.spawnSync)(e,t,{encoding:"utf-8",input:i,timeout:3e3,stdio:["pipe","pipe","ignore"]});return{ok:n.status===0,stdout:(n.stdout||"").trim()}}catch{return{ok:!1,stdout:""}}}function Or(){return process.platform==="darwin"?!0:process.platform==="linux"?Dt("secret-tool",["--help"]).ok:!1}function Ir(e={}){if(e.refresh&&(ti=void 0),ti!==void 0)return ti??void 0;let t;if(process.platform==="darwin"){let i=Dt("security",["find-generic-password","-s",ii,"-a",ni,"-w"]);i.ok&&i.stdout&&(t=i.stdout)}else if(process.platform==="linux"){let i=Dt("secret-tool",["lookup","service",ii,"account",ni]);i.ok&&i.stdout&&(t=i.stdout)}return ti=t??null,t}function Rr(e){let t=!1;return process.platform==="darwin"?t=Dt("security",["add-generic-password","-U","-s",ii,"-a",ni,"-w",e]).ok:process.platform==="linux"&&(t=Dt("secret-tool",["store","--label=domani CLI token","service",ii,"account",ni],e+`
28
+ `).ok),t&&(ti=e),t}function Ar(){process.platform==="darwin"?Dt("security",["delete-generic-password","-s",ii,"-a",ni]):process.platform==="linux"&&Dt("secret-tool",["clear","service",ii,"account",ni]),ti=null}var Cr,ii,ni,ti,Tr=Ie(()=>{"use strict";Cr=require("child_process"),ii="domani-cli",ni="default"});function Dr(e){Pr=e}function bt(){try{let e=Ct.default.readFileSync(es,"utf-8");return JSON.parse(e)}catch{return{}}}function si(e){e.token&&Or()&&Rr(e.token)&&(e={...e,token:void 0,token_in_keychain:!0}),Ct.default.mkdirSync(zi,{recursive:!0,mode:448}),Ct.default.writeFileSync(es,JSON.stringify(e,null,2),{mode:384})}function Ur(){Ar();try{Ct.default.unlinkSync(es)}catch{}}function Je(){return Pr||bt().api_url||bi}function Be(e={}){if(process.env.DOMANI_API_KEY)return process.env.DOMANI_API_KEY;let t=bt();if(t.token)return t.token;if(t.token_in_keychain)return Ir({refresh:e.refreshKeychain})}function Ad(){try{let e=Ct.default.readFileSync(Nr,"utf-8");return JSON.parse(e)}catch{return null}}function Td(e){try{Ct.default.mkdirSync(zi,{recursive:!0,mode:448}),Ct.default.writeFileSync(Nr,JSON.stringify(e),{mode:384})}catch{}}function Gi(e,t){let i=e.split(".").map(Number),n=t.split(".").map(Number);for(let s=0;s<3;s++){if((i[s]||0)>(n[s]||0))return 1;if((i[s]||0)<(n[s]||0))return-1}return 0}async function qr(){let e=Ad();if(e&&Date.now()-e.checkedAt<Rd)return Gi(e.version,Ce)>0?{update:e.version,forced:Gi(Ce,e.min)<0}:null;try{let t=Je(),i=await fetch(`${t}/api/cli/version`,{signal:AbortSignal.timeout(3e3)});if(!i.ok)return null;let n=await i.json();if(Td({version:n.version,min:n.min,checkedAt:Date.now()}),Gi(n.version,Ce)>0)return{update:n.version,forced:Gi(Ce,n.min)<0}}catch{}return null}var Ct,Ki,Er,zi,es,Pr,Nr,Rd,ts,Ce,wt=Ie(()=>{"use strict";Ct=U(require("fs"),1),Ki=U(require("path"),1),Er=U(require("os"),1);wi();Tr();zi=process.env.DOMANI_CONFIG_DIR||Ki.default.join(Er.default.homedir(),".domani"),es=Ki.default.join(zi,"config.json");Nr=Ki.default.join(zi,"version-check.json"),Rd=1440*60*1e3;ts=process.stdout.isTTY??!1,Ce="0.4.73"});var ns=gt((jm,Mr)=>{"use strict";var is={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"},Ed={up:(e=1)=>"\x1B[S".repeat(e),down:(e=1)=>"\x1B[T".repeat(e)},Pd={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?is.up():"");return e&&(t+=is.left),t}};Mr.exports={cursor:is,scroll:Ed,erase:Pd,beep:"\x07"}});function vt(e,t,i){if(!i.some(o=>!o.disabled))return e;let n=e+t,s=Math.max(i.length-1,0),r=n<0?s:n>s?0:n;return i[r].disabled?vt(r,t<0?-1:1,i):r}function ds(e,t,i){return String(e).normalize().replaceAll(`\r
29
29
  `,`
30
30
  `).split(`
31
- `).map(s=>Sl(s,t,i)).join(`
32
- `)}function Ar(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];me.actions.has(s)&&(me.aliases.has(i)||me.aliases.set(i,s))}}if(e.messages!==void 0){let t=e.messages;t.cancel!==void 0&&(me.messages.cancel=t.cancel),t.error!==void 0&&(me.messages.error=t.error)}e.withGuide!==void 0&&(me.withGuide=e.withGuide!==!1)}function Zs(e,t){if(typeof e=="string")return me.aliases.get(e)===t;for(let i of e)if(i!==void 0&&Zs(i,t))return!0;return!1}function Ol(e,t){if(e===t)return;let i=e.split(`
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 ce(e){return e===zs}function Fi(e,t){let i=e;i.isTTY&&i.setRawMode(t)}function Tr({input:e=Et.stdin,output:t=Et.stdout,overwrite:i=!0,hideCursor:s=!0}={}){let n=Ct.createInterface({input:e,output:t,prompt:"",tabSize:1});Ct.emitKeypressEvents(e,n),e instanceof Gs.ReadStream&&e.isTTY&&e.setRawMode(!0);let r=(o,{name:a,sequence:l})=>{let f=String(o);if(Zs([f,a,l],"cancel")){s&&t.write(Ee.cursor.show),process.exit(0);return}if(!i)return;Ct.moveCursor(t,a==="return"?0:-1,a==="return"?-1:0,()=>{Ct.clearLine(t,1,()=>{e.once("keypress",r)})})};return s&&t.write(Ee.cursor.hide),e.once("keypress",r),()=>{e.off("keypress",r),s&&t.write(Ee.cursor.show),e instanceof Gs.ReadStream&&e.isTTY&&!Il&&e.setRawMode(!1),n.terminal=!1,n.close()}}function at(e,t,i,s=i){let n=Pt(e??Et.stdout);return Ks(t,n-i.length,{hard:!0,trim:!1}).split(`
35
- `).map((r,o)=>`${o===0?s:i}${r}`).join(`
36
- `)}function Rl(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 Al(e,t){return(t.label??String(t.value)).toLowerCase().includes(e.toLowerCase())}function Tl(e,t){if(t)return e?t:t[0]}var St,Et,Ct,Sr,Ee,Gs,hl,gl,yl,Hs,Ui,qi,Js,Mi,bl,wl,Cr,vl,ui,Gi,Or,$l,Ys,Ir,kl,Rr,Xs,_r,_l,xr,jr,xl,Bs,jl,Sl,Cl,me,Il,zs,Pt,Qs,ot,mi,Li,Vi,Wi,Er,Hi,Ji,Bi,en=Te(()=>{St=D(F(),1),Et=require("node:process"),Ct=D(require("node:readline"),1),Sr=D(require("node:readline"),1),Ee=D(Ws(),1),Gs=require("node:tty");hl=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,gl=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,yl=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,Hs=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,Ui=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,qi=/\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"),Mi=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,bl=new RegExp("\\p{M}+","gu"),wl={limit:1/0,ellipsis:""},Cr=(e,t={},i={})=>{let s=t.limit??1/0,n=t.ellipsis??"",r=t?.ellipsisWidth??(n?Cr(n,wl,i).width:0),o=i.ansiWidth??0,a=i.controlWidth??0,l=i.tabWidth??8,f=i.ambiguousWidth??1,m=i.emojiWidth??2,h=i.fullWidthWidth??2,b=i.regularWidth??1,k=i.wideWidth??2,$=0,g=0,x=e.length,S=0,O=!1,A=x,W=Math.max(0,s-r),H=0,se=0,P=0,E=0;e:for(;;){if(se>H||g>=x&&g>$){let U=e.slice(H,se)||e.slice($,g);S=0;for(let te of U.replaceAll(bl,"")){let X=te.codePointAt(0)||0;if(gl(X)?E=h:yl(X)?E=k:f!==b&&hl(X)?E=f:E=b,P+E>W&&(A=Math.min(A,Math.max(H,$)+S)),P+E>s){O=!0;break e}S+=te.length,P+=E}H=se=0}if(g>=x)break;if(Mi.lastIndex=g,Mi.test(e)){if(S=Mi.lastIndex-g,E=S*b,P+E>W&&(A=Math.min(A,g+Math.floor((W-P)/b))),P+E>s){O=!0;break}P+=E,H=$,se=g,g=$=Mi.lastIndex;continue}if(Hs.lastIndex=g,Hs.test(e)){if(P+o>W&&(A=Math.min(A,g)),P+o>s){O=!0;break}P+=o,H=$,se=g,g=$=Hs.lastIndex;continue}if(Ui.lastIndex=g,Ui.test(e)){if(S=Ui.lastIndex-g,E=S*a,P+E>W&&(A=Math.min(A,g+Math.floor((W-P)/a))),P+E>s){O=!0;break}P+=E,H=$,se=g,g=$=Ui.lastIndex;continue}if(qi.lastIndex=g,qi.test(e)){if(S=qi.lastIndex-g,E=S*l,P+E>W&&(A=Math.min(A,g+Math.floor((W-P)/l))),P+E>s){O=!0;break}P+=E,H=$,se=g,g=$=qi.lastIndex;continue}if(Js.lastIndex=g,Js.test(e)){if(P+m>W&&(A=Math.min(A,g)),P+m>s){O=!0;break}P+=m,H=$,se=g,g=$=Js.lastIndex;continue}g+=1}return{width:O?W:P,index:O?A:x,truncated:O,ellipsed:O&&s>=r}},vl={limit:1/0,ellipsis:"",ellipsisWidth:0},ui=(e,t={})=>Cr(e,vl,t).width,Gi="\x1B",Or="\x9B",$l=39,Ys="\x07",Ir="[",kl="]",Rr="m",Xs=`${kl}8;;`,_r=new RegExp(`(?:\\${Ir}(?<code>\\d+)m|\\${Xs}(?<uri>.*)${Ys})`,"y"),_l=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},xr=e=>`${Gi}${Ir}${e}${Rr}`,jr=e=>`${Gi}${Xs}${e}${Ys}`,xl=e=>e.map(t=>ui(t)),Bs=(e,t,i)=>{let s=t[Symbol.iterator](),n=!1,r=!1,o=e.at(-1),a=o===void 0?0:ui(o),l=s.next(),f=s.next(),m=0;for(;!l.done;){let h=l.value,b=ui(h);a+b<=i?e[e.length-1]+=h:(e.push(h),a=0),(h===Gi||h===Or)&&(n=!0,r=t.startsWith(Xs,m+1)),n?r?h===Ys&&(n=!1,r=!1):h===Rr&&(n=!1):(a+=b,a===i&&!f.done&&(e.push(""),a=0)),l=f,f=s.next(),m+=h.length}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop())},jl=e=>{let t=e.split(" "),i=t.length;for(;i>0&&!(ui(t[i-1])>0);)i--;return i===t.length?e:t.slice(0,i).join(" ")+t.slice(i).join("")},Sl=(e,t,i={})=>{if(i.trim!==!1&&e.trim()==="")return"";let s="",n,r,o=e.split(" "),a=xl(o),l=[""];for(let[$,g]of o.entries()){i.trim!==!1&&(l[l.length-1]=(l.at(-1)??"").trimStart());let x=ui(l.at(-1)??"");if($!==0&&(x>=t&&(i.wordWrap===!1||i.trim===!1)&&(l.push(""),x=0),(x>0||i.trim===!1)&&(l[l.length-1]+=" ",x++)),i.hard&&a[$]>t){let S=t-x,O=1+Math.floor((a[$]-S-1)/t);Math.floor((a[$]-1)/t)<O&&l.push(""),Bs(l,g,t);continue}if(x+a[$]>t&&x>0&&a[$]>0){if(i.wordWrap===!1&&x<t){Bs(l,g,t);continue}l.push("")}if(x+a[$]>t&&i.wordWrap===!1){Bs(l,g,t);continue}l[l.length-1]+=g}i.trim!==!1&&(l=l.map($=>jl($)));let f=l.join(`
37
- `),m=f[Symbol.iterator](),h=m.next(),b=m.next(),k=0;for(;!h.done;){let $=h.value,g=b.value;if(s+=$,$===Gi||$===Or){_r.lastIndex=k+1;let S=_r.exec(f)?.groups;if(S?.code!==void 0){let O=Number.parseFloat(S.code);n=O===$l?void 0:O}else S?.uri!==void 0&&(r=S.uri.length===0?void 0:S.uri)}let x=n?_l(n):void 0;g===`
38
- `?(r&&(s+=jr("")),n&&x&&(s+=xr(x))):$===`
39
- `&&(n&&x&&(s+=xr(n)),r&&(s+=jr(r))),k+=$.length,h=b,b=m.next()}return s};Cl=["up","down","left","right","space","enter","cancel"],me={actions:new Set(Cl),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0};Il=globalThis.process.platform.startsWith("win"),zs=Symbol("clack:cancel");Pt=e=>"columns"in e&&typeof e.columns=="number"?e.columns:80,Qs=e=>"rows"in e&&typeof e.rows=="number"?e.rows:20;ot=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=Et.stdin,output:n=Et.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(zs);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=Sr.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),Fi(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(Ee.cursor.show),this.output.off("resize",this.render),Fi(this.input,!1),t(this.value)}),this.once("cancel",()=>{this.output.write(Ee.cursor.show),this.output.off("resize",this.render),Fi(this.input,!1),t(zs)})})}_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&&me.aliases.has(i.name)&&this.emit("cursor",me.aliases.get(i.name)),me.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")}Zs([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
- `),Fi(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let t=Ks(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
41
- `).length-1;this.output.write(Ee.cursor.move(-999,t*-1))}render(){let t=Ks(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(t!==this._prevFrame){if(this.state==="initial")this.output.write(Ee.cursor.hide);else{let i=Ol(this._prevFrame,t),s=Qs(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(Ee.cursor.move(0,o-r)),this.output.write(Ee.erase.lines(1));let a=t.split(`
42
- `);this.output.write(a[o]),this._prevFrame=t,this.output.write(Ee.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(Ee.cursor.move(0,l))}this.output.write(Ee.erase.down());let a=t.split(`
31
+ `).map(n=>Bd(n,t,i)).join(`
32
+ `)}function Kr(e){if(e.aliases!==void 0){let t=e.aliases;for(let i in t){if(!Object.hasOwn(t,i))continue;let n=t[i];ue.actions.has(n)&&(ue.aliases.has(i)||ue.aliases.set(i,n))}}if(e.messages!==void 0){let t=e.messages;t.cancel!==void 0&&(ue.messages.cancel=t.cancel),t.error!==void 0&&(ue.messages.error=t.error)}e.withGuide!==void 0&&(ue.withGuide=e.withGuide!==!1)}function ms(e,t){if(typeof e=="string")return ue.aliases.get(e)===t;for(let i of e)if(i!==void 0&&ms(i,t))return!0;return!1}function Kd(e,t){if(e===t)return;let i=e.split(`
33
+ `),n=t.split(`
34
+ `),s=Math.max(i.length,n.length),r=[];for(let o=0;o<s;o++)i[o]!==n[o]&&r.push(o);return{lines:r,numLinesBefore:i.length,numLinesAfter:n.length,numLines:s}}function ae(e){return e===ls}function Qi(e,t){let i=e;i.isTTY&&i.setRawMode(t)}function zr({input:e=Nt.stdin,output:t=Nt.stdout,overwrite:i=!0,hideCursor:n=!0}={}){let s=It.createInterface({input:e,output:t,prompt:"",tabSize:1});It.emitKeypressEvents(e,s),e instanceof as.ReadStream&&e.isTTY&&e.setRawMode(!0);let r=(o,{name:a,sequence:d})=>{let f=String(o);if(ms([f,a,d],"cancel")){n&&t.write(Pe.cursor.show),process.exit(0);return}if(!i)return;It.moveCursor(t,a==="return"?0:-1,a==="return"?-1:0,()=>{It.clearLine(t,1,()=>{e.once("keypress",r)})})};return n&&t.write(Pe.cursor.hide),e.once("keypress",r),()=>{e.off("keypress",r),n&&t.write(Pe.cursor.show),e instanceof as.ReadStream&&e.isTTY&&!zd&&e.setRawMode(!1),s.terminal=!1,s.close()}}function at(e,t,i,n=i){let s=Ut(e??Nt.stdout);return ds(t,s-i.length,{hard:!0,trim:!1}).split(`
35
+ `).map((r,o)=>`${o===0?n:i}${r}`).join(`
36
+ `)}function Yd(e,t){if(e===void 0||t.length===0)return 0;let i=t.findIndex(n=>n.value===e);return i!==-1?i:0}function Xd(e,t){return(t.label??String(t.value)).toLowerCase().includes(e.toLowerCase())}function Zd(e,t){if(t)return e?t:t[0]}var Ot,Nt,It,Wr,Pe,as,Dd,Nd,Ud,ss,Yi,Xi,rs,Zi,qd,Md,Hr,Fd,vi,an,Jr,Ld,cs,Br,Vd,Gr,us,Fr,Wd,Lr,Vr,Hd,os,Jd,Bd,Gd,ue,zd,ls,Ut,fs,ot,$i,en,tn,nn,Yr,sn,rn,on,ps=Ie(()=>{Ot=U(M(),1),Nt=require("node:process"),It=U(require("node:readline"),1),Wr=U(require("node:readline"),1),Pe=U(ns(),1),as=require("node:tty");Dd=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,Nd=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Ud=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,ss=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,Yi=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Xi=/\t{1,1000}/y,rs=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"),Zi=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,qd=new RegExp("\\p{M}+","gu"),Md={limit:1/0,ellipsis:""},Hr=(e,t={},i={})=>{let n=t.limit??1/0,s=t.ellipsis??"",r=t?.ellipsisWidth??(s?Hr(s,Md,i).width:0),o=i.ansiWidth??0,a=i.controlWidth??0,d=i.tabWidth??8,f=i.ambiguousWidth??1,m=i.emojiWidth??2,p=i.fullWidthWidth??2,y=i.regularWidth??1,k=i.wideWidth??2,b=0,g=0,S=e.length,j=0,O=!1,T=S,W=Math.max(0,n-r),H=0,ee=0,q=0,N=0;e:for(;;){if(ee>H||g>=S&&g>b){let le=e.slice(H,ee)||e.slice(b,g);j=0;for(let de of le.replaceAll(qd,"")){let P=de.codePointAt(0)||0;if(Nd(P)?N=p:Ud(P)?N=k:f!==y&&Dd(P)?N=f:N=y,q+N>W&&(T=Math.min(T,Math.max(H,b)+j)),q+N>n){O=!0;break e}j+=de.length,q+=N}H=ee=0}if(g>=S)break;if(Zi.lastIndex=g,Zi.test(e)){if(j=Zi.lastIndex-g,N=j*y,q+N>W&&(T=Math.min(T,g+Math.floor((W-q)/y))),q+N>n){O=!0;break}q+=N,H=b,ee=g,g=b=Zi.lastIndex;continue}if(ss.lastIndex=g,ss.test(e)){if(q+o>W&&(T=Math.min(T,g)),q+o>n){O=!0;break}q+=o,H=b,ee=g,g=b=ss.lastIndex;continue}if(Yi.lastIndex=g,Yi.test(e)){if(j=Yi.lastIndex-g,N=j*a,q+N>W&&(T=Math.min(T,g+Math.floor((W-q)/a))),q+N>n){O=!0;break}q+=N,H=b,ee=g,g=b=Yi.lastIndex;continue}if(Xi.lastIndex=g,Xi.test(e)){if(j=Xi.lastIndex-g,N=j*d,q+N>W&&(T=Math.min(T,g+Math.floor((W-q)/d))),q+N>n){O=!0;break}q+=N,H=b,ee=g,g=b=Xi.lastIndex;continue}if(rs.lastIndex=g,rs.test(e)){if(q+m>W&&(T=Math.min(T,g)),q+m>n){O=!0;break}q+=m,H=b,ee=g,g=b=rs.lastIndex;continue}g+=1}return{width:O?W:q,index:O?T:S,truncated:O,ellipsed:O&&n>=r}},Fd={limit:1/0,ellipsis:"",ellipsisWidth:0},vi=(e,t={})=>Hr(e,Fd,t).width,an="\x1B",Jr="\x9B",Ld=39,cs="\x07",Br="[",Vd="]",Gr="m",us=`${Vd}8;;`,Fr=new RegExp(`(?:\\${Br}(?<code>\\d+)m|\\${us}(?<uri>.*)${cs})`,"y"),Wd=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},Lr=e=>`${an}${Br}${e}${Gr}`,Vr=e=>`${an}${us}${e}${cs}`,Hd=e=>e.map(t=>vi(t)),os=(e,t,i)=>{let n=t[Symbol.iterator](),s=!1,r=!1,o=e.at(-1),a=o===void 0?0:vi(o),d=n.next(),f=n.next(),m=0;for(;!d.done;){let p=d.value,y=vi(p);a+y<=i?e[e.length-1]+=p:(e.push(p),a=0),(p===an||p===Jr)&&(s=!0,r=t.startsWith(us,m+1)),s?r?p===cs&&(s=!1,r=!1):p===Gr&&(s=!1):(a+=y,a===i&&!f.done&&(e.push(""),a=0)),d=f,f=n.next(),m+=p.length}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop())},Jd=e=>{let t=e.split(" "),i=t.length;for(;i>0&&!(vi(t[i-1])>0);)i--;return i===t.length?e:t.slice(0,i).join(" ")+t.slice(i).join("")},Bd=(e,t,i={})=>{if(i.trim!==!1&&e.trim()==="")return"";let n="",s,r,o=e.split(" "),a=Hd(o),d=[""];for(let[b,g]of o.entries()){i.trim!==!1&&(d[d.length-1]=(d.at(-1)??"").trimStart());let S=vi(d.at(-1)??"");if(b!==0&&(S>=t&&(i.wordWrap===!1||i.trim===!1)&&(d.push(""),S=0),(S>0||i.trim===!1)&&(d[d.length-1]+=" ",S++)),i.hard&&a[b]>t){let j=t-S,O=1+Math.floor((a[b]-j-1)/t);Math.floor((a[b]-1)/t)<O&&d.push(""),os(d,g,t);continue}if(S+a[b]>t&&S>0&&a[b]>0){if(i.wordWrap===!1&&S<t){os(d,g,t);continue}d.push("")}if(S+a[b]>t&&i.wordWrap===!1){os(d,g,t);continue}d[d.length-1]+=g}i.trim!==!1&&(d=d.map(b=>Jd(b)));let f=d.join(`
37
+ `),m=f[Symbol.iterator](),p=m.next(),y=m.next(),k=0;for(;!p.done;){let b=p.value,g=y.value;if(n+=b,b===an||b===Jr){Fr.lastIndex=k+1;let j=Fr.exec(f)?.groups;if(j?.code!==void 0){let O=Number.parseFloat(j.code);s=O===Ld?void 0:O}else j?.uri!==void 0&&(r=j.uri.length===0?void 0:j.uri)}let S=s?Wd(s):void 0;g===`
38
+ `?(r&&(n+=Vr("")),s&&S&&(n+=Lr(S))):b===`
39
+ `&&(s&&S&&(n+=Lr(s)),r&&(n+=Vr(r))),k+=b.length,p=y,y=m.next()}return n};Gd=["up","down","left","right","space","enter","cancel"],ue={actions:new Set(Gd),aliases:new Map([["k","up"],["j","down"],["h","left"],["l","right"],["","cancel"],["escape","cancel"]]),messages:{cancel:"Canceled",error:"Something went wrong"},withGuide:!0};zd=globalThis.process.platform.startsWith("win"),ls=Symbol("clack:cancel");Ut=e=>"columns"in e&&typeof e.columns=="number"?e.columns:80,fs=e=>"rows"in e&&typeof e.rows=="number"?e.rows:20;ot=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:n=Nt.stdin,output:s=Nt.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=n,this.output=s}unsubscribe(){this._subscribers.clear()}setSubscriber(t,i){let n=this._subscribers.get(t)??[];n.push(i),this._subscribers.set(t,n)}on(t,i){this.setSubscriber(t,{cb:i})}once(t,i){this.setSubscriber(t,{cb:i,once:!0})}emit(t,...i){let n=this._subscribers.get(t)??[],s=[];for(let r of n)r.cb(...i),r.once&&s.push(()=>n.splice(n.indexOf(r),1));for(let r of s)r()}prompt(){return new Promise(t=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state="cancel",this.close(),t(ls);this._abortSignal.addEventListener("abort",()=>{this.state="cancel",this.close()},{once:!0})}this.rl=Wr.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),Qi(this.input,!0),this.output.on("resize",this.render),this.render(),this.once("submit",()=>{this.output.write(Pe.cursor.show),this.output.off("resize",this.render),Qi(this.input,!1),t(this.value)}),this.once("cancel",()=>{this.output.write(Pe.cursor.show),this.output.off("resize",this.render),Qi(this.input,!1),t(ls)})})}_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&&ue.aliases.has(i.name)&&this.emit("cursor",ue.aliases.get(i.name)),ue.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 n=this.opts.validate(this.value);n&&(this.error=n instanceof Error?n.message:n,this.state="error",this.rl?.write(this.userInput))}this.state!=="error"&&(this.state="submit")}ms([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
+ `),Qi(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let t=ds(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
41
+ `).length-1;this.output.write(Pe.cursor.move(-999,t*-1))}render(){let t=ds(this._render(this)??"",process.stdout.columns,{hard:!0,trim:!1});if(t!==this._prevFrame){if(this.state==="initial")this.output.write(Pe.cursor.hide);else{let i=Kd(this._prevFrame,t),n=fs(this.output);if(this.restoreCursor(),i){let s=Math.max(0,i.numLinesAfter-n),r=Math.max(0,i.numLinesBefore-n),o=i.lines.find(a=>a>=s);if(o===void 0){this._prevFrame=t;return}if(i.lines.length===1){this.output.write(Pe.cursor.move(0,o-r)),this.output.write(Pe.erase.lines(1));let a=t.split(`
42
+ `);this.output.write(a[o]),this._prevFrame=t,this.output.write(Pe.cursor.move(0,a.length-o-1));return}else if(i.lines.length>1){if(s<r)o=s;else{let d=o-r;d>0&&this.output.write(Pe.cursor.move(0,d))}this.output.write(Pe.erase.down());let a=t.split(`
43
43
  `).slice(o);this.output.write(a.join(`
44
- `)),this._prevFrame=t;return}}this.output.write(Ee.erase.down())}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t}}};mi=class extends ot{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#e=0;#i="";#s;#t;get cursor(){return this.#e}get userInputWithCursor(){if(!this.userInput)return St.default.inverse(St.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}${St.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??Al;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=bt(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=Tl(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=Rl(this.focusedValue,this.filteredOptions);this.#e=bt(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())}}},Li=class extends ot{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(Ee.cursor.move(0,-1)),this.value=i,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}},Vi=class extends ot{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}})}},Wi=class extends ot{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?bt(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=bt(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=bt(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}},Er=class extends ot{_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}${St.default.inverse(St.default.hidden("_"))}`;let t=this.masked,i=t.slice(0,this.cursor),s=t.slice(this.cursor);return`${i}${St.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)})}},Hi=class extends ot{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?bt(s,1,this.options):s,this.changeValue(),this.on("cursor",n=>{switch(n){case"left":case"up":this.cursor=bt(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=bt(this.cursor,1,this.options);break}this.changeValue()})}},Ji=class extends ot{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"))})}},Bi=class extends ot{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}${St.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 wn={};zt(wn,{S_BAR:()=>T,S_BAR_END:()=>Se,S_BAR_END_RIGHT:()=>Hr,S_BAR_H:()=>ts,S_BAR_START:()=>ln,S_BAR_START_RIGHT:()=>Wr,S_CHECKBOX_ACTIVE:()=>es,S_CHECKBOX_INACTIVE:()=>ii,S_CHECKBOX_SELECTED:()=>Nt,S_CONNECT_LEFT:()=>Br,S_CORNER_BOTTOM_LEFT:()=>un,S_CORNER_BOTTOM_RIGHT:()=>cn,S_CORNER_TOP_LEFT:()=>Gr,S_CORNER_TOP_RIGHT:()=>dn,S_ERROR:()=>hn,S_INFO:()=>mn,S_PASSWORD_MASK:()=>Jr,S_RADIO_ACTIVE:()=>hi,S_RADIO_INACTIVE:()=>qt,S_STEP_ACTIVE:()=>Vr,S_STEP_CANCEL:()=>on,S_STEP_ERROR:()=>an,S_STEP_SUBMIT:()=>Mt,S_SUCCESS:()=>fn,S_WARN:()=>pn,autocomplete:()=>Qr,autocompleteMultiselect:()=>Kl,box:()=>Zl,cancel:()=>td,confirm:()=>Xe,group:()=>Ql,groupMultiselect:()=>ed,intro:()=>id,isCI:()=>rn,isCancel:()=>ce,isTTY:()=>Lr,limitOptions:()=>ni,log:()=>Be,multiselect:()=>nd,note:()=>ad,outro:()=>sd,password:()=>ld,path:()=>dd,progress:()=>ud,select:()=>it,selectKey:()=>md,settings:()=>me,spinner:()=>gi,stream:()=>Dt,symbol:()=>tt,symbolBar:()=>gn,taskLog:()=>hd,tasks:()=>fd,text:()=>Pe,unicode:()=>Qi,unicodeOr:()=>le,updateSettings:()=>Ar});function El(){return Je.default.platform!=="win32"?Je.default.env.TERM!=="linux":!!Je.default.env.CI||!!Je.default.env.WT_SESSION||!!Je.default.env.TERMINUS_SUBLIME||Je.default.env.ConEmuTask==="{cmd::Cmder}"||Je.default.env.TERM_PROGRAM==="Terminus-Sublime"||Je.default.env.TERM_PROGRAM==="vscode"||Je.default.env.TERM==="xterm-256color"||Je.default.env.TERM==="alacritty"||Je.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}function si(e,t,i){return String(e).normalize().replaceAll(`\r
44
+ `)),this._prevFrame=t;return}}this.output.write(Pe.erase.down())}this.output.write(t),this.state==="initial"&&(this.state="active"),this._prevFrame=t}}};$i=class extends ot{filteredOptions;multiple;isNavigating=!1;selectedValues=[];focusedValue;#e=0;#i="";#n;#t;get cursor(){return this.#e}get userInputWithCursor(){if(!this.userInput)return Ot.default.inverse(Ot.default.hidden("_"));if(this._cursor>=this.userInput.length)return`${this.userInput}\u2588`;let t=this.userInput.slice(0,this._cursor),[i,...n]=this.userInput.slice(this._cursor);return`${t}${Ot.default.inverse(i)}${n.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.#n=t.filter??Xd;let n;if(t.initialValue&&Array.isArray(t.initialValue)?this.multiple?n=t.initialValue:n=t.initialValue.slice(0,1):!this.multiple&&this.options.length>0&&(n=[this.options[0].value]),n)for(let s of n){let r=i.findIndex(o=>o.value===s);r!==-1&&(this.toggleSelected(s),this.#e=r)}this.focusedValue=this.options[this.#e]?.value,this.on("key",(s,r)=>this.#s(s,r)),this.on("userInput",s=>this.#r(s))}_isActionKey(t,i){return t===" "||this.multiple&&this.isNavigating&&i.name==="space"&&t!==void 0&&t!==""}#s(t,i){let n=i.name==="up",s=i.name==="down",r=i.name==="return";n||s?(this.#e=vt(this.#e,n?-1:1,this.filteredOptions),this.focusedValue=this.filteredOptions[this.#e]?.value,this.multiple||(this.selectedValues=[this.focusedValue]),this.isNavigating=!0):r?this.value=Zd(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.#n(t,r)):this.filteredOptions=[...i];let n=Yd(this.focusedValue,this.filteredOptions);this.#e=vt(n,0,this.filteredOptions);let s=this.filteredOptions[this.#e];s&&!s.disabled?this.focusedValue=s.value:this.focusedValue=void 0,this.multiple||(this.focusedValue!==void 0?this.toggleSelected(this.focusedValue):this.deselectAll())}}},en=class extends ot{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(Pe.cursor.move(0,-1)),this.value=i,this.state="submit",this.close()}),this.on("cursor",()=>{this.value=!this.value})}},tn=class extends ot{options;cursor=0;#e;getGroupItems(t){return this.options.filter(i=>i.group===t)}isGroupSelected(t){let i=this.getGroupItems(t),n=this.value;return n===void 0?!1:i.every(s=>n.includes(s.value))}toggleValue(){let t=this.options[this.cursor];if(this.value===void 0&&(this.value=[]),t.group===!0){let i=t.value,n=this.getGroupItems(i);this.isGroupSelected(i)?this.value=this.value.filter(s=>n.findIndex(r=>r.value===s)===-1):this.value=[...this.value,...n.map(s=>s.value)],this.value=Array.from(new Set(this.value))}else{let i=this.value.includes(t.value);this.value=i?this.value.filter(n=>n!==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(([n,s])=>[{value:n,group:!0,label:n},...s.map(r=>({...r,group:n}))]),this.value=[...t.initialValues??[]],this.cursor=Math.max(this.options.findIndex(({value:n})=>n===t.cursorAt),this.#e?0:1),this.on("cursor",n=>{switch(n){case"left":case"up":{this.cursor=this.cursor===0?this.options.length-1:this.cursor-1;let s=this.options[this.cursor]?.group===!0;!this.#e&&s&&(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 s=this.options[this.cursor]?.group===!0;!this.#e&&s&&(this.cursor=this.cursor===this.options.length-1?0:this.cursor+1);break}case"space":this.toggleValue();break}})}},nn=class extends ot{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(n=>n.value)}toggleInvert(){let t=this.value;if(!t)return;let i=this._enabledOptions.filter(n=>!t.includes(n.value));this.value=i.map(n=>n.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:n})=>n===t.cursorAt),0);this.cursor=this.options[i].disabled?vt(i,1,this.options):i,this.on("key",n=>{n==="a"&&this.toggleAll(),n==="i"&&this.toggleInvert()}),this.on("cursor",n=>{switch(n){case"left":case"up":this.cursor=vt(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=vt(this.cursor,1,this.options);break;case"space":this.toggleValue();break}})}},Yr=class extends ot{_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}${Ot.default.inverse(Ot.default.hidden("_"))}`;let t=this.masked,i=t.slice(0,this.cursor),n=t.slice(this.cursor);return`${i}${Ot.default.inverse(n[0])}${n.slice(1)}`}clear(){this._clearUserInput()}constructor({mask:e,...t}){super(t),this._mask=e??"\u2022",this.on("userInput",i=>{this._setValue(i)})}},sn=class extends ot{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:s})=>s===t.initialValue),n=i===-1?0:i;this.cursor=this.options[n].disabled?vt(n,1,this.options):n,this.changeValue(),this.on("cursor",s=>{switch(s){case"left":case"up":this.cursor=vt(this.cursor,-1,this.options);break;case"down":case"right":this.cursor=vt(this.cursor,1,this.options);break}this.changeValue()})}},rn=class extends ot{options;cursor=0;constructor(t){super(t,!1),this.options=t.options;let i=t.caseSensitive===!0,n=this.options.map(({value:[s]})=>i?s:s?.toLowerCase());this.cursor=Math.max(n.indexOf(t.initialValue),0),this.on("key",(s,r)=>{if(!s)return;let o=i&&r.shift?s.toUpperCase():s;if(!n.includes(o))return;let a=this.options.find(({value:[d]})=>i?d===o:d?.toLowerCase()===s);a&&(this.value=a.value,this.state="submit",this.emit("submit"))})}},on=class extends ot{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),[n,...s]=t.slice(this.cursor);return`${i}${Ot.default.inverse(n)}${s.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 Ts={};Qt(Ts,{S_BAR:()=>D,S_BAR_END:()=>Oe,S_BAR_END_RIGHT:()=>ao,S_BAR_H:()=>hn,S_BAR_START:()=>$s,S_BAR_START_RIGHT:()=>oo,S_CHECKBOX_ACTIVE:()=>pn,S_CHECKBOX_INACTIVE:()=>oi,S_CHECKBOX_SELECTED:()=>Mt,S_CONNECT_LEFT:()=>co,S_CORNER_BOTTOM_LEFT:()=>xs,S_CORNER_BOTTOM_RIGHT:()=>_s,S_CORNER_TOP_LEFT:()=>uo,S_CORNER_TOP_RIGHT:()=>ks,S_ERROR:()=>Os,S_INFO:()=>js,S_PASSWORD_MASK:()=>lo,S_RADIO_ACTIVE:()=>xi,S_RADIO_INACTIVE:()=>Lt,S_STEP_ACTIVE:()=>ro,S_STEP_CANCEL:()=>ws,S_STEP_ERROR:()=>vs,S_STEP_SUBMIT:()=>Vt,S_SUCCESS:()=>Ss,S_WARN:()=>Cs,autocomplete:()=>yo,autocompleteMultiselect:()=>pl,box:()=>bl,cancel:()=>$l,confirm:()=>Ve,group:()=>wl,groupMultiselect:()=>vl,intro:()=>kl,isCI:()=>bs,isCancel:()=>ae,isTTY:()=>so,limitOptions:()=>di,log:()=>Ke,multiselect:()=>xl,note:()=>Cl,outro:()=>_l,password:()=>Ol,path:()=>Il,progress:()=>Al,select:()=>it,selectKey:()=>Tl,settings:()=>ue,spinner:()=>ji,stream:()=>qt,symbol:()=>tt,symbolBar:()=>Is,taskLog:()=>Dl,tasks:()=>El,text:()=>De,unicode:()=>fn,unicodeOr:()=>oe,updateSettings:()=>Kr});function Qd(){return Ge.default.platform!=="win32"?Ge.default.env.TERM!=="linux":!!Ge.default.env.CI||!!Ge.default.env.WT_SESSION||!!Ge.default.env.TERMINUS_SUBLIME||Ge.default.env.ConEmuTask==="{cmd::Cmder}"||Ge.default.env.TERM_PROGRAM==="Terminus-Sublime"||Ge.default.env.TERM_PROGRAM==="vscode"||Ge.default.env.TERM==="xterm-256color"||Ge.default.env.TERM==="alacritty"||Ge.default.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}function ai(e,t,i){return String(e).normalize().replaceAll(`\r
45
45
  `,`
46
46
  `).split(`
47
- `).map(s=>Jl(s,t,i)).join(`
48
- `)}function Ur(e){return e.label??String(e.value??"")}function Zr(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 Gl(e,t){let i=[];for(let s of t)e.includes(s.value)&&i.push(s);return i}function qr(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 ud({style:e="heavy",max:t=100,size:i=40,...s}={}){let n=gi(s),r=0,o="",a=Math.max(1,t),l=Math.max(1,i),f=k=>{switch(k){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=(k,$)=>{let g=Math.floor(r/a*l);return`${f(k)(Mr[e].repeat(g))}${p.default.dim(Mr[e].repeat(l-g))} ${$}`},h=(k="")=>{o=k,n.start(m("initial",k))},b=(k=1,$)=>{r=Math.min(a,k+r),n.message(m("active",$??o)),o=$??o};return{start:h,stop:n.stop,cancel:n.cancel,error:n.error,clear:n.clear,advance:b,isCancelled:n.isCancelled,message:k=>b(0,k)}}var p,Je,Ut,pi,ti,Zi,Qi,rn,Lr,le,Vr,on,an,Mt,ln,T,Se,Wr,Hr,hi,qt,es,Nt,ii,Jr,ts,dn,Br,cn,un,Gr,mn,fn,pn,hn,tt,gn,Pl,Dl,Nl,tn,Ki,zi,sn,Yi,Ul,ql,Kr,Ml,Ne,is,zr,Fl,yn,Yr,Ll,Xr,bn,Pr,Vl,Dr,Nr,Wl,nn,Hl,Jl,Bl,ni,Qr,Kl,zl,Yl,Xl,Zl,Xe,Ql,ed,Be,td,id,sd,fi,nd,rd,od,ad,ld,dd,cd,gi,Mr,Xi,it,md,Fr,Dt,fd,pd,hd,Pe,Ue=Te(()=>{en();en();p=D(F(),1),Je=D(require("node:process"),1),Ut=require("node:fs"),pi=require("node:path"),ti=D(Ws(),1),Zi=require("node:util");Qi=El(),rn=()=>process.env.CI==="true",Lr=e=>e.isTTY===!0,le=(e,t)=>Qi?e:t,Vr=le("\u25C6","*"),on=le("\u25A0","x"),an=le("\u25B2","x"),Mt=le("\u25C7","o"),ln=le("\u250C","T"),T=le("\u2502","|"),Se=le("\u2514","\u2014"),Wr=le("\u2510","T"),Hr=le("\u2518","\u2014"),hi=le("\u25CF",">"),qt=le("\u25CB"," "),es=le("\u25FB","[\u2022]"),Nt=le("\u25FC","[+]"),ii=le("\u25FB","[ ]"),Jr=le("\u25AA","\u2022"),ts=le("\u2500","-"),dn=le("\u256E","+"),Br=le("\u251C","+"),cn=le("\u256F","+"),un=le("\u2570","+"),Gr=le("\u256D","+"),mn=le("\u25CF","\u2022"),fn=le("\u25C6","*"),pn=le("\u25B2","!"),hn=le("\u25A0","x"),tt=e=>{switch(e){case"initial":case"active":return p.default.cyan(Vr);case"cancel":return p.default.red(on);case"error":return p.default.yellow(an);case"submit":return p.default.green(Mt)}},gn=e=>{switch(e){case"initial":case"active":return p.default.cyan(T);case"cancel":return p.default.red(T);case"error":return p.default.yellow(T);case"submit":return p.default.green(T)}},Pl=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,Dl=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,Nl=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,tn=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,Ki=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,zi=/\t{1,1000}/y,sn=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"),Yi=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Ul=new RegExp("\\p{M}+","gu"),ql={limit:1/0,ellipsis:""},Kr=(e,t={},i={})=>{let s=t.limit??1/0,n=t.ellipsis??"",r=t?.ellipsisWidth??(n?Kr(n,ql,i).width:0),o=i.ansiWidth??0,a=i.controlWidth??0,l=i.tabWidth??8,f=i.ambiguousWidth??1,m=i.emojiWidth??2,h=i.fullWidthWidth??2,b=i.regularWidth??1,k=i.wideWidth??2,$=0,g=0,x=e.length,S=0,O=!1,A=x,W=Math.max(0,s-r),H=0,se=0,P=0,E=0;e:for(;;){if(se>H||g>=x&&g>$){let U=e.slice(H,se)||e.slice($,g);S=0;for(let te of U.replaceAll(Ul,"")){let X=te.codePointAt(0)||0;if(Dl(X)?E=h:Nl(X)?E=k:f!==b&&Pl(X)?E=f:E=b,P+E>W&&(A=Math.min(A,Math.max(H,$)+S)),P+E>s){O=!0;break e}S+=te.length,P+=E}H=se=0}if(g>=x)break;if(Yi.lastIndex=g,Yi.test(e)){if(S=Yi.lastIndex-g,E=S*b,P+E>W&&(A=Math.min(A,g+Math.floor((W-P)/b))),P+E>s){O=!0;break}P+=E,H=$,se=g,g=$=Yi.lastIndex;continue}if(tn.lastIndex=g,tn.test(e)){if(P+o>W&&(A=Math.min(A,g)),P+o>s){O=!0;break}P+=o,H=$,se=g,g=$=tn.lastIndex;continue}if(Ki.lastIndex=g,Ki.test(e)){if(S=Ki.lastIndex-g,E=S*a,P+E>W&&(A=Math.min(A,g+Math.floor((W-P)/a))),P+E>s){O=!0;break}P+=E,H=$,se=g,g=$=Ki.lastIndex;continue}if(zi.lastIndex=g,zi.test(e)){if(S=zi.lastIndex-g,E=S*l,P+E>W&&(A=Math.min(A,g+Math.floor((W-P)/l))),P+E>s){O=!0;break}P+=E,H=$,se=g,g=$=zi.lastIndex;continue}if(sn.lastIndex=g,sn.test(e)){if(P+m>W&&(A=Math.min(A,g)),P+m>s){O=!0;break}P+=m,H=$,se=g,g=$=sn.lastIndex;continue}g+=1}return{width:O?W:P,index:O?A:x,truncated:O,ellipsed:O&&s>=r}},Ml={limit:1/0,ellipsis:"",ellipsisWidth:0},Ne=(e,t={})=>Kr(e,Ml,t).width,is="\x1B",zr="\x9B",Fl=39,yn="\x07",Yr="[",Ll="]",Xr="m",bn=`${Ll}8;;`,Pr=new RegExp(`(?:\\${Yr}(?<code>\\d+)m|\\${bn}(?<uri>.*)${yn})`,"y"),Vl=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},Dr=e=>`${is}${Yr}${e}${Xr}`,Nr=e=>`${is}${bn}${e}${yn}`,Wl=e=>e.map(t=>Ne(t)),nn=(e,t,i)=>{let s=t[Symbol.iterator](),n=!1,r=!1,o=e.at(-1),a=o===void 0?0:Ne(o),l=s.next(),f=s.next(),m=0;for(;!l.done;){let h=l.value,b=Ne(h);a+b<=i?e[e.length-1]+=h:(e.push(h),a=0),(h===is||h===zr)&&(n=!0,r=t.startsWith(bn,m+1)),n?r?h===yn&&(n=!1,r=!1):h===Xr&&(n=!1):(a+=b,a===i&&!f.done&&(e.push(""),a=0)),l=f,f=s.next(),m+=h.length}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop())},Hl=e=>{let t=e.split(" "),i=t.length;for(;i>0&&!(Ne(t[i-1])>0);)i--;return i===t.length?e:t.slice(0,i).join(" ")+t.slice(i).join("")},Jl=(e,t,i={})=>{if(i.trim!==!1&&e.trim()==="")return"";let s="",n,r,o=e.split(" "),a=Wl(o),l=[""];for(let[$,g]of o.entries()){i.trim!==!1&&(l[l.length-1]=(l.at(-1)??"").trimStart());let x=Ne(l.at(-1)??"");if($!==0&&(x>=t&&(i.wordWrap===!1||i.trim===!1)&&(l.push(""),x=0),(x>0||i.trim===!1)&&(l[l.length-1]+=" ",x++)),i.hard&&a[$]>t){let S=t-x,O=1+Math.floor((a[$]-S-1)/t);Math.floor((a[$]-1)/t)<O&&l.push(""),nn(l,g,t);continue}if(x+a[$]>t&&x>0&&a[$]>0){if(i.wordWrap===!1&&x<t){nn(l,g,t);continue}l.push("")}if(x+a[$]>t&&i.wordWrap===!1){nn(l,g,t);continue}l[l.length-1]+=g}i.trim!==!1&&(l=l.map($=>Hl($)));let f=l.join(`
49
- `),m=f[Symbol.iterator](),h=m.next(),b=m.next(),k=0;for(;!h.done;){let $=h.value,g=b.value;if(s+=$,$===is||$===zr){Pr.lastIndex=k+1;let S=Pr.exec(f)?.groups;if(S?.code!==void 0){let O=Number.parseFloat(S.code);n=O===Fl?void 0:O}else S?.uri!==void 0&&(r=S.uri.length===0?void 0:S.uri)}let x=n?Vl(n):void 0;g===`
50
- `?(r&&(s+=Nr("")),n&&x&&(s+=Dr(x))):$===`
51
- `&&(n&&x&&(s+=Dr(n)),r&&(s+=Nr(r))),k+=$.length,h=b,b=m.next()}return s};Bl=(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}},ni=e=>{let{cursor:t,options:i,style:s}=e,n=e.output??process.stdout,r=Pt(n),o=e.columnPadding??0,a=e.rowPadding??4,l=r-o,f=Qs(n),m=p.default.dim("..."),h=e.maxItems??Number.POSITIVE_INFINITY,b=Math.max(f-a,0),k=Math.max(Math.min(h,b),5),$=0;t>=k-3&&($=Math.max(Math.min(t-k+3,i.length-k),0));let g=k<i.length&&$>0,x=k<i.length&&$+k<i.length,S=Math.min($+k,i.length),O=[],A=0;g&&A++,x&&A++;let W=$+(g?1:0),H=S-(x?1:0);for(let P=W;P<H;P++){let E=si(s(i[P],P===t),l,{hard:!0,trim:!1}).split(`
52
- `);O.push(E),A+=E.length}if(A>b){let P=0,E=0,U=A,te=t-W,X=(q,re)=>Bl(O,U,q,re,b);g?({lineCount:U,removals:P}=X(0,te),U>b&&({lineCount:U,removals:E}=X(te+1,O.length))):({lineCount:U,removals:E}=X(te+1,O.length),U>b&&({lineCount:U,removals:P}=X(0,te))),P>0&&(g=!0,O.splice(0,P)),E>0&&(x=!0,O.splice(O.length-E,E))}let se=[];g&&se.push(m);for(let P of O)for(let E of P)se.push(E);return x&&se.push(m),se};Qr=e=>new mi({options:e.options,initialValue:e.initialValue?[e.initialValue]:void 0,initialUserInput:e.initialUserInput,filter:e.filter??((t,i)=>Zr(t,i)),signal:e.signal,input:e.input,output:e.output,validate:e.validate,render(){let t=e.withGuide??me.withGuide,i=t?[`${p.default.gray(T)}`,`${tt(this.state)} ${e.message}`]:[`${tt(this.state)} ${e.message}`],s=this.userInput,n=this.options,r=e.placeholder,o=s===""&&r!==void 0,a=(l,f)=>{let m=Ur(l),h=l.hint&&l.value===this.focusedValue?p.default.dim(` (${l.hint})`):"";switch(f){case"active":return`${p.default.green(hi)} ${m}${h}`;case"inactive":return`${p.default.dim(qt)} ${p.default.dim(m)}`;case"disabled":return`${p.default.gray(qt)} ${p.default.strikethrough(p.default.gray(m))}`}};switch(this.state){case"submit":{let l=Gl(this.selectedValues,n),f=l.length>0?` ${p.default.dim(l.map(Ur).join(", "))}`:"",m=t?p.default.gray(T):"";return`${i.join(`
47
+ `).map(n=>ul(n,t,i)).join(`
48
+ `)}function eo(e){return e.label??String(e.value??"")}function go(e,t){if(!e)return!0;let i=(t.label??String(t.value??"")).toLowerCase(),n=(t.hint??"").toLowerCase(),s=String(t.value).toLowerCase(),r=e.toLowerCase();return i.includes(r)||n.includes(r)||s.includes(r)}function fl(e,t){let i=[];for(let n of t)e.includes(n.value)&&i.push(n);return i}function to(e,t,i,n){let s=i,r=i;return n==="center"?s=Math.floor((t-e)/2):n==="right"&&(s=t-e-i),r=t-s-e,[s,r]}function Al({style:e="heavy",max:t=100,size:i=40,...n}={}){let s=ji(n),r=0,o="",a=Math.max(1,t),d=Math.max(1,i),f=k=>{switch(k){case"initial":case"active":return h.default.magenta;case"error":case"cancel":return h.default.red;case"submit":return h.default.green;default:return h.default.magenta}},m=(k,b)=>{let g=Math.floor(r/a*d);return`${f(k)(io[e].repeat(g))}${h.default.dim(io[e].repeat(d-g))} ${b}`},p=(k="")=>{o=k,s.start(m("initial",k))},y=(k=1,b)=>{r=Math.min(a,k+r),s.message(m("active",b??o)),o=b??o};return{start:p,stop:s.stop,cancel:s.cancel,error:s.error,clear:s.clear,advance:y,isCancelled:s.isCancelled,message:k=>y(0,k)}}var h,Ge,Ft,_i,ri,mn,fn,bs,so,oe,ro,ws,vs,Vt,$s,D,Oe,oo,ao,xi,Lt,pn,Mt,oi,lo,hn,ks,co,_s,xs,uo,js,Ss,Cs,Os,tt,Is,el,tl,il,hs,dn,ln,gs,cn,nl,sl,mo,rl,Me,gn,fo,ol,Rs,po,al,ho,As,Xr,dl,Zr,Qr,ll,ys,cl,ul,ml,di,yo,pl,hl,gl,yl,bl,Ve,wl,vl,Ke,$l,kl,_l,ki,xl,jl,Sl,Cl,Ol,Il,Rl,ji,io,un,it,Tl,no,qt,El,Pl,Dl,De,Ne=Ie(()=>{ps();ps();h=U(M(),1),Ge=U(require("node:process"),1),Ft=require("node:fs"),_i=require("node:path"),ri=U(ns(),1),mn=require("node:util");fn=Qd(),bs=()=>process.env.CI==="true",so=e=>e.isTTY===!0,oe=(e,t)=>fn?e:t,ro=oe("\u25C6","*"),ws=oe("\u25A0","x"),vs=oe("\u25B2","x"),Vt=oe("\u25C7","o"),$s=oe("\u250C","T"),D=oe("\u2502","|"),Oe=oe("\u2514","\u2014"),oo=oe("\u2510","T"),ao=oe("\u2518","\u2014"),xi=oe("\u25CF",">"),Lt=oe("\u25CB"," "),pn=oe("\u25FB","[\u2022]"),Mt=oe("\u25FC","[+]"),oi=oe("\u25FB","[ ]"),lo=oe("\u25AA","\u2022"),hn=oe("\u2500","-"),ks=oe("\u256E","+"),co=oe("\u251C","+"),_s=oe("\u256F","+"),xs=oe("\u2570","+"),uo=oe("\u256D","+"),js=oe("\u25CF","\u2022"),Ss=oe("\u25C6","*"),Cs=oe("\u25B2","!"),Os=oe("\u25A0","x"),tt=e=>{switch(e){case"initial":case"active":return h.default.cyan(ro);case"cancel":return h.default.red(ws);case"error":return h.default.yellow(vs);case"submit":return h.default.green(Vt)}},Is=e=>{switch(e){case"initial":case"active":return h.default.cyan(D);case"cancel":return h.default.red(D);case"error":return h.default.yellow(D);case"submit":return h.default.green(D)}},el=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,tl=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,il=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,hs=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/y,dn=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,ln=/\t{1,1000}/y,gs=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"),cn=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,nl=new RegExp("\\p{M}+","gu"),sl={limit:1/0,ellipsis:""},mo=(e,t={},i={})=>{let n=t.limit??1/0,s=t.ellipsis??"",r=t?.ellipsisWidth??(s?mo(s,sl,i).width:0),o=i.ansiWidth??0,a=i.controlWidth??0,d=i.tabWidth??8,f=i.ambiguousWidth??1,m=i.emojiWidth??2,p=i.fullWidthWidth??2,y=i.regularWidth??1,k=i.wideWidth??2,b=0,g=0,S=e.length,j=0,O=!1,T=S,W=Math.max(0,n-r),H=0,ee=0,q=0,N=0;e:for(;;){if(ee>H||g>=S&&g>b){let le=e.slice(H,ee)||e.slice(b,g);j=0;for(let de of le.replaceAll(nl,"")){let P=de.codePointAt(0)||0;if(tl(P)?N=p:il(P)?N=k:f!==y&&el(P)?N=f:N=y,q+N>W&&(T=Math.min(T,Math.max(H,b)+j)),q+N>n){O=!0;break e}j+=de.length,q+=N}H=ee=0}if(g>=S)break;if(cn.lastIndex=g,cn.test(e)){if(j=cn.lastIndex-g,N=j*y,q+N>W&&(T=Math.min(T,g+Math.floor((W-q)/y))),q+N>n){O=!0;break}q+=N,H=b,ee=g,g=b=cn.lastIndex;continue}if(hs.lastIndex=g,hs.test(e)){if(q+o>W&&(T=Math.min(T,g)),q+o>n){O=!0;break}q+=o,H=b,ee=g,g=b=hs.lastIndex;continue}if(dn.lastIndex=g,dn.test(e)){if(j=dn.lastIndex-g,N=j*a,q+N>W&&(T=Math.min(T,g+Math.floor((W-q)/a))),q+N>n){O=!0;break}q+=N,H=b,ee=g,g=b=dn.lastIndex;continue}if(ln.lastIndex=g,ln.test(e)){if(j=ln.lastIndex-g,N=j*d,q+N>W&&(T=Math.min(T,g+Math.floor((W-q)/d))),q+N>n){O=!0;break}q+=N,H=b,ee=g,g=b=ln.lastIndex;continue}if(gs.lastIndex=g,gs.test(e)){if(q+m>W&&(T=Math.min(T,g)),q+m>n){O=!0;break}q+=m,H=b,ee=g,g=b=gs.lastIndex;continue}g+=1}return{width:O?W:q,index:O?T:S,truncated:O,ellipsed:O&&n>=r}},rl={limit:1/0,ellipsis:"",ellipsisWidth:0},Me=(e,t={})=>mo(e,rl,t).width,gn="\x1B",fo="\x9B",ol=39,Rs="\x07",po="[",al="]",ho="m",As=`${al}8;;`,Xr=new RegExp(`(?:\\${po}(?<code>\\d+)m|\\${As}(?<uri>.*)${Rs})`,"y"),dl=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},Zr=e=>`${gn}${po}${e}${ho}`,Qr=e=>`${gn}${As}${e}${Rs}`,ll=e=>e.map(t=>Me(t)),ys=(e,t,i)=>{let n=t[Symbol.iterator](),s=!1,r=!1,o=e.at(-1),a=o===void 0?0:Me(o),d=n.next(),f=n.next(),m=0;for(;!d.done;){let p=d.value,y=Me(p);a+y<=i?e[e.length-1]+=p:(e.push(p),a=0),(p===gn||p===fo)&&(s=!0,r=t.startsWith(As,m+1)),s?r?p===Rs&&(s=!1,r=!1):p===ho&&(s=!1):(a+=y,a===i&&!f.done&&(e.push(""),a=0)),d=f,f=n.next(),m+=p.length}o=e.at(-1),!a&&o!==void 0&&o.length>0&&e.length>1&&(e[e.length-2]+=e.pop())},cl=e=>{let t=e.split(" "),i=t.length;for(;i>0&&!(Me(t[i-1])>0);)i--;return i===t.length?e:t.slice(0,i).join(" ")+t.slice(i).join("")},ul=(e,t,i={})=>{if(i.trim!==!1&&e.trim()==="")return"";let n="",s,r,o=e.split(" "),a=ll(o),d=[""];for(let[b,g]of o.entries()){i.trim!==!1&&(d[d.length-1]=(d.at(-1)??"").trimStart());let S=Me(d.at(-1)??"");if(b!==0&&(S>=t&&(i.wordWrap===!1||i.trim===!1)&&(d.push(""),S=0),(S>0||i.trim===!1)&&(d[d.length-1]+=" ",S++)),i.hard&&a[b]>t){let j=t-S,O=1+Math.floor((a[b]-j-1)/t);Math.floor((a[b]-1)/t)<O&&d.push(""),ys(d,g,t);continue}if(S+a[b]>t&&S>0&&a[b]>0){if(i.wordWrap===!1&&S<t){ys(d,g,t);continue}d.push("")}if(S+a[b]>t&&i.wordWrap===!1){ys(d,g,t);continue}d[d.length-1]+=g}i.trim!==!1&&(d=d.map(b=>cl(b)));let f=d.join(`
49
+ `),m=f[Symbol.iterator](),p=m.next(),y=m.next(),k=0;for(;!p.done;){let b=p.value,g=y.value;if(n+=b,b===gn||b===fo){Xr.lastIndex=k+1;let j=Xr.exec(f)?.groups;if(j?.code!==void 0){let O=Number.parseFloat(j.code);s=O===ol?void 0:O}else j?.uri!==void 0&&(r=j.uri.length===0?void 0:j.uri)}let S=s?dl(s):void 0;g===`
50
+ `?(r&&(n+=Qr("")),s&&S&&(n+=Zr(S))):b===`
51
+ `&&(s&&S&&(n+=Zr(s)),r&&(n+=Qr(r))),k+=b.length,p=y,y=m.next()}return n};ml=(e,t,i,n,s)=>{let r=t,o=0;for(let a=i;a<n;a++){let d=e[a];if(r=r-d.length,o++,r<=s)break}return{lineCount:r,removals:o}},di=e=>{let{cursor:t,options:i,style:n}=e,s=e.output??process.stdout,r=Ut(s),o=e.columnPadding??0,a=e.rowPadding??4,d=r-o,f=fs(s),m=h.default.dim("..."),p=e.maxItems??Number.POSITIVE_INFINITY,y=Math.max(f-a,0),k=Math.max(Math.min(p,y),5),b=0;t>=k-3&&(b=Math.max(Math.min(t-k+3,i.length-k),0));let g=k<i.length&&b>0,S=k<i.length&&b+k<i.length,j=Math.min(b+k,i.length),O=[],T=0;g&&T++,S&&T++;let W=b+(g?1:0),H=j-(S?1:0);for(let q=W;q<H;q++){let N=ai(n(i[q],q===t),d,{hard:!0,trim:!1}).split(`
52
+ `);O.push(N),T+=N.length}if(T>y){let q=0,N=0,le=T,de=t-W,P=(pe,ne)=>ml(O,le,pe,ne,y);g?({lineCount:le,removals:q}=P(0,de),le>y&&({lineCount:le,removals:N}=P(de+1,O.length))):({lineCount:le,removals:N}=P(de+1,O.length),le>y&&({lineCount:le,removals:q}=P(0,de))),q>0&&(g=!0,O.splice(0,q)),N>0&&(S=!0,O.splice(O.length-N,N))}let ee=[];g&&ee.push(m);for(let q of O)for(let N of q)ee.push(N);return S&&ee.push(m),ee};yo=e=>new $i({options:e.options,initialValue:e.initialValue?[e.initialValue]:void 0,initialUserInput:e.initialUserInput,filter:e.filter??((t,i)=>go(t,i)),signal:e.signal,input:e.input,output:e.output,validate:e.validate,render(){let t=e.withGuide??ue.withGuide,i=t?[`${h.default.gray(D)}`,`${tt(this.state)} ${e.message}`]:[`${tt(this.state)} ${e.message}`],n=this.userInput,s=this.options,r=e.placeholder,o=n===""&&r!==void 0,a=(d,f)=>{let m=eo(d),p=d.hint&&d.value===this.focusedValue?h.default.dim(` (${d.hint})`):"";switch(f){case"active":return`${h.default.green(xi)} ${m}${p}`;case"inactive":return`${h.default.dim(Lt)} ${h.default.dim(m)}`;case"disabled":return`${h.default.gray(Lt)} ${h.default.strikethrough(h.default.gray(m))}`}};switch(this.state){case"submit":{let d=fl(this.selectedValues,s),f=d.length>0?` ${h.default.dim(d.map(eo).join(", "))}`:"",m=t?h.default.gray(D):"";return`${i.join(`
53
53
  `)}
54
- ${m}${f}`}case"cancel":{let l=s?` ${p.default.strikethrough(p.default.dim(s))}`:"",f=t?p.default.gray(T):"";return`${i.join(`
54
+ ${m}${f}`}case"cancel":{let d=n?` ${h.default.strikethrough(h.default.dim(n))}`:"",f=t?h.default.gray(D):"";return`${i.join(`
55
55
  `)}
56
- ${f}${l}`}default:{let l=this.state==="error"?p.default.yellow:p.default.cyan,f=t?`${l(T)} `:"",m=t?l(Se):"",h="";if(this.isNavigating||o){let O=o?r:s;h=O!==""?` ${p.default.dim(O)}`:""}else h=` ${this.userInputWithCursor}`;let b=this.filteredOptions.length!==n.length?p.default.dim(` (${this.filteredOptions.length} match${this.filteredOptions.length===1?"":"es"})`):"",k=this.filteredOptions.length===0&&s?[`${f}${p.default.yellow("No matches found")}`]:[],$=this.state==="error"?[`${f}${p.default.yellow(this.error)}`]:[];t&&i.push(`${f.trimEnd()}`),i.push(`${f}${p.default.dim("Search:")}${h}${b}`,...k,...$);let g=[`${p.default.dim("\u2191/\u2193")} to select`,`${p.default.dim("Enter:")} confirm`,`${p.default.dim("Type:")} to search`],x=[`${f}${g.join(" \u2022 ")}`,m],S=this.filteredOptions.length===0?[]:ni({cursor:this.cursor,options:this.filteredOptions,columnPadding:t?3:0,rowPadding:i.length+x.length,style:(O,A)=>a(O,O.disabled?"disabled":A?"active":"inactive"),maxItems:e.maxItems,output:e.output});return[...i,...S.map(O=>`${f}${O}`),...x].join(`
57
- `)}}}}).prompt(),Kl=e=>{let t=(s,n,r,o)=>{let a=r.includes(s.value),l=s.label??String(s.value??""),f=s.hint&&o!==void 0&&s.value===o?p.default.dim(` (${s.hint})`):"",m=a?p.default.green(Nt):p.default.dim(ii);return s.disabled?`${p.default.gray(ii)} ${p.default.strikethrough(p.default.gray(l))}`:n?`${m} ${l}${f}`:`${m} ${p.default.dim(l)}`},i=new mi({options:e.options,multiple:!0,filter:e.filter??((s,n)=>Zr(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(T)}
56
+ ${f}${d}`}default:{let d=this.state==="error"?h.default.yellow:h.default.cyan,f=t?`${d(D)} `:"",m=t?d(Oe):"",p="";if(this.isNavigating||o){let O=o?r:n;p=O!==""?` ${h.default.dim(O)}`:""}else p=` ${this.userInputWithCursor}`;let y=this.filteredOptions.length!==s.length?h.default.dim(` (${this.filteredOptions.length} match${this.filteredOptions.length===1?"":"es"})`):"",k=this.filteredOptions.length===0&&n?[`${f}${h.default.yellow("No matches found")}`]:[],b=this.state==="error"?[`${f}${h.default.yellow(this.error)}`]:[];t&&i.push(`${f.trimEnd()}`),i.push(`${f}${h.default.dim("Search:")}${p}${y}`,...k,...b);let g=[`${h.default.dim("\u2191/\u2193")} to select`,`${h.default.dim("Enter:")} confirm`,`${h.default.dim("Type:")} to search`],S=[`${f}${g.join(" \u2022 ")}`,m],j=this.filteredOptions.length===0?[]:di({cursor:this.cursor,options:this.filteredOptions,columnPadding:t?3:0,rowPadding:i.length+S.length,style:(O,T)=>a(O,O.disabled?"disabled":T?"active":"inactive"),maxItems:e.maxItems,output:e.output});return[...i,...j.map(O=>`${f}${O}`),...S].join(`
57
+ `)}}}}).prompt(),pl=e=>{let t=(n,s,r,o)=>{let a=r.includes(n.value),d=n.label??String(n.value??""),f=n.hint&&o!==void 0&&n.value===o?h.default.dim(` (${n.hint})`):"",m=a?h.default.green(Mt):h.default.dim(oi);return n.disabled?`${h.default.gray(oi)} ${h.default.strikethrough(h.default.gray(d))}`:s?`${m} ${d}${f}`:`${m} ${h.default.dim(d)}`},i=new $i({options:e.options,multiple:!0,filter:e.filter??((n,s)=>go(n,s)),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 n=`${h.default.gray(D)}
58
58
  ${tt(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,f=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(T)} ${p.default.dim(`${this.selectedValues.length} items selected`)}`;case"cancel":return`${s}${p.default.gray(T)} ${p.default.strikethrough(p.default.dim(n))}`;default:{let m=this.state==="error"?p.default.yellow:p.default.cyan,h=[`${p.default.dim("\u2191/\u2193")} to navigate`,`${p.default.dim(this.isNavigating?"Space/Tab:":"Tab:")} select`,`${p.default.dim("Enter:")} confirm`,`${p.default.dim("Type:")} to search`],b=this.filteredOptions.length===0&&n?[`${m(T)} ${p.default.yellow("No matches found")}`]:[],k=this.state==="error"?[`${m(T)} ${p.default.yellow(this.error)}`]:[],$=[...`${s}${m(T)}`.split(`
60
- `),`${m(T)} ${p.default.dim("Search:")} ${a}${f}`,...b,...k],g=[`${m(T)} ${h.join(" \u2022 ")}`,`${m(Se)}`],x=ni({cursor:this.cursor,options:this.filteredOptions,style:(S,O)=>t(S,O,this.selectedValues,this.focusedValue),maxItems:e.maxItems,output:e.output,rowPadding:$.length+g.length});return[...$,...x.map(S=>`${m(T)} ${S}`),...g].join(`
61
- `)}}}});return i.prompt()},zl=[Gr,dn,un,cn],Yl=[ln,Wr,Se,Hr];Xl=e=>e,Zl=(e="",t="",i)=>{let s=i?.output??process.stdout,n=Pt(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),f=i?.withGuide??me.withGuide?`${T} `:"",m=i?.formatBorder??Xl,h=(i?.rounded?zl:Yl).map(m),b=m(ts),k=m(T),$=Ne(f),g=Ne(t),x=n-$,S=Math.floor(n*l)-$;if(i?.width==="auto"){let U=e.split(`
62
- `),te=g+o*2;for(let q of U){let re=Ne(q)+a*2;re>te&&(te=re)}let X=te+r;X<S&&(S=X)}S%2!==0&&(S<x?S++:S--);let O=S-r,A=O-o*2,W=g>A?`${t.slice(0,A-3)}...`:t,[H,se]=qr(Ne(W),O,o,i?.titleAlign),P=si(e,O-a*2,{hard:!0,trim:!1});s.write(`${f}${h[0]}${b.repeat(H)}${W}${b.repeat(se)}${h[1]}
63
- `);let E=P.split(`
64
- `);for(let U of E){let[te,X]=qr(Ne(U),O,a,i?.contentAlign);s.write(`${f}${k}${" ".repeat(te)}${U}${" ".repeat(X)}${k}
65
- `)}s.write(`${f}${h[2]}${b.repeat(O)}${h[3]}
66
- `)},Xe=e=>{let t=e.active??"Yes",i=e.inactive??"No";return new Li({active:t,inactive:i,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let s=e.withGuide??me.withGuide,n=`${s?`${p.default.gray(T)}
59
+ `,s=this.userInput,r=e.placeholder,o=s===""&&r!==void 0,a=this.isNavigating||o?h.default.dim(o?r:s):this.userInputWithCursor,d=this.options,f=this.filteredOptions.length!==d.length?h.default.dim(` (${this.filteredOptions.length} match${this.filteredOptions.length===1?"":"es"})`):"";switch(this.state){case"submit":return`${n}${h.default.gray(D)} ${h.default.dim(`${this.selectedValues.length} items selected`)}`;case"cancel":return`${n}${h.default.gray(D)} ${h.default.strikethrough(h.default.dim(s))}`;default:{let m=this.state==="error"?h.default.yellow:h.default.cyan,p=[`${h.default.dim("\u2191/\u2193")} to navigate`,`${h.default.dim(this.isNavigating?"Space/Tab:":"Tab:")} select`,`${h.default.dim("Enter:")} confirm`,`${h.default.dim("Type:")} to search`],y=this.filteredOptions.length===0&&s?[`${m(D)} ${h.default.yellow("No matches found")}`]:[],k=this.state==="error"?[`${m(D)} ${h.default.yellow(this.error)}`]:[],b=[...`${n}${m(D)}`.split(`
60
+ `),`${m(D)} ${h.default.dim("Search:")} ${a}${f}`,...y,...k],g=[`${m(D)} ${p.join(" \u2022 ")}`,`${m(Oe)}`],S=di({cursor:this.cursor,options:this.filteredOptions,style:(j,O)=>t(j,O,this.selectedValues,this.focusedValue),maxItems:e.maxItems,output:e.output,rowPadding:b.length+g.length});return[...b,...S.map(j=>`${m(D)} ${j}`),...g].join(`
61
+ `)}}}});return i.prompt()},hl=[uo,ks,xs,_s],gl=[$s,oo,Oe,ao];yl=e=>e,bl=(e="",t="",i)=>{let n=i?.output??process.stdout,s=Ut(n),r=2,o=i?.titlePadding??1,a=i?.contentPadding??2,d=i?.width===void 0||i.width==="auto"?1:Math.min(1,i.width),f=i?.withGuide??ue.withGuide?`${D} `:"",m=i?.formatBorder??yl,p=(i?.rounded?hl:gl).map(m),y=m(hn),k=m(D),b=Me(f),g=Me(t),S=s-b,j=Math.floor(s*d)-b;if(i?.width==="auto"){let le=e.split(`
62
+ `),de=g+o*2;for(let pe of le){let ne=Me(pe)+a*2;ne>de&&(de=ne)}let P=de+r;P<j&&(j=P)}j%2!==0&&(j<S?j++:j--);let O=j-r,T=O-o*2,W=g>T?`${t.slice(0,T-3)}...`:t,[H,ee]=to(Me(W),O,o,i?.titleAlign),q=ai(e,O-a*2,{hard:!0,trim:!1});n.write(`${f}${p[0]}${y.repeat(H)}${W}${y.repeat(ee)}${p[1]}
63
+ `);let N=q.split(`
64
+ `);for(let le of N){let[de,P]=to(Me(le),O,a,i?.contentAlign);n.write(`${f}${k}${" ".repeat(de)}${le}${" ".repeat(P)}${k}
65
+ `)}n.write(`${f}${p[2]}${y.repeat(O)}${p[3]}
66
+ `)},Ve=e=>{let t=e.active??"Yes",i=e.inactive??"No";return new en({active:t,inactive:i,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let n=e.withGuide??ue.withGuide,s=`${n?`${h.default.gray(D)}
67
67
  `:""}${tt(this.state)} ${e.message}
68
- `,r=this.value?t:i;switch(this.state){case"submit":{let o=s?`${p.default.gray(T)} `:"";return`${n}${o}${p.default.dim(r)}`}case"cancel":{let o=s?`${p.default.gray(T)} `:"";return`${n}${o}${p.default.strikethrough(p.default.dim(r))}${s?`
69
- ${p.default.gray(T)}`:""}`}default:{let o=s?`${p.default.cyan(T)} `:"",a=s?p.default.cyan(Se):"";return`${n}${o}${this.value?`${p.default.green(hi)} ${t}`:`${p.default.dim(qt)} ${p.default.dim(t)}`}${e.vertical?s?`
70
- ${p.default.cyan(T)} `:`
71
- `:` ${p.default.dim("/")} `}${this.value?`${p.default.dim(qt)} ${p.default.dim(i)}`:`${p.default.green(hi)} ${i}`}
68
+ `,r=this.value?t:i;switch(this.state){case"submit":{let o=n?`${h.default.gray(D)} `:"";return`${s}${o}${h.default.dim(r)}`}case"cancel":{let o=n?`${h.default.gray(D)} `:"";return`${s}${o}${h.default.strikethrough(h.default.dim(r))}${n?`
69
+ ${h.default.gray(D)}`:""}`}default:{let o=n?`${h.default.cyan(D)} `:"",a=n?h.default.cyan(Oe):"";return`${s}${o}${this.value?`${h.default.green(xi)} ${t}`:`${h.default.dim(Lt)} ${h.default.dim(t)}`}${e.vertical?n?`
70
+ ${h.default.cyan(D)} `:`
71
+ `:` ${h.default.dim("/")} `}${this.value?`${h.default.dim(Lt)} ${h.default.dim(i)}`:`${h.default.green(xi)} ${i}`}
72
72
  ${a}
73
- `}}}}).prompt()},Ql=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"&&ce(o)){i[n]="canceled",t.onCancel({results:i});continue}i[n]=o}return i},ed=e=>{let{selectableGroups:t=!0,groupSpacing:i=0}=e,s=(r,o,a=[])=>{let l=r.label??String(r.value),f=typeof r.group=="string",m=f&&(a[a.indexOf(r)+1]??{group:!0}),h=f&&m&&m.group===!0,b=f?t?`${h?Se:T} `:" ":"",k="";if(i>0&&!f){let g=`
74
- ${p.default.cyan(T)}`;k=`${g.repeat(i-1)}${g} `}if(o==="active")return`${k}${p.default.dim(b)}${p.default.cyan(es)} ${l}${r.hint?` ${p.default.dim(`(${r.hint})`)}`:""}`;if(o==="group-active")return`${k}${b}${p.default.cyan(es)} ${p.default.dim(l)}`;if(o==="group-active-selected")return`${k}${b}${p.default.green(Nt)} ${p.default.dim(l)}`;if(o==="selected"){let g=f||t?p.default.green(Nt):"";return`${k}${p.default.dim(b)}${g} ${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`${k}${p.default.dim(b)}${p.default.green(Nt)} ${l}${r.hint?` ${p.default.dim(`(${r.hint})`)}`:""}`;if(o==="submitted")return`${p.default.dim(l)}`;let $=f||t?p.default.dim(ii):"";return`${k}${p.default.dim(b)}${$} ${p.default.dim(l)}`},n=e.required??!0;return new Vi({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
- ${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(T)}
73
+ `}}}}).prompt()},wl=async(e,t)=>{let i={},n=Object.keys(e);for(let s of n){let r=e[s],o=await r({results:i})?.catch(a=>{throw a});if(typeof t?.onCancel=="function"&&ae(o)){i[s]="canceled",t.onCancel({results:i});continue}i[s]=o}return i},vl=e=>{let{selectableGroups:t=!0,groupSpacing:i=0}=e,n=(r,o,a=[])=>{let d=r.label??String(r.value),f=typeof r.group=="string",m=f&&(a[a.indexOf(r)+1]??{group:!0}),p=f&&m&&m.group===!0,y=f?t?`${p?Oe:D} `:" ":"",k="";if(i>0&&!f){let g=`
74
+ ${h.default.cyan(D)}`;k=`${g.repeat(i-1)}${g} `}if(o==="active")return`${k}${h.default.dim(y)}${h.default.cyan(pn)} ${d}${r.hint?` ${h.default.dim(`(${r.hint})`)}`:""}`;if(o==="group-active")return`${k}${y}${h.default.cyan(pn)} ${h.default.dim(d)}`;if(o==="group-active-selected")return`${k}${y}${h.default.green(Mt)} ${h.default.dim(d)}`;if(o==="selected"){let g=f||t?h.default.green(Mt):"";return`${k}${h.default.dim(y)}${g} ${h.default.dim(d)}${r.hint?` ${h.default.dim(`(${r.hint})`)}`:""}`}if(o==="cancelled")return`${h.default.strikethrough(h.default.dim(d))}`;if(o==="active-selected")return`${k}${h.default.dim(y)}${h.default.green(Mt)} ${d}${r.hint?` ${h.default.dim(`(${r.hint})`)}`:""}`;if(o==="submitted")return`${h.default.dim(d)}`;let b=f||t?h.default.dim(oi):"";return`${k}${h.default.dim(y)}${b} ${h.default.dim(d)}`},s=e.required??!0;return new tn({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:s,cursorAt:e.cursorAt,selectableGroups:t,validate(r){if(s&&(r===void 0||r.length===0))return`Please select at least one option.
75
+ ${h.default.reset(h.default.dim(`Press ${h.default.gray(h.default.bgWhite(h.default.inverse(" space ")))} to select, ${h.default.gray(h.default.bgWhite(h.default.inverse(" enter ")))} to submit`))}`},render(){let r=`${h.default.gray(D)}
76
76
  ${tt(this.state)} ${e.message}
77
- `,o=this.value??[];switch(this.state){case"submit":{let a=this.options.filter(({value:f})=>o.includes(f)).map(f=>s(f,"submitted")),l=a.length===0?"":` ${a.join(p.default.dim(", "))}`;return`${r}${p.default.gray(T)}${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(T)} ${a.trim()?`${a}
78
- ${p.default.gray(T)}`:""}`}case"error":{let a=this.error.split(`
79
- `).map((l,f)=>f===0?`${p.default.yellow(Se)} ${p.default.yellow(l)}`:` ${l}`).join(`
80
- `);return`${r}${p.default.yellow(T)} ${this.options.map((l,f,m)=>{let h=o.includes(l.value)||l.group===!0&&this.isGroupSelected(`${l.value}`),b=f===this.cursor;return!b&&typeof l.group=="string"&&this.options[this.cursor].value===l.group?s(l,h?"group-active-selected":"group-active",m):b&&h?s(l,"active-selected",m):h?s(l,"selected",m):s(l,b?"active":"inactive",m)}).join(`
81
- ${p.default.yellow(T)} `)}
77
+ `,o=this.value??[];switch(this.state){case"submit":{let a=this.options.filter(({value:f})=>o.includes(f)).map(f=>n(f,"submitted")),d=a.length===0?"":` ${a.join(h.default.dim(", "))}`;return`${r}${h.default.gray(D)}${d}`}case"cancel":{let a=this.options.filter(({value:d})=>o.includes(d)).map(d=>n(d,"cancelled")).join(h.default.dim(", "));return`${r}${h.default.gray(D)} ${a.trim()?`${a}
78
+ ${h.default.gray(D)}`:""}`}case"error":{let a=this.error.split(`
79
+ `).map((d,f)=>f===0?`${h.default.yellow(Oe)} ${h.default.yellow(d)}`:` ${d}`).join(`
80
+ `);return`${r}${h.default.yellow(D)} ${this.options.map((d,f,m)=>{let p=o.includes(d.value)||d.group===!0&&this.isGroupSelected(`${d.value}`),y=f===this.cursor;return!y&&typeof d.group=="string"&&this.options[this.cursor].value===d.group?n(d,p?"group-active-selected":"group-active",m):y&&p?n(d,"active-selected",m):p?n(d,"selected",m):n(d,y?"active":"inactive",m)}).join(`
81
+ ${h.default.yellow(D)} `)}
82
82
  ${a}
83
- `}default:{let a=this.options.map((f,m,h)=>{let b=o.includes(f.value)||f.group===!0&&this.isGroupSelected(`${f.value}`),k=m===this.cursor,$=!k&&typeof f.group=="string"&&this.options[this.cursor].value===f.group,g="";return $?g=s(f,b?"group-active-selected":"group-active",h):k&&b?g=s(f,"active-selected",h):b?g=s(f,"selected",h):g=s(f,k?"active":"inactive",h),`${m!==0&&!g.startsWith(`
83
+ `}default:{let a=this.options.map((f,m,p)=>{let y=o.includes(f.value)||f.group===!0&&this.isGroupSelected(`${f.value}`),k=m===this.cursor,b=!k&&typeof f.group=="string"&&this.options[this.cursor].value===f.group,g="";return b?g=n(f,y?"group-active-selected":"group-active",p):k&&y?g=n(f,"active-selected",p):y?g=n(f,"selected",p):g=n(f,k?"active":"inactive",p),`${m!==0&&!g.startsWith(`
84
84
  `)?" ":""}${g}`}).join(`
85
- ${p.default.cyan(T)}`),l=a.startsWith(`
86
- `)?"":" ";return`${r}${p.default.cyan(T)}${l}${a}
87
- ${p.default.cyan(Se)}
88
- `}}}}).prompt()},Be={message:(e=[],{symbol:t=p.default.gray(T),secondarySymbol:i=p.default.gray(T),output:s=process.stdout,spacing:n=1,withGuide:r}={})=>{let o=[],a=r??me.withGuide,l=a?i:"",f=a?`${t} `:"",m=a?`${i} `:"";for(let b=0;b<n;b++)o.push(l);let h=Array.isArray(e)?e:e.split(`
89
- `);if(h.length>0){let[b,...k]=h;b.length>0?o.push(`${f}${b}`):o.push(a?t:"");for(let $ of k)$.length>0?o.push(`${m}${$}`):o.push(a?i:"")}s.write(`${o.join(`
85
+ ${h.default.cyan(D)}`),d=a.startsWith(`
86
+ `)?"":" ";return`${r}${h.default.cyan(D)}${d}${a}
87
+ ${h.default.cyan(Oe)}
88
+ `}}}}).prompt()},Ke={message:(e=[],{symbol:t=h.default.gray(D),secondarySymbol:i=h.default.gray(D),output:n=process.stdout,spacing:s=1,withGuide:r}={})=>{let o=[],a=r??ue.withGuide,d=a?i:"",f=a?`${t} `:"",m=a?`${i} `:"";for(let y=0;y<s;y++)o.push(d);let p=Array.isArray(e)?e:e.split(`
89
+ `);if(p.length>0){let[y,...k]=p;y.length>0?o.push(`${f}${y}`):o.push(a?t:"");for(let b of k)b.length>0?o.push(`${m}${b}`):o.push(a?i:"")}n.write(`${o.join(`
90
90
  `)}
91
- `)},info:(e,t)=>{Be.message(e,{...t,symbol:p.default.blue(mn)})},success:(e,t)=>{Be.message(e,{...t,symbol:p.default.green(fn)})},step:(e,t)=>{Be.message(e,{...t,symbol:p.default.green(Mt)})},warn:(e,t)=>{Be.message(e,{...t,symbol:p.default.yellow(pn)})},warning:(e,t)=>{Be.warn(e,t)},error:(e,t)=>{Be.message(e,{...t,symbol:p.default.red(hn)})}},td=(e="",t)=>{(t?.output??process.stdout).write(`${p.default.gray(Se)} ${p.default.red(e)}
91
+ `)},info:(e,t)=>{Ke.message(e,{...t,symbol:h.default.blue(js)})},success:(e,t)=>{Ke.message(e,{...t,symbol:h.default.green(Ss)})},step:(e,t)=>{Ke.message(e,{...t,symbol:h.default.green(Vt)})},warn:(e,t)=>{Ke.message(e,{...t,symbol:h.default.yellow(Cs)})},warning:(e,t)=>{Ke.warn(e,t)},error:(e,t)=>{Ke.message(e,{...t,symbol:h.default.red(Os)})}},$l=(e="",t)=>{(t?.output??process.stdout).write(`${h.default.gray(Oe)} ${h.default.red(e)}
92
92
 
93
- `)},id=(e="",t)=>{(t?.output??process.stdout).write(`${p.default.gray(ln)} ${e}
94
- `)},sd=(e="",t)=>{(t?.output??process.stdout).write(`${p.default.gray(T)}
95
- ${p.default.gray(Se)} ${e}
93
+ `)},kl=(e="",t)=>{(t?.output??process.stdout).write(`${h.default.gray($s)} ${e}
94
+ `)},_l=(e="",t)=>{(t?.output??process.stdout).write(`${h.default.gray(D)}
95
+ ${h.default.gray(Oe)} ${e}
96
96
 
97
- `)},fi=(e,t)=>e.split(`
97
+ `)},ki=(e,t)=>e.split(`
98
98
  `).map(i=>t(i)).join(`
99
- `),nd=e=>{let t=(s,n)=>{let r=s.label??String(s.value);return n==="disabled"?`${p.default.gray(ii)} ${fi(r,o=>p.default.strikethrough(p.default.gray(o)))}${s.hint?` ${p.default.dim(`(${s.hint??"disabled"})`)}`:""}`:n==="active"?`${p.default.cyan(es)} ${r}${s.hint?` ${p.default.dim(`(${s.hint})`)}`:""}`:n==="selected"?`${p.default.green(Nt)} ${fi(r,p.default.dim)}${s.hint?` ${p.default.dim(`(${s.hint})`)}`:""}`:n==="cancelled"?`${fi(r,o=>p.default.strikethrough(p.default.dim(o)))}`:n==="active-selected"?`${p.default.green(Nt)} ${r}${s.hint?` ${p.default.dim(`(${s.hint})`)}`:""}`:n==="submitted"?`${fi(r,p.default.dim)}`:`${p.default.dim(ii)} ${fi(r,p.default.dim)}`},i=e.required??!0;return new Wi({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=at(e.output,e.message,`${gn(this.state)} `,`${tt(this.state)} `),n=`${p.default.gray(T)}
101
- ${s}
102
- `,r=this.value??[],o=(a,l)=>{if(a.disabled)return t(a,"disabled");let f=r.includes(a.value);return l&&f?t(a,"active-selected"):f?t(a,"selected"):t(a,l?"active":"inactive")};switch(this.state){case"submit":{let a=this.options.filter(({value:f})=>r.includes(f)).map(f=>t(f,"submitted")).join(p.default.dim(", "))||p.default.dim("none"),l=at(e.output,a,`${p.default.gray(T)} `);return`${n}${l}`}case"cancel":{let a=this.options.filter(({value:f})=>r.includes(f)).map(f=>t(f,"cancelled")).join(p.default.dim(", "));if(a.trim()==="")return`${n}${p.default.gray(T)}`;let l=at(e.output,a,`${p.default.gray(T)} `);return`${n}${l}
103
- ${p.default.gray(T)}`}case"error":{let a=`${p.default.yellow(T)} `,l=this.error.split(`
104
- `).map((h,b)=>b===0?`${p.default.yellow(Se)} ${p.default.yellow(h)}`:` ${h}`).join(`
105
- `),f=n.split(`
106
- `).length,m=l.split(`
107
- `).length+1;return`${n}${a}${ni({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:a.length,rowPadding:f+m,style:o}).join(`
99
+ `),xl=e=>{let t=(n,s)=>{let r=n.label??String(n.value);return s==="disabled"?`${h.default.gray(oi)} ${ki(r,o=>h.default.strikethrough(h.default.gray(o)))}${n.hint?` ${h.default.dim(`(${n.hint??"disabled"})`)}`:""}`:s==="active"?`${h.default.cyan(pn)} ${r}${n.hint?` ${h.default.dim(`(${n.hint})`)}`:""}`:s==="selected"?`${h.default.green(Mt)} ${ki(r,h.default.dim)}${n.hint?` ${h.default.dim(`(${n.hint})`)}`:""}`:s==="cancelled"?`${ki(r,o=>h.default.strikethrough(h.default.dim(o)))}`:s==="active-selected"?`${h.default.green(Mt)} ${r}${n.hint?` ${h.default.dim(`(${n.hint})`)}`:""}`:s==="submitted"?`${ki(r,h.default.dim)}`:`${h.default.dim(oi)} ${ki(r,h.default.dim)}`},i=e.required??!0;return new nn({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValues:e.initialValues,required:i,cursorAt:e.cursorAt,validate(n){if(i&&(n===void 0||n.length===0))return`Please select at least one option.
100
+ ${h.default.reset(h.default.dim(`Press ${h.default.gray(h.default.bgWhite(h.default.inverse(" space ")))} to select, ${h.default.gray(h.default.bgWhite(h.default.inverse(" enter ")))} to submit`))}`},render(){let n=at(e.output,e.message,`${Is(this.state)} `,`${tt(this.state)} `),s=`${h.default.gray(D)}
101
+ ${n}
102
+ `,r=this.value??[],o=(a,d)=>{if(a.disabled)return t(a,"disabled");let f=r.includes(a.value);return d&&f?t(a,"active-selected"):f?t(a,"selected"):t(a,d?"active":"inactive")};switch(this.state){case"submit":{let a=this.options.filter(({value:f})=>r.includes(f)).map(f=>t(f,"submitted")).join(h.default.dim(", "))||h.default.dim("none"),d=at(e.output,a,`${h.default.gray(D)} `);return`${s}${d}`}case"cancel":{let a=this.options.filter(({value:f})=>r.includes(f)).map(f=>t(f,"cancelled")).join(h.default.dim(", "));if(a.trim()==="")return`${s}${h.default.gray(D)}`;let d=at(e.output,a,`${h.default.gray(D)} `);return`${s}${d}
103
+ ${h.default.gray(D)}`}case"error":{let a=`${h.default.yellow(D)} `,d=this.error.split(`
104
+ `).map((p,y)=>y===0?`${h.default.yellow(Oe)} ${h.default.yellow(p)}`:` ${p}`).join(`
105
+ `),f=s.split(`
106
+ `).length,m=d.split(`
107
+ `).length+1;return`${s}${a}${di({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:a.length,rowPadding:f+m,style:o}).join(`
108
108
  ${a}`)}
109
- ${l}
110
- `}default:{let a=`${p.default.cyan(T)} `,l=n.split(`
111
- `).length;return`${n}${a}${ni({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:a.length,rowPadding:l+2,style:o}).join(`
109
+ ${d}
110
+ `}default:{let a=`${h.default.cyan(D)} `,d=s.split(`
111
+ `).length;return`${s}${a}${di({output:e.output,options:this.options,cursor:this.cursor,maxItems:e.maxItems,columnPadding:a.length,rowPadding:d+2,style:o}).join(`
112
112
  ${a}`)}
113
- ${p.default.cyan(Se)}
114
- `}}}}).prompt()},rd=e=>p.default.dim(e),od=(e,t,i)=>{let s={hard:!0,trim:!1},n=si(e,t,s).split(`
115
- `),r=n.reduce((l,f)=>Math.max(Ne(f),l),0),o=n.map(i).reduce((l,f)=>Math.max(Ne(f),l),0),a=t-(o-r);return si(e,a,s)},ad=(e="",t="",i)=>{let s=i?.output??Je.default.stdout,n=i?.withGuide??me.withGuide,r=i?.format??rd,o=["",...od(e,Pt(s)-6,r).split(`
116
- `).map(r),""],a=Ne(t),l=Math.max(o.reduce((b,k)=>{let $=Ne(k);return $>b?$:b},0),a)+2,f=o.map(b=>`${p.default.gray(T)} ${b}${" ".repeat(l-Ne(b))}${p.default.gray(T)}`).join(`
117
- `),m=n?`${p.default.gray(T)}
118
- `:"",h=n?Br:un;s.write(`${m}${p.default.green(Mt)} ${p.default.reset(t)} ${p.default.gray(ts.repeat(Math.max(l-a-1,1))+dn)}
113
+ ${h.default.cyan(Oe)}
114
+ `}}}}).prompt()},jl=e=>h.default.dim(e),Sl=(e,t,i)=>{let n={hard:!0,trim:!1},s=ai(e,t,n).split(`
115
+ `),r=s.reduce((d,f)=>Math.max(Me(f),d),0),o=s.map(i).reduce((d,f)=>Math.max(Me(f),d),0),a=t-(o-r);return ai(e,a,n)},Cl=(e="",t="",i)=>{let n=i?.output??Ge.default.stdout,s=i?.withGuide??ue.withGuide,r=i?.format??jl,o=["",...Sl(e,Ut(n)-6,r).split(`
116
+ `).map(r),""],a=Me(t),d=Math.max(o.reduce((y,k)=>{let b=Me(k);return b>y?b:y},0),a)+2,f=o.map(y=>`${h.default.gray(D)} ${y}${" ".repeat(d-Me(y))}${h.default.gray(D)}`).join(`
117
+ `),m=s?`${h.default.gray(D)}
118
+ `:"",p=s?co:xs;n.write(`${m}${h.default.green(Vt)} ${h.default.reset(t)} ${h.default.gray(hn.repeat(Math.max(d-a-1,1))+ks)}
119
119
  ${f}
120
- ${p.default.gray(h+ts.repeat(l+2)+cn)}
121
- `)},ld=e=>new Er({validate:e.validate,mask:e.mask??Jr,signal:e.signal,input:e.input,output:e.output,render(){let t=e.withGuide??me.withGuide,i=`${t?`${p.default.gray(T)}
120
+ ${h.default.gray(p+hn.repeat(d+2)+_s)}
121
+ `)},Ol=e=>new Yr({validate:e.validate,mask:e.mask??lo,signal:e.signal,input:e.input,output:e.output,render(){let t=e.withGuide??ue.withGuide,i=`${t?`${h.default.gray(D)}
122
122
  `:""}${tt(this.state)} ${e.message}
123
- `,s=this.userInputWithCursor,n=this.masked;switch(this.state){case"error":{let r=t?`${p.default.yellow(T)} `:"",o=t?`${p.default.yellow(Se)} `:"",a=n??"";return e.clearOnError&&this.clear(),`${i.trim()}
123
+ `,n=this.userInputWithCursor,s=this.masked;switch(this.state){case"error":{let r=t?`${h.default.yellow(D)} `:"",o=t?`${h.default.yellow(Oe)} `:"",a=s??"";return e.clearOnError&&this.clear(),`${i.trim()}
124
124
  ${r}${a}
125
- ${o}${p.default.yellow(this.error)}
126
- `}case"submit":{let r=t?`${p.default.gray(T)} `:"",o=n?p.default.dim(n):"";return`${i}${r}${o}`}case"cancel":{let r=t?`${p.default.gray(T)} `:"",o=n?p.default.strikethrough(p.default.dim(n)):"";return`${i}${r}${o}${n&&t?`
127
- ${p.default.gray(T)}`:""}`}default:{let r=t?`${p.default.cyan(T)} `:"",o=t?p.default.cyan(Se):"";return`${i}${r}${s}
125
+ ${o}${h.default.yellow(this.error)}
126
+ `}case"submit":{let r=t?`${h.default.gray(D)} `:"",o=s?h.default.dim(s):"";return`${i}${r}${o}`}case"cancel":{let r=t?`${h.default.gray(D)} `:"",o=s?h.default.strikethrough(h.default.dim(s)):"";return`${i}${r}${o}${s&&t?`
127
+ ${h.default.gray(D)}`:""}`}default:{let r=t?`${h.default.cyan(D)} `:"",o=t?h.default.cyan(Oe):"";return`${i}${r}${n}
128
128
  ${o}
129
- `}}}}).prompt(),dd=e=>{let t=e.validate;return Qr({...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,Ut.existsSync)(i)?(0,Ut.lstatSync)(i).isDirectory()?s=i:s=(0,pi.dirname)(i):s=(0,pi.dirname)(i),(0,Ut.readdirSync)(s).map(n=>{let r=(0,pi.join)(s,n),o=(0,Ut.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[]}}})},cd=p.default.magenta,gi=({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 f=rn(),m,h,b=!1,k=!1,$="",g,x=performance.now(),S=Pt(i),O=l?.styleFrame??cd,A=M=>{let Z=M>1?n??me.messages.error:s??me.messages.cancel;k=M===1,b&&(re(Z,M),k&&typeof t=="function"&&t())},W=()=>A(2),H=()=>A(1),se=()=>{process.on("uncaughtExceptionMonitor",W),process.on("unhandledRejection",W),process.on("SIGINT",H),process.on("SIGTERM",H),process.on("exit",A),a&&a.addEventListener("abort",H)},P=()=>{process.removeListener("uncaughtExceptionMonitor",W),process.removeListener("unhandledRejection",W),process.removeListener("SIGINT",H),process.removeListener("SIGTERM",H),process.removeListener("exit",A),a&&a.removeEventListener("abort",H)},E=()=>{if(g===void 0)return;f&&i.write(`
130
- `);let M=si(g,S,{hard:!0,trim:!1}).split(`
131
- `);M.length>1&&i.write(ti.cursor.up(M.length-1)),i.write(ti.cursor.to(0)),i.write(ti.erase.down())},U=M=>M.replace(/\.+$/,""),te=M=>{let Z=(performance.now()-M)/1e3,ie=Math.floor(Z/60),z=Math.floor(Z%60);return ie>0?`[${ie}m ${z}s]`:`[${z}s]`},X=l.withGuide??me.withGuide,q=(M="")=>{b=!0,m=Tr({output:i}),$=U(M),x=performance.now(),X&&i.write(`${p.default.gray(T)}
132
- `);let Z=0,ie=0;se(),h=setInterval(()=>{if(f&&$===g)return;E(),g=$;let z=O(r[Z]),Ae;if(f)Ae=`${z} ${$}...`;else if(e==="timer")Ae=`${z} ${$} ${te(x)}`;else{let ue=".".repeat(Math.floor(ie)).slice(0,3);Ae=`${z} ${$}${ue}`}let ze=si(Ae,S,{hard:!0,trim:!1});i.write(ze),Z=Z+1<r.length?Z+1:0,ie=ie<4?ie+.125:0},o)},re=(M="",Z=0,ie=!1)=>{if(!b)return;b=!1,clearInterval(h),E();let z=Z===0?p.default.green(Mt):Z===1?p.default.red(on):p.default.red(an);$=M??$,ie||(e==="timer"?i.write(`${z} ${$} ${te(x)}
133
- `):i.write(`${z} ${$}
134
- `)),P(),m()};return{start:q,stop:(M="")=>re(M,0),message:(M="")=>{$=U(M??$)},cancel:(M="")=>re(M,1),error:(M="")=>re(M,2),clear:()=>re("",0,!0),get isCancelled(){return k}}},Mr={light:le("\u2500","-"),heavy:le("\u2501","="),block:le("\u2588","#")};Xi=(e,t)=>e.includes(`
129
+ `}}}}).prompt(),Il=e=>{let t=e.validate;return yo({...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 n;return(0,Ft.existsSync)(i)?(0,Ft.lstatSync)(i).isDirectory()?n=i:n=(0,_i.dirname)(i):n=(0,_i.dirname)(i),(0,Ft.readdirSync)(n).map(s=>{let r=(0,_i.join)(n,s),o=(0,Ft.lstatSync)(r);return{name:s,path:r,isDirectory:o.isDirectory()}}).filter(({path:s,isDirectory:r})=>s.startsWith(i)&&(e.directory||!r)).map(s=>({value:s.path}))}catch{return[]}}})},Rl=h.default.magenta,ji=({indicator:e="dots",onCancel:t,output:i=process.stdout,cancelMessage:n,errorMessage:s,frames:r=fn?["\u25D2","\u25D0","\u25D3","\u25D1"]:["\u2022","o","O","0"],delay:o=fn?80:120,signal:a,...d}={})=>{let f=bs(),m,p,y=!1,k=!1,b="",g,S=performance.now(),j=Ut(i),O=d?.styleFrame??Rl,T=I=>{let L=I>1?s??ue.messages.error:n??ue.messages.cancel;k=I===1,y&&(ne(L,I),k&&typeof t=="function"&&t())},W=()=>T(2),H=()=>T(1),ee=()=>{process.on("uncaughtExceptionMonitor",W),process.on("unhandledRejection",W),process.on("SIGINT",H),process.on("SIGTERM",H),process.on("exit",T),a&&a.addEventListener("abort",H)},q=()=>{process.removeListener("uncaughtExceptionMonitor",W),process.removeListener("unhandledRejection",W),process.removeListener("SIGINT",H),process.removeListener("SIGTERM",H),process.removeListener("exit",T),a&&a.removeEventListener("abort",H)},N=()=>{if(g===void 0)return;f&&i.write(`
130
+ `);let I=ai(g,j,{hard:!0,trim:!1}).split(`
131
+ `);I.length>1&&i.write(ri.cursor.up(I.length-1)),i.write(ri.cursor.to(0)),i.write(ri.erase.down())},le=I=>I.replace(/\.+$/,""),de=I=>{let L=(performance.now()-I)/1e3,te=Math.floor(L/60),X=Math.floor(L%60);return te>0?`[${te}m ${X}s]`:`[${X}s]`},P=d.withGuide??ue.withGuide,pe=(I="")=>{y=!0,m=zr({output:i}),b=le(I),S=performance.now(),P&&i.write(`${h.default.gray(D)}
132
+ `);let L=0,te=0;ee(),p=setInterval(()=>{if(f&&b===g)return;N(),g=b;let X=O(r[L]),ce;if(f)ce=`${X} ${b}...`;else if(e==="timer")ce=`${X} ${b} ${de(S)}`;else{let he=".".repeat(Math.floor(te)).slice(0,3);ce=`${X} ${b}${he}`}let ke=ai(ce,j,{hard:!0,trim:!1});i.write(ke),L=L+1<r.length?L+1:0,te=te<4?te+.125:0},o)},ne=(I="",L=0,te=!1)=>{if(!y)return;y=!1,clearInterval(p),N();let X=L===0?h.default.green(Vt):L===1?h.default.red(ws):h.default.red(vs);b=I??b,te||(e==="timer"?i.write(`${X} ${b} ${de(S)}
133
+ `):i.write(`${X} ${b}
134
+ `)),q(),m()};return{start:pe,stop:(I="")=>ne(I,0),message:(I="")=>{b=le(I??b)},cancel:(I="")=>ne(I,1),error:(I="")=>ne(I,2),clear:()=>ne("",0,!0),get isCancelled(){return k}}},io={light:oe("\u2500","-"),heavy:oe("\u2501","="),block:oe("\u2588","#")};un=(e,t)=>e.includes(`
135
135
  `)?e.split(`
136
136
  `).map(i=>t(i)).join(`
137
- `):t(e),it=e=>{let t=(i,s)=>{let n=i.label??String(i.value);switch(s){case"disabled":return`${p.default.gray(qt)} ${Xi(n,p.default.gray)}${i.hint?` ${p.default.dim(`(${i.hint??"disabled"})`)}`:""}`;case"selected":return`${Xi(n,p.default.dim)}`;case"active":return`${p.default.green(hi)} ${n}${i.hint?` ${p.default.dim(`(${i.hint})`)}`:""}`;case"cancelled":return`${Xi(n,r=>p.default.strikethrough(p.default.dim(r)))}`;default:return`${p.default.dim(qt)} ${Xi(n,p.default.dim)}`}};return new Hi({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let i=e.withGuide??me.withGuide,s=`${tt(this.state)} `,n=`${gn(this.state)} `,r=at(e.output,e.message,n,s),o=`${i?`${p.default.gray(T)}
137
+ `):t(e),it=e=>{let t=(i,n)=>{let s=i.label??String(i.value);switch(n){case"disabled":return`${h.default.gray(Lt)} ${un(s,h.default.gray)}${i.hint?` ${h.default.dim(`(${i.hint??"disabled"})`)}`:""}`;case"selected":return`${un(s,h.default.dim)}`;case"active":return`${h.default.green(xi)} ${s}${i.hint?` ${h.default.dim(`(${i.hint})`)}`:""}`;case"cancelled":return`${un(s,r=>h.default.strikethrough(h.default.dim(r)))}`;default:return`${h.default.dim(Lt)} ${un(s,h.default.dim)}`}};return new sn({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let i=e.withGuide??ue.withGuide,n=`${tt(this.state)} `,s=`${Is(this.state)} `,r=at(e.output,e.message,s,n),o=`${i?`${h.default.gray(D)}
138
138
  `:""}${r}
139
- `;switch(this.state){case"submit":{let a=i?`${p.default.gray(T)} `:"",l=at(e.output,t(this.options[this.cursor],"selected"),a);return`${o}${l}`}case"cancel":{let a=i?`${p.default.gray(T)} `:"",l=at(e.output,t(this.options[this.cursor],"cancelled"),a);return`${o}${l}${i?`
140
- ${p.default.gray(T)}`:""}`}default:{let a=i?`${p.default.cyan(T)} `:"",l=i?p.default.cyan(Se):"",f=o.split(`
141
- `).length,m=i?2:1;return`${o}${a}${ni({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:a.length,rowPadding:f+m,style:(h,b)=>t(h,h.disabled?"disabled":b?"active":"inactive")}).join(`
139
+ `;switch(this.state){case"submit":{let a=i?`${h.default.gray(D)} `:"",d=at(e.output,t(this.options[this.cursor],"selected"),a);return`${o}${d}`}case"cancel":{let a=i?`${h.default.gray(D)} `:"",d=at(e.output,t(this.options[this.cursor],"cancelled"),a);return`${o}${d}${i?`
140
+ ${h.default.gray(D)}`:""}`}default:{let a=i?`${h.default.cyan(D)} `:"",d=i?h.default.cyan(Oe):"",f=o.split(`
141
+ `).length,m=i?2:1;return`${o}${a}${di({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:a.length,rowPadding:f+m,style:(p,y)=>t(p,p.disabled?"disabled":y?"active":"inactive")}).join(`
142
142
  ${a}`)}
143
- ${l}
144
- `}}}}).prompt()},md=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 Ji({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,caseSensitive:e.caseSensitive,render(){let i=e.withGuide??me.withGuide,s=`${i?`${p.default.gray(T)}
143
+ ${d}
144
+ `}}}}).prompt()},Tl=e=>{let t=(i,n="inactive")=>{let s=i.label??String(i.value);return n==="selected"?`${h.default.dim(s)}`:n==="cancelled"?`${h.default.strikethrough(h.default.dim(s))}`:n==="active"?`${h.default.bgCyan(h.default.gray(` ${i.value} `))} ${s}${i.hint?` ${h.default.dim(`(${i.hint})`)}`:""}`:`${h.default.gray(h.default.bgWhite(h.default.inverse(` ${i.value} `)))} ${s}${i.hint?` ${h.default.dim(`(${i.hint})`)}`:""}`};return new rn({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,caseSensitive:e.caseSensitive,render(){let i=e.withGuide??ue.withGuide,n=`${i?`${h.default.gray(D)}
145
145
  `:""}${tt(this.state)} ${e.message}
146
- `;switch(this.state){case"submit":{let n=i?`${p.default.gray(T)} `:"",r=this.options.find(a=>a.value===this.value)??e.options[0],o=at(e.output,t(r,"selected"),n);return`${s}${o}`}case"cancel":{let n=i?`${p.default.gray(T)} `:"",r=at(e.output,t(this.options[0],"cancelled"),n);return`${s}${r}${i?`
147
- ${p.default.gray(T)}`:""}`}default:{let n=i?`${p.default.cyan(T)} `:"",r=i?p.default.cyan(Se):"",o=this.options.map((a,l)=>at(e.output,t(a,l===this.cursor?"active":"inactive"),n)).join(`
148
- `);return`${s}${o}
146
+ `;switch(this.state){case"submit":{let s=i?`${h.default.gray(D)} `:"",r=this.options.find(a=>a.value===this.value)??e.options[0],o=at(e.output,t(r,"selected"),s);return`${n}${o}`}case"cancel":{let s=i?`${h.default.gray(D)} `:"",r=at(e.output,t(this.options[0],"cancelled"),s);return`${n}${r}${i?`
147
+ ${h.default.gray(D)}`:""}`}default:{let s=i?`${h.default.cyan(D)} `:"",r=i?h.default.cyan(Oe):"",o=this.options.map((a,d)=>at(e.output,t(a,d===this.cursor?"active":"inactive"),s)).join(`
148
+ `);return`${n}${o}
149
149
  ${r}
150
- `}}}}).prompt()},Fr=`${p.default.gray(T)} `,Dt={message:async(e,{symbol:t=p.default.gray(T)}={})=>{process.stdout.write(`${p.default.gray(T)}
151
- ${t} `);let i=3;for await(let s of e){s=s.replace(/\n/g,`
152
- ${Fr}`),s.includes(`
153
- `)&&(i=3+(0,Zi.stripVTControlCharacters)(s.slice(s.lastIndexOf(`
154
- `))).length);let n=(0,Zi.stripVTControlCharacters)(s).length;i+n<process.stdout.columns?(i+=n,process.stdout.write(s)):(process.stdout.write(`
155
- ${Fr}${s.trimStart()}`),i=3+(0,Zi.stripVTControlCharacters)(s.trimStart()).length)}process.stdout.write(`
156
- `)},info:e=>Dt.message(e,{symbol:p.default.blue(mn)}),success:e=>Dt.message(e,{symbol:p.default.green(fn)}),step:e=>Dt.message(e,{symbol:p.default.green(Mt)}),warn:e=>Dt.message(e,{symbol:p.default.yellow(pn)}),warning:e=>Dt.warn(e),error:e=>Dt.message(e,{symbol:p.default.red(hn)})},fd=async(e,t)=>{for(let i of e){if(i.enabled===!1)continue;let s=gi(t);s.start(i.title);let n=await i.task(s.message);s.stop(n||i.title)}},pd=e=>e.replace(/\x1b\[(?:\d+;)*\d*[ABCDEFGHfJKSTsu]|\x1b\[(s|u)/g,""),hd=e=>{let t=e.output??process.stdout,i=Pt(t),s=p.default.gray(T),n=e.spacing??1,r=3,o=e.retainLog===!0,a=!rn()&&Lr(t);t.write(`${s}
157
- `),t.write(`${p.default.green(Mt)} ${e.title}
158
- `);for(let x=0;x<n;x++)t.write(`${s}
159
- `);let l=[{value:"",full:""}],f=!1,m=x=>{if(l.length===0)return;let S=0;x&&(S+=n+2);for(let O of l){let{value:A,result:W}=O,H=W?.message??A;if(H.length===0)continue;W===void 0&&O.header!==void 0&&O.header!==""&&(H+=`
160
- ${O.header}`);let se=H.split(`
161
- `).reduce((P,E)=>E===""?P+1:P+Math.ceil((E.length+r)/i),0);S+=se}S>0&&(S+=1,t.write(ti.erase.lines(S)))},h=(x,S,O)=>{let A=O?`${x.full}
162
- ${x.value}`:x.value;x.header!==void 0&&x.header!==""&&Be.message(x.header.split(`
163
- `).map(p.default.bold),{output:t,secondarySymbol:s,symbol:s,spacing:0}),Be.message(A.split(`
164
- `).map(p.default.dim),{output:t,secondarySymbol:s,symbol:s,spacing:S??n})},b=()=>{for(let x of l){let{header:S,value:O,full:A}=x;(S===void 0||S.length===0)&&O.length===0||h(x,void 0,o===!0&&A.length>0)}},k=(x,S,O)=>{if(m(!1),(O?.raw!==!0||!f)&&x.value!==""&&(x.value+=`
165
- `),x.value+=pd(S),f=O?.raw===!0,e.limit!==void 0){let A=x.value.split(`
166
- `),W=A.length-e.limit;if(W>0){let H=A.splice(0,W);o&&(x.full+=(x.full===""?"":`
150
+ `}}}}).prompt()},no=`${h.default.gray(D)} `,qt={message:async(e,{symbol:t=h.default.gray(D)}={})=>{process.stdout.write(`${h.default.gray(D)}
151
+ ${t} `);let i=3;for await(let n of e){n=n.replace(/\n/g,`
152
+ ${no}`),n.includes(`
153
+ `)&&(i=3+(0,mn.stripVTControlCharacters)(n.slice(n.lastIndexOf(`
154
+ `))).length);let s=(0,mn.stripVTControlCharacters)(n).length;i+s<process.stdout.columns?(i+=s,process.stdout.write(n)):(process.stdout.write(`
155
+ ${no}${n.trimStart()}`),i=3+(0,mn.stripVTControlCharacters)(n.trimStart()).length)}process.stdout.write(`
156
+ `)},info:e=>qt.message(e,{symbol:h.default.blue(js)}),success:e=>qt.message(e,{symbol:h.default.green(Ss)}),step:e=>qt.message(e,{symbol:h.default.green(Vt)}),warn:e=>qt.message(e,{symbol:h.default.yellow(Cs)}),warning:e=>qt.warn(e),error:e=>qt.message(e,{symbol:h.default.red(Os)})},El=async(e,t)=>{for(let i of e){if(i.enabled===!1)continue;let n=ji(t);n.start(i.title);let s=await i.task(n.message);n.stop(s||i.title)}},Pl=e=>e.replace(/\x1b\[(?:\d+;)*\d*[ABCDEFGHfJKSTsu]|\x1b\[(s|u)/g,""),Dl=e=>{let t=e.output??process.stdout,i=Ut(t),n=h.default.gray(D),s=e.spacing??1,r=3,o=e.retainLog===!0,a=!bs()&&so(t);t.write(`${n}
157
+ `),t.write(`${h.default.green(Vt)} ${e.title}
158
+ `);for(let S=0;S<s;S++)t.write(`${n}
159
+ `);let d=[{value:"",full:""}],f=!1,m=S=>{if(d.length===0)return;let j=0;S&&(j+=s+2);for(let O of d){let{value:T,result:W}=O,H=W?.message??T;if(H.length===0)continue;W===void 0&&O.header!==void 0&&O.header!==""&&(H+=`
160
+ ${O.header}`);let ee=H.split(`
161
+ `).reduce((q,N)=>N===""?q+1:q+Math.ceil((N.length+r)/i),0);j+=ee}j>0&&(j+=1,t.write(ri.erase.lines(j)))},p=(S,j,O)=>{let T=O?`${S.full}
162
+ ${S.value}`:S.value;S.header!==void 0&&S.header!==""&&Ke.message(S.header.split(`
163
+ `).map(h.default.bold),{output:t,secondarySymbol:n,symbol:n,spacing:0}),Ke.message(T.split(`
164
+ `).map(h.default.dim),{output:t,secondarySymbol:n,symbol:n,spacing:j??s})},y=()=>{for(let S of d){let{header:j,value:O,full:T}=S;(j===void 0||j.length===0)&&O.length===0||p(S,void 0,o===!0&&T.length>0)}},k=(S,j,O)=>{if(m(!1),(O?.raw!==!0||!f)&&S.value!==""&&(S.value+=`
165
+ `),S.value+=Pl(j),f=O?.raw===!0,e.limit!==void 0){let T=S.value.split(`
166
+ `),W=T.length-e.limit;if(W>0){let H=T.splice(0,W);o&&(S.full+=(S.full===""?"":`
167
167
  `)+H.join(`
168
- `))}x.value=A.join(`
169
- `)}a&&$()},$=()=>{for(let x of l)x.result?x.result.status==="error"?Be.error(x.result.message,{output:t,secondarySymbol:s,spacing:0}):Be.success(x.result.message,{output:t,secondarySymbol:s,spacing:0}):x.value!==""&&h(x,0)},g=(x,S)=>{m(!1),x.result=S,a&&$()};return{message(x,S){k(l[0],x,S)},group(x){let S={header:x,value:"",full:""};return l.push(S),{message(O,A){k(S,O,A)},error(O){g(S,{status:"error",message:O})},success(O){g(S,{status:"success",message:O})}}},error(x,S){m(!0),Be.error(x,{output:t,secondarySymbol:s,spacing:1}),S?.showLog!==!1&&b(),l.splice(1,l.length-1),l[0].value="",l[0].full=""},success(x,S){m(!0),Be.success(x,{output:t,secondarySymbol:s,spacing:1}),S?.showLog===!0&&b(),l.splice(1,l.length-1),l[0].value="",l[0].full=""}}},Pe=e=>new Bi({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??me.withGuide,i=`${`${t?`${p.default.gray(T)}
168
+ `))}S.value=T.join(`
169
+ `)}a&&b()},b=()=>{for(let S of d)S.result?S.result.status==="error"?Ke.error(S.result.message,{output:t,secondarySymbol:n,spacing:0}):Ke.success(S.result.message,{output:t,secondarySymbol:n,spacing:0}):S.value!==""&&p(S,0)},g=(S,j)=>{m(!1),S.result=j,a&&b()};return{message(S,j){k(d[0],S,j)},group(S){let j={header:S,value:"",full:""};return d.push(j),{message(O,T){k(j,O,T)},error(O){g(j,{status:"error",message:O})},success(O){g(j,{status:"success",message:O})}}},error(S,j){m(!0),Ke.error(S,{output:t,secondarySymbol:n,spacing:1}),j?.showLog!==!1&&y(),d.splice(1,d.length-1),d[0].value="",d[0].full=""},success(S,j){m(!0),Ke.success(S,{output:t,secondarySymbol:n,spacing:1}),j?.showLog===!0&&y(),d.splice(1,d.length-1),d[0].value="",d[0].full=""}}},De=e=>new on({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??ue.withGuide,i=`${`${t?`${h.default.gray(D)}
170
170
  `:""}${tt(this.state)} `}${e.message}
171
- `,s=e.placeholder?p.default.inverse(e.placeholder[0])+p.default.dim(e.placeholder.slice(1)):p.default.inverse(p.default.hidden("_")),n=this.userInput?this.userInputWithCursor:s,r=this.value??"";switch(this.state){case"error":{let o=this.error?` ${p.default.yellow(this.error)}`:"",a=t?`${p.default.yellow(T)} `:"",l=t?p.default.yellow(Se):"";return`${i.trim()}
172
- ${a}${n}
173
- ${l}${o}
174
- `}case"submit":{let o=r?` ${p.default.dim(r)}`:"",a=t?p.default.gray(T):"";return`${i}${a}${o}`}case"cancel":{let o=r?` ${p.default.strikethrough(p.default.dim(r))}`:"",a=t?p.default.gray(T):"";return`${i}${a}${o}${r.trim()?`
175
- ${a}`:""}`}default:{let o=t?`${p.default.cyan(T)} `:"",a=t?p.default.cyan(Se):"";return`${i}${o}${n}
171
+ `,n=e.placeholder?h.default.inverse(e.placeholder[0])+h.default.dim(e.placeholder.slice(1)):h.default.inverse(h.default.hidden("_")),s=this.userInput?this.userInputWithCursor:n,r=this.value??"";switch(this.state){case"error":{let o=this.error?` ${h.default.yellow(this.error)}`:"",a=t?`${h.default.yellow(D)} `:"",d=t?h.default.yellow(Oe):"";return`${i.trim()}
172
+ ${a}${s}
173
+ ${d}${o}
174
+ `}case"submit":{let o=r?` ${h.default.dim(r)}`:"",a=t?h.default.gray(D):"";return`${i}${a}${o}`}case"cancel":{let o=r?` ${h.default.strikethrough(h.default.dim(r))}`:"",a=t?h.default.gray(D):"";return`${i}${a}${o}${r.trim()?`
175
+ ${a}`:""}`}default:{let o=t?`${h.default.cyan(D)} `:"",a=t?h.default.cyan(Oe):"";return`${i}${o}${s}
176
176
  ${a}
177
- `}}}}).prompt()});function gd(e){return!!(e.json||!Ce)}function j(e,t=50){console.log(),console.log(` ${J.default.bold(e)}`),console.log(` ${J.default.dim("\u2500".repeat(t))}`)}function d(e,t,i=2){let s=" ".repeat(i);console.log(`${s}${J.default.dim(e.padEnd(16))} ${t}`)}function c(){console.log()}function be(e){console.log(` ${J.default.dim(e)}`)}function R(e,t){console.log(` ${J.default.dim(e)} ${J.default.cyan(t)}`)}function so(e){return e.split(/(https?:\/\/[^\s]+)/g).map(i=>/^https?:\/\//.test(i)?`\x1B]8;;${i}\x1B\\${J.default.underline(J.default.cyan(i))}\x1B]8;;\x1B\\`:J.default.dim(i)).join("")}function $n(e,t){console.error(` ${w.error} ${J.default.red(e)}`),t&&console.error(` ${so(t)}`)}function C(e=!0){return e?gi():yd}function no(e){return e.replace(bd,"")}function ss(e,t){let i=no(e).length,s=Math.max(0,t-i);return e+" ".repeat(s)}function B(e,t,i){let s=i||e.map((o,a)=>{let l=t.reduce((f,m)=>Math.max(f,no(m[a]||"").length),0);return Math.max(o.length,l)+2}),n=e.map((o,a)=>J.default.dim(o.padEnd(s[a]))).join(" "),r=s.map(o=>J.default.dim("\u2500".repeat(o))).join(" ");console.log(` ${n}`),console.log(` ${r}`);for(let o of t){let a=o.map((l,f)=>ss(l,s[f])).join(" ");console.log(` ${a}`)}}function wd(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function vn(e){if(Array.isArray(e))return e.map(vn);if(e&&typeof e=="object"&&!(e instanceof Date)){let t={};for(let[i,s]of Object.entries(e))t[wd(i)]=vn(s);return t}return e}function y(e,t){let i=vn(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=>eo(r,s));console.log(JSON.stringify(n,null,2))}else console.log(JSON.stringify(i&&typeof i=="object"?eo(i,s):i,null,2))}function eo(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 Ft(e){return!!(e.yes||gd(e))}function K(e,t,i,s){if(i){y({dry_run:!0,action:e,...t},s);return}console.log(),console.log(` ${J.default.yellow("\u25B8 DRY RUN")} ${J.default.dim("- no changes made")}`),console.log(` ${J.default.dim("Action:")} ${J.default.bold(e)}`);for(let[n,r]of Object.entries(t))r!=null&&(Array.isArray(r)?console.log(` ${J.default.dim(n+":")} ${r.map(String).join(", ")}`):console.log(typeof r=="object"?` ${J.default.dim(n+":")} ${JSON.stringify(r)}`:` ${J.default.dim(n+":")} ${String(r)}`));console.log()}function $d(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||$d(i,t?.status,t?.fixUrl),n=t?.fixCommand||vd[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),y(r,t.fields)}else $n(i,t?.hint),n?console.error(` ${J.default.dim("Or run:")} ${J.default.cyan(n)}`):t?.fixUrl&&console.error(` ${so(`Add a payment method at ${t.fixUrl}`)}`);process.exit(1)}function qe(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";(0,io.execFile)(t,[e])}function wt(e){return new Promise(t=>setTimeout(t,e))}function Lt(e,t,i,s=!0){let n=process.stdout.isTTY??!1;if(!s)return{start(){},markDone(){},stop(){}};let r=0,o=null,a=2+t.length;function l(){let b=" "+e.map((g,x)=>J.default.dim(g.padEnd(i[x]))).join(" "),k=" "+i.map(g=>J.default.dim("\u2500".repeat(g))).join(" "),$=[b,k];for(let g of t){let x=g.status==="done"?g.icon??w.success:J.default.cyan(to[r%to.length]),S=g.cells.map((O,A)=>ss(O,i[A])).join(" ");$.push(` ${x} ${S}`)}return $}let f=!1,m=()=>process.stdout.write("\x1B[?25h");function h(){let b=l();if(f&&n){process.stdout.write(`\x1B[${a}A`);for(let k of b)process.stdout.write(`\x1B[2K${k}
178
- `)}else{for(let k of b)console.log(k);f=!0}}return{start(){n&&(process.stdout.write("\x1B[?25l"),process.on("exit",m)),h(),n&&(o=setInterval(()=>{r++,h()},80))},markDone(b,k){t[b].status="done",k!==void 0&&(t[b].icon=k),n&&h()},stop(){o&&clearInterval(o);for(let b of t)b.status="done";h(),n&&(process.stdout.write("\x1B[?25h"),process.removeListener("exit",m))}}}var J,io,Ce,w,v,yd,bd,vd,to,L=Te(()=>{"use strict";J=D(F(),1),io=require("child_process");Ue();Ce=process.stdout.isTTY??!1;w={success:J.default.green("\u2713"),error:J.default.red("\u2717"),warning:J.default.yellow("!"),info:J.default.cyan("\u25CF"),arrow:J.default.dim("\u2192"),dot:J.default.dim("\xB7"),dash:J.default.dim("\u2500")},v={domain:e=>J.default.bold(J.default.white(e)),price:e=>J.default.green(`$${e}`),label:e=>J.default.dim(e),value:e=>J.default.white(e),dim:e=>J.default.dim(e),bold:e=>J.default.bold(e),success:e=>J.default.green(e),error:e=>J.default.red(e),warn:e=>J.default.yellow(e),cyan:e=>J.default.cyan(e),url:e=>`\x1B]8;;${e}\x1B\\${J.default.underline(J.default.cyan(e))}\x1B]8;;\x1B\\`};yd={start:()=>{},stop:()=>{},message:()=>{}};bd=/\x1b\]8;;[^\x1b]*\x1b\\|\x1b\[[0-9;]*m/g;vd={auth_required:"domani login",payment_required:"domani card add",contact_required:"domani contact set"};to=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"]});function ro(e){return typeof e=="string"&&["pro","agent","fleet","scale","mail_solo","mail_team","mail_business"].includes(e)}function oo(e){return ro(e.plan)||Array.isArray(e.workspace_plans)&&e.workspace_plans.some(ro)}async function ao(){if(_n)return;let e=process.argv.includes("--json")||!Ls,t=We(),i=He();try{let r=await(await fetch(`${t}/api/me`,{headers:{Authorization:`Bearer ${i}`}})).json();if(oo(r)){_n=!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)),c(),console.log(` ${ke.default.dim("This feature requires a")} ${ke.default.bold("paid plan")} ${ke.default.dim("(including an active Mailzero workspace plan or legacy Pro subscription).")}`),console.log(` ${ke.default.dim("Opening pricing page")} ${w.arrow} ${ke.default.cyan("domani.run/pricing")}`),qe(`${t.replace("http://localhost:3000","https://domani.run")}/pricing`),c();let s=C(!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(oo(o)){_n=!0,s.stop(`${w.success} Paid plan active! Continuing...`),c();return}}catch{}}s.stop("Timed out"),console.error(` ${ke.default.red("\u2717")} No upgrade detected. Visit ${ke.default.cyan("domani.run/settings")} to upgrade.`),process.exit(1)}async function lo(){if(kn||He()){kn=!0;return}(process.argv.includes("--json")||!Ls)&&(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)),c(),console.log(` ${ke.default.dim("You're not logged in.")} Starting authentication...`),c();let t=We(),i=C(!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(` ${ke.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(` ${ke.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(` ${ke.default.red("\u2717")} Invalid response from server.`),process.exit(1)}i.stop(`${w.success} Auth code ready`),c(),console.log(` ${ke.default.dim("Verification code:")} ${ke.default.bold(ke.default.cyan(n))}`),console.log(` ${ke.default.dim("Opening browser")} ${w.arrow} ${v.url(r)}`),qe(r),c(),i.start("Waiting for browser approval");for(let o=0;o<120;o++){await new Promise(f=>setTimeout(f,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"){ei({...gt(),token:l.token,email:l.email,api_url:t}),kn=!0,i.stop(`${w.success} Logged in as ${ke.default.bold(l.email)}`),c();return}}i.stop("Timed out"),console.error(` ${ke.default.red("\u2717")} No approval received. Run ${ke.default.cyan("domani login")} to try again.`),process.exit(1)}var ke,kn,_n,xn=Te(()=>{"use strict";ke=D(F(),1);yt();L();kn=!1,_n=!1});function mo(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 _(e,t={},i=!1){let s=He(),n=`${We()}${e}`,r=await fetch(n,{...t,headers:{Authorization:`Bearer ${s}`,"Content-Type":"application/json","User-Agent":`domani-cli/${je}`,...t.headers}});if(!i){let o=await r.clone().text();try{if(JSON.parse(o).code==="UPGRADE_REQUIRED")return await ao(),_(e,t,!0)}catch{}}return mo(r)}async function ve(e,t={}){let i=`${We()}${e}`,s=He(),n=await fetch(i,{...t,headers:{"Content-Type":"application/json","User-Agent":`domani-cli/${je}`,...s?{Authorization:`Bearer ${s}`}:{},...t.headers}});return mo(n)}var G=Te(()=>{"use strict";yt();xn()});function Ot(){return{ok:!0}}function vt(e,t,i){return{ok:!1,error:{message:e,code:t,hint:i}}}function ho(e){return xd.test(e)?vt("Input contains control characters","invalid_input","Remove non-printable characters from the input"):Ot()}function Rd(e){return jd.test(e)?vt("Input contains path traversal","invalid_input","Domain names cannot contain '../' or '..\\'"):Ot()}function Ad(e){return Sd.test(e)?vt("Input contains query string or fragment","invalid_input","Remove '?' or '#' from the domain name"):Ot()}function Td(e){return Cd.test(e)?vt("Input contains percent-encoded characters","invalid_input","Use plain text, not URL-encoded values (e.g. 'example.com' not 'example%2Ecom')"):Ot()}function go(e){if(!e)return vt("Domain name is required","validation_error");if(e.length>po)return vt(`Domain name too long (${e.length} chars, max ${po})`,"validation_error");for(let t of[ho,Rd,Ad,Td]){let i=t(e);if(!i.ok)return i}return Od.test(e)?Ot():vt(`Invalid domain name: ${e}`,"validation_error","Domain names can only contain letters, digits, hyphens, and dots")}function Ed(e){if(!e)return vt("TLD is required","validation_error");let t=ho(e);return t.ok?Id.test(e)?Ot():vt(`Invalid TLD: ${e}`,"validation_error","TLDs contain only letters (e.g. 'com', '.dev', 'ai')"):t}function Pd(e){for(let t of e){let i=go(t);if(!i.ok)return i}return Ot()}function Dd(e){for(let t of e){let i=Ed(t);if(!i.ok)return i}return Ot()}function Y(e,t){let i=go(e);i.ok||u(i.error.message,{code:i.error.code,hint:i.error.hint,json:t?.json,fields:t?.fields})}function yo(e,t){let i=Pd(e);i.ok||u(i.error.message,{code:i.error.code,hint:i.error.hint,json:t?.json,fields:t?.fields})}function ns(e,t){let i=Dd(e);i.ok||u(i.error.message,{code:i.error.code,hint:i.error.hint,json:t?.json,fields:t?.fields})}var xd,jd,Sd,Cd,Od,Id,po,we=Te(()=>{"use strict";L();xd=/[\x00-\x08\x0b\x0c\x0e-\x1f]/,jd=/\.\.[/\\]/,Sd=/[?#]/,Cd=/%[0-9a-fA-F]{2}/,Od=/^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?)*\.?$/,Id=/^\.?[a-zA-Z]{2,63}$/,po=253});async function he(){Ce||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=C(!0);e.start("Loading your domains");let t=await _("/api/domains"),i=await t.json();t.ok||(e.stop("Failed"),$n(i.error,i.hint),process.exit(1));let s=i.domains||[];s.length===0&&(e.stop("No domains"),c(),console.log(` ${Sn.default.dim("No domains yet.")} Use: ${Sn.default.cyan("domani buy <domain>")}`),c(),process.exit(0)),e.stop(`${s.length} domain(s)`);let n=await it({message:"Which domain?",options:s.map(r=>({value:r.domain,label:r.domain,hint:r.status!=="active"?r.status:void 0}))});return ce(n)&&process.exit(0),n}var Sn,Ze=Te(()=>{"use strict";G();Ue();Sn=D(F(),1);L()});var wo={};zt(wo,{connect:()=>Cn});async function Cn(e,t,i){e||(e=await he()),Y(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 K("connect",{domain:e,note:"No provider specified. Pass --provider <name> to connect."},i.json,i.fields);if(!s&&!i.provider&&!i.list){let n=C(!i.json);n.start(`Loading providers for ${v.domain(e)}`);let r=await _(`/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){y(o,i.fields);return}let a=[];for(let g of["hosting","email"]){let x=o.providers?.[g]||[];for(let S of x)a.push({value:`${g}:${S.name}`,label:S.name,hint:g})}a.length===0&&u("No providers available",{code:"not_found",json:i.json,fields:i.fields});let l=await it({message:"Choose a provider",options:a});ce(l)&&process.exit(0);let[f,m]=l.split(":"),b=(o.providers?.[f]||[]).find(g=>g.name===m),k;if(b&&b.methods.length>1){let g=await it({message:"Choose a method",options:b.methods.map(x=>({value:x.name,label:x.name,hint:x.default?"default":void 0}))});ce(g)&&process.exit(0),k=g}let $;if(f==="hosting"&&b?.requires_target){b.notes?.setup&&be(b.notes.setup);let g=await Pe({message:"Target hostname or IP"});ce(g)&&process.exit(0),$=g.trim()}return bo(e,{target:$,provider:m,method:k,dryRun:i.dryRun,json:!1})}if(i.list){let n=C(!i.json);n.start(`Loading providers for ${v.domain(e)}`);let r=await _(`/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){y(o,i.fields);return}j(`Providers for ${v.domain(o.domain)}`);for(let a of["hosting","email"]){let l=o.providers?.[a];if(l?.length){c(),console.log(` ${fe.default.bold(a.toUpperCase())}`);for(let f of l){let m=f.methods.map(h=>h.default?fe.default.green(`${h.name} (default)`):fe.default.dim(h.name)).join(fe.default.dim(", "));console.log(` ${fe.default.cyan(f.name.padEnd(20))} ${m}`)}}}c();return}return bo(e,i)}async function bo(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 K("connect",{domain:e,...i},t.json,t.fields);let s=C(!t.json);s.start(`Connecting ${v.domain(e)}`);let n=await _(`/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?`${w.success} DNS instructions for ${fe.default.cyan(r.provider)}`:`${w.success} Connected to ${fe.default.cyan(r.provider)}`),t.json){y(r,t.fields);return}if(j(o?`Add these records at your registrar for ${v.domain(r.domain)}`:`Connected ${v.domain(r.domain)}`),d("Provider",fe.default.cyan(r.provider)),d("Method",r.method),r.records?.length){let a=[8,22,40];c(),console.log(` ${fe.default.bold("DNS Records")}`);let l=["Type","Name","Value"].map((m,h)=>fe.default.dim(m.padEnd(a[h]))).join(" "),f=a.map(m=>fe.default.dim("\u2500".repeat(m))).join(" ");console.log(` ${l}`),console.log(` ${f}`);for(let m of r.records){let h=m.record,b=m.status!=="already_set";process.stdout.isTTY&&b&&await wt(50);let $=[fe.default.yellow(h.type),h.name,fe.default.cyan(h.value)+(h.priority?fe.default.dim(` pri=${h.priority}`):"")].map((S,O)=>ss(S,a[O])).join(" "),g=m.status==="already_set"?fe.default.dim("\u2713"):m.status==="updated"?fe.default.yellow("\u21BA"):m.status==="pending"?fe.default.yellow("\u2192"):w.success,x=m.status==="already_set"?fe.default.dim(" already set"):m.status==="updated"?fe.default.dim(" updated"):m.status==="pending"?fe.default.dim(" add this"):"";console.log(` ${g} ${$}${x}`)}}c(),r.next_steps?.length?(console.log(` ${fe.default.bold("Next steps")}`),r.next_steps.forEach((a,l)=>{console.log(` ${fe.default.dim(`${l+1}.`)} ${a}`)})):r.hint&&console.log(` ${fe.default.dim(r.hint)}`),r.docs&&console.log(` ${fe.default.dim("Docs:")} ${v.url(r.docs)}`),c()}var fe,On=Te(()=>{"use strict";G();fe=D(F(),1);Ue();L();we();Ze()});function Vt(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 Wt(e){return e?Object.keys(e):[]}var rs=Te(()=>{"use strict"});var Ro={};zt(Ro,{contactsQuery:()=>jo,email:()=>bi,inboxQuery:()=>Co,parseRecipients:()=>as,recipientField:()=>ls});function qd(e){return[I.default.yellow(e.type),e.name,I.default.cyan(e.value)+(e.priority?I.default.dim(` pri=${e.priority}`):"")]}function Rn(e){return Ud[e]||e}function as(e){return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function ls(e){if(e.length!==0)return e.length===1?e[0]:e}function Md(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?(Y(e.domain,e),e.domain):he()}async function bi(e,t,i){if(e&&e.includes(".")&&!Nd.includes(e))return i.check?$o(e,!!i.json,i.fields):t?ko(e,t,!!i.json,i.fields):Oo(e,!!i.json,i.fields);if(Md(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 vo(i);case"list":return vo(i);case"inbox":return fc(i);case"folders":return pc(i);case"archive":case"trash":case"restore":case"read":case"unread":case"star":case"unstar":return hc(e,i);case"setup":return tc(i);case"status":return ic(i);case"remove":return sc(i);case"create":return nc(i);case"delete":return rc(i);case"send":return oc(i);case"webhook":return gc(i);case"webhook-test":return yc(i);case"forward":return bc(i);case"work":return Yd(i);case"triage":return Xd(i);case"note":return Zd(i);case"notes":return Qd(i);case"activity":return ec(i);case"changes":return Wd(i);case"search":return Hd(t,i);case"threads":return Jd(i);case"thread":return Bd(t,i);case"label":return Gd(i);case"facts":return Kd(t,i);case"extract":return zd(t,i);case"coordination":return Fd(i);case"presence":return Ld(i);case"release-presence":return Vd(i);case"escalate":return ac(i);case"remind":return lc(i);case"contacts":return dc(i);case"contact-add":return cc(i);case"contact-remove":return uc(i);case"tone":return mc(i);case"check":return $o(i.domain||await he(),!!i.json,i.fields);case"connect":return ko(i.domain||await he(),t||void 0,!!i.json,i.fields);default:u(`Unknown action: ${e}`,{hint:"Actions: list, inbox, folders, archive, trash, restore, read, unread, star, unstar, create, delete, send, forward, webhook, webhook-test, work, triage, notes, note, activity, changes, coordination, presence, release-presence, setup, status, check, connect",code:"validation_error",json:i.json,fields:i.fields})}}function An(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 Fd(e){let{mailboxId:t,threadKey:i}=An(e),s=new URLSearchParams({mailbox_id:t,thread_key:i}),n=await _(`/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 y(r,e.fields);j("Conversation Coordination"),d("Conversation",r.conversation_id),d("Reply version",String(r.reply_version)),d("Presence",String(r.presence?.length||0)),d("Compose lease",r.compose_lease?.holder?.label||"none")}async function Ld(e){let{mailboxId:t,threadKey:i}=An(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 _("/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 y(r,e.fields);j("Conversation Presence"),d("Mode",s),d("Reply version",String(r.reply_version)),d("Lease ID",r.compose_lease?.lease_id||"none"),d("Expires",r.compose_lease?.expires_at||r.presence?.find(o=>o.client_id===e.clientId)?.expires_at||"unknown")}async function Vd(e){let{mailboxId:t,threadKey:i}=An(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 _("/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 y(n,e.fields);j("Conversation Presence"),d("Released",e.clientId),d("Remaining presence",String(n.presence?.length||0))}async function Wd(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 _(`/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 y(n,e.fields);if(j("Mailbox Changes"),n.requires_full_sync){d("Full sync","Required"),d("Baseline cursor",n.next_cursor),be("Take a bounded mailbox snapshot, then call this command again with --cursor to replay concurrent changes.");return}n.changes.length?B(["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(` ${I.default.dim("No changes since this cursor.")}`),d("Next cursor",n.next_cursor),n.has_more&&be("More changes are available; call again with the next cursor.")}function os(e){return(e||"").split(",").map(t=>t.trim()).filter(Boolean)}async function Hd(e,t){let i=(t.query||(e&&!e.includes("@")?e:void 0)||"").trim();i||u("Query required",{hint:'Usage: domani email search "the invoice from tucows" [--from hi@myapp.dev] [--mode hybrid|semantic|keyword] [--limit 10] [--label billing]',code:"validation_error",json:t.json,fields:t.fields});let s=new URLSearchParams({q:i});t.mode&&s.set("mode",t.mode),t.limit&&s.set("limit",t.limit),t.slug&&t.domain&&s.set("mailbox",`${t.slug}@${t.domain}`),t.folder&&s.set("folder",t.folder),t.since&&s.set("since",t.since),t.until&&s.set("until",t.until),t.label&&s.set("label",t.label);let n=await _(`/api/emails/search?${s}`),r=await n.json();if(n.ok||u(r.error||r.message,{hint:r.hint,status:n.status,json:t.json,fields:t.fields}),t.json)return y(r,t.fields);if(j(`Search: ${i}`),!r.results.length){console.log(` ${I.default.dim(r.hint||"No mail matches this search.")}`);return}B(["Why","From","Subject","Mailbox","Message"],r.results.map(o=>[o.why,o.message.from.slice(0,28),(o.message.subject||"").slice(0,44),o.message.mailbox.slice(0,28),o.message.id]),[8,30,46,30,28]),be(`${r.results.length} result${r.results.length===1?"":"s"} in ${r.took_ms} ms, mode ${r.mode}. Open one with: domani email thread <thread_id> --from <mailbox>`)}async function Jd(e){let{address:t}=It(e,"Usage: domani email threads --from hi@myapp.dev [--folder inbox] [--since <iso>] [--limit 25] [--cursor <cursor>] [--label billing]"),i=new URLSearchParams;e.folder&&i.set("folder",e.folder),e.since&&i.set("since",e.since),e.limit&&i.set("limit",e.limit),e.cursor&&i.set("cursor",e.cursor),e.label&&i.set("label",e.label);let s=i.toString(),n=await _(`/api/emails/${encodeURIComponent(t)}/threads${s?`?${s}`:""}`),r=await n.json();if(n.ok||u(r.error||r.message,{hint:r.hint,status:n.status,json:e.json,fields:e.fields}),e.json)return y(r,e.fields);if(j(`Threads in ${t}`),!r.threads.length){console.log(` ${I.default.dim("No conversations here.")}`);return}B(["Messages","Unread","Subject","With","Last","Thread"],r.threads.map(o=>[String(o.message_count),String(o.unread_count),(o.subject||"").slice(0,40),o.participants.filter(a=>a!==t).join(", ").slice(0,30),o.last_message_at.slice(0,16),o.id]),[9,7,42,32,17,28]),r.next_cursor&&d("Next cursor",r.next_cursor)}async function Bd(e,t){let i=t.threadId||(e&&!e.includes("@")?e:void 0),{address:s}=It(t,"Usage: domani email thread <thread_id> --from hi@myapp.dev");i||u("Thread ID required",{hint:"Usage: domani email thread <thread_id> --from hi@myapp.dev",code:"validation_error",json:t.json,fields:t.fields});let n=await _(`/api/emails/${encodeURIComponent(s)}/threads/${encodeURIComponent(i)}`),r=await n.json();if(n.ok||u(r.error||r.message,{hint:r.hint,status:n.status,json:t.json,fields:t.fields}),t.json)return y(r,t.fields);j(r.subject||"Conversation"),d("Messages",String(r.message_count)),d("Unread",String(r.unread_count)),d("With",r.participants.join(", "));for(let o of r.messages)console.log(`
179
- ${I.default.bold(o.direction==="out"?"\u2192":"\u2190")} ${o.from} ${I.default.dim(o.created_at.slice(0,16))}${o.labels?.length?` ${I.default.dim(`[${o.labels.join(", ")}]`)}`:""} ${I.default.dim(o.id)}`),o.text&&console.log(` ${o.text.replace(/\s+/g," ").trim().slice(0,300)}`)}async function Gd(e){let{address:t}=It(e,"Usage: domani email label --from hi@myapp.dev --message-ids m1,m2 --add billing[,urgent] [--remove old] | --set a,b"),i=os(e.messageIds),s=os(e.add),n=os(e.remove),r=e.set===void 0?void 0:os(e.set);(!i.length||!s.length&&!n.length&&r===void 0)&&u("Message IDs and labels required",{hint:"Usage: domani email label --from hi@myapp.dev --message-ids m1,m2 --add billing[,urgent] [--remove old] | --set a,b",code:"validation_error",json:e.json,fields:e.fields});let o={message_ids:i,action:"label",idempotency_key:e.idempotencyKey||(0,In.randomUUID)()};s.length&&(o.add=s),n.length&&(o.remove=n),r!==void 0&&(o.set=r);let a=await _(`/api/emails/${encodeURIComponent(t)}/messages/actions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),l=await a.json();if(a.ok||u(l.error||l.message,{hint:l.hint,status:a.status,json:e.json,fields:e.fields}),e.json)return y(l,e.fields);let f=l.results||[];j("Labels"),B(["Message","Result"],f.map(m=>[m.message_id,m.ok?m.changed?"updated":"unchanged":m.error?.message||"failed"]),[30,40])}async function Kd(e,t){let i=t.messageIds||(e&&!e.includes("@")?e:void 0),{address:s}=It(t,"Usage: domani email facts <message_id> --from hi@myapp.dev");i||u("Message ID required",{hint:"Usage: domani email facts <message_id> --from hi@myapp.dev",code:"validation_error",json:t.json,fields:t.fields});let n=await _(`/api/emails/${encodeURIComponent(s)}/messages/${encodeURIComponent(i)}/facts`),r=await n.json();if(n.ok||u(r.error||r.message,{hint:r.hint,status:n.status,json:t.json,fields:t.fields}),t.json)return y(r,t.fields);if(j("Facts"),!r.analysed){d("Analysed","no"),d("Reason",r.reason),be(r.reason==="not_enabled"?"Enable the mailbox in the assistant: domani assistant set --enable --mailboxes <id>":"The analysis has not happened yet; try again in a minute.");return}d("Analysis",`${r.analysis.id} (${r.analysis.generated_at.slice(0,16)}, ${r.analysis.coverage})`),r.facts.length?B(["Subject","Predicate","Value","Basis"],r.facts.map(o=>[(o.subject||"").slice(0,28),(o.predicate||"").slice(0,28),`${o.value?.value??o.object??""}${o.value?.currency?` ${o.value.currency}`:""}`.slice(0,32),o.basis||""]),[30,30,34,18]):console.log(` ${I.default.dim("No claim recorded.")}`);for(let o of r.commitments)d("Promised",`${o.who}: ${o.what}`);for(let o of r.expectations)d("Awaited",`${o.who}: ${o.what}`)}async function zd(e,t){let i=t.messageIds||(e&&!e.includes("@")?e:void 0),s=`Usage: domani email extract <message_id> --from hi@myapp.dev --schema '{"type":"object","properties":{"total":{"type":"number"}}}' [--instructions "amounts in EUR"] (or --schema @fields.json)`,{address:n}=It(t,s);(!i||!t.schema)&&u("Message ID and --schema required",{hint:s,code:"validation_error",json:t.json,fields:t.fields});let r;try{let l=t.schema.startsWith("@")?(0,_o.readFileSync)(t.schema.slice(1),"utf8"):t.schema;r=JSON.parse(l)}catch(l){u("Schema must be JSON (inline or @file)",{hint:l instanceof Error?l.message:String(l),code:"validation_error",json:t.json,fields:t.fields})}let o=await _(`/api/emails/${encodeURIComponent(n)}/messages/${encodeURIComponent(i)}/extract`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({schema:r,...t.instructions?{instructions:t.instructions}:{}})}),a=await o.json();if(o.ok||u(a.error||a.message,{hint:a.hint,status:o.status,json:t.json,fields:t.fields}),t.json)return y(a,t.fields);j("Extraction"),d("Confidence",String(a.confidence)),d("Cached",a.cached?"yes":"no"),d("Model",a.model);for(let[l,f]of Object.entries(a.data))d(l,f===null?I.default.dim("null"):typeof f=="object"?JSON.stringify(f):String(f));for(let l of a.evidence_quotes)console.log(` ${I.default.dim(`"${l.slice(0,120)}"`)}`)}async function Yd(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 _(`/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 y(n,e.fields);if(j("Shared Inbox Work"),!n.items.length)return console.log(` ${I.default.dim("No conversations match this queue.")}`);B(["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&&be("This is a bounded snapshot. Increase --limit or use the API scan_limit when you need a wider queue.")}async function Xd(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 _("/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 y(s,e.fields);j("Conversation Updated"),d("Status",s.status),d("Assignee",s.assignee?.label||"Unassigned"),d("Version",s.version)}async function Zd(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 _(`/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 y(i,e.fields);console.log(`${w.success} Private note added`)}async function Qd(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 _(`/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 y(i,e.fields);if(j("Private Notes"),!i.notes.length)return console.log(` ${I.default.dim("No private notes yet.")}`);B(["Author","Created","Note"],i.notes.map(s=>[s.author.label,s.created_at,s.body]),[28,24,64])}async function ec(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 _(`/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 y(i,e.fields);if(j("Conversation Activity"),!i.activity.length)return console.log(` ${I.default.dim("No activity yet.")}`);B(["Type","Actor","Created"],i.activity.map(s=>[s.type,s.actor.label,s.created_at]),[36,32,24])}async function tc(e){let t=await Qe(e);if(e.dryRun)return K("email_setup",{domain:t},e.json,e.fields);let i=C(!e.json);i.start(`Setting up email on ${v.domain(t)}`);let s=await _(`/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(`${w.success} Email ${n.status==="already_configured"?"already configured":"configured"}`),e.json){y(n,e.fields);return}if(n.records?.length){c(),j(`Email DNS Records ${v.domain(t)}`);let r=n.records.map(o=>[I.default.yellow(o.type),o.name,o.value.length>40?o.value.slice(0,40)+"...":o.value,o.status==="verified"||o.status==="created"?I.default.green(o.status):I.default.yellow(o.status)]);B(["Type","Name","Value","Status"],r,[8,28,44,12])}c(),n.hint&&be(n.hint),R("Check status:",`domani email status --domain ${t}`),c()}async function ic(e){let t=await Qe(e),i=C(!e.json);i.start(`Checking email status for ${v.domain(t)}`);let s=await _(`/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(`${w.success} Status loaded`),e.json){y(n,e.fields);return}if(j(`Email ${v.domain(t)}`),d("Enabled",n.enabled?I.default.green("yes"):I.default.dim("no")),n.enabled&&(d("Verified",n.verified?I.default.green("yes"):I.default.yellow("pending")),d("Mailboxes",String(n.mailbox_count))),c(),!n.enabled)R("Set up email:",`domani email setup --domain ${t}`),c();else if(!n.verified&&n.records?.length){console.log(` ${I.default.yellow("!")} Add these DNS records to verify:`);for(let r of n.records)console.log(` ${I.default.yellow(r.type)} ${r.name} ${I.default.dim("\u2192")} ${r.value.length>50?r.value.slice(0,50)+"...":r.value}`);c()}}async function sc(e){let t=await Qe(e);if(e.dryRun)return K("email_remove",{domain:t},e.json,e.fields);let i=C(!e.json);i.start(`Removing email from ${v.domain(t)}`);let s=await _(`/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(`${w.success} Email disabled`),e.json){y(n,e.fields);return}n.mailboxes_deleted>0&&console.log(` ${I.default.dim(`${n.mailboxes_deleted} mailbox(es) deleted.`)}`),c()}async function vo(e){let t=C(!e.json);t.start("Loading mailboxes");let i=e.domain?`?domain=${encodeURIComponent(e.domain)}`:"",s=await _(`/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(`${w.success} ${r.length} mailbox(es)`),e.json){y(n,e.fields);return}if(r.length===0){c(),console.log(` ${I.default.dim("No mailboxes.")}`),c(),R("Create one:","domani email create hello@example.com"),c();return}c(),j("Mailboxes");let o=r.map(a=>[I.default.cyan(a.address),String(a.message_count),a.webhook_url?v.url(a.webhook_url):I.default.dim("-"),I.default.dim(new Date(a.created_at).toLocaleDateString())]);B(["Address","Messages","Webhook","Created"],o,[32,10,36,14]),c()}async function nc(e){let t=await Qe(e);if(e.dryRun)return K("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 f=await Pe({message:`Email handle for @${t}:`,placeholder:"hello"});ce(f)&&process.exit(0),i=f}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=C(!e.json);n.start("Creating mailbox");let r=await _("/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 f=o.txt_record,m=o.email_records||[],h=[{type:"TXT",name:f?.name||"@",value:f?.value||"",note:"ownership proof"},...m];c(),console.log(" Add these records at your DNS provider:"),c();for(let S of h){let O=S.priority!==void 0?` ${I.default.dim(`priority: ${S.priority}`)}`:"",A=S.note?` ${I.default.dim(`(${S.note})`)}`:"";console.log(` ${I.default.yellow(S.type)} ${I.default.bold(S.name)}${O}${A}`),console.log(` ${I.default.dim("\u2192")} ${I.default.cyan(S.value)}`),c()}be("DNS propagation typically takes 5\u201330 minutes. Checking automatically..."),c();let b=h.map(S=>({cells:[I.default.yellow(S.type),S.name,S.note?I.default.dim(`(${S.note})`):""],status:"pending"})),k=Lt(["Type","Name",""],b,[6,24,16]);k.start();let $=0;for(;r.status===202&&$<60;)await wt(15e3),$++,r=await _("/api/emails",{method:"POST",body:JSON.stringify({address:s,workspace_id:e.workspace})}),o=await r.json(),r.status!==202&&!r.ok&&(k.stop(),u(o.error||o.message,{hint:o.hint,status:r.status,json:e.json,fields:e.fields}));r.status===202&&(k.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})),k.markDone(0);let g=S=>`${S.type}:${S.name}`,x=new Map;h.slice(1).forEach((S,O)=>x.set(g(S),O+1));for(let S=0;S<60;S++){await wt(15e3);let O=await _(`/api/domains/${encodeURIComponent(t)}/email/status`),A=await O.json();if(O.ok&&A.records){for(let W of A.records)if(W.status==="verified"||W.status==="created"){let H=x.get(g(W));H!==void 0&&k.markDone(H)}}if(O.ok&&A.verified)break}k.stop(),c()}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(`${w.success} ${I.default.cyan(o.address)} created`),e.json){y(o,e.fields);return}let a=await _(`/api/domains/${encodeURIComponent(t)}/email/status`),l=await a.json();c(),a.ok&&l.verified?(R("Read inbox:",`domani email inbox ${o.address}`),R("Web inbox:",`${di}/inbox?address=${encodeURIComponent(o.address)}`)):(R("Check propagation:",`domani email status --domain ${t}`),R("Web inbox:",`${di}/inbox?address=${encodeURIComponent(o.address)}`)),c()}async function rc(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 K("email_delete_mailbox",{domain:t,address:`${e.slug}@${t}`},e.json,e.fields);let i=C(!e.json);i.start(`Deleting ${e.slug}@${t}`);let s=encodeURIComponent(`${e.slug}@${t}`),n=await _(`/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(`${w.success} Mailbox deleted`),e.json){y(r,e.fields);return}console.log(` ${I.default.dim(`${r.address} and all messages deleted.`)}`),c()}async function oc(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 K("email_send",{from:`${e.slug}@${t}`,to:e.to,subject:e.subject},e.json,e.fields);let i=C(!e.json);i.start(`Sending from ${e.slug}@${t}`);let s={to:ls(as(e.to))},n=ls(as(e.cc)),r=ls(as(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),e.sendAt&&(s.send_at=e.sendAt);let o=encodeURIComponent(`${e.slug}@${t}`),a=await _(`/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 ${I.default.cyan("domani upgrade")} to switch to Pro (10,000 emails/month).`:l.hint;u(l.error||l.message,{hint:m,status:a.status,json:e.json,fields:e.fields})}let f=Array.isArray(l.to)?l.to.join(", "):l.to;if(i.stop(l.status==="scheduled"?`${w.success} Scheduled for ${I.default.cyan(e.sendAt||"")} to ${I.default.cyan(f)} ${I.default.dim("(trash the message before then to cancel)")}`:`${w.success} Sent to ${I.default.cyan(f)}`),e.json){y(l,e.fields);return}}function It(e,t){return(!e.slug||!e.domain)&&u("Mailbox address required",{hint:t,code:"validation_error",json:e.json,fields:e.fields}),{domain:e.domain,slug:e.slug,address:`${e.slug}@${e.domain}`}}async function xo(e,t,i,s,n){let r=C(!i.json);r.start(s);let o=await _(e,{method:"POST",body:JSON.stringify(t)}),a=await o.json();o.ok||(r.stop("Failed"),u(a.error||a.message,{hint:a.hint,status:o.status,json:i.json,fields:i.fields})),r.stop(n(a)),i.json&&y(a,i.fields)}async function ac(e){let t='Usage: domani email escalate hello@example.com --message-id MSG_ID [--reason "refund over $500"] [--clear]',{address:i}=It(e,t);e.messageId||u("Message ID required",{hint:t,code:"validation_error",json:e.json,fields:e.fields});let s={};e.reason&&(s.reason=e.reason),e.clear&&(s.clear=!0),await xo(`/api/emails/${encodeURIComponent(i)}/messages/${encodeURIComponent(e.messageId)}/escalate`,s,e,e.clear?"Clearing escalation":"Flagging for a human",n=>n.needs_human?`${w.success} Flagged for a human ${I.default.dim("(conversation held, email.escalated fired)")}`:`${w.success} Escalation cleared`)}async function lc(e){let t='Usage: domani email remind hello@example.com --message-id MSG_ID --at 2026-09-03T09:00:00Z [--note "chase the invoice"] [--clear]',{address:i}=It(e,t);e.messageId||u("Message ID required",{hint:t,code:"validation_error",json:e.json,fields:e.fields}),!e.at&&!e.clear&&u("Reminder time required",{hint:t,code:"validation_error",json:e.json,fields:e.fields});let s={};e.at&&(s.remind_at=e.at),e.note&&(s.note=e.note),e.clear&&(s.clear=!0),await xo(`/api/emails/${encodeURIComponent(i)}/messages/${encodeURIComponent(e.messageId)}/remind`,s,e,e.clear?"Clearing reminder":"Setting follow-up reminder",n=>n.remind_at?`${w.success} Reminder set for ${I.default.cyan(String(n.remind_at))} ${I.default.dim("(fires only if still unanswered)")}`:`${w.success} Reminder cleared`)}function jo(e){let t=new URLSearchParams;e.q&&t.set("q",e.q),e.limit&&t.set("limit",e.limit),e.order&&t.set("order",e.order),e.cursor&&t.set("cursor",e.cursor);let i=t.toString();return i?`?${i}`:""}async function dc(e){let t=await _(`/api/contacts${jo(e)}`),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){y(i,e.fields);return}let s=i.contacts||[];if(s.length===0){console.log(I.default.dim("No contacts yet. The address book fills itself as mail flows in and out."));return}for(let n of s){let r=n.name?` ${I.default.dim(n.name)}`:"",o=n.notes?` ${I.default.dim("-")} ${n.notes}`:"";console.log(`${I.default.cyan(n.address)}${r} ${I.default.dim(`(${n.message_count} msg${n.message_count!==1?"s":""}, last ${n.last_direction||"-"})`)}${o}`)}i.next_cursor&&console.log(I.default.dim(`More: --cursor ${i.next_cursor}`))}function So(e,t){return e.slug&&e.domain?`${e.slug}@${e.domain}`:(u("Contact address required",{hint:t,code:"validation_error",json:e.json,fields:e.fields}),"")}async function cc(e){let i=So(e,'Usage: domani email contact-add ada@example.com [--name "Ada"] [--notes "prefers short emails"]'),s={address:i};e.name!==void 0&&(s.name=e.name),e.notes!==void 0&&(s.notes=e.notes);let n=await _("/api/contacts",{method:"POST",body:JSON.stringify(s)}),r=await n.json();if(n.ok||u(r.error||r.message,{hint:r.hint,status:n.status,json:e.json,fields:e.fields}),e.json){y(r,e.fields);return}console.log(`${w.success} Contact ${I.default.cyan(i)} saved.`)}async function uc(e){let i=So(e,"Usage: domani email contact-remove ada@example.com"),s=await _(`/api/contacts/${encodeURIComponent(i)}`,{method:"DELETE"}),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){y(n,e.fields);return}console.log(n.deleted?`${w.success} Contact ${I.default.cyan(i)} deleted.`:I.default.dim(`No contact ${i}.`))}async function mc(e){let t='Usage: domani email tone hello@example.com [--set "lowercase, friendly, sign as Ada"] [--clear]',{address:i}=It(e,t),s=encodeURIComponent(i);if(e.set===void 0&&!e.clear){let o=await _(`/api/emails/${s}`),a=await o.json();if(o.ok||u(a.error||a.message,{hint:a.hint,status:o.status,json:e.json,fields:e.fields}),e.json){y({address:i,tone_notes:a.tone_notes??null},e.fields);return}console.log(a.tone_notes?a.tone_notes:I.default.dim(`No tone notes on ${i}. Set them with --set.`));return}let n=await _(`/api/emails/${s}`,{method:"PATCH",body:JSON.stringify({tone_notes:e.clear?null:e.set})}),r=await n.json();if(n.ok||u(r.error||r.message,{hint:r.hint,status:n.status,json:e.json,fields:e.fields}),e.json){y(r,e.fields);return}console.log(e.clear?`${w.success} Tone notes cleared on ${I.default.cyan(i)}.`:`${w.success} Tone notes set on ${I.default.cyan(i)}.`)}function Co(e){let t=new URLSearchParams;e.direction&&t.set("direction",e.direction),e.folder&&t.set("folder",e.folder),e.view&&t.set("view",e.view),e.limit&&t.set("limit",e.limit),e.since&&t.set("since",e.since),e.until&&t.set("until",e.until),e.label&&t.set("label",e.label),e.cursor&&t.set("cursor",e.cursor);let i=t.toString();return i?`?${i}`:""}async function fc(e){let t=await Qe(e);e.slug||u("Slug required",{hint:"Usage: domani email inbox hello@example.com [--direction in|out] [--limit 20] [--cursor <next_cursor>]",code:"validation_error",json:e.json,fields:e.fields});let i=Co(e),s=C(!e.json);s.start(`Loading messages for ${e.slug}@${t}`);let n=encodeURIComponent(`${e.slug}@${t}`),r=await _(`/api/emails/${n}/messages${i}`),o=await r.json();r.ok||(s.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:e.json,fields:e.fields}));let a=o.messages||[];if(e.json){s.stop(`${w.success} ${a.length} message(s)`),y(o,e.fields);return}if(a.length===0){s.stop(`${I.default.dim("No messages")}`);return}let l=a.length>1?"s":"";s.stop(`${w.success} ${I.default.cyan(`${e.slug}@${t}`)} ${I.default.dim("\xB7 "+a.length+" message"+l)}`);for(let f of a){let m=f.direction==="in"?I.default.green("in "):I.default.dim("out"),h=f.direction==="in"?f.from:f.to,b=f.subject||"(no subject)",k=I.default.dim(new Date(f.created_at).toLocaleString()),$=b;if(f.text){let g=f.text.replace(/\s+/g," ").trim(),x=g.length>60?g.slice(0,60)+"\u2026":g;$=`${b} ${I.default.dim("- "+x)}`}console.log(` ${m} ${h.padEnd(30)} ${$} ${k}`)}o.next_cursor&&console.log(I.default.dim(`More: --cursor ${o.next_cursor}`))}async function pc(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 _(`/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 y(n,e.fields);j(`Folders for ${e.slug}@${t}`);for(let r of n.folders||[])d(r.id,`${r.total} total, ${r.unread} unread`);for(let r of n.views||[])d(r.id,`${r.total} total, ${r.unread} unread`)}async function hc(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(m=>m.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,In.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 K("email_messages_action",{address:`${t.slug}@${i}`,...n},t.json,t.fields);let r=encodeURIComponent(`${t.slug}@${i}`),o=await _(`/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 y(a,t.fields);let l=(a.results||[]).filter(m=>m.ok).length,f=(a.results||[]).length-l;console.log(`${w.success} ${l} updated${f?I.default.yellow(`, ${f} failed`):""}`),a.operation_id&&(d("Operation",a.operation_id),d("Idempotency key",a.idempotency_key),a.idempotent_replay&&d("Receipt","replayed (no duplicate mutation)"))}async function gc(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=Vt(e)}catch(a){u(a instanceof Error?a.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})}let r;if(e.events!==void 0&&(r=e.events.split(",").map(a=>a.trim()).filter(Boolean),r.length===0&&u("--events needs at least one event",{hint:"Example: --events email.received,email.bounced,email.delivered",code:"validation_error",json:e.json,fields:e.fields}),e.url||u("--url is required when changing webhook events",{hint:"Pass the existing webhook URL together with --events.",code:"validation_error",json:e.json,fields:e.fields})),!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 K("email_webhook",{address:i,webhook_url:e.url||null,...r!==void 0?{events:r}:{},...n!==void 0?{header_names:Wt(n)}:{}},e.json,e.fields);let o=C(!e.json);if(e.url){o.start(`Setting webhook for ${i}`);let a=await _(`/api/emails/${s}/webhook`,{method:"PUT",body:JSON.stringify({url:e.url,...n!==void 0?{headers:n}:{},...r!==void 0?{events:r}:{}})}),l=await a.json();if(a.ok||(o.stop("Failed"),u(l.error||l.message,{hint:l.hint,status:a.status,json:e.json,fields:e.fields})),o.stop(`${w.success} Webhook set`),e.json){y(l,e.fields);return}j(`Mailbox ${l.address}`),d("Webhook",v.url(l.webhook_url)),d("Events",l.events?.join(", ")||I.default.dim("email.received")),d("Auth headers",l.header_names?.join(", ")||I.default.dim("none")),d("Signing secret",I.default.dim(l.signing_secret)),c()}else{o.start(`Removing webhook for ${i}`);let a=await _(`/api/emails/${s}/webhook`,{method:"DELETE"}),l=await a.json();if(a.ok||(o.stop("Failed"),u(l.error||l.message,{hint:l.hint,status:a.status,json:e.json,fields:e.fields})),o.stop(`${w.success} Webhook removed`),e.json){y(l,e.fields);return}j(`Mailbox ${l.address}`),d("Webhook",I.default.dim("none")),c()}}async function yc(e){let t=await Qe(e);e.slug||u("Slug required",{hint:"Usage: domani email webhook-test hello@example.com",code:"validation_error",json:e.json,fields:e.fields});let i=`${e.slug}@${t}`;if(e.dryRun)return K("email_webhook_test",{address:i},e.json,e.fields);let s=C(!e.json);s.start(`Testing webhook for ${i}`);let n=await _(`/api/emails/${encodeURIComponent(i)}/webhook/test`,{method:"POST"}),r=await n.json();if((!n.ok||!r.success)&&(s.stop("Failed"),u(r.error||r.message||"Webhook test failed",{hint:r.hint||"Check the endpoint and sender authentication, then retry.",status:n.status,json:e.json,fields:e.fields})),s.stop(`${w.success} Test delivered`),e.json)return y(r,e.fields);j(`Mailbox ${i}`),d("Delivery",I.default.green("successful")),typeof r.status=="number"&&d("Endpoint",`HTTP ${r.status}`),c()}async function bc(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 K("email_forward",{address:`${e.slug}@${t}`,forward_to:e.forwardTo||null},e.json,e.fields);let i=C(!e.json),s=e.forwardTo||null;i.start(`Updating forward for ${e.slug}@${t}`);let n=encodeURIComponent(`${e.slug}@${t}`),r=await _(`/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(`${w.success} Forward ${s?"set":"removed"}`),e.json){y(o,e.fields);return}j(`Mailbox ${o.address}`),d("Forward to",o.forward_to?I.default.cyan(o.forward_to):I.default.dim("none")),c()}async function $o(e,t,i){let s=C(!t);s.start(`Checking email health for ${v.domain(e)}`);let n=await _(`/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){y(r,i);return}if(j(`Email Health ${v.domain(r.domain)}`),r.provider?d("Provider",I.default.cyan(Rn(r.provider))):d("Provider",I.default.dim("unknown")),r.mx.configured?d("MX",`${w.success} ${I.default.green("propagated")} ${I.default.dim(`(${r.mx.records.length} record${r.mx.records.length!==1?"s":""})`)}`):d("MX",`${w.error} ${I.default.red("not configured")}`),r.spf.configured?d("SPF",`${w.success} ${I.default.green(r.spf.value)}`):d("SPF",`${w.error} ${I.default.red("missing")}`),r.dmarc.configured){let o=r.dmarc.value.length>50?r.dmarc.value.slice(0,50)+"...":r.dmarc.value;d("DMARC",`${w.success} ${I.default.green(o)}`)}else d("DMARC",`${w.error} ${I.default.red("missing")}`);r.dkim.configured?d("DKIM",`${w.success} ${I.default.green("found")} ${I.default.dim(`(${r.dkim.selectors.join(", ")})`)}`):d("DKIM",`${w.warning} ${I.default.yellow("not found")}`),c(),r.mx.configured?(!r.spf.configured||!r.dmarc.configured)&&(be("SPF and DMARC protect against email spoofing. Re-run email setup to add them."),c()):(R("Set up email:",`domani email ${e} google`),c())}async function ko(e,t,i,s){return t?Io(e,t,i,s):Oo(e,i,s)}async function Oo(e,t,i){let s=C(!t);s.start("Loading email providers");let n=await _(`/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 it({message:"Choose an email provider",options:o.map(l=>({value:l.name,label:Rn(l.name)}))});return ce(a)&&process.exit(0),Io(e,a,t,i)}async function Io(e,t,i,s){if(i){let f=await _(`/api/domains/${encodeURIComponent(e)}/connect`,{method:"POST",body:JSON.stringify({target:t})}),m=await f.json();f.ok||u(m.error||m.message,{hint:m.hint,status:f.status,json:i,fields:s}),y(m,s);return}let n=await _(`/api/domains/${encodeURIComponent(e)}/connect?provider=${encodeURIComponent(t)}`);if(!n.ok){let f=await n.json();u(f.error||f.message,{hint:f.hint,status:n.status,json:i,fields:s})}let r=await n.json(),o=r.preview?.records??[],a=r.preview?.provider??t,l=Rn(a);if(j(`Email ${v.domain(e)}`),d("Provider",I.default.cyan(l)),o.length){c(),console.log(` ${I.default.bold("DNS Records")}`);let f=[8,24,40],m=Lt(["Type","Name","Value"],o.map(S=>({cells:qd(S),status:"pending"})),f);m.start();let h=await _(`/api/domains/${encodeURIComponent(e)}/connect`,{method:"POST",body:JSON.stringify({target:t})}),b=await h.json();h.ok||(m.stop(),c(),u(b.error||b.message,{hint:b.hint,status:h.status,json:i,fields:s}));let k=b.records||[];for(let S=0;S<o.length;S++)k.find(A=>A.record.type===o[S].type&&A.record.name===o[S].name&&A.record.value===o[S].value)?.status==="already_set"||await wt(60),m.markDone(S);await wt(80),m.stop();let $=k.filter(S=>S.status==="created"||S.status==="updated").length,g=k.filter(S=>S.status==="already_set").length,x;g===k.length?x=`All ${g} records already set`:g>0?x=`${$} created, ${g} already set`:x=`${$} DNS records set`,c(),console.log(` ${w.success} ${I.default.green(`Email configured - ${x}`)}`)}else{let f=C(!0);f.start("Setting DNS records");let m=await _(`/api/domains/${encodeURIComponent(e)}/connect`,{method:"POST",body:JSON.stringify({target:t})}),h=await m.json();m.ok||(f.stop("Failed"),u(h.error||h.message,{hint:h.hint,status:m.status,json:i,fields:s})),f.stop(`${w.success} Email configured via ${I.default.cyan(l)}`)}c(),R("Verify propagation:",`domani email ${e} --check`),c()}var I,In,_o,Nd,Ud,Tn=Te(()=>{"use strict";G();ci();I=D(F(),1);Ue();L();we();Ze();In=require("node:crypto"),_o=require("node:fs");rs();Nd=["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","escalate","remind","contacts","contact-add","contact-remove","tone","search","threads","thread","label","facts","extract"],Ud={"google-workspace":"Google Workspace",fastmail:"Fastmail",proton:"Proton Mail"}});var Ao={};zt(Ao,{dns:()=>Pn});async function Pn(e,t,i,s,n,r){e||(e=await he()),Y(e,r);let o=r?.json??!1,a=r?.type||i,l=r?.name||s,f=r?.value||n;if(!t||t==="get"){let m=C(!o);m.start(`Loading DNS for ${v.domain(e)}`);let h=await _(`/api/domains/${encodeURIComponent(e)}/dns`),b=await h.json();if(h.ok||(m.stop("Failed"),u(b.error||b.message,{hint:b.hint,status:h.status,json:o,fields:r?.fields})),m.stop(`${b.records.length} record(s)`),o){y(b,r?.fields);return}if(b.records.length===0){c(),console.log(` ${Oe.default.dim(`No DNS records for ${e}`)}`),c(),R("Auto-configure DNS:",`domani connect ${e}`),c();return}let k=[8,24,40,8];j(`DNS ${v.domain(e)}`,k.reduce((g,x)=>g+x,0)+k.length-1);let $=b.records.map(g=>{let x=g.priority?Oe.default.dim(` pri=${g.priority}`):"";return[Oe.default.yellow(g.type),g.name,Oe.default.cyan(g.value)+x,Oe.default.dim(String(g.ttl))]});B(["Type","Name","Value","TTL"],$,k),c();return}if(t==="set"){if((!a||!l||!f)&&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 K("dns_set",{domain:e,record:{type:a.toUpperCase(),name:l,value:f,ttl:3600}},o,r?.fields);let m=C(!o);m.start(`Setting ${Oe.default.yellow(a.toUpperCase())} record`);let h=await _(`/api/domains/${encodeURIComponent(e)}/dns`),b=await h.json(),$=(h.ok?b.records:[]).filter(S=>!(S.type===a.toUpperCase()&&S.name===l));$.push({type:a.toUpperCase(),name:l,value:f,ttl:3600});let g=await _(`/api/domains/${encodeURIComponent(e)}/dns`,{method:"PUT",body:JSON.stringify({records:$})}),x=await g.json();g.ok||(m.stop("Failed"),u(x.error||x.message,{hint:x.hint,status:g.status,json:o,fields:r?.fields})),m.stop(`${w.success} ${Oe.default.yellow(a.toUpperCase())} ${l} ${w.arrow} ${Oe.default.cyan(f)}`),o?y(x,r?.fields):(c(),R("Check propagation:",`domani status ${e}`),c());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 K("dns_delete",{domain:e,record:{type:a.toUpperCase(),name:l}},o,r?.fields);let m=C(!o);m.start(`Deleting ${Oe.default.yellow(a.toUpperCase())} ${l}`);let h=await _(`/api/domains/${encodeURIComponent(e)}/dns?type=${encodeURIComponent(a.toUpperCase())}&name=${encodeURIComponent(l)}`,{method:"DELETE"}),b=await h.json();h.ok||(m.stop("Failed"),u(b.error||b.message,{hint:b.hint,status:h.status,json:o,fields:r?.fields})),m.stop(`${w.success} Deleted ${Oe.default.yellow(a.toUpperCase())} ${l}`),o?y(b,r?.fields):(c(),R("Check propagation:",`domani status ${e}`),c());return}if(t==="snapshot"){if(r?.dryRun)return K("dns_snapshot",{domain:e},o,r?.fields);let m=C(!o);m.start(`Capturing DNS snapshot for ${v.domain(e)}`);let h=await _(`/api/domains/${encodeURIComponent(e)}/dns/snapshot`,{method:"POST"}),b=await h.json();h.ok||(m.stop("Failed"),u(b.error||b.message,{hint:b.hint,status:h.status,json:o,fields:r?.fields}));let k=b.records?.length??0;if(m.stop(`${w.success} Captured ${k} record(s)`),o){y(b,r?.fields);return}let $=`${e}.dns.json`,g=(0,En.resolve)(process.cwd(),$);(0,ds.writeFileSync)(g,JSON.stringify(b,null,2)+`
180
- `),j("DNS Snapshot"),d("Domain",v.domain(b.domain)),d("Records",String(k)),d("Subdomains",String(b.subdomains?.length??0)),d("Sources",(b.sources||[]).join(", ")||"none"),d("Captured",b.capturedAt||b.captured_at||"now"),d("Saved to",Oe.default.cyan($)),c(),R("Restore from this snapshot:",`domani dns ${e} restore --file ${$}`),c();return}if(t==="restore"){if(r?.dryRun)return K("dns_restore",{domain:e,source:r?.file||"server_backup"},o,r?.fields);let m=C(!o),h;if(r?.file){let $=(0,En.resolve)(process.cwd(),r.file);$.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 g=(0,ds.readFileSync)($,"utf-8"),x=JSON.parse(g);h=JSON.stringify({snapshot:x}),m.start(`Restoring DNS for ${v.domain(e)} from ${Oe.default.cyan(r.file)}`)}catch(g){u(`Failed to read snapshot file: ${g instanceof Error?g.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 ${v.domain(e)} from server backup`);let b=await _(`/api/domains/${encodeURIComponent(e)}/dns/restore`,{method:"POST",...h?{body:h}:{}}),k=await b.json();if(b.ok||(m.stop("Failed"),u(k.error||k.message,{hint:k.hint,status:b.status,json:o,fields:r?.fields})),m.stop(`${w.success} Restored DNS`),o){y(k,r?.fields);return}if(j("DNS Restored"),d("Domain",v.domain(k.domain)),d("Applied",Oe.default.green(String(k.applied??0))),d("Skipped",Oe.default.dim(String(k.skipped??0))),k.errors?.length>0){d("Errors",Oe.default.red(String(k.errors.length)));for(let $ of k.errors)console.log(` ${Oe.default.red("\u2022")} ${$}`)}c(),R("Verify DNS records:",`domani dns ${e}`),c();return}u(`Unknown action: ${t}`,{hint:"Use 'get', 'set', 'delete', 'snapshot', or 'restore'.",code:"validation_error",json:o,fields:r?.fields})}var Oe,ds,En,Dn=Te(()=>{"use strict";G();Oe=D(F(),1);L();we();Ze();ds=require("node:fs"),En=require("node:path")});var To={};zt(To,{status:()=>Nn});function wc(e){return[st.default.yellow(e.type),e.name,st.default.cyan(e.value)+(e.priority?st.default.dim(` pri=${e.priority}`):"")]}function vc(e){if(j(`Status ${v.domain(e.domain)}`),e.expires){let t=new Date(e.expires).toLocaleDateString(),i=e.days_until_expiry,s=i!=null&&i<30?st.default.red:i!=null&&i<90?st.default.yellow:st.default.green;d("Expires",`${t} ${st.default.dim("(")}${s(`${i} days`)}${st.default.dim(")")}`)}}async function Nn(e,t){if(e||(e=await he()),Y(e,t),t.json){let h=await _(`/api/domains/${encodeURIComponent(e)}/status`),b=await h.json();h.ok||u(b.error||b.message,{hint:b.hint,status:h.status,json:t.json,fields:t.fields}),y(b,t.fields);return}let i=C(!0);i.start(`Checking ${v.domain(e)}`);let s;try{s=await _(`/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 h=await s.json();u(h.error||h.message,{hint:h.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=[],f=!1,m="";try{for await(let h of n){o+=r.decode(h,{stream:!0});let b=o.split(`
181
- `);o=b.pop()??"";for(let k of b)if(k.startsWith("event: "))m=k.slice(7);else if(k.startsWith("data: ")){let $=JSON.parse(k.slice(6));if(m==="info"&&(i.stop("Status retrieved"),f=!0,vc($)),m==="records")if(l=$,l.length>0){c(),console.log(` ${st.default.bold("DNS Records")}`);let g=[8,10,34];a=Lt(["Type","Name","Value"],l.map(x=>({cells:wc(x),status:"pending"})),g),a.start()}else c(),d("DNS",st.default.dim("no records")),R("Auto-configure DNS:",`domani connect ${e}`);if(m==="propagation"&&a){let{index:g,propagated:x}=$,S=x?w.success:`${w.warning}`;a.markDone(g,S)}m==="done"&&a&&a.stop(),m==="error"&&(f||i.stop("Failed"),a&&a.stop(),u($.message||"Status check failed"))}}}catch{f||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})}f||i.stop("Done"),c()}var st,Un=Te(()=>{"use strict";G();st=D(F(),1);L();we();Ze()});var wi={};zt(wi,{buy:()=>Mn});async function qn(e){let t=await it({message:`What's next for ${Me.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(ce(t)||t==="done"){c();return}if(c(),t==="connect"){let{connect:i}=await Promise.resolve().then(()=>(On(),wo));await i(e,void 0,{})}else if(t==="email"){let i=await Pe({message:`Mailbox name for ${Me.default.cyan(e)}`,placeholder:"e.g. hey, hello, contact"});if(ce(i)||!i){c();return}c();let{email:s}=await Promise.resolve().then(()=>(Tn(),Ro));await s("create",void 0,{domain:e,slug:i})}else if(t==="dns"){let{dns:i}=await Promise.resolve().then(()=>(Dn(),Ao));await i(e)}else if(t==="status"){let{status:i}=await Promise.resolve().then(()=>(Un(),To));await i(e,{})}}async function $c(e,t){Y(e,t);let i;if(t.preChecked)i={available:!0,...t.preChecked};else{let m=C(!t.json);m.start(`Checking ${v.domain(e)}`);let h=await _(`/api/domains/search?q=${encodeURIComponent(e)}`);i=await h.json(),h.ok||(m.stop("Search failed"),u(i.error,{hint:i.hint,status:h.status,json:t.json,fields:t.fields})),i.available||(m.stop(`${w.error} ${v.domain(e)} is not available`),u(`${e} is not available`,{code:"not_available",json:t.json,fields:t.fields})),m.stop(`${w.success} ${v.domain(e)} ${w.dot} available ${w.dot} ${v.price(i.price)}/yr`)}if(t.dryRun)return K("buy",{domain:e,available:!0,price:i.price,currency:i.currency||"USD"},t.json,t.fields);if(!Ft(t)){let m=await Xe({message:`Purchase ${Me.default.bold(e)} for ${v.price(i.price)}/yr?`});if(!m||typeof m=="symbol"){console.log(` ${Me.default.dim("Cancelled.")}`);return}}let s=C(!t.json);s.start("Purchasing");let n=await _("/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(()=>({}));u(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 h=a.split(`
182
- `);a=h.pop()??"";for(let b of h)if(b.startsWith("event: "))l=b.slice(7).trim();else if(b.startsWith("data: ")){let k=JSON.parse(b.slice(6));l==="checking"?s.message(`Checking ${v.domain(k.domain)}`):l==="payment"?s.message(`Charging ${v.price(k.total)}`):l==="registering"?s.message(`Registering ${v.domain(k.domain)}`):l==="registered"?r=k:l==="error"&&(s.stop("Purchase failed"),u(k.error,{hint:k.hint,fixUrl:k.setup_url,status:n.status,json:t.json,fields:t.fields}))}}let f=r.expires?Me.default.dim(` \xB7 expires ${new Date(r.expires).toLocaleDateString()}`):"";if(s.stop(`${w.success} ${v.domain(r.domain)} is yours!${f}`),t.json){y(r,t.fields);return}Ce?await qn(r.domain):(R("Connect to a service:",`domani connect ${r.domain}`),R("Set up email:",`domani email setup ${r.domain}`),R("Configure DNS:",`domani dns ${r.domain}`),c())}async function kc(e,t){yo(e,t);let i=!!t.json,s=C(!i);s.start(`Checking ${e.length} domains`);let n=await Promise.all(e.map(async g=>{try{let x=await _(`/api/domains/search?q=${encodeURIComponent(g)}`),S=await x.json();return{domain:g,available:x.ok&&S.available,price:S.price}}catch{return{domain:g,available:!1,price:void 0}}})),r=n.filter(g=>g.available),o=n.filter(g=>!g.available);r.length===0&&(s.stop(`${w.error} None of the ${e.length} domains are available`),process.exit(1));let a=r.reduce((g,x)=>g+(x.price||0),0);if(s.stop(`${w.success} ${r.length}/${e.length} available ${w.dot} ${v.price(a.toFixed(2))} total`),o.length>0)for(let g of o)console.log(` ${w.error} ${v.domain(g.domain)} ${Me.default.dim("not available")}`);if(t.dryRun)return K("buy_bulk",{domains:r.map(g=>({domain:g.domain,price:g.price})),unavailable:o.map(g=>g.domain),total_price:parseFloat(a.toFixed(2))},t.json,t.fields);if(!Ft(t)){let g=await Xe({message:`Purchase ${Me.default.bold(String(r.length))} domain${r.length>1?"s":""} for ${v.price(a.toFixed(2))}?`});if(!g||typeof g=="symbol"){console.log(` ${Me.default.dim("Cancelled.")}`);return}}c();let l=r.map(g=>({cells:[v.domain(g.domain),g.price?`${v.price(g.price.toFixed(2))}/yr`:""],status:"pending"})),f=Lt(["Domain","Price"],l,[30,12],!i);f.start();let h=await(await _("/api/domains/buy",{method:"POST",body:JSON.stringify({domains:r.map(g=>g.domain)})})).json(),b=new Set((h.results||[]).map(g=>g.domain));for(let g=0;g<r.length;g++){let x=r[g].domain.toLowerCase().trim();b.has(x)?f.markDone(g,w.success):f.markDone(g,w.error)}if(f.stop(),i){y(h,t.fields);return}c();let k=h.summary?.succeeded??0,$=h.summary?.failed??0;if(k>0&&console.log(` ${w.success} ${Me.default.green(`${k} domain${k>1?"s":""} registered`)}`),$>0){console.log(` ${w.error} ${Me.default.red(`${$} failed`)}`);for(let g of h.errors||[])console.log(` ${Me.default.dim("\u2500")} ${v.domain(g.domain)}: ${Me.default.dim(g.error)}${g.hint?` ${Me.default.dim(`(${g.hint})`)}`:""}`)}if(c(),k>0&&Ce){let g=(h.results||[]).filter(x=>x.success).map(x=>x.domain);if(g.length===1)await qn(g[0]);else{let x=await it({message:"Set up one of your new domains?",options:[...g.map(S=>({value:S,label:Me.default.cyan(S)})),{value:"done",label:"Done"}]});!ce(x)&&x!=="done"?(c(),await qn(x)):c()}}else k>0&&(R("Connect to a service:","domani connect <domain>"),R("Set up email:","domani email setup <domain>"),c())}async function Mn(e,t){let i=e.filter(Boolean);if(i.length===0){Ce||u("Missing required argument: domain(s)",{hint:"Usage: domani buy <domain> [domain2 ...]",code:"missing_argument",json:t.json});let s=await Pe({message:"Domain to purchase",placeholder:"e.g. myapp.dev (space-separated for multiple)"});(ce(s)||!s)&&process.exit(0),i=s.split(/\s+/).filter(Boolean)}return i.length===1?$c(i[0],t):kc(i,t)}var Me,ri=Te(()=>{"use strict";G();Ue();Me=D(F(),1);L();we()});var or=D(rr(),1),{program:Lu,createCommand:Vu,createArgument:Wu,createOption:Hu,CommanderError:Ju,InvalidArgumentError:Bu,InvalidOptionArgumentError:Gu,Command:ar,Argument:Ku,Option:zu,Help:Yu}=or.default;var mt=D(F(),1);yt();xn();L();ci();yt();var lt=D(F(),1);L();var kd=new Set(["cli","mcp","plugin","skill","api"]);function _d(e){let t=e.scopes?.split(",").map(o=>o.trim()).filter(Boolean),i=e.mailboxes?.split(",").map(o=>o.trim().toLowerCase()).filter(Boolean),s=!!(t?.length||i?.length||e.label||e.expiresIn),n=e.surface||"cli";if(!kd.has(n))throw new RangeError("--surface must be one of: cli, mcp, plugin, skill, api");let r=e.expiresIn===void 0?void 0:Number(e.expiresIn);if(r!==void 0&&(!Number.isInteger(r)||r<3600||r>31536e3))throw new RangeError("--expires-in must be an integer between 3600 and 31536000 seconds");return{delegated:s,body:{...t?.length?{scopes:t}:{},...i?.length?{mailboxes:i}:{},...e.label?{label:e.label}:{},...r!==void 0?{expires_in:r}:{},surface:n,intent:"programmatic_access"}}}async function co(e){let t=We(),i=C(!e.json),s;try{s=_d(e)}catch(k){u(k instanceof Error?k.message:"Invalid login options",{code:"invalid_expires_in",json:e.json})}let{body:n,delegated:r}=s,o=gt(),a=He();if(a&&!r){i.start("Checking session");try{let k=await fetch(`${t}/api/me`,{headers:{Authorization:`Bearer ${a}`}});if(k.ok){let $=await k.json();i.stop(`Already logged in as ${lt.default.bold($.email)}`),e.json&&y({status:"already_logged_in",email:$.email});return}}catch{}i.stop("Session expired, re-authenticating"),c()}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 k=await l.json();u(k.error||k.message||`Server error (${l.status})`,{hint:k.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:f,auth_url:m,expires_in:h}=await l.json();if(i.stop("Auth code received"),e.json){y({status:"awaiting_approval",code:f,auth_url:m,expires_in:h});return}c(),console.log(` ${lt.default.dim("Verification code:")} ${lt.default.bold(lt.default.cyan(f))}`),e.open!==!1?(console.log(` ${lt.default.dim("Opening browser")} ${w.arrow} ${v.url(m)}`),qe(m)):console.log(` ${lt.default.dim("Open this URL to approve:")} ${v.url(m)}`),c(),i.start("Waiting for approval");let b=120;for(let k=0;k<b;k++){await new Promise(x=>setTimeout(x,5e3));let $=await fetch(`${t}/api/auth/cli/poll?code=${f}`);!$.ok&&$.status!==202&&(i.stop("Login failed"),u(`Server error (${$.status})`,{code:"login_failed"}));let g=await $.json();if(g.status==="complete"){ei({...gt(),token:g.token,email:g.email,api_url:t}),i.stop(`Logged in as ${lt.default.bold(g.email)}`),c(),console.log(` ${lt.default.bold("Get one real result:")}`),R("1. Create your free inbox:","domani email create YOUR_HANDLE@domani.run"),R("2. Connect your webhook:","domani email webhook YOUR_HANDLE@domani.run --url https://YOUR_AGENT/webhook"),R("3. Prove delivery:","domani email webhook-test YOUR_HANDLE@domani.run"),console.log(` ${lt.default.dim("A custom domain can wait until this loop works.")}`),c();return}g.error&&(i.stop("Login failed"),u(g.error||g.message,{hint:g.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"})}yt();var jn=D(F(),1);L();async function uo(e){let t=gt();if(!t.token){e.json?y({status:"not_logged_in"}):console.log(` ${jn.default.dim("Not logged in.")}`);return}let{api_url:i}=t;vr(),i&&ei({api_url:i}),e.json?y({status:"logged_out",email:t.email||null}):console.log(` ${w.success} Logged out${t.email?` ${jn.default.dim(`(${t.email})`)}`:""}`)}G();var yi=D(F(),1);L();async function fo(e){let[t,i]=await Promise.all([_("/api/me"),_("/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){y({...s,activation:n},e.fields);return}if(j("Account"),d("Email",yi.default.bold(s.email)),d("Payment",s.has_payment_method?`${w.success} ${yi.default.green("active")}`:`${w.error} ${yi.default.dim("none")}`),d("Domains",String(s.domain_count)),d("API tokens",String(s.token_count)),d("Referral code",s.referral_code||yi.default.dim("-")),d("Created",new Date(s.created_at).toLocaleDateString()),n){d("Activation",n.status);let r=n.recommended_actions?.[0];r&&d("Next action",r.label)}c()}G();Ue();var N=D(F(),1);L();we();var Ge=10,oi=200,cs=["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"],us=null;async function Eo(){if(us)return us;try{let e=await ve("/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(cs),n=new Set(i),r=[...cs.filter(o=>n.has(o)),...i.filter(o=>!s.has(o))];return us=r,r}}}catch{}return us=cs,cs}async function _c(e,t,i,s,n){let r=[],o=[],a=Ge,l=0,f=!0,m=0,h=0,b=!1,k=!1,$=null,g="",x=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],S=0,O=setInterval(()=>{k||!f||(S=(S+1)%x.length,E())},80);function A(){m>0&&(process.stdout.write(`\x1B[${m}A\x1B[0J`),m=0)}function W(){if(f)return[];let M=Ge+h*Ge;return r.length>a||s&&M<n.length?["more","new","skip"]:["new","skip"]}function H(){return r.slice(0,a)}function se(){let M=W();return Math.max(0,H().length+M.length-1)}let P=6;function E(){A();let M=[],Z=H(),ie=!f&&Z.length===0&&o.length>0,z=ie?o.slice(0,P):Z,Ae=z.reduce((ue,de)=>Math.max(ue,de.domain.length),0),ze=W();for(let ue=0;ue<z.length;ue++){let de=z[ue];if(ie)M.push(`${N.default.dim("\u2502")} ${N.default.dim("\u2715")} ${N.default.dim(de.domain.padEnd(Ae))} ${N.default.dim("taken")}`);else{let xe=ue===l,ft=xe?N.default.green("\u25CF"):N.default.dim("\u25CB"),ne=de.domain.padEnd(Ae),rt=xe?N.default.bold(N.default.cyan(ne)):ne,xt=de.for_sale?N.default.cyan(`$${de.for_sale.price} (for sale)`):N.default.dim(`$${de.price}/yr`);M.push(`${N.default.dim("\u2502")} ${ft} ${rt} ${xt}`)}}if(ie&&o.length>P&&M.push(`${N.default.dim("\u2502")} ${N.default.dim(`\u2026 and ${o.length-P} more taken`)}`),f){let ue=g?N.default.dim(`checking ${g}\u2026`):N.default.dim("searching\u2026");M.push(`${N.default.dim("\u2502")} ${N.default.cyan(x[S])} ${ue}`)}else{let ue=Ge+h*Ge;s&&ue>=n.length&&M.push(`${N.default.dim("\u2502")} ${N.default.dim(`All ${Math.min(ue,n.length)} TLDs searched`)}`);for(let xe=0;xe<ze.length;xe++){let rt=H().length+xe===l?N.default.green("\u25CF"):N.default.dim("\u25CB"),xt=ze[xe]==="more"?N.default.dim("More \u2192"):ze[xe]==="new"?N.default.dim("New search \u2192"):N.default.dim("Skip");M.push(`${N.default.dim("\u2502")} ${rt} ${xt}`)}M.push(N.default.dim("\u2514"))}process.stdout.write(M.join(`
177
+ `}}}}).prompt()});function Nl(e){return!!(e.json||!Re)}function x(e,t=50){console.log(),console.log(` ${J.default.bold(e)}`),console.log(` ${J.default.dim("\u2500".repeat(t))}`)}function l(e,t,i=2){let n=" ".repeat(i);console.log(`${n}${J.default.dim(e.padEnd(16))} ${t}`)}function c(){console.log()}function ve(e){console.log(` ${J.default.dim(e)}`)}function A(e,t){console.log(` ${J.default.dim(e)} ${J.default.cyan(t)}`)}function $o(e){return e.split(/(https?:\/\/[^\s]+)/g).map(i=>/^https?:\/\//.test(i)?`\x1B]8;;${i}\x1B\\${J.default.underline(J.default.cyan(i))}\x1B]8;;\x1B\\`:J.default.dim(i)).join("")}function Ps(e,t){console.error(` ${w.error} ${J.default.red(e)}`),t&&console.error(` ${$o(t)}`)}function C(e=!0){return e?ji():Ul}function ko(e){return e.replace(ql,"")}function yn(e,t){let i=ko(e).length,n=Math.max(0,t-i);return e+" ".repeat(n)}function B(e,t,i){let n=i||e.map((o,a)=>{let d=t.reduce((f,m)=>Math.max(f,ko(m[a]||"").length),0);return Math.max(o.length,d)+2}),s=e.map((o,a)=>J.default.dim(o.padEnd(n[a]))).join(" "),r=n.map(o=>J.default.dim("\u2500".repeat(o))).join(" ");console.log(` ${s}`),console.log(` ${r}`);for(let o of t){let a=o.map((d,f)=>yn(d,n[f])).join(" ");console.log(` ${a}`)}}function Ml(e){return e.replace(/[A-Z]/g,t=>`_${t.toLowerCase()}`)}function Es(e){if(Array.isArray(e))return e.map(Es);if(e&&typeof e=="object"&&!(e instanceof Date)){let t={};for(let[i,n]of Object.entries(e))t[Ml(i)]=Es(n);return t}return e}function v(e,t){let i=Es(e);if(!t){console.log(JSON.stringify(i,null,2));return}let n=t.split(",").map(s=>s.trim()).filter(Boolean);if(Array.isArray(i)){let s=i.map(r=>bo(r,n));console.log(JSON.stringify(s,null,2))}else console.log(JSON.stringify(i&&typeof i=="object"?bo(i,n):i,null,2))}function bo(e,t){let i={};for(let n of t)n in e&&(i[n]=e[n]);if(Object.keys(i).length===0){for(let[n,s]of Object.entries(e))if(Array.isArray(s)&&s.length>0&&typeof s[0]=="object"){let r=s.map(o=>{let a={};for(let d of t)d in o&&(a[d]=o[d]);return a});Object.keys(r[0]).length>0&&(i[n]=r)}}return i}function $t(e){return!!(e.yes||Nl(e))}function K(e,t,i,n){if(i){v({dry_run:!0,action:e,...t},n);return}console.log(),console.log(` ${J.default.yellow("\u25B8 DRY RUN")} ${J.default.dim("- no changes made")}`),console.log(` ${J.default.dim("Action:")} ${J.default.bold(e)}`);for(let[s,r]of Object.entries(t))r!=null&&(Array.isArray(r)?console.log(` ${J.default.dim(s+":")} ${r.map(String).join(", ")}`):console.log(typeof r=="object"?` ${J.default.dim(s+":")} ${JSON.stringify(r)}`:` ${J.default.dim(s+":")} ${String(r)}`));console.log()}function Ll(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})`:""}`,n=t?.code||Ll(i,t?.status,t?.fixUrl),s=t?.fixCommand||Fl[n];if(t?.json){let r={error:i,code:n,...t.data};t.hint&&(r.hint=t.hint),s&&(r.fix_command=s),t.fixUrl&&(r.fix_url=t.fixUrl),v(r,t.fields)}else Ps(i,t?.hint),s?console.error(` ${J.default.dim("Or run:")} ${J.default.cyan(s)}`):t?.fixUrl&&console.error(` ${$o(`Add a payment method at ${t.fixUrl}`)}`);process.exit(1)}function Fe(e){let t=process.platform==="darwin"?"open":process.platform==="win32"?"start":"xdg-open";(0,vo.execFile)(t,[e])}function kt(e){return new Promise(t=>setTimeout(t,e))}function Wt(e,t,i,n=!0){let s=process.stdout.isTTY??!1;if(!n)return{start(){},markDone(){},stop(){}};let r=0,o=null,a=2+t.length;function d(){let y=" "+e.map((g,S)=>J.default.dim(g.padEnd(i[S]))).join(" "),k=" "+i.map(g=>J.default.dim("\u2500".repeat(g))).join(" "),b=[y,k];for(let g of t){let S=g.status==="done"?g.icon??w.success:J.default.cyan(wo[r%wo.length]),j=g.cells.map((O,T)=>yn(O,i[T])).join(" ");b.push(` ${S} ${j}`)}return b}let f=!1,m=()=>process.stdout.write("\x1B[?25h");function p(){let y=d();if(f&&s){process.stdout.write(`\x1B[${a}A`);for(let k of y)process.stdout.write(`\x1B[2K${k}
178
+ `)}else{for(let k of y)console.log(k);f=!0}}return{start(){s&&(process.stdout.write("\x1B[?25l"),process.on("exit",m)),p(),s&&(o=setInterval(()=>{r++,p()},80))},markDone(y,k){t[y].status="done",k!==void 0&&(t[y].icon=k),s&&p()},stop(){o&&clearInterval(o);for(let y of t)y.status="done";p(),s&&(process.stdout.write("\x1B[?25h"),process.removeListener("exit",m))}}}var J,vo,Re,w,$,Ul,ql,Fl,wo,F=Ie(()=>{"use strict";J=U(M(),1),vo=require("child_process");Ne();Re=process.stdout.isTTY??!1;w={success:J.default.green("\u2713"),error:J.default.red("\u2717"),warning:J.default.yellow("!"),info:J.default.cyan("\u25CF"),arrow:J.default.dim("\u2192"),dot:J.default.dim("\xB7"),dash:J.default.dim("\u2500")},$={domain:e=>J.default.bold(J.default.white(e)),price:e=>J.default.green(`$${e}`),label:e=>J.default.dim(e),value:e=>J.default.white(e),dim:e=>J.default.dim(e),bold:e=>J.default.bold(e),success:e=>J.default.green(e),error:e=>J.default.red(e),warn:e=>J.default.yellow(e),cyan:e=>J.default.cyan(e),url:e=>`\x1B]8;;${e}\x1B\\${J.default.underline(J.default.cyan(e))}\x1B]8;;\x1B\\`};Ul={start:()=>{},stop:()=>{},message:()=>{}};ql=/\x1b\]8;;[^\x1b]*\x1b\\|\x1b\[[0-9;]*m/g;Fl={auth_required:"domani login",payment_required:"domani card add",contact_required:"domani contact set"};wo=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"]});function _o(e){return typeof e=="string"&&["pro","agent","fleet","scale","mail_solo","mail_team","mail_business"].includes(e)}function xo(e){return _o(e.plan)||Array.isArray(e.workspace_plans)&&e.workspace_plans.some(_o)}async function jo(){if(Ns)return;let e=process.argv.includes("--json")||!ts,t=Je(),i=Be();try{let r=await(await fetch(`${t}/api/me`,{headers:{Authorization:`Bearer ${i}`}})).json();if(xo(r)){Ns=!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)),c(),console.log(` ${je.default.dim("This feature requires a")} ${je.default.bold("paid plan")} ${je.default.dim("(including an active Mailzero workspace plan or legacy Pro subscription).")}`),console.log(` ${je.default.dim("Opening pricing page")} ${w.arrow} ${je.default.cyan("domani.run/pricing")}`),Fe(`${t.replace("http://localhost:3000","https://domani.run")}/pricing`),c();let n=C(!0);n.start("Waiting for upgrade...");for(let s=0;s<120;s++){await new Promise(r=>setTimeout(r,5e3));try{let o=await(await fetch(`${t}/api/me`,{headers:{Authorization:`Bearer ${i}`}})).json();if(xo(o)){Ns=!0,n.stop(`${w.success} Paid plan active! Continuing...`),c();return}}catch{}}n.stop("Timed out"),console.error(` ${je.default.red("\u2717")} No upgrade detected. Visit ${je.default.cyan("domani.run/settings")} to upgrade.`),process.exit(1)}async function So(){if(Ds||Be()){Ds=!0;return}(process.argv.includes("--json")||!ts)&&(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)),c(),console.log(` ${je.default.dim("You're not logged in.")} Starting authentication...`),c();let t=Je(),i=C(!0);i.start("Requesting auth code");let n;try{n=await fetch(`${t}/api/auth/cli`,{method:"POST",headers:{"Content-Type":"application/json"}})}catch{i.stop("Failed"),console.error(` ${je.default.red("\u2717")} Could not reach ${t}. Check your connection.`),process.exit(1)}if(!n.ok){i.stop("Failed");let o=`Server error (${n.status})`;try{let a=await n.json();o=a.error||a.message||o}catch{}console.error(` ${je.default.red("\u2717")} ${o}`),process.exit(1)}let s,r;try{({code:s,auth_url:r}=await n.json())}catch{i.stop("Failed"),console.error(` ${je.default.red("\u2717")} Invalid response from server.`),process.exit(1)}i.stop(`${w.success} Auth code ready`),c(),console.log(` ${je.default.dim("Verification code:")} ${je.default.bold(je.default.cyan(s))}`),console.log(` ${je.default.dim("Opening browser")} ${w.arrow} ${$.url(r)}`),Fe(r),c(),i.start("Waiting for browser approval");for(let o=0;o<120;o++){await new Promise(f=>setTimeout(f,5e3));let a=await fetch(`${t}/api/auth/cli/poll?code=${s}`).catch(()=>null);if(!a||!a.ok&&a.status!==202)continue;let d=await a.json().catch(()=>({}));if(d.status==="complete"){si({...bt(),token:d.token,email:d.email,api_url:t}),Ds=!0,i.stop(`${w.success} Logged in as ${je.default.bold(d.email)}`),c();return}}i.stop("Timed out"),console.error(` ${je.default.red("\u2717")} No approval received. Run ${je.default.cyan("domani login")} to try again.`),process.exit(1)}var je,Ds,Ns,Us=Ie(()=>{"use strict";je=U(M(),1);wt();F();Ds=!1,Ns=!1});function Io(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 _(e,t={},i=!1){let n=Be(),s=`${Je()}${e}`,r=await fetch(s,{...t,headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json","User-Agent":`domani-cli/${Ce}`,...t.headers}});if(!i){let o=await r.clone().text();try{if(JSON.parse(o).code==="UPGRADE_REQUIRED")return await jo(),_(e,t,!0)}catch{}}return Io(r)}async function _e(e,t={}){let i=`${Je()}${e}`,n=Be(),s=await fetch(i,{...t,headers:{"Content-Type":"application/json","User-Agent":`domani-cli/${Ce}`,...n?{Authorization:`Bearer ${n}`}:{},...t.headers}});return Io(s)}var G=Ie(()=>{"use strict";wt();Us()});function Rt(){return{ok:!0}}function _t(e,t,i){return{ok:!1,error:{message:e,code:t,hint:i}}}function To(e){return Hl.test(e)?_t("Input contains control characters","invalid_input","Remove non-printable characters from the input"):Rt()}function Yl(e){return Jl.test(e)?_t("Input contains path traversal","invalid_input","Domain names cannot contain '../' or '..\\'"):Rt()}function Xl(e){return Bl.test(e)?_t("Input contains query string or fragment","invalid_input","Remove '?' or '#' from the domain name"):Rt()}function Zl(e){return Gl.test(e)?_t("Input contains percent-encoded characters","invalid_input","Use plain text, not URL-encoded values (e.g. 'example.com' not 'example%2Ecom')"):Rt()}function Eo(e){if(!e)return _t("Domain name is required","validation_error");if(e.length>Ao)return _t(`Domain name too long (${e.length} chars, max ${Ao})`,"validation_error");for(let t of[To,Yl,Xl,Zl]){let i=t(e);if(!i.ok)return i}return Kl.test(e)?Rt():_t(`Invalid domain name: ${e}`,"validation_error","Domain names can only contain letters, digits, hyphens, and dots")}function Ql(e){if(!e)return _t("TLD is required","validation_error");let t=To(e);return t.ok?zl.test(e)?Rt():_t(`Invalid TLD: ${e}`,"validation_error","TLDs contain only letters (e.g. 'com', '.dev', 'ai')"):t}function ec(e){for(let t of e){let i=Eo(t);if(!i.ok)return i}return Rt()}function tc(e){for(let t of e){let i=Ql(t);if(!i.ok)return i}return Rt()}function Y(e,t){let i=Eo(e);i.ok||u(i.error.message,{code:i.error.code,hint:i.error.hint,json:t?.json,fields:t?.fields})}function Po(e,t){let i=ec(e);i.ok||u(i.error.message,{code:i.error.code,hint:i.error.hint,json:t?.json,fields:t?.fields})}function bn(e,t){let i=tc(e);i.ok||u(i.error.message,{code:i.error.code,hint:i.error.hint,json:t?.json,fields:t?.fields})}var Hl,Jl,Bl,Gl,Kl,zl,Ao,$e=Ie(()=>{"use strict";F();Hl=/[\x00-\x08\x0b\x0c\x0e-\x1f]/,Jl=/\.\.[/\\]/,Bl=/[?#]/,Gl=/%[0-9a-fA-F]{2}/,Kl=/^[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?)*\.?$/,zl=/^\.?[a-zA-Z]{2,63}$/,Ao=253});function Ci(e){return Math.round(e*100)/100}function At(e){return e.code==="PRICE_ABOVE_MAX"&&typeof e.price=="number"?e.price:void 0}function Ms(e){return`Nothing was charged. Re-run with --max-price ${e.toFixed(2)} to accept the new price.`}async function Oi(e,t,i,n,s){$t(s)&&u(i.error??`The price is now $${e.toFixed(2)}, above $${t.toFixed(2)}. Nothing was charged.`,{code:"price_above_max",hint:Ms(e),data:{price:e},json:s.json,fields:s.fields});let r=await Ve({message:`The price changed: ${$.price(e.toFixed(2))} instead of ${$.price(t.toFixed(2))}. Nothing was charged. ${n} for ${$.price(e.toFixed(2))}?`});if(!r||typeof r=="symbol"){console.log(` ${Do.default.dim("Cancelled.")}`);return}return e}function Ht(e,t){if(e===void 0)return;let i=Number(e);return(!Number.isFinite(i)||i<=0)&&u(`--max-price must be a positive amount in USD, got "${e}"`,{code:"validation_error",json:t.json,fields:t.fields}),i}var Do,wn=Ie(()=>{"use strict";Ne();Do=U(M(),1);F()});async function ge(){Re||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=C(!0);e.start("Loading your domains");let t=await _("/api/domains"),i=await t.json();t.ok||(e.stop("Failed"),Ps(i.error,i.hint),process.exit(1));let n=i.domains||[];n.length===0&&(e.stop("No domains"),c(),console.log(` ${Fs.default.dim("No domains yet.")} Use: ${Fs.default.cyan("domani buy <domain>")}`),c(),process.exit(0)),e.stop(`${n.length} domain(s)`);let s=await it({message:"Which domain?",options:n.map(r=>({value:r.domain,label:r.domain,hint:r.status!=="active"?r.status:void 0}))});return ae(s)&&process.exit(0),s}var Fs,Ze=Ie(()=>{"use strict";G();Ne();Fs=U(M(),1);F()});var Uo={};Qt(Uo,{connect:()=>Ls});async function Ls(e,t,i){e||(e=await ge()),Y(e,i);let n;if(t&&!i.provider?t.includes(".")?n=t:i.provider=t:n=t,!n&&!i.provider&&!i.list&&i.dryRun)return K("connect",{domain:e,note:"No provider specified. Pass --provider <name> to connect."},i.json,i.fields);if(!n&&!i.provider&&!i.list){let s=C(!i.json);s.start(`Loading providers for ${$.domain(e)}`);let r=await _(`/api/domains/${encodeURIComponent(e)}/connect`),o=await r.json();if(r.ok||(s.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:i.json,fields:i.fields})),s.stop("Providers loaded"),i.json){v(o,i.fields);return}let a=[];for(let g of["hosting","email"]){let S=o.providers?.[g]||[];for(let j of S)a.push({value:`${g}:${j.name}`,label:j.name,hint:g})}a.length===0&&u("No providers available",{code:"not_found",json:i.json,fields:i.fields});let d=await it({message:"Choose a provider",options:a});ae(d)&&process.exit(0);let[f,m]=d.split(":"),y=(o.providers?.[f]||[]).find(g=>g.name===m),k;if(y&&y.methods.length>1){let g=await it({message:"Choose a method",options:y.methods.map(S=>({value:S.name,label:S.name,hint:S.default?"default":void 0}))});ae(g)&&process.exit(0),k=g}let b;if(f==="hosting"&&y?.requires_target){y.notes?.setup&&ve(y.notes.setup);let g=await De({message:"Target hostname or IP"});ae(g)&&process.exit(0),b=g.trim()}return No(e,{target:b,provider:m,method:k,dryRun:i.dryRun,json:!1})}if(i.list){let s=C(!i.json);s.start(`Loading providers for ${$.domain(e)}`);let r=await _(`/api/domains/${encodeURIComponent(e)}/connect`),o=await r.json();if(r.ok||(s.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:i.json,fields:i.fields})),s.stop("Providers loaded"),i.json){v(o,i.fields);return}x(`Providers for ${$.domain(o.domain)}`);for(let a of["hosting","email"]){let d=o.providers?.[a];if(d?.length){c(),console.log(` ${me.default.bold(a.toUpperCase())}`);for(let f of d){let m=f.methods.map(p=>p.default?me.default.green(`${p.name} (default)`):me.default.dim(p.name)).join(me.default.dim(", "));console.log(` ${me.default.cyan(f.name.padEnd(20))} ${m}`)}}}c();return}return No(e,i)}async function No(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 K("connect",{domain:e,...i},t.json,t.fields);let n=C(!t.json);n.start(`Connecting ${$.domain(e)}`);let s=await _(`/api/domains/${encodeURIComponent(e)}/connect`,{method:"POST",body:JSON.stringify(i)}),r=await s.json();s.ok||(n.stop("Connection failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:t.json,fields:t.fields}));let o=r.status==="manual_setup_required";if(n.stop(o?`${w.success} DNS instructions for ${me.default.cyan(r.provider)}`:`${w.success} Connected to ${me.default.cyan(r.provider)}`),t.json){v(r,t.fields);return}if(x(o?`Add these records at your registrar for ${$.domain(r.domain)}`:`Connected ${$.domain(r.domain)}`),l("Provider",me.default.cyan(r.provider)),l("Method",r.method),r.records?.length){let a=[8,22,40];c(),console.log(` ${me.default.bold("DNS Records")}`);let d=["Type","Name","Value"].map((m,p)=>me.default.dim(m.padEnd(a[p]))).join(" "),f=a.map(m=>me.default.dim("\u2500".repeat(m))).join(" ");console.log(` ${d}`),console.log(` ${f}`);for(let m of r.records){let p=m.record,y=m.status!=="already_set";process.stdout.isTTY&&y&&await kt(50);let b=[me.default.yellow(p.type),p.name,me.default.cyan(p.value)+(p.priority?me.default.dim(` pri=${p.priority}`):"")].map((j,O)=>yn(j,a[O])).join(" "),g=m.status==="already_set"?me.default.dim("\u2713"):m.status==="updated"?me.default.yellow("\u21BA"):m.status==="pending"?me.default.yellow("\u2192"):w.success,S=m.status==="already_set"?me.default.dim(" already set"):m.status==="updated"?me.default.dim(" updated"):m.status==="pending"?me.default.dim(" add this"):"";console.log(` ${g} ${b}${S}`)}}c(),r.next_steps?.length?(console.log(` ${me.default.bold("Next steps")}`),r.next_steps.forEach((a,d)=>{console.log(` ${me.default.dim(`${d+1}.`)} ${a}`)})):r.hint&&console.log(` ${me.default.dim(r.hint)}`),r.docs&&console.log(` ${me.default.dim("Docs:")} ${$.url(r.docs)}`),c()}var me,Vs=Ie(()=>{"use strict";G();me=U(M(),1);Ne();F();$e();Ze()});function Jt(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={},n=[["Authorization",e.authorizationEnv],["X-API-Key",e.apiKeyEnv]];for(let[s,r]of n){if(!r)continue;let o=t[r];if(!o)throw new Error(`Environment variable ${r} is not set`);i[s]=o}return Object.keys(i).length>0?i:void 0}function Bt(e){return e?Object.keys(e):[]}var vn=Ie(()=>{"use strict"});var Ko={};Qt(Ko,{contactsQuery:()=>Wo,email:()=>Ii,inboxQuery:()=>Jo,parseRecipients:()=>kn,recipientField:()=>_n});function sc(e){return[R.default.yellow(e.type),e.name,R.default.cyan(e.value)+(e.priority?R.default.dim(` pri=${e.priority}`):"")]}function Hs(e){return nc[e]||e}function kn(e){return e?e.split(",").map(t=>t.trim()).filter(Boolean):[]}function _n(e){if(e.length!==0)return e.length===1?e[0]:e}function rc(e,t){if(e&&e.includes("@")){let[i,n]=e.split("@",2);!t.slug&&i&&(t.slug=i),!t.domain&&n&&(t.domain=n)}}async function Qe(e){return e.domain?(Y(e.domain,e),e.domain):ge()}async function Ii(e,t,i){if(e&&e.includes(".")&&!ic.includes(e))return i.check?Mo(e,!!i.json,i.fields):t?Fo(e,t,!!i.json,i.fields):Bo(e,!!i.json,i.fields);if(rc(t,i),i.body&&!i.text&&(i.text=i.body),i.title&&!i.subject&&(i.subject=i.title),i.from&&i.from.includes("@")){let[n,s]=i.from.split("@",2);!i.slug&&n&&(i.slug=n),!i.domain&&s&&(i.domain=s)}switch(e){case void 0:return qo(i);case"list":return qo(i);case"inbox":return Ec(i);case"folders":return Pc(i);case"archive":case"trash":case"restore":case"read":case"unread":case"star":case"unstar":return Dc(e,i);case"setup":return $c(i);case"status":return kc(i);case"remove":return _c(i);case"create":return xc(i);case"delete":return jc(i);case"send":return Sc(i);case"webhook":return Nc(i);case"webhook-test":return Uc(i);case"forward":return qc(i);case"work":return gc(i);case"triage":return yc(i);case"note":return bc(i);case"notes":return wc(i);case"activity":return vc(i);case"changes":return lc(i);case"search":return cc(t,i);case"threads":return uc(i);case"thread":return mc(t,i);case"label":return fc(i);case"facts":return pc(t,i);case"extract":return hc(t,i);case"coordination":return oc(i);case"presence":return ac(i);case"release-presence":return dc(i);case"escalate":return Cc(i);case"remind":return Oc(i);case"contacts":return Ic(i);case"contact-add":return Rc(i);case"contact-remove":return Ac(i);case"tone":return Tc(i);case"check":return Mo(i.domain||await ge(),!!i.json,i.fields);case"connect":return Fo(i.domain||await ge(),t||void 0,!!i.json,i.fields);default:u(`Unknown action: ${e}`,{hint:"Actions: list, inbox, folders, archive, trash, restore, read, unread, star, unstar, create, delete, send, forward, webhook, webhook-test, work, triage, notes, note, activity, changes, coordination, presence, release-presence, setup, status, check, connect",code:"validation_error",json:i.json,fields:i.fields})}}function Js(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 oc(e){let{mailboxId:t,threadKey:i}=Js(e),n=new URLSearchParams({mailbox_id:t,thread_key:i}),s=await _(`/api/email/collaboration/coordination?${n}`),r=await s.json();if(s.ok||u(r.error||"Could not read coordination",{code:r.code||"api_error",json:e.json,fields:e.fields}),e.json)return v(r,e.fields);x("Conversation Coordination"),l("Conversation",r.conversation_id),l("Reply version",String(r.reply_version)),l("Presence",String(r.presence?.length||0)),l("Compose lease",r.compose_lease?.holder?.label||"none")}async function ac(e){let{mailboxId:t,threadKey:i}=Js(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 n=e.mode||"viewing";["viewing","composing"].includes(n)||u("Mode must be viewing or composing",{code:"validation_error",json:e.json,fields:e.fields});let s=await _("/api/email/collaboration/coordination",{method:"PUT",body:JSON.stringify({mailbox_id:t,thread_key:i,client_id:e.clientId,mode:n,acquire_lease:e.acquireLease!==!1})}),r=await s.json();if(s.ok||u(r.error||"Could not heartbeat presence",{code:r.code||"api_error",json:e.json,fields:e.fields}),e.json)return v(r,e.fields);x("Conversation Presence"),l("Mode",n),l("Reply version",String(r.reply_version)),l("Lease ID",r.compose_lease?.lease_id||"none"),l("Expires",r.compose_lease?.expires_at||r.presence?.find(o=>o.client_id===e.clientId)?.expires_at||"unknown")}async function dc(e){let{mailboxId:t,threadKey:i}=Js(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 n=await _("/api/email/collaboration/coordination",{method:"DELETE",body:JSON.stringify({mailbox_id:t,thread_key:i,client_id:e.clientId,lease_id:e.leaseId})}),s=await n.json();if(n.ok||u(s.error||"Could not release presence",{code:s.code||"api_error",json:e.json,fields:e.fields}),e.json)return v(s,e.fields);x("Conversation Presence"),l("Released",e.clientId),l("Remaining presence",String(s.presence?.length||0))}async function lc(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 n=await _(`/api/email/changes?${i}`),s=await n.json();if(n.ok||u(s.error||s.message,{hint:s.hint,status:n.status,json:e.json,fields:e.fields}),e.json)return v(s,e.fields);if(x("Mailbox Changes"),s.requires_full_sync){l("Full sync","Required"),l("Baseline cursor",s.next_cursor),ve("Take a bounded mailbox snapshot, then call this command again with --cursor to replay concurrent changes.");return}s.changes.length?B(["Sequence","Type","Resource","Created"],s.changes.map(r=>[r.sequence,r.type,`${r.resource_type}:${r.resource_id||"-"}`,r.created_at]),[12,32,40,24]):console.log(` ${R.default.dim("No changes since this cursor.")}`),l("Next cursor",s.next_cursor),s.has_more&&ve("More changes are available; call again with the next cursor.")}function $n(e){return(e||"").split(",").map(t=>t.trim()).filter(Boolean)}async function cc(e,t){let i=(t.query||(e&&!e.includes("@")?e:void 0)||"").trim();i||u("Query required",{hint:'Usage: domani email search "the invoice from tucows" [--from hi@myapp.dev] [--mode hybrid|semantic|keyword] [--limit 10] [--label billing]',code:"validation_error",json:t.json,fields:t.fields});let n=new URLSearchParams({q:i});t.mode&&n.set("mode",t.mode),t.limit&&n.set("limit",t.limit),t.slug&&t.domain&&n.set("mailbox",`${t.slug}@${t.domain}`),t.folder&&n.set("folder",t.folder),t.since&&n.set("since",t.since),t.until&&n.set("until",t.until),t.label&&n.set("label",t.label);let s=await _(`/api/emails/search?${n}`),r=await s.json();if(s.ok||u(r.error||r.message,{hint:r.hint,status:s.status,json:t.json,fields:t.fields}),t.json)return v(r,t.fields);if(x(`Search: ${i}`),!r.results.length){console.log(` ${R.default.dim(r.hint||"No mail matches this search.")}`);return}B(["Why","From","Subject","Mailbox","Message"],r.results.map(o=>[o.why,o.message.from.slice(0,28),(o.message.subject||"").slice(0,44),o.message.mailbox.slice(0,28),o.message.id]),[8,30,46,30,28]),ve(`${r.results.length} result${r.results.length===1?"":"s"} in ${r.took_ms} ms, mode ${r.mode}. Open one with: domani email thread <thread_id> --from <mailbox>`)}async function uc(e){let{address:t}=Tt(e,"Usage: domani email threads --from hi@myapp.dev [--folder inbox] [--since <iso>] [--limit 25] [--cursor <cursor>] [--label billing]"),i=new URLSearchParams;e.folder&&i.set("folder",e.folder),e.since&&i.set("since",e.since),e.limit&&i.set("limit",e.limit),e.cursor&&i.set("cursor",e.cursor),e.label&&i.set("label",e.label);let n=i.toString(),s=await _(`/api/emails/${encodeURIComponent(t)}/threads${n?`?${n}`:""}`),r=await s.json();if(s.ok||u(r.error||r.message,{hint:r.hint,status:s.status,json:e.json,fields:e.fields}),e.json)return v(r,e.fields);if(x(`Threads in ${t}`),!r.threads.length){console.log(` ${R.default.dim("No conversations here.")}`);return}B(["Messages","Unread","Subject","With","Last","Thread"],r.threads.map(o=>[String(o.message_count),String(o.unread_count),(o.subject||"").slice(0,40),o.participants.filter(a=>a!==t).join(", ").slice(0,30),o.last_message_at.slice(0,16),o.id]),[9,7,42,32,17,28]),r.next_cursor&&l("Next cursor",r.next_cursor)}async function mc(e,t){let i=t.threadId||(e&&!e.includes("@")?e:void 0),{address:n}=Tt(t,"Usage: domani email thread <thread_id> --from hi@myapp.dev");i||u("Thread ID required",{hint:"Usage: domani email thread <thread_id> --from hi@myapp.dev",code:"validation_error",json:t.json,fields:t.fields});let s=await _(`/api/emails/${encodeURIComponent(n)}/threads/${encodeURIComponent(i)}`),r=await s.json();if(s.ok||u(r.error||r.message,{hint:r.hint,status:s.status,json:t.json,fields:t.fields}),t.json)return v(r,t.fields);x(r.subject||"Conversation"),l("Messages",String(r.message_count)),l("Unread",String(r.unread_count)),l("With",r.participants.join(", "));for(let o of r.messages)console.log(`
179
+ ${R.default.bold(o.direction==="out"?"\u2192":"\u2190")} ${o.from} ${R.default.dim(o.created_at.slice(0,16))}${o.labels?.length?` ${R.default.dim(`[${o.labels.join(", ")}]`)}`:""} ${R.default.dim(o.id)}`),o.text&&console.log(` ${o.text.replace(/\s+/g," ").trim().slice(0,300)}`)}async function fc(e){let{address:t}=Tt(e,"Usage: domani email label --from hi@myapp.dev --message-ids m1,m2 --add billing[,urgent] [--remove old] | --set a,b"),i=$n(e.messageIds),n=$n(e.add),s=$n(e.remove),r=e.set===void 0?void 0:$n(e.set);(!i.length||!n.length&&!s.length&&r===void 0)&&u("Message IDs and labels required",{hint:"Usage: domani email label --from hi@myapp.dev --message-ids m1,m2 --add billing[,urgent] [--remove old] | --set a,b",code:"validation_error",json:e.json,fields:e.fields});let o={message_ids:i,action:"label",idempotency_key:e.idempotencyKey||(0,Ws.randomUUID)()};n.length&&(o.add=n),s.length&&(o.remove=s),r!==void 0&&(o.set=r);let a=await _(`/api/emails/${encodeURIComponent(t)}/messages/actions`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)}),d=await a.json();if(a.ok||u(d.error||d.message,{hint:d.hint,status:a.status,json:e.json,fields:e.fields}),e.json)return v(d,e.fields);let f=d.results||[];x("Labels"),B(["Message","Result"],f.map(m=>[m.message_id,m.ok?m.changed?"updated":"unchanged":m.error?.message||"failed"]),[30,40])}async function pc(e,t){let i=t.messageIds||(e&&!e.includes("@")?e:void 0),{address:n}=Tt(t,"Usage: domani email facts <message_id> --from hi@myapp.dev");i||u("Message ID required",{hint:"Usage: domani email facts <message_id> --from hi@myapp.dev",code:"validation_error",json:t.json,fields:t.fields});let s=await _(`/api/emails/${encodeURIComponent(n)}/messages/${encodeURIComponent(i)}/facts`),r=await s.json();if(s.ok||u(r.error||r.message,{hint:r.hint,status:s.status,json:t.json,fields:t.fields}),t.json)return v(r,t.fields);if(x("Facts"),!r.analysed){l("Analysed","no"),l("Reason",r.reason),ve(r.reason==="not_enabled"?"Enable the mailbox in the assistant: domani assistant set --enable --mailboxes <id>":"The analysis has not happened yet; try again in a minute.");return}l("Analysis",`${r.analysis.id} (${r.analysis.generated_at.slice(0,16)}, ${r.analysis.coverage})`),r.facts.length?B(["Subject","Predicate","Value","Basis"],r.facts.map(o=>[(o.subject||"").slice(0,28),(o.predicate||"").slice(0,28),`${o.value?.value??o.object??""}${o.value?.currency?` ${o.value.currency}`:""}`.slice(0,32),o.basis||""]),[30,30,34,18]):console.log(` ${R.default.dim("No claim recorded.")}`);for(let o of r.commitments)l("Promised",`${o.who}: ${o.what}`);for(let o of r.expectations)l("Awaited",`${o.who}: ${o.what}`)}async function hc(e,t){let i=t.messageIds||(e&&!e.includes("@")?e:void 0),n=`Usage: domani email extract <message_id> --from hi@myapp.dev --schema '{"type":"object","properties":{"total":{"type":"number"}}}' [--instructions "amounts in EUR"] (or --schema @fields.json)`,{address:s}=Tt(t,n);(!i||!t.schema)&&u("Message ID and --schema required",{hint:n,code:"validation_error",json:t.json,fields:t.fields});let r;try{let d=t.schema.startsWith("@")?(0,Lo.readFileSync)(t.schema.slice(1),"utf8"):t.schema;r=JSON.parse(d)}catch(d){u("Schema must be JSON (inline or @file)",{hint:d instanceof Error?d.message:String(d),code:"validation_error",json:t.json,fields:t.fields})}let o=await _(`/api/emails/${encodeURIComponent(s)}/messages/${encodeURIComponent(i)}/extract`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({schema:r,...t.instructions?{instructions:t.instructions}:{}})}),a=await o.json();if(o.ok||u(a.error||a.message,{hint:a.hint,status:o.status,json:t.json,fields:t.fields}),t.json)return v(a,t.fields);x("Extraction"),l("Confidence",String(a.confidence)),l("Cached",a.cached?"yes":"no"),l("Model",a.model);for(let[d,f]of Object.entries(a.data))l(d,f===null?R.default.dim("null"):typeof f=="object"?JSON.stringify(f):String(f));for(let d of a.evidence_quotes)console.log(` ${R.default.dim(`"${d.slice(0,120)}"`)}`)}async function gc(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 n=await _(`/api/email/work-queue?${i}`),s=await n.json();if(n.ok||u(s.error||s.message,{hint:s.hint,status:n.status,json:e.json,fields:e.fields}),e.json)return v(s,e.fields);if(x("Shared Inbox Work"),!s.items.length)return console.log(` ${R.default.dim("No conversations match this queue.")}`);B(["Thread","Status","Assignee","Subject"],s.items.map(r=>[r.thread_key,r.status,r.assignee?.label||"Unassigned",r.subject||"(no subject)"]),[28,10,28,48]),s.partial&&ve("This is a bounded snapshot. Increase --limit or use the API scan_limit when you need a wider queue.")}async function yc(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 _("/api/email/collaboration",{method:"PATCH",body:JSON.stringify({mailbox_id:e.mailboxIds.split(",")[0],thread_key:e.threadKey,thread_aliases:e.threadAliases?.split(",").map(s=>s.trim()).filter(Boolean),status:e.status,assignee:t,version:e.ifVersion?Number.parseInt(e.ifVersion,10):void 0})}),n=await i.json();if(i.ok||u(n.error||n.message,{hint:n.hint,status:i.status,json:e.json,fields:e.fields}),e.json)return v(n,e.fields);x("Conversation Updated"),l("Status",n.status),l("Assignee",n.assignee?.label||"Unassigned"),l("Version",n.version)}async function bc(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 _(`/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 v(i,e.fields);console.log(`${w.success} Private note added`)}async function wc(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 _(`/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 v(i,e.fields);if(x("Private Notes"),!i.notes.length)return console.log(` ${R.default.dim("No private notes yet.")}`);B(["Author","Created","Note"],i.notes.map(n=>[n.author.label,n.created_at,n.body]),[28,24,64])}async function vc(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 _(`/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 v(i,e.fields);if(x("Conversation Activity"),!i.activity.length)return console.log(` ${R.default.dim("No activity yet.")}`);B(["Type","Actor","Created"],i.activity.map(n=>[n.type,n.actor.label,n.created_at]),[36,32,24])}async function $c(e){let t=await Qe(e);if(e.dryRun)return K("email_setup",{domain:t},e.json,e.fields);let i=C(!e.json);i.start(`Setting up email on ${$.domain(t)}`);let n=await _(`/api/domains/${encodeURIComponent(t)}/email/setup`,{method:"POST"}),s=await n.json();if(n.ok||(i.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:n.status,json:e.json,fields:e.fields})),i.stop(`${w.success} Email ${s.status==="already_configured"?"already configured":"configured"}`),e.json){v(s,e.fields);return}if(s.records?.length){c(),x(`Email DNS Records ${$.domain(t)}`);let r=s.records.map(o=>[R.default.yellow(o.type),o.name,o.value.length>40?o.value.slice(0,40)+"...":o.value,o.status==="verified"||o.status==="created"?R.default.green(o.status):R.default.yellow(o.status)]);B(["Type","Name","Value","Status"],r,[8,28,44,12])}c(),s.hint&&ve(s.hint),A("Check status:",`domani email status --domain ${t}`),c()}async function kc(e){let t=await Qe(e),i=C(!e.json);i.start(`Checking email status for ${$.domain(t)}`);let n=await _(`/api/domains/${encodeURIComponent(t)}/email/status`),s=await n.json();if(n.ok||(i.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:n.status,json:e.json,fields:e.fields})),i.stop(`${w.success} Status loaded`),e.json){v(s,e.fields);return}if(x(`Email ${$.domain(t)}`),l("Enabled",s.enabled?R.default.green("yes"):R.default.dim("no")),s.enabled&&(l("Verified",s.verified?R.default.green("yes"):R.default.yellow("pending")),l("Mailboxes",String(s.mailbox_count))),c(),!s.enabled)A("Set up email:",`domani email setup --domain ${t}`),c();else if(!s.verified&&s.records?.length){console.log(` ${R.default.yellow("!")} Add these DNS records to verify:`);for(let r of s.records)console.log(` ${R.default.yellow(r.type)} ${r.name} ${R.default.dim("\u2192")} ${r.value.length>50?r.value.slice(0,50)+"...":r.value}`);c()}}async function _c(e){let t=await Qe(e);if(e.dryRun)return K("email_remove",{domain:t},e.json,e.fields);let i=C(!e.json);i.start(`Removing email from ${$.domain(t)}`);let n=await _(`/api/domains/${encodeURIComponent(t)}/email/setup`,{method:"DELETE"}),s=await n.json();if(n.ok||(i.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:n.status,json:e.json,fields:e.fields})),i.stop(`${w.success} Email disabled`),e.json){v(s,e.fields);return}s.mailboxes_deleted>0&&console.log(` ${R.default.dim(`${s.mailboxes_deleted} mailbox(es) deleted.`)}`),c()}async function qo(e){let t=C(!e.json);t.start("Loading mailboxes");let i=e.domain?`?domain=${encodeURIComponent(e.domain)}`:"",n=await _(`/api/emails${i}`),s=await n.json();n.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:n.status,json:e.json,fields:e.fields}));let r=s.mailboxes||[];if(t.stop(`${w.success} ${r.length} mailbox(es)`),e.json){v(s,e.fields);return}if(r.length===0){c(),console.log(` ${R.default.dim("No mailboxes.")}`),c(),A("Create one:","domani email create hello@example.com"),c();return}c(),x("Mailboxes");let o=r.map(a=>[R.default.cyan(a.address),String(a.message_count),a.webhook_url?$.url(a.webhook_url):R.default.dim("-"),R.default.dim(new Date(a.created_at).toLocaleDateString())]);B(["Address","Messages","Webhook","Created"],o,[32,10,36,14]),c()}async function xc(e){let t=await Qe(e);if(e.dryRun)return K("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 f=await De({message:`Email handle for @${t}:`,placeholder:"hello"});ae(f)&&process.exit(0),i=f}i||u("Slug required",{hint:`Usage: domani email create hello@${t}`,code:"validation_error",json:e.json,fields:e.fields});let n=`${i}@${t}`,s=C(!e.json);s.start("Creating mailbox");let r=await _("/api/emails",{method:"POST",body:JSON.stringify({address:n,workspace_id:e.workspace})}),o=await r.json();if(r.status===202&&!e.json){s.stop("");let f=o.txt_record,m=o.email_records||[],p=[{type:"TXT",name:f?.name||"@",value:f?.value||"",note:"ownership proof"},...m];c(),console.log(" Add these records at your DNS provider:"),c();for(let j of p){let O=j.priority!==void 0?` ${R.default.dim(`priority: ${j.priority}`)}`:"",T=j.note?` ${R.default.dim(`(${j.note})`)}`:"";console.log(` ${R.default.yellow(j.type)} ${R.default.bold(j.name)}${O}${T}`),console.log(` ${R.default.dim("\u2192")} ${R.default.cyan(j.value)}`),c()}ve("DNS propagation typically takes 5\u201330 minutes. Checking automatically..."),c();let y=p.map(j=>({cells:[R.default.yellow(j.type),j.name,j.note?R.default.dim(`(${j.note})`):""],status:"pending"})),k=Wt(["Type","Name",""],y,[6,24,16]);k.start();let b=0;for(;r.status===202&&b<60;)await kt(15e3),b++,r=await _("/api/emails",{method:"POST",body:JSON.stringify({address:n,workspace_id:e.workspace})}),o=await r.json(),r.status!==202&&!r.ok&&(k.stop(),u(o.error||o.message,{hint:o.hint,status:r.status,json:e.json,fields:e.fields}));r.status===202&&(k.stop(),u("TXT record not detected after 15 minutes.",{hint:`Check the record is set, then retry: domani email create ${n}`,code:"timeout",json:e.json,fields:e.fields})),k.markDone(0);let g=j=>`${j.type}:${j.name}`,S=new Map;p.slice(1).forEach((j,O)=>S.set(g(j),O+1));for(let j=0;j<60;j++){await kt(15e3);let O=await _(`/api/domains/${encodeURIComponent(t)}/email/status`),T=await O.json();if(O.ok&&T.records){for(let W of T.records)if(W.status==="verified"||W.status==="created"){let H=S.get(g(W));H!==void 0&&k.markDone(H)}}if(O.ok&&T.verified)break}k.stop(),c()}if(r.ok||(s.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:e.json,fields:e.fields})),s.stop(`${w.success} ${R.default.cyan(o.address)} created`),e.json){v(o,e.fields);return}let a=await _(`/api/domains/${encodeURIComponent(t)}/email/status`),d=await a.json();c(),a.ok&&d.verified?(A("Read inbox:",`domani email inbox ${o.address}`),A("Web inbox:",`${bi}/inbox?address=${encodeURIComponent(o.address)}`)):(A("Check propagation:",`domani email status --domain ${t}`),A("Web inbox:",`${bi}/inbox?address=${encodeURIComponent(o.address)}`)),c()}async function jc(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 K("email_delete_mailbox",{domain:t,address:`${e.slug}@${t}`},e.json,e.fields);let i=C(!e.json);i.start(`Deleting ${e.slug}@${t}`);let n=encodeURIComponent(`${e.slug}@${t}`),s=await _(`/api/emails/${n}`,{method:"DELETE",body:JSON.stringify({confirm:!0})}),r=await s.json();if(s.ok||(i.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:e.json,fields:e.fields})),i.stop(`${w.success} Mailbox deleted`),e.json){v(r,e.fields);return}console.log(` ${R.default.dim(`${r.address} and all messages deleted.`)}`),c()}async function Sc(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 K("email_send",{from:`${e.slug}@${t}`,to:e.to,subject:e.subject},e.json,e.fields);let i=C(!e.json);i.start(`Sending from ${e.slug}@${t}`);let n={to:_n(kn(e.to))},s=_n(kn(e.cc)),r=_n(kn(e.bcc));s&&(n.cc=s),r&&(n.bcc=r),e.subject&&(n.subject=e.subject),e.text&&(n.text=e.text),e.inReplyTo&&(n.in_reply_to=e.inReplyTo),e.references&&(n.references=e.references),e.sendAt&&(n.send_at=e.sendAt);let o=encodeURIComponent(`${e.slug}@${t}`),a=await _(`/api/emails/${o}/send`,{method:"POST",body:JSON.stringify(n)}),d=await a.json();if(!a.ok){i.stop("Failed");let m=d.code==="MONTHLY_LIMIT_EXCEEDED"?`Run ${R.default.cyan("domani upgrade")} to switch to Pro (10,000 emails/month).`:d.hint;u(d.error||d.message,{hint:m,status:a.status,json:e.json,fields:e.fields})}let f=Array.isArray(d.to)?d.to.join(", "):d.to;if(i.stop(d.status==="scheduled"?`${w.success} Scheduled for ${R.default.cyan(e.sendAt||"")} to ${R.default.cyan(f)} ${R.default.dim("(trash the message before then to cancel)")}`:`${w.success} Sent to ${R.default.cyan(f)}`),e.json){v(d,e.fields);return}}function Tt(e,t){return(!e.slug||!e.domain)&&u("Mailbox address required",{hint:t,code:"validation_error",json:e.json,fields:e.fields}),{domain:e.domain,slug:e.slug,address:`${e.slug}@${e.domain}`}}async function Vo(e,t,i,n,s){let r=C(!i.json);r.start(n);let o=await _(e,{method:"POST",body:JSON.stringify(t)}),a=await o.json();o.ok||(r.stop("Failed"),u(a.error||a.message,{hint:a.hint,status:o.status,json:i.json,fields:i.fields})),r.stop(s(a)),i.json&&v(a,i.fields)}async function Cc(e){let t='Usage: domani email escalate hello@example.com --message-id MSG_ID [--reason "refund over $500"] [--clear]',{address:i}=Tt(e,t);e.messageId||u("Message ID required",{hint:t,code:"validation_error",json:e.json,fields:e.fields});let n={};e.reason&&(n.reason=e.reason),e.clear&&(n.clear=!0),await Vo(`/api/emails/${encodeURIComponent(i)}/messages/${encodeURIComponent(e.messageId)}/escalate`,n,e,e.clear?"Clearing escalation":"Flagging for a human",s=>s.needs_human?`${w.success} Flagged for a human ${R.default.dim("(conversation held, email.escalated fired)")}`:`${w.success} Escalation cleared`)}async function Oc(e){let t='Usage: domani email remind hello@example.com --message-id MSG_ID --at 2026-09-03T09:00:00Z [--note "chase the invoice"] [--clear]',{address:i}=Tt(e,t);e.messageId||u("Message ID required",{hint:t,code:"validation_error",json:e.json,fields:e.fields}),!e.at&&!e.clear&&u("Reminder time required",{hint:t,code:"validation_error",json:e.json,fields:e.fields});let n={};e.at&&(n.remind_at=e.at),e.note&&(n.note=e.note),e.clear&&(n.clear=!0),await Vo(`/api/emails/${encodeURIComponent(i)}/messages/${encodeURIComponent(e.messageId)}/remind`,n,e,e.clear?"Clearing reminder":"Setting follow-up reminder",s=>s.remind_at?`${w.success} Reminder set for ${R.default.cyan(String(s.remind_at))} ${R.default.dim("(fires only if still unanswered)")}`:`${w.success} Reminder cleared`)}function Wo(e){let t=new URLSearchParams;e.q&&t.set("q",e.q),e.limit&&t.set("limit",e.limit),e.order&&t.set("order",e.order),e.cursor&&t.set("cursor",e.cursor);let i=t.toString();return i?`?${i}`:""}async function Ic(e){let t=await _(`/api/contacts${Wo(e)}`),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){v(i,e.fields);return}let n=i.contacts||[];if(n.length===0){console.log(R.default.dim("No contacts yet. The address book fills itself as mail flows in and out."));return}for(let s of n){let r=s.name?` ${R.default.dim(s.name)}`:"",o=s.notes?` ${R.default.dim("-")} ${s.notes}`:"";console.log(`${R.default.cyan(s.address)}${r} ${R.default.dim(`(${s.message_count} msg${s.message_count!==1?"s":""}, last ${s.last_direction||"-"})`)}${o}`)}i.next_cursor&&console.log(R.default.dim(`More: --cursor ${i.next_cursor}`))}function Ho(e,t){return e.slug&&e.domain?`${e.slug}@${e.domain}`:(u("Contact address required",{hint:t,code:"validation_error",json:e.json,fields:e.fields}),"")}async function Rc(e){let i=Ho(e,'Usage: domani email contact-add ada@example.com [--name "Ada"] [--notes "prefers short emails"]'),n={address:i};e.name!==void 0&&(n.name=e.name),e.notes!==void 0&&(n.notes=e.notes);let s=await _("/api/contacts",{method:"POST",body:JSON.stringify(n)}),r=await s.json();if(s.ok||u(r.error||r.message,{hint:r.hint,status:s.status,json:e.json,fields:e.fields}),e.json){v(r,e.fields);return}console.log(`${w.success} Contact ${R.default.cyan(i)} saved.`)}async function Ac(e){let i=Ho(e,"Usage: domani email contact-remove ada@example.com"),n=await _(`/api/contacts/${encodeURIComponent(i)}`,{method:"DELETE"}),s=await n.json();if(n.ok||u(s.error||s.message,{hint:s.hint,status:n.status,json:e.json,fields:e.fields}),e.json){v(s,e.fields);return}console.log(s.deleted?`${w.success} Contact ${R.default.cyan(i)} deleted.`:R.default.dim(`No contact ${i}.`))}async function Tc(e){let t='Usage: domani email tone hello@example.com [--set "lowercase, friendly, sign as Ada"] [--clear]',{address:i}=Tt(e,t),n=encodeURIComponent(i);if(e.set===void 0&&!e.clear){let o=await _(`/api/emails/${n}`),a=await o.json();if(o.ok||u(a.error||a.message,{hint:a.hint,status:o.status,json:e.json,fields:e.fields}),e.json){v({address:i,tone_notes:a.tone_notes??null},e.fields);return}console.log(a.tone_notes?a.tone_notes:R.default.dim(`No tone notes on ${i}. Set them with --set.`));return}let s=await _(`/api/emails/${n}`,{method:"PATCH",body:JSON.stringify({tone_notes:e.clear?null:e.set})}),r=await s.json();if(s.ok||u(r.error||r.message,{hint:r.hint,status:s.status,json:e.json,fields:e.fields}),e.json){v(r,e.fields);return}console.log(e.clear?`${w.success} Tone notes cleared on ${R.default.cyan(i)}.`:`${w.success} Tone notes set on ${R.default.cyan(i)}.`)}function Jo(e){let t=new URLSearchParams;e.direction&&t.set("direction",e.direction),e.folder&&t.set("folder",e.folder),e.view&&t.set("view",e.view),e.limit&&t.set("limit",e.limit),e.since&&t.set("since",e.since),e.until&&t.set("until",e.until),e.label&&t.set("label",e.label),e.cursor&&t.set("cursor",e.cursor);let i=t.toString();return i?`?${i}`:""}async function Ec(e){let t=await Qe(e);e.slug||u("Slug required",{hint:"Usage: domani email inbox hello@example.com [--direction in|out] [--limit 20] [--cursor <next_cursor>]",code:"validation_error",json:e.json,fields:e.fields});let i=Jo(e),n=C(!e.json);n.start(`Loading messages for ${e.slug}@${t}`);let s=encodeURIComponent(`${e.slug}@${t}`),r=await _(`/api/emails/${s}/messages${i}`),o=await r.json();r.ok||(n.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:e.json,fields:e.fields}));let a=o.messages||[];if(e.json){n.stop(`${w.success} ${a.length} message(s)`),v(o,e.fields);return}if(a.length===0){n.stop(`${R.default.dim("No messages")}`);return}let d=a.length>1?"s":"";n.stop(`${w.success} ${R.default.cyan(`${e.slug}@${t}`)} ${R.default.dim("\xB7 "+a.length+" message"+d)}`);for(let f of a){let m=f.direction==="in"?R.default.green("in "):R.default.dim("out"),p=f.direction==="in"?f.from:f.to,y=f.subject||"(no subject)",k=R.default.dim(new Date(f.created_at).toLocaleString()),b=y;if(f.text){let g=f.text.replace(/\s+/g," ").trim(),S=g.length>60?g.slice(0,60)+"\u2026":g;b=`${y} ${R.default.dim("- "+S)}`}console.log(` ${m} ${p.padEnd(30)} ${b} ${k}`)}o.next_cursor&&console.log(R.default.dim(`More: --cursor ${o.next_cursor}`))}async function Pc(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}`),n=await _(`/api/emails/${i}/folders`),s=await n.json();if(n.ok||u(s.error||s.message,{hint:s.hint,status:n.status,json:e.json,fields:e.fields}),e.json)return v(s,e.fields);x(`Folders for ${e.slug}@${t}`);for(let r of s.folders||[])l(r.id,`${r.total} total, ${r.unread} unread`);for(let r of s.views||[])l(r.id,`${r.total} total, ${r.unread} unread`)}async function Dc(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 n=(t.messageIds||"").split(",").map(m=>m.trim()).filter(Boolean);n.length||u("Message IDs required",{hint:"Pass --message-ids id1,id2",code:"validation_error",json:t.json,fields:t.fields});let s={message_ids:n,idempotency_key:t.idempotencyKey||(0,Ws.randomUUID)()};if((e==="archive"||e==="trash")&&Object.assign(s,{action:"move",destination:e==="archive"?"archive":"trash"}),e==="restore"&&(s.action="restore"),(e==="read"||e==="unread")&&Object.assign(s,{action:"mark_read",read:e==="read"}),(e==="star"||e==="unstar")&&Object.assign(s,{action:"star",starred:e==="star"}),t.dryRun)return K("email_messages_action",{address:`${t.slug}@${i}`,...s},t.json,t.fields);let r=encodeURIComponent(`${t.slug}@${i}`),o=await _(`/api/emails/${r}/messages/actions`,{method:"POST",body:JSON.stringify(s)}),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 v(a,t.fields);let d=(a.results||[]).filter(m=>m.ok).length,f=(a.results||[]).length-d;console.log(`${w.success} ${d} updated${f?R.default.yellow(`, ${f} failed`):""}`),a.operation_id&&(l("Operation",a.operation_id),l("Idempotency key",a.idempotency_key),a.idempotent_replay&&l("Receipt","replayed (no duplicate mutation)"))}async function Nc(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}`,n=encodeURIComponent(i),s;try{s=Jt(e)}catch(a){u(a instanceof Error?a.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})}let r;if(e.events!==void 0&&(r=e.events.split(",").map(a=>a.trim()).filter(Boolean),r.length===0&&u("--events needs at least one event",{hint:"Example: --events email.received,email.bounced,email.delivered",code:"validation_error",json:e.json,fields:e.fields}),e.url||u("--url is required when changing webhook events",{hint:"Pass the existing webhook URL together with --events.",code:"validation_error",json:e.json,fields:e.fields})),!e.url&&s!==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 K("email_webhook",{address:i,webhook_url:e.url||null,...r!==void 0?{events:r}:{},...s!==void 0?{header_names:Bt(s)}:{}},e.json,e.fields);let o=C(!e.json);if(e.url){o.start(`Setting webhook for ${i}`);let a=await _(`/api/emails/${n}/webhook`,{method:"PUT",body:JSON.stringify({url:e.url,...s!==void 0?{headers:s}:{},...r!==void 0?{events:r}:{}})}),d=await a.json();if(a.ok||(o.stop("Failed"),u(d.error||d.message,{hint:d.hint,status:a.status,json:e.json,fields:e.fields})),o.stop(`${w.success} Webhook set`),e.json){v(d,e.fields);return}x(`Mailbox ${d.address}`),l("Webhook",$.url(d.webhook_url)),l("Events",d.events?.join(", ")||R.default.dim("email.received")),l("Auth headers",d.header_names?.join(", ")||R.default.dim("none")),l("Signing secret",R.default.dim(d.signing_secret)),c()}else{o.start(`Removing webhook for ${i}`);let a=await _(`/api/emails/${n}/webhook`,{method:"DELETE"}),d=await a.json();if(a.ok||(o.stop("Failed"),u(d.error||d.message,{hint:d.hint,status:a.status,json:e.json,fields:e.fields})),o.stop(`${w.success} Webhook removed`),e.json){v(d,e.fields);return}x(`Mailbox ${d.address}`),l("Webhook",R.default.dim("none")),c()}}async function Uc(e){let t=await Qe(e);e.slug||u("Slug required",{hint:"Usage: domani email webhook-test hello@example.com",code:"validation_error",json:e.json,fields:e.fields});let i=`${e.slug}@${t}`;if(e.dryRun)return K("email_webhook_test",{address:i},e.json,e.fields);let n=C(!e.json);n.start(`Testing webhook for ${i}`);let s=await _(`/api/emails/${encodeURIComponent(i)}/webhook/test`,{method:"POST"}),r=await s.json();if((!s.ok||!r.success)&&(n.stop("Failed"),u(r.error||r.message||"Webhook test failed",{hint:r.hint||"Check the endpoint and sender authentication, then retry.",status:s.status,json:e.json,fields:e.fields})),n.stop(`${w.success} Test delivered`),e.json)return v(r,e.fields);x(`Mailbox ${i}`),l("Delivery",R.default.green("successful")),typeof r.status=="number"&&l("Endpoint",`HTTP ${r.status}`),c()}async function qc(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 K("email_forward",{address:`${e.slug}@${t}`,forward_to:e.forwardTo||null},e.json,e.fields);let i=C(!e.json),n=e.forwardTo||null;i.start(`Updating forward for ${e.slug}@${t}`);let s=encodeURIComponent(`${e.slug}@${t}`),r=await _(`/api/emails/${s}`,{method:"PATCH",body:JSON.stringify({forward_to:n})}),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(`${w.success} Forward ${n?"set":"removed"}`),e.json){v(o,e.fields);return}x(`Mailbox ${o.address}`),l("Forward to",o.forward_to?R.default.cyan(o.forward_to):R.default.dim("none")),c()}async function Mo(e,t,i){let n=C(!t);n.start(`Checking email health for ${$.domain(e)}`);let s=await _(`/api/domains/${encodeURIComponent(e)}/email/check`),r=await s.json();if(s.ok||(n.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:t,fields:i})),n.stop("Email health checked"),t){v(r,i);return}if(x(`Email Health ${$.domain(r.domain)}`),r.provider?l("Provider",R.default.cyan(Hs(r.provider))):l("Provider",R.default.dim("unknown")),r.mx.configured?l("MX",`${w.success} ${R.default.green("propagated")} ${R.default.dim(`(${r.mx.records.length} record${r.mx.records.length!==1?"s":""})`)}`):l("MX",`${w.error} ${R.default.red("not configured")}`),r.spf.configured?l("SPF",`${w.success} ${R.default.green(r.spf.value)}`):l("SPF",`${w.error} ${R.default.red("missing")}`),r.dmarc.configured){let o=r.dmarc.value.length>50?r.dmarc.value.slice(0,50)+"...":r.dmarc.value;l("DMARC",`${w.success} ${R.default.green(o)}`)}else l("DMARC",`${w.error} ${R.default.red("missing")}`);r.dkim.configured?l("DKIM",`${w.success} ${R.default.green("found")} ${R.default.dim(`(${r.dkim.selectors.join(", ")})`)}`):l("DKIM",`${w.warning} ${R.default.yellow("not found")}`),c(),r.mx.configured?(!r.spf.configured||!r.dmarc.configured)&&(ve("SPF and DMARC protect against email spoofing. Re-run email setup to add them."),c()):(A("Set up email:",`domani email ${e} google`),c())}async function Fo(e,t,i,n){return t?Go(e,t,i,n):Bo(e,i,n)}async function Bo(e,t,i){let n=C(!t);n.start("Loading email providers");let s=await _(`/api/domains/${encodeURIComponent(e)}/connect`),r=await s.json();s.ok||(n.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:t,fields:i})),n.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 it({message:"Choose an email provider",options:o.map(d=>({value:d.name,label:Hs(d.name)}))});return ae(a)&&process.exit(0),Go(e,a,t,i)}async function Go(e,t,i,n){if(i){let f=await _(`/api/domains/${encodeURIComponent(e)}/connect`,{method:"POST",body:JSON.stringify({target:t})}),m=await f.json();f.ok||u(m.error||m.message,{hint:m.hint,status:f.status,json:i,fields:n}),v(m,n);return}let s=await _(`/api/domains/${encodeURIComponent(e)}/connect?provider=${encodeURIComponent(t)}`);if(!s.ok){let f=await s.json();u(f.error||f.message,{hint:f.hint,status:s.status,json:i,fields:n})}let r=await s.json(),o=r.preview?.records??[],a=r.preview?.provider??t,d=Hs(a);if(x(`Email ${$.domain(e)}`),l("Provider",R.default.cyan(d)),o.length){c(),console.log(` ${R.default.bold("DNS Records")}`);let f=[8,24,40],m=Wt(["Type","Name","Value"],o.map(j=>({cells:sc(j),status:"pending"})),f);m.start();let p=await _(`/api/domains/${encodeURIComponent(e)}/connect`,{method:"POST",body:JSON.stringify({target:t})}),y=await p.json();p.ok||(m.stop(),c(),u(y.error||y.message,{hint:y.hint,status:p.status,json:i,fields:n}));let k=y.records||[];for(let j=0;j<o.length;j++)k.find(T=>T.record.type===o[j].type&&T.record.name===o[j].name&&T.record.value===o[j].value)?.status==="already_set"||await kt(60),m.markDone(j);await kt(80),m.stop();let b=k.filter(j=>j.status==="created"||j.status==="updated").length,g=k.filter(j=>j.status==="already_set").length,S;g===k.length?S=`All ${g} records already set`:g>0?S=`${b} created, ${g} already set`:S=`${b} DNS records set`,c(),console.log(` ${w.success} ${R.default.green(`Email configured - ${S}`)}`)}else{let f=C(!0);f.start("Setting DNS records");let m=await _(`/api/domains/${encodeURIComponent(e)}/connect`,{method:"POST",body:JSON.stringify({target:t})}),p=await m.json();m.ok||(f.stop("Failed"),u(p.error||p.message,{hint:p.hint,status:m.status,json:i,fields:n})),f.stop(`${w.success} Email configured via ${R.default.cyan(d)}`)}c(),A("Verify propagation:",`domani email ${e} --check`),c()}var R,Ws,Lo,ic,nc,Bs=Ie(()=>{"use strict";G();wi();R=U(M(),1);Ne();F();$e();Ze();Ws=require("node:crypto"),Lo=require("node:fs");vn();ic=["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","escalate","remind","contacts","contact-add","contact-remove","tone","search","threads","thread","label","facts","extract"],nc={"google-workspace":"Google Workspace",fastmail:"Fastmail",proton:"Proton Mail"}});var zo={};Qt(zo,{dns:()=>Ks});async function Ks(e,t,i,n,s,r){e||(e=await ge()),Y(e,r);let o=r?.json??!1,a=r?.type||i,d=r?.name||n,f=r?.value||s;if(!t||t==="get"){let m=C(!o);m.start(`Loading DNS for ${$.domain(e)}`);let p=await _(`/api/domains/${encodeURIComponent(e)}/dns`),y=await p.json();if(p.ok||(m.stop("Failed"),u(y.error||y.message,{hint:y.hint,status:p.status,json:o,fields:r?.fields})),m.stop(`${y.records.length} record(s)`),o){v(y,r?.fields);return}if(y.records.length===0){c(),console.log(` ${Ae.default.dim(`No DNS records for ${e}`)}`),c(),A("Auto-configure DNS:",`domani connect ${e}`),c();return}let k=[8,24,40,8];x(`DNS ${$.domain(e)}`,k.reduce((g,S)=>g+S,0)+k.length-1);let b=y.records.map(g=>{let S=g.priority?Ae.default.dim(` pri=${g.priority}`):"";return[Ae.default.yellow(g.type),g.name,Ae.default.cyan(g.value)+S,Ae.default.dim(String(g.ttl))]});B(["Type","Name","Value","TTL"],b,k),c();return}if(t==="set"){if((!a||!d||!f)&&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 K("dns_set",{domain:e,record:{type:a.toUpperCase(),name:d,value:f,ttl:3600}},o,r?.fields);let m=C(!o);m.start(`Setting ${Ae.default.yellow(a.toUpperCase())} record`);let p=await _(`/api/domains/${encodeURIComponent(e)}/dns`),y=await p.json(),b=(p.ok?y.records:[]).filter(j=>!(j.type===a.toUpperCase()&&j.name===d));b.push({type:a.toUpperCase(),name:d,value:f,ttl:3600});let g=await _(`/api/domains/${encodeURIComponent(e)}/dns`,{method:"PUT",body:JSON.stringify({records:b})}),S=await g.json();g.ok||(m.stop("Failed"),u(S.error||S.message,{hint:S.hint,status:g.status,json:o,fields:r?.fields})),m.stop(`${w.success} ${Ae.default.yellow(a.toUpperCase())} ${d} ${w.arrow} ${Ae.default.cyan(f)}`),o?v(S,r?.fields):(c(),A("Check propagation:",`domani status ${e}`),c());return}if(t==="delete"){if((!a||!d)&&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 K("dns_delete",{domain:e,record:{type:a.toUpperCase(),name:d}},o,r?.fields);let m=C(!o);m.start(`Deleting ${Ae.default.yellow(a.toUpperCase())} ${d}`);let p=await _(`/api/domains/${encodeURIComponent(e)}/dns?type=${encodeURIComponent(a.toUpperCase())}&name=${encodeURIComponent(d)}`,{method:"DELETE"}),y=await p.json();p.ok||(m.stop("Failed"),u(y.error||y.message,{hint:y.hint,status:p.status,json:o,fields:r?.fields})),m.stop(`${w.success} Deleted ${Ae.default.yellow(a.toUpperCase())} ${d}`),o?v(y,r?.fields):(c(),A("Check propagation:",`domani status ${e}`),c());return}if(t==="snapshot"){if(r?.dryRun)return K("dns_snapshot",{domain:e},o,r?.fields);let m=C(!o);m.start(`Capturing DNS snapshot for ${$.domain(e)}`);let p=await _(`/api/domains/${encodeURIComponent(e)}/dns/snapshot`,{method:"POST"}),y=await p.json();p.ok||(m.stop("Failed"),u(y.error||y.message,{hint:y.hint,status:p.status,json:o,fields:r?.fields}));let k=y.records?.length??0;if(m.stop(`${w.success} Captured ${k} record(s)`),o){v(y,r?.fields);return}let b=`${e}.dns.json`,g=(0,Gs.resolve)(process.cwd(),b);(0,xn.writeFileSync)(g,JSON.stringify(y,null,2)+`
180
+ `),x("DNS Snapshot"),l("Domain",$.domain(y.domain)),l("Records",String(k)),l("Subdomains",String(y.subdomains?.length??0)),l("Sources",(y.sources||[]).join(", ")||"none"),l("Captured",y.capturedAt||y.captured_at||"now"),l("Saved to",Ae.default.cyan(b)),c(),A("Restore from this snapshot:",`domani dns ${e} restore --file ${b}`),c();return}if(t==="restore"){if(r?.dryRun)return K("dns_restore",{domain:e,source:r?.file||"server_backup"},o,r?.fields);let m=C(!o),p;if(r?.file){let b=(0,Gs.resolve)(process.cwd(),r.file);b.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 g=(0,xn.readFileSync)(b,"utf-8"),S=JSON.parse(g);p=JSON.stringify({snapshot:S}),m.start(`Restoring DNS for ${$.domain(e)} from ${Ae.default.cyan(r.file)}`)}catch(g){u(`Failed to read snapshot file: ${g instanceof Error?g.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 ${$.domain(e)} from server backup`);let y=await _(`/api/domains/${encodeURIComponent(e)}/dns/restore`,{method:"POST",...p?{body:p}:{}}),k=await y.json();if(y.ok||(m.stop("Failed"),u(k.error||k.message,{hint:k.hint,status:y.status,json:o,fields:r?.fields})),m.stop(`${w.success} Restored DNS`),o){v(k,r?.fields);return}if(x("DNS Restored"),l("Domain",$.domain(k.domain)),l("Applied",Ae.default.green(String(k.applied??0))),l("Skipped",Ae.default.dim(String(k.skipped??0))),k.errors?.length>0){l("Errors",Ae.default.red(String(k.errors.length)));for(let b of k.errors)console.log(` ${Ae.default.red("\u2022")} ${b}`)}c(),A("Verify DNS records:",`domani dns ${e}`),c();return}u(`Unknown action: ${t}`,{hint:"Use 'get', 'set', 'delete', 'snapshot', or 'restore'.",code:"validation_error",json:o,fields:r?.fields})}var Ae,xn,Gs,zs=Ie(()=>{"use strict";G();Ae=U(M(),1);F();$e();Ze();xn=require("node:fs"),Gs=require("node:path")});var Yo={};Qt(Yo,{status:()=>Ys});function Mc(e){return[nt.default.yellow(e.type),e.name,nt.default.cyan(e.value)+(e.priority?nt.default.dim(` pri=${e.priority}`):"")]}function Fc(e){if(x(`Status ${$.domain(e.domain)}`),e.expires){let t=new Date(e.expires).toLocaleDateString(),i=e.days_until_expiry,n=i!=null&&i<30?nt.default.red:i!=null&&i<90?nt.default.yellow:nt.default.green;l("Expires",`${t} ${nt.default.dim("(")}${n(`${i} days`)}${nt.default.dim(")")}`)}}async function Ys(e,t){if(e||(e=await ge()),Y(e,t),t.json){let p=await _(`/api/domains/${encodeURIComponent(e)}/status`),y=await p.json();p.ok||u(y.error||y.message,{hint:y.hint,status:p.status,json:t.json,fields:t.fields}),v(y,t.fields);return}let i=C(!0);i.start(`Checking ${$.domain(e)}`);let n;try{n=await _(`/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(!n.ok){i.stop("Failed");try{let p=await n.json();u(p.error||p.message,{hint:p.hint,status:n.status,json:t.json,fields:t.fields})}catch{u(`Server error (${n.status})`,{status:n.status,json:t.json,fields:t.fields})}}let s=n.body;s||(i.stop("Failed"),u("Empty response"));let r=new TextDecoder,o="",a=null,d=[],f=!1,m="";try{for await(let p of s){o+=r.decode(p,{stream:!0});let y=o.split(`
181
+ `);o=y.pop()??"";for(let k of y)if(k.startsWith("event: "))m=k.slice(7);else if(k.startsWith("data: ")){let b=JSON.parse(k.slice(6));if(m==="info"&&(i.stop("Status retrieved"),f=!0,Fc(b)),m==="records")if(d=b,d.length>0){c(),console.log(` ${nt.default.bold("DNS Records")}`);let g=[8,10,34];a=Wt(["Type","Name","Value"],d.map(S=>({cells:Mc(S),status:"pending"})),g),a.start()}else c(),l("DNS",nt.default.dim("no records")),A("Auto-configure DNS:",`domani connect ${e}`);if(m==="propagation"&&a){let{index:g,propagated:S}=b,j=S?w.success:`${w.warning}`;a.markDone(g,j)}m==="done"&&a&&a.stop(),m==="error"&&(f||i.stop("Failed"),a&&a.stop(),u(b.message||"Status check failed"))}}}catch{f||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})}f||i.stop("Done"),c()}var nt,Xs=Ie(()=>{"use strict";G();nt=U(M(),1);F();$e();Ze()});var Ri={};Qt(Ri,{buy:()=>Qs});async function Zs(e){let t=await it({message:`What's next for ${Ue.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(ae(t)||t==="done"){c();return}if(c(),t==="connect"){let{connect:i}=await Promise.resolve().then(()=>(Vs(),Uo));await i(e,void 0,{})}else if(t==="email"){let i=await De({message:`Mailbox name for ${Ue.default.cyan(e)}`,placeholder:"e.g. hey, hello, contact"});if(ae(i)||!i){c();return}c();let{email:n}=await Promise.resolve().then(()=>(Bs(),Ko));await n("create",void 0,{domain:e,slug:i})}else if(t==="dns"){let{dns:i}=await Promise.resolve().then(()=>(zs(),zo));await i(e)}else if(t==="status"){let{status:i}=await Promise.resolve().then(()=>(Xs(),Yo));await i(e,{})}}async function Xo(e,t,i){let n=C(!i.json);n.start("Purchasing");let s=await _("/api/domains/buy",{method:"POST",headers:{Accept:"text/event-stream"},body:JSON.stringify({domain:e,...t!==void 0?{max_price:t}:{}})});if(!s.ok||!s.body){let m=await s.json().catch(()=>({})),p=At(m);if(p!==void 0)return n.stop("Price changed - nothing was charged"),{refused:{price:p,error:m.error}};n.stop("Purchase failed"),u(m.error||m.message,{hint:m.hint,fixUrl:m.setup_url||m.payment_options?.card?.setup_url,status:s.status,json:i.json,fields:i.fields})}let r={},o=new TextDecoder,a="",d="";for await(let m of s.body){a+=o.decode(m,{stream:!0});let p=a.split(`
182
+ `);a=p.pop()??"";for(let y of p)if(y.startsWith("event: "))d=y.slice(7).trim();else if(y.startsWith("data: ")){let k=JSON.parse(y.slice(6));if(d==="checking")n.message(`Checking ${$.domain(k.domain)}`);else if(d==="payment")n.message(`Charging ${$.price(k.total)}`);else if(d==="registering")n.message(`Registering ${$.domain(k.domain)}`);else if(d==="registered")r=k;else if(d==="error"){let b=At(k);if(b!==void 0)return n.stop("Price changed - nothing was charged"),{refused:{price:b,error:k.error}};n.stop("Purchase failed"),u(k.error,{hint:k.hint,fixUrl:k.setup_url,status:s.status,json:i.json,fields:i.fields})}}}let f=r.expires?Ue.default.dim(` \xB7 expires ${new Date(r.expires).toLocaleDateString()}`):"";return n.stop(`${w.success} ${$.domain(r.domain)} is yours!${f}`),{registered:r}}async function Lc(e,t){Y(e,t);let i=Ht(t.maxPrice,t),n;if(t.preChecked)n={available:!0,...t.preChecked};else{let a=C(!t.json);a.start(`Checking ${$.domain(e)}`);let d=await _(`/api/domains/search?q=${encodeURIComponent(e)}`);n=await d.json(),d.ok||(a.stop("Search failed"),u(n.error,{hint:n.hint,status:d.status,json:t.json,fields:t.fields})),n.available||(a.stop(`${w.error} ${$.domain(e)} is not available`),u(`${e} is not available`,{code:"not_available",json:t.json,fields:t.fields})),a.stop(`${w.success} ${$.domain(e)} ${w.dot} available ${w.dot} ${$.price(n.price)}/yr`)}let s=i??(typeof n.price=="number"?Ci(n.price):void 0);if(t.dryRun)return K("buy",{domain:e,available:!0,price:n.price,currency:n.currency||"USD",max_price:s},t.json,t.fields);if(!$t(t)){let a=await Ve({message:`Purchase ${Ue.default.bold(e)} for ${$.price(n.price)}/yr?`});if(!a||typeof a=="symbol"){console.log(` ${Ue.default.dim("Cancelled.")}`);return}}let r=await Xo(e,s,t);for(;"refused"in r;){let a=await Oi(r.refused.price,s??n.price,r.refused,"Buy",t);if(a===void 0)return;s=a,r=await Xo(e,s,t)}let o=r.registered;if(t.json){v(o,t.fields);return}Re?await Zs(o.domain):(A("Connect to a service:",`domani connect ${o.domain}`),A("Set up email:",`domani email setup ${o.domain}`),A("Configure DNS:",`domani dns ${o.domain}`),c())}async function Vc(e,t){Po(e,t);let i=Ht(t.maxPrice,t),n=!!t.json,s=C(!n);s.start(`Checking ${e.length} domains`);let r=await Promise.all(e.map(async b=>{try{let g=await _(`/api/domains/search?q=${encodeURIComponent(b)}`),S=await g.json();return{domain:b,available:g.ok&&S.available,price:S.price}}catch{return{domain:b,available:!1,price:void 0}}})),o=r.filter(b=>b.available),a=r.filter(b=>!b.available);o.length===0&&(s.stop(`${w.error} None of the ${e.length} domains are available`),process.exit(1));let d=o.reduce((b,g)=>b+(g.price||0),0);if(s.stop(`${w.success} ${o.length}/${e.length} available ${w.dot} ${$.price(d.toFixed(2))} total`),a.length>0)for(let b of a)console.log(` ${w.error} ${$.domain(b.domain)} ${Ue.default.dim("not available")}`);let f=i??(o.every(b=>typeof b.price=="number")?Ci(d):void 0);if(t.dryRun)return K("buy_bulk",{domains:o.map(b=>({domain:b.domain,price:b.price})),unavailable:a.map(b=>b.domain),total_price:parseFloat(d.toFixed(2)),max_price:f},t.json,t.fields);if(!$t(t)){let b=await Ve({message:`Purchase ${Ue.default.bold(String(o.length))} domain${o.length>1?"s":""} for ${$.price(d.toFixed(2))}?`});if(!b||typeof b=="symbol"){console.log(` ${Ue.default.dim("Cancelled.")}`);return}}c();let m,p;for(;;){let b=Wt(["Domain","Price"],o.map(j=>({cells:[$.domain(j.domain),j.price?`${$.price(j.price.toFixed(2))}/yr`:""],status:"pending"})),[30,12],!n);b.start(),m=await _("/api/domains/buy",{method:"POST",body:JSON.stringify({domains:o.map(j=>j.domain),...f!==void 0?{max_price:f}:{}})}),p=await m.json();let g=m.ok?void 0:At(p);if(g===void 0){let j=new Set((p.results||[]).map(O=>O.domain));for(let O=0;O<o.length;O++){let T=o[O].domain.toLowerCase().trim();b.markDone(O,j.has(T)?w.success:w.error)}b.stop();break}for(let j=0;j<o.length;j++)b.markDone(j,Ue.default.dim("\xB7"));b.stop(),c();let S=await Oi(g,f??d,p,"Buy",t);if(S===void 0)return;f=S,c()}if(m.ok||u(p.error,{hint:p.hint,fixUrl:p.setup_url,status:m.status,json:t.json,fields:t.fields}),n){v(p,t.fields);return}c();let y=p.summary?.succeeded??0,k=p.summary?.failed??0;if(y>0&&console.log(` ${w.success} ${Ue.default.green(`${y} domain${y>1?"s":""} registered`)}`),k>0){console.log(` ${w.error} ${Ue.default.red(`${k} failed`)}`);for(let b of p.errors||[])console.log(` ${Ue.default.dim("\u2500")} ${$.domain(b.domain)}: ${Ue.default.dim(b.error)}${b.hint?` ${Ue.default.dim(`(${b.hint})`)}`:""}`)}if(c(),y>0&&Re){let b=(p.results||[]).filter(g=>g.success).map(g=>g.domain);if(b.length===1)await Zs(b[0]);else{let g=await it({message:"Set up one of your new domains?",options:[...b.map(S=>({value:S,label:Ue.default.cyan(S)})),{value:"done",label:"Done"}]});!ae(g)&&g!=="done"?(c(),await Zs(g)):c()}}else y>0&&(A("Connect to a service:","domani connect <domain>"),A("Set up email:","domani email setup <domain>"),c())}async function Qs(e,t){let i=e.filter(Boolean);if(i.length===0){Re||u("Missing required argument: domain(s)",{hint:"Usage: domani buy <domain> [domain2 ...]",code:"missing_argument",json:t.json});let n=await De({message:"Domain to purchase",placeholder:"e.g. myapp.dev (space-separated for multiple)"});(ae(n)||!n)&&process.exit(0),i=n.split(/\s+/).filter(Boolean)}return i.length===1?Lc(i[0],t):Vc(i,t)}var Ue,li=Ie(()=>{"use strict";G();Ne();Ue=U(M(),1);F();$e();wn()});var _r=U(kr(),1),{program:dm,createCommand:lm,createArgument:cm,createOption:um,CommanderError:mm,InvalidArgumentError:fm,InvalidOptionArgumentError:pm,Command:xr,Argument:hm,Option:gm,Help:ym}=_r.default;var ht=U(M(),1);wt();Us();F();wi();wt();var dt=U(M(),1);F();var Vl=new Set(["cli","mcp","plugin","skill","api"]);function Wl(e){let t=e.scopes?.split(",").map(o=>o.trim()).filter(Boolean),i=e.mailboxes?.split(",").map(o=>o.trim().toLowerCase()).filter(Boolean),n=!!(t?.length||i?.length||e.label||e.expiresIn),s=e.surface||"cli";if(!Vl.has(s))throw new RangeError("--surface must be one of: cli, mcp, plugin, skill, api");let r=e.expiresIn===void 0?void 0:Number(e.expiresIn);if(r!==void 0&&(!Number.isInteger(r)||r<3600||r>31536e3))throw new RangeError("--expires-in must be an integer between 3600 and 31536000 seconds");return{delegated:n,body:{...t?.length?{scopes:t}:{},...i?.length?{mailboxes:i}:{},...e.label?{label:e.label}:{},...r!==void 0?{expires_in:r}:{},surface:s,intent:"programmatic_access"}}}async function Co(e){let t=Je(),i=C(!e.json),n;try{n=Wl(e)}catch(k){u(k instanceof Error?k.message:"Invalid login options",{code:"invalid_expires_in",json:e.json})}let{body:s,delegated:r}=n,o=bt(),a=Be();if(a&&!r){i.start("Checking session");try{let k=await fetch(`${t}/api/me`,{headers:{Authorization:`Bearer ${a}`}});if(k.ok){let b=await k.json();i.stop(`Already logged in as ${dt.default.bold(b.email)}`),e.json&&v({status:"already_logged_in",email:b.email});return}}catch{}i.stop("Session expired, re-authenticating"),c()}i.start("Requesting auth code");let d=await fetch(`${t}/api/auth/cli`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!d.ok){i.stop("Failed to initiate login");try{let k=await d.json();u(k.error||k.message||`Server error (${d.status})`,{hint:k.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:f,auth_url:m,expires_in:p}=await d.json();if(i.stop("Auth code received"),e.json){v({status:"awaiting_approval",code:f,auth_url:m,expires_in:p});return}c(),console.log(` ${dt.default.dim("Verification code:")} ${dt.default.bold(dt.default.cyan(f))}`),e.open!==!1?(console.log(` ${dt.default.dim("Opening browser")} ${w.arrow} ${$.url(m)}`),Fe(m)):console.log(` ${dt.default.dim("Open this URL to approve:")} ${$.url(m)}`),c(),i.start("Waiting for approval");let y=120;for(let k=0;k<y;k++){await new Promise(S=>setTimeout(S,5e3));let b=await fetch(`${t}/api/auth/cli/poll?code=${f}`);!b.ok&&b.status!==202&&(i.stop("Login failed"),u(`Server error (${b.status})`,{code:"login_failed"}));let g=await b.json();if(g.status==="complete"){si({...bt(),token:g.token,email:g.email,api_url:t}),i.stop(`Logged in as ${dt.default.bold(g.email)}`),c(),console.log(` ${dt.default.bold("Get one real result:")}`),A("1. Create your free inbox:","domani email create YOUR_HANDLE@domani.run"),A("2. Connect your webhook:","domani email webhook YOUR_HANDLE@domani.run --url https://YOUR_AGENT/webhook"),A("3. Prove delivery:","domani email webhook-test YOUR_HANDLE@domani.run"),console.log(` ${dt.default.dim("A custom domain can wait until this loop works.")}`),c();return}g.error&&(i.stop("Login failed"),u(g.error||g.message,{hint:g.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"})}wt();var qs=U(M(),1);F();async function Oo(e){let t=bt();if(!t.token){e.json?v({status:"not_logged_in"}):console.log(` ${qs.default.dim("Not logged in.")}`);return}let{api_url:i}=t;Ur(),i&&si({api_url:i}),e.json?v({status:"logged_out",email:t.email||null}):console.log(` ${w.success} Logged out${t.email?` ${qs.default.dim(`(${t.email})`)}`:""}`)}G();var Si=U(M(),1);F();async function Ro(e){let[t,i]=await Promise.all([_("/api/me"),_("/api/me/activation")]),n=await t.json();t.ok||u(n.error||n.message,{hint:n.hint,status:t.status,json:e.json,fields:e.fields});let s=i.ok?await i.json():null;if(e.json){v({...n,activation:s},e.fields);return}if(x("Account"),l("Email",Si.default.bold(n.email)),l("Payment",n.has_payment_method?`${w.success} ${Si.default.green("active")}`:`${w.error} ${Si.default.dim("none")}`),l("Domains",String(n.domain_count)),l("API tokens",String(n.token_count)),l("Referral code",n.referral_code||Si.default.dim("-")),l("Created",new Date(n.created_at).toLocaleDateString()),s){l("Activation",s.status);let r=s.recommended_actions?.[0];r&&l("Next action",r.label)}c()}G();Ne();var E=U(M(),1);F();$e();function ci(e){return e.tld_kind==="alt_root"}function er(e){return e.reason||`${e.domain} does not resolve in public DNS: its TLD is not in the DNS root zone (IANA). Domani does not offer it.`}function lt(e){return e.registry_status==="premium"||e.registry_status==="reserved"}function mi(e){return e.registry_status==="reserved"?"reserved":e.registry_price!==void 0?`premium $${e.registry_price.toFixed(2)}`:"premium"}function tr(e){if(e.reason)return e.reason;if(e.registry_status==="reserved")return`${e.domain} is reserved by the registry and cannot be registered.`;let t=e.registry_price!==void 0?`: the registry prices it at $${e.registry_price.toFixed(2)}`:" priced by the registry";return`${e.domain} is a premium name${t}. Premium names cannot be bought at the standard price.`}function Gt(e,t){let i=e.findIndex(n=>n.domain===t);return i!==-1&&e.splice(i,1),i}var ze=10,ui=200,jn=["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"],Sn=null;async function Zo(){if(Sn)return Sn;try{let e=await _e("/api/tlds?sort=price&order=asc&limit=1000");if(e.ok){let i=(await e.json()).tlds.map(n=>n.tld);if(i.length>0){let n=new Set(jn),s=new Set(i),r=[...jn.filter(o=>s.has(o)),...i.filter(o=>!n.has(o))];return Sn=r,r}}}catch{}return Sn=jn,jn}async function Wc(e,t,i,n,s){let r=[],o=[],a=ze,d=0,f=!0,m=0,p=0,y=!1,k=!1,b=null,g="",S=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"],j=0,O=setInterval(()=>{k||!f||(j=(j+1)%S.length,N())},80);function T(){m>0&&(process.stdout.write(`\x1B[${m}A\x1B[0J`),m=0)}function W(){if(f)return[];let I=ze+p*ze;return r.length>a||n&&I<s.length?["more","new","skip"]:["new","skip"]}function H(){return r.slice(0,a)}function ee(){let I=W();return Math.max(0,H().length+I.length-1)}let q=6;function N(){T();let I=[],L=H(),te=!f&&L.length===0&&o.length>0,X=te?o.slice(0,q):L,ce=X.reduce((he,ie)=>Math.max(he,ie.domain.length),0),ke=W();for(let he=0;he<X.length;he++){let ie=X[he];if(te)I.push(`${E.default.dim("\u2502")} ${E.default.dim("\u2715")} ${E.default.dim(ie.domain.padEnd(ce))} ${E.default.dim(lt(ie)?mi(ie):"taken")}`);else{let be=he===d,rt=be?E.default.green("\u25CF"):E.default.dim("\u25CB"),St=ie.domain.padEnd(ce),hi=be?E.default.bold(E.default.cyan(St)):St,gi=ie.for_sale?E.default.cyan(`$${ie.for_sale.price} (for sale)`):E.default.dim(`$${ie.price}/yr`);I.push(`${E.default.dim("\u2502")} ${rt} ${hi} ${gi}`)}}if(te&&o.length>q&&I.push(`${E.default.dim("\u2502")} ${E.default.dim(`\u2026 and ${o.length-q} more taken`)}`),f){let he=g?E.default.dim(`checking ${g}\u2026`):E.default.dim("searching\u2026");I.push(`${E.default.dim("\u2502")} ${E.default.cyan(S[j])} ${he}`)}else{let he=ze+p*ze;n&&he>=s.length&&I.push(`${E.default.dim("\u2502")} ${E.default.dim(`All ${Math.min(he,s.length)} TLDs searched`)}`);for(let be=0;be<ke.length;be++){let hi=H().length+be===d?E.default.green("\u25CF"):E.default.dim("\u25CB"),gi=ke[be]==="more"?E.default.dim("More \u2192"):ke[be]==="new"?E.default.dim("New search \u2192"):E.default.dim("Skip");I.push(`${E.default.dim("\u2502")} ${hi} ${gi}`)}I.push(E.default.dim("\u2514"))}process.stdout.write(I.join(`
183
183
  `)+`
184
- `),m=M.length}process.stdout.write(`${N.default.cyan("\u25C6")} Register a domain?
185
- `),process.stdout.write("\x1B[?25l"),process.stdin.setRawMode(!0),process.stdin.resume();let U=M=>{let Z=M.toString();if(Z==="\x1B[A")l=Math.max(0,l-1),E();else if(Z==="\x1B[B")l=Math.min(se(),l+1),E();else if(Z==="\r"){let ie=H();if(f&&ie.length===0)return;if(l<ie.length)$=ie[l]?.domain??null,k=!0;else{let Ae=W()[l-ie.length];Ae==="more"?(a+=Ge,r.length<a?b=!0:(l=Math.min(l,se()),E())):(Ae==="new"&&($="__new__"),k=!0)}}else(Z===""||Z==="\x1B")&&(k=!0)};process.stdin.on("data",U),E();async function te(M){let Z=new TextDecoder,ie="",z="";for await(let Ae of M){if(k)break;ie+=Z.decode(Ae,{stream:!0});let ze=ie.split(`
186
- `);ie=ze.pop()??"";for(let ue of ze)if(ue.startsWith("event: "))z=ue.slice(7);else if(ue.startsWith("data: ")){let de=JSON.parse(ue.slice(6));if(z==="error"&&(process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdout.write("\x1B[?25h"),u(de.message||de.error||"Search failed",{code:de.code||"error"})),z==="result"&&(g=de.domain),z==="result"&&(de.available||de.for_sale||i)){if(h===0){let xe=r.findIndex(ft=>ft.price>de.price);xe===-1?r.push(de):(r.splice(xe,0,de),xe<=l&&l++)}else r.push(de);E()}else if(z==="result"&&!de.available&&!de.error)o.length<8&&o.push(de);else if(z==="done"){f=!1,l=Math.min(l,se());let xe=Ge+h*Ge;r.length<a&&s&&xe<n.length&&(b=!0),b||E()}}}f=!1}for(await te(e);!k;)if(await new Promise(M=>{let Z=setInterval(()=>{(k||b)&&(clearInterval(Z),M())},16)}),b&&!k){b=!1;let M=Ge+h*Ge,Z=n.slice(M,M+Ge);h++,f=!0,l=Math.min(l,Math.max(0,r.length-1)),E();let ie=new URLSearchParams;ie.set("domains",Z.map(z=>`${t}.${z}`).join(","));try{let z=await ve(`/api/domains/search?${ie}`,{headers:{Accept:"text/event-stream"}});z.ok&&z.body?await te(z.body):(f=!1,E())}catch{f=!1,E()}}clearInterval(O),process.stdin.removeListener("data",U),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.pause(),process.stdout.write("\x1B[?25h"),A();let X=$==="__new__",q=X?null:$,re=q?r.find(M=>M.domain===q)??null:null;return q?process.stdout.write(`${N.default.dim("\u25C7")} Register a domain?
187
- ${N.default.dim("\u2502")} ${N.default.bold(N.default.cyan(q))}
188
- ${N.default.dim("\u2514")}
189
- `):process.stdout.write(`${N.default.dim("\u2514")}
190
- `),{chosen:q,chosenResult:re,searchAgain:X,allTaken:r.length===0&&o.length>0,expanded:h>0}}async function Po(e,t,i){if(!e){Ce||u("Missing required argument: domain",{hint:"Usage: domani search <domain> [tlds...]",code:"missing_argument",json:i.json});let U=await Pe({message:"Search for a domain",placeholder:"e.g. myapp or myapp.dev"});(ce(U)||!U)&&process.exit(0),e=U}let s=t.map(U=>U.replace(/^\./,"")),n=i.tlds?.split(",").map(U=>U.trim())||[],r=[...new Set([...s,...n])];if(r.length>0&&ns(r,i),Y(e,i),e.includes(".")&&r.length===0){let U=C(!i.json);U.start(`Checking ${v.domain(e)}`);let[te,X]=await Promise.all([ve(`/api/domains/search?q=${encodeURIComponent(e)}`),ve(`/api/domains/${encodeURIComponent(e)}/og`).catch(()=>null)]),q=await te.json();if(te.ok||(U.stop("Search failed"),u(q.error||q.message,{hint:q.hint,status:te.status,json:i.json,fields:i.fields})),i.json){let re=q.domain.split(".")[0];y({name:re,results:[q],total:1,available:q.available?1:0},i.fields);return}if(q.available)if(U.stop(`${w.success} ${v.domain(q.domain)} ${w.dot} available ${w.dot} ${v.price(q.price)}/yr`),Ce&&!i.json){let{buy:re}=await Promise.resolve().then(()=>(ri(),wi));await re([q.domain],{preChecked:{price:q.price,currency:q.currency}})}else c(),R("Register it:",`domani buy ${q.domain}`),c();else if(q.for_sale?.buyable)if(U.stop(`${w.info} ${v.domain(q.domain)} ${w.dot} ${N.default.cyan("for sale")} ${w.dot} ${v.price(q.for_sale.price)}`),Ce&&!i.json){let{buy:re}=await Promise.resolve().then(()=>(ri(),wi));await re([q.domain],{preChecked:{price:q.for_sale.price,currency:q.for_sale.currency,marketplace:!0}})}else c(),R("Buy it:",`domani buy ${q.domain}`),c();else if(q.error)U.stop(`${N.default.dim("?")} ${v.domain(q.domain)} ${w.dot} ${N.default.dim("lookup failed")}`);else{let re;try{if(X?.ok){let Z=await X.json();Z?.title&&(re=Z.title)}}catch{}let M=re?` ${w.dot} ${N.default.dim(`"${re}"`)}`:"";U.stop(`${w.error} ${v.domain(q.domain)} ${w.dot} ${N.default.red("taken")}${M}`)}return}let o=e.split(".")[0];if(Ce&&!i.json&&r.length>0){let U=new URLSearchParams;U.set("domains",r.map(ne=>`${o}.${ne}`).join(",")),i.maxPrice&&U.set("max_price",i.maxPrice);let te=await ve(`/api/domains/search?${U}`,{headers:{Accept:"text/event-stream"}});if(!te.ok||!te.body){u("Search failed",{json:i.json});return}let X=[],q=new TextDecoder,re="",M="",Z=C(!0);Z.start(`Checking ${r.length} TLD${r.length>1?"s":""}`);for await(let ne of te.body){re+=q.decode(ne,{stream:!0});let rt=re.split(`
191
- `);re=rt.pop()??"";for(let xt of rt)xt.startsWith("event: ")?M=xt.slice(7):xt.startsWith("data: ")&&M==="result"&&X.push(JSON.parse(xt.slice(6)))}Z.stop("");let ie=Math.max(...r.map(ne=>`${o}.${ne}`.length))+2,z=X.filter(ne=>ne.available),Ae=X.filter(ne=>!ne.available&&!ne.error),ze=X.filter(ne=>!ne.available&&ne.for_sale);for(let ne of[...z,...ze,...Ae.filter(rt=>!rt.for_sale)])ne.available?console.log(` ${N.default.green("\u2713")} ${N.default.bold(N.default.white(ne.domain.padEnd(ie)))} ${N.default.green(v.price(ne.price)+"/yr")}`):ne.for_sale?console.log(` ${N.default.cyan("$")} ${N.default.bold(N.default.white(ne.domain.padEnd(ie)))} ${N.default.cyan(v.price(ne.for_sale.price))} ${N.default.dim("(for sale)")}`):console.log(` ${N.default.dim("\u2717")} ${N.default.dim(ne.domain.padEnd(ie))} ${N.default.dim("taken")}`);if(z.length===0){console.log(` ${N.default.dim("No domains available")}`),c();return}let{buy:ue}=await Promise.resolve().then(()=>(ri(),wi));if(z.length===1){await ue([z[0].domain],{preChecked:{price:z[0].price,currency:z[0].currency}});return}let{select:de,isCancel:xe}=await Promise.resolve().then(()=>(Ue(),wn)),ft=await de({message:"Register one?",options:[...z.map(ne=>({value:ne.domain,label:v.domain(ne.domain),hint:v.price(ne.price)+"/yr"})),{value:"__skip__",label:"Skip"}]});if(!xe(ft)&&ft!=="__skip__"){c();let ne=z.find(rt=>rt.domain===ft);await ue([ft],{preChecked:ne?{price:ne.price,currency:ne.currency}:void 0})}else c();return}if(Ce&&!i.json){let U=await Eo();for(i.expand&&U.length>oi&&console.error(N.default.dim(` (--expand: checking the first ${oi} of ${U.length} TLDs - server limit per request)`));;){let te=i.expand?U.slice(0,oi):U.slice(0,Ge),X=new URLSearchParams;X.set("domains",te.map(de=>`${o}.${de}`).join(",")),i.maxPrice&&X.set("max_price",i.maxPrice);let q=C(!0);q.start(`Searching available domains for ${N.default.bold(o)}`);let re=await ve(`/api/domains/search?${X}`,{headers:{Accept:"text/event-stream"}});if(!re.ok||!re.body){q.stop("Search failed");break}q.stop("");let M=!i.expand,{chosen:Z,chosenResult:ie,searchAgain:z}=await _c(re.body,o,i.all??!1,M,U);if(Z){c();let{buy:de}=await Promise.resolve().then(()=>(ri(),wi)),xe=ie?{price:ie.price,currency:ie.currency}:void 0;await de([Z],{preChecked:xe});return}if(!z)break;let{text:Ae,isCancel:ze}=await Promise.resolve().then(()=>(Ue(),wn)),ue=await Ae({message:"Search for a domain",placeholder:"e.g. myapp or myapp.dev"});if(ze(ue)||!ue)break;o=ue.split(".")[0]}c();return}let a=o,l=await Eo(),f=r.length>0?r:i.expand?l.slice(0,oi):l.slice(0,Ge);i.expand&&r.length===0&&l.length>oi&&console.error(`(--expand: checking the first ${oi} of ${l.length} TLDs - server limit per request; use --tlds to target others)`);let m=f.map(U=>`${a}.${U}`),h=new URLSearchParams;h.set("domains",m.join(",")),i.maxPrice&&h.set("max_price",i.maxPrice);let b=C(!i.json);b.start(`Searching available domains for ${N.default.bold(a)}`);let k=await ve(`/api/domains/search?${h}`,{headers:{Accept:"text/event-stream"}});if(!k.ok){b.stop("Search failed");try{let U=await k.json();u(U.error||U.message||`Server error (${k.status})`,{hint:U.hint,status:k.status,json:i.json,fields:i.fields})}catch{u(`Server error (${k.status})`,{status:k.status,json:i.json,fields:i.fields})}}let $=k.body;$||(b.stop("Search failed"),u("Empty response",{code:"error",json:i.json,fields:i.fields}));let g=[],x=!1,S=0,O=i.all??!1;function A(){x||(x=!0,b.stop(`Checking TLDs for ${N.default.bold(a)}`),c())}function W(U){A(),U.available?console.log(` ${w.success} ${v.domain(U.domain).padEnd(37)} ${v.price(U.price)}${N.default.dim("/yr")}`):U.for_sale?console.log(` ${w.info} ${v.domain(U.domain).padEnd(37)} ${N.default.cyan(v.price(U.for_sale.price))} ${N.default.dim("(for sale)")}`):U.error||console.log(` ${w.error} ${N.default.dim(U.domain.padEnd(38))} ${N.default.red("taken")}`)}function H(){x||b.message(`Checking TLDs for ${N.default.bold(a)} ${N.default.dim(`(${S} checked)`)}`)}let se=new TextDecoder,P="",E="";for await(let U of $){P+=se.decode(U,{stream:!0});let te=P.split(`
192
- `);P=te.pop()??"";for(let X of te)if(X.startsWith("event: "))E=X.slice(7);else if(X.startsWith("data: ")){let q=JSON.parse(X.slice(6));if(E==="error")b.stop("Search failed"),u(q.message||q.error||"Search failed",{code:q.code||"error",json:i.json,fields:i.fields});else if(E==="result")S++,q.available||q.for_sale||O?(i.json||W(q),g.push(q)):i.json||H();else if(E==="done"){if(i.json){g.sort((ie,z)=>ie.price-z.price),y({name:a,results:g,total:q.total,available:q.available},i.fields);return}x&&console.log(` ${N.default.dim("\u2500".repeat(50))}`);let re=q.total-q.available,M=q.total>=5&&re/q.total>=.5,Z=`Checked ${q.total} TLDs \xB7 ${q.available} available${M?" \xB7 popular name":""}`;console.log(` ${N.default.dim(Z)}`),q.available===0&&!i.expand&&r.length===0&&(c(),R("Try more TLDs:",`domani search ${a} --expand`))}}}c()}ri();G();var vi=D(F(),1);L();we();rs();function Do(e,t,i=process.env){let s=Vt(t,i);if(s!==void 0&&!e)throw new Error("--webhook is required when setting webhook authentication");return{request:{...e?{webhook_url:e}:{},...s!==void 0?{webhook_headers:s}:{}},preview:{...e?{webhook_url:e}:{},...s!==void 0?{webhook_header_names:Wt(s)}:{}}}}async function No(e,t){Y(e,t);let i={domain:e};t.slug&&(i.slug=t.slug),t.name&&(i.name=t.name);let s;try{s=Do(t.webhook,t)}catch(a){u(a instanceof Error?a.message:"Invalid webhook headers",{hint:"Set the named environment variable and retry.",code:"validation_error",json:t.json,fields:t.fields})}if(Object.assign(i,s.request),t.years&&(i.years=Number(t.years)),t.paymentMethod&&(i.payment_method=t.paymentMethod),t.dryRun){let a={...i};delete a.webhook_headers,Object.assign(a,s.preview),K("POST /api/agents/provision",a,t.json,t.fields);return}let n=C(!t.json);n.start(`Provisioning ${v.domain(e)}`);let r=await _("/api/agents/provision",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)}),o=await r.json();if(r.ok||(n.stop("Provisioning failed"),u(o.error||"Provisioning failed",{hint:o.hint,status:r.status,json:t.json,fields:t.fields})),n.stop(`${v.domain(e)} is ready`),t.json){y(o,t.fields);return}if(c(),j("Agent identity"),d("Domain",`${o.domain} (${o.domain_status})`),d("Mailbox",o.mailbox?vi.default.green(o.mailbox.address):vi.default.yellow("pending DNS")),d("Webhook",o.webhook?o.webhook.url:vi.default.dim("none")),o.webhook?.header_names.length&&d("Webhook auth",o.webhook.header_names.join(", ")),o.webhook?.secret&&d("Signing secret",o.webhook.secret),o.warnings?.length){c();for(let a of o.warnings)be(vi.default.yellow(a))}if(o.next_steps?.length){c(),j("Next");for(let a of o.next_steps)be(a)}c()}G();var $t=D(F(),1);L();async function Uo(e){let t=C(!e.json);t.start("Loading domains");let i=await _("/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){y({...s,count:s.domains.length},e.fields);return}if(s.domains.length===0){c(),console.log(` ${$t.default.dim("No domains yet.")} Use: ${$t.default.cyan("domani buy <domain>")}`),c();return}let n=[30,12,12,14];j(`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"?$t.default.green:o.status==="pending"?$t.default.yellow:$t.default.red,f=o.autoRenew?$t.default.green("on"):$t.default.dim("off");return[v.domain(o.domain),l(o.status),f,$t.default.dim(a)]});B(["Domain","Status","Auto-renew","Expires"],r,n),c()}Dn();G();var Ht=D(F(),1);L();async function qo(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=C(!e.json);i.start("Loading TLDs");let s=await ve(`/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){y(n,e.fields);return}let r=n.tlds;if(r.length===0){c(),console.log(` ${Ht.default.dim("No TLDs match your filters.")}`),c();return}j("TLD Pricing");let o=r.map(a=>[Ht.default.bold(`.${a.tld}`),v.price(a.registration.toFixed(2))+Ht.default.dim("/yr"),Ht.default.dim("renew ")+v.price(a.renewal.toFixed(2))+Ht.default.dim("/yr")]);B(["TLD","Register","Renewal"],o,[22,16,20]),c(),console.log(` ${Ht.default.dim(`${n.total} TLDs total`)}`),c()}G();var Ie=D(F(),1);L();we();async function Mo(e,t){Y(e,t);let i=C(!t.json);i.start(`Looking up ${v.domain(e)}`);let[s,n]=await Promise.all([ve(`/api/domains/whois?q=${encodeURIComponent(e)}`),ve(`/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){y({...r,...o?{og:o}:{}},t.fields);return}if(j(`WHOIS ${v.domain(r.domain)}`),!r.registered){d("Status",`${w.success} ${Ie.default.green("not registered")}`),c(),R("Register it:",`domani buy ${r.domain}`),c();return}if(d("Status",`${w.error} ${Ie.default.red("registered")}`),(o?.title||o?.description)&&(c(),console.log(` ${Ie.default.bold("Website preview")}`),console.log(` ${Ie.default.dim("\u2500".repeat(50))}`),o.title&&d("Title",o.title),o.description&&d("Description",Ie.default.dim(o.description.length>80?o.description.slice(0,80)+"\u2026":o.description)),c()),r.registrar&&d("Registrar",r.registrar),r.created&&d("Created",r.created),r.expires&&d("Expires",r.expires),r.days_until_expiry!=null){let l=r.days_until_expiry,f=l<30?Ie.default.red:l<90?Ie.default.yellow:Ie.default.green;d("Days left",f(String(l)))}r.updated&&d("Updated",r.updated),d("DNSSEC",r.dnssec?Ie.default.green("yes"):Ie.default.dim("no")),r.nameservers?.length>0&&d("Nameservers",r.nameservers.map(l=>Ie.default.cyan(l)).join(Ie.default.dim(", "))),r.status?.length>0&&d("Status codes",Ie.default.dim(r.status.join(", ")));let a=r.contacts?.registrant;a&&!r.redacted?(c(),console.log(` ${Ie.default.bold("Registrant")}`),console.log(` ${Ie.default.dim("\u2500".repeat(50))}`),a.name&&d("Name",a.name),a.organization&&d("Organization",a.organization),a.email&&d("Email",v.url(a.email)),a.country&&d("Country",a.country)):r.redacted&&d("Contact",Ie.default.dim("redacted (WHOIS privacy)")),c()}G();Ue();var kt=D(F(),1);L();we();async function Fo(e,t){if(!e){Ce||u("Missing required argument: prompt",{hint:'Usage: domani suggest "describe your project"',code:"missing_argument",json:t.json});let g=await Pe({message:"Describe your project or idea",placeholder:"e.g. AI coding assistant, pet food delivery..."});(ce(g)||!g)&&process.exit(0),e=g}let i=new URLSearchParams({prompt:e});if(t.count&&i.set("count",t.count),t.tlds&&i.set("tlds",t.tlds),t.tlds&&ns(t.tlds.split(",").map(g=>g.trim()),t),t.style&&i.set("style",t.style),t.lang&&i.set("lang",t.lang),t.json){let g=C(!1);g.start("Finding available domains");let x=t.timeout?parseInt(t.timeout,10)*1e3:6e4,S;try{S=await ve(`/api/domains/suggest?${i}`,{signal:AbortSignal.timeout(x)})}catch{g.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 S.json();S.ok||(g.stop("Failed"),u(O.error||O.message,{hint:O.hint,status:S.status,json:t.json,fields:t.fields})),y(O,t.fields);return}let s=C(!0);s.start("Finding available domains");let n=t.timeout?parseInt(t.timeout,10)*1e3:6e4,r;try{r=await ve(`/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 g=await r.json();u(g.error||g.message||`Server error (${r.status})`,{hint:g.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=[],f=!1,m=0;function h(){f||(f=!0,s.stop("Finding available domains"),c())}let b=new TextDecoder,k="",$="";for await(let g of o){k+=b.decode(g,{stream:!0});let x=k.split(`
193
- `);k=x.pop()??"";for(let S of x)if(S.startsWith("event: "))$=S.slice(7);else if(S.startsWith("data: "))try{let O=JSON.parse(S.slice(6));if($==="result")m++,O.available?a.push(O):l.push(O),f||s.message(`Finding available domains ${kt.default.dim(`(${m} checked, ${a.length} available)`)}`);else if($==="iteration")f||s.message(`Finding available domains ${kt.default.dim(`(round ${O.n})`)}`);else if($==="done"){h();for(let A of a){let W=A.reason?` ${kt.default.dim(A.reason)}`:"";console.log(` ${w.success} ${v.domain(A.domain).padEnd(37)} ${v.price(A.price)}${kt.default.dim("/yr")}${W}`)}for(let A of l)console.log(` ${w.error} ${kt.default.dim(A.domain.padEnd(38))} ${kt.default.red("taken")}`);console.log(` ${kt.default.dim("\u2500".repeat(50))}`),console.log(` ${kt.default.dim(`Found ${O.total} available \xB7 checked ${O.checked} \xB7 ${O.iterations} round${O.iterations>1?"s":""}`)}`)}else $==="error"&&(f||s.stop("Failed"),u(O.message))}catch{}}a.length===0&&l.length===0&&(f||s.stop("No results"),u("Could not find available domains for this prompt.")),c(),a.length>0&&(R("Register one:",`domani buy ${a[0].domain}`),c())}On();Un();G();Ue();var dt=D(F(),1);L();we();ci();async function Lo(e){let t=e.maxConsecutiveFailures??10,i=0;for(let s=1;s<=e.maxAttempts;s++){let n=await e.fetchPlan().catch(()=>null);if(e.onTick?.(n,s),n!==null){if(i=0,e.isEligible(n))return{status:"eligible",plan:n}}else if(i++,i>=t)return{status:"unreachable",failures:i};s<e.maxAttempts&&await e.sleep(e.intervalMs)}return{status:"timeout",attempts:e.maxAttempts}}var $i=D(F(),1);L();function ki(e){if(e){c(),console.log(` ${$i.default.bold(`Exit path (${e.managed_via})`)}`),console.log(` ${$i.default.dim("Unlock:")} ${e.unlock}`),console.log(` ${$i.default.dim("Auth code:")} ${e.auth_code}`);for(let t of e.notes||[])console.log(` ${$i.default.yellow("!")} ${t}`)}}var xc=6e4,jc=1440;async function Vo(e,t){Y(e,t);let i=C(!t.json);i.start(`Planning safe adoption for ${v.domain(e)}`);let s=await _(`/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(`${w.success} Eligible for transfer`);else{i.stop(`${w.error} Not eligible`);let a=n.options?.transfer;if(t.watch&&a?.eligible_at){let l=await _("/api/domains/transfer-watch",{method:"POST",body:JSON.stringify({domain:e})}),f=await l.json();if(l.ok||u(f.error||f.message,{hint:f.hint,status:l.status,json:t.json,fields:t.fields}),t.json){y(f,t.fields);return}j("Transfer Watch Registered"),d("Domain",v.domain(e)),d("Eligible from",f.eligible_at||a.eligible_at),f.hint&&(c(),console.log(` ${dt.default.dim(f.hint)}`)),c();return}if(t.watch){t.json||(console.log(` ${dt.default.dim(a?.reason||"Domain is not eligible for transfer yet.")}`),ki(a?.guidance),c());let l=C(!t.json);l.start(`Watching ${v.domain(e)} until it becomes transferable (every 60s, Ctrl+C to stop)`);let f=await Lo({fetchPlan:async()=>{let m=await _(`/api/domains/adoption-plan?domain=${encodeURIComponent(e)}`);return m.ok?m.json():null},isEligible:m=>!!m.options?.transfer?.eligible,sleep:m=>new Promise(h=>setTimeout(h,m)),intervalMs:xc,maxAttempts:jc});f.status!=="eligible"&&(l.stop(`${w.error} Watch ended`),u(f.status==="timeout"?"Domain did not become eligible within 24 hours.":"Gave up after repeated failures fetching the adoption plan.",{hint:"The transfer lock is disabled at the losing registrar; rerun with --watch once you have flipped it.",code:f.status==="timeout"?"watch_timeout":"watch_unreachable",json:t.json,fields:t.fields})),n=f.plan,l.stop(`${w.success} Now eligible for transfer`)}else{t.json||ki(a?.guidance);let l=a?.eligible_at?`Eligible from ${a.eligible_at}. Rerun with --watch to register a server watch (email + webhook when the date arrives).`:"Fix the blocker above, then rerun - or rerun with --watch to poll until the domain becomes eligible and continue automatically.",f=t.json&&a?.guidance?` The registrar exit playbook is in the adoption plan (options.transfer.guidance, \`domani adopt ${e} --json\`).`:"";u(a?.reason||"Domain is not eligible for transfer.",{hint:[l+f,...n.warnings?.length?[n.warnings.join(" ")]:[]].join(" "),code:"not_eligible",json:t.json,fields:t.fields})}}if(t.dryRun)return K("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(!Ft(t)){j("Transfer Safety Plan"),d("Registrar",n.current.registrar||"Unknown"),d("DNS provider",n.current.dns_provider),d("Nameservers",`${n.current.nameservers.length} preserved`),d("DNSSEC",n.current.dnssec_enabled?dt.default.yellow("Enabled, DS will be verified"):"Not enabled"),d("DNS migration","Not requested"),c();let a=n.options.transfer.price!=null?` for ${v.price(n.options.transfer.price.toFixed(2))}`:"",l=await Xe({message:`Transfer ${dt.default.bold(e)} to ${Yt}${a}? Nameservers stay unchanged and 1 year is included.`});if(!l||typeof l=="symbol"){console.log(` ${dt.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}),n.options?.transfer?.guidance&&console.log(` ${dt.default.dim("Where to get it:")} ${n.options.transfer.guidance.auth_code}`);let a=await Pe({message:"Enter the EPP/auth code from your current registrar:",validate:l=>!l||l.trim().length===0?"Auth code is required":void 0});ce(a)&&process.exit(0),t.authCode=a}i.start(`Initiating transfer for ${v.domain(e)}`);let r=await _("/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(`${w.success} Transfer initiated`),t.json){y(o,t.fields);return}j("Transfer Initiated"),d("Domain",v.domain(o.domain)),d("Status",dt.default.yellow(o.status||"pending")),o.price&&d("Price",v.price(o.price)+dt.default.dim(` ${o.currency||"USD"}`)),o.payment_method&&d("Payment",o.payment_method),o.expires&&d("Expires",new Date(o.expires).toLocaleDateString()),o.hint&&(c(),console.log(` ${dt.default.dim(o.hint)}`)),c(),R("Check transfer progress:",`domani status ${o.domain}`),c()}G();var _i=D(F(),1);L();we();async function Wo(e,t){Y(e,t);let i=C(!t.json);i.start(`Inspecting ${v.domain(e)}`);let s=await _(`/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(`${w.success} Adoption plan ready`),t.json){y(n,t.fields);return}if(j(`Adopt ${v.domain(n.domain)}`),d("Registrar",n.current.registrar||"Unknown"),d("DNS provider",n.current.dns_provider),d("Nameservers",n.current.nameservers.join(", ")||"None detected"),d("DNSSEC",n.current.dnssec_enabled?_i.default.yellow("Enabled"):"Not enabled"),d("Account",n.account_state),d("Recommended",_i.default.cyan(n.recommended_action)),c(),n.recommended_action==="connect"&&R("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}`;R(`Transfer registration for ${r}, preserving nameservers:`,`domani transfer ${n.domain}`),!n.options.transfer.eligible&&n.options.transfer.reason&&(console.log(` ${_i.default.yellow("!")} ${n.options.transfer.reason}`),R("Wait for eligibility and transfer in one go:",`domani transfer ${n.domain} --watch`)),ki(n.options.transfer.guidance)}for(let r of n.warnings||[])console.log(` ${_i.default.yellow("!")} ${r}`);c()}G();Ue();var ms=D(F(),1);L();we();Ze();async function Ho(e,t){e||(e=await he()),Y(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 K("renew",{domain:e,years:i},t.json,t.fields);if(!Ft(t)){let o=await Xe({message:`Renew ${ms.default.bold(e)} for ${i} year${i>1?"s":""}? You will be charged.`});if(!o||typeof o=="symbol"){console.log(` ${ms.default.dim("Cancelled.")}`);return}}let s=C(!t.json);s.start(`Renewing ${v.domain(e)}`);let n=await _(`/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(`${w.success} Domain renewed`),t.json){y(r,t.fields);return}j("Renewal Complete"),d("Domain",v.domain(r.domain)),d("Years",String(r.renewed_years)),d("New expiry",new Date(r.new_expiry).toLocaleDateString()),r.price&&d("Price",v.price(r.price)+ms.default.dim(` ${r.currency||"USD"}`)),r.payment_method&&d("Payment",r.payment_method),c(),R("Verify renewal:",`domani status ${r.domain}`),c()}G();var ct=D(F(),1);L();we();async function Jo(e,t){e||u("Domain is required",{hint:`Usage: domani import <domain>
194
- domani import <domain> --verify`,code:"validation_error",json:t.json,fields:t.fields}),Y(e,t);let i=t.verify?"/api/domains/import/verify":"/api/domains/import",s=C(!t.json);s.start(t.verify?`Verifying ownership of ${v.domain(e)}`:`Initiating import for ${v.domain(e)}`);let n=await _(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(""),y(r,t.fields);return}t.verify?(s.stop(`${w.success} ${v.domain(e)} imported!`),j("Domain Imported"),d("Domain",v.domain(r.domain)),d("Status",ct.default.green(r.status||"active")),r.expires_at&&d("Expires",new Date(r.expires_at).toLocaleDateString()),r.registrar&&d("Registrar",r.registrar),c(),R("Check domain health:",`domani status ${r.domain}`),c()):(s.stop(`${w.success} Verification record ready`),j("Import Domain"),d("Domain",v.domain(r.domain)),d("Status",ct.default.yellow("pending verification")),c(),console.log(" Add this TXT record at your DNS provider:"),c(),console.log(` ${ct.default.dim("Type:")} ${ct.default.bold("TXT")}`),console.log(` ${ct.default.dim("Name:")} ${ct.default.bold(r.txt_record?.name||"@")}`),console.log(` ${ct.default.dim("Value:")} ${ct.default.bold(r.txt_record?.value||`domani-verify=${r.token}`)}`),c(),console.log(` ${ct.default.dim("DNS propagation may take a few minutes to 48 hours.")}`),c(),R("Once the record is set, verify:",`domani import ${e} --verify`),c())}Tn();yt();L();function Bo(e){let t=He();if(t||(c(),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?y({token:t}):console.log(t)}G();var Fe=D(F(),1);L();async function Go(e,t){switch(e){case void 0:case"list":return Sc(t.json,t.fields);case"create":return Cc(t);case"revoke":return Oc(t);default:u(`Unknown action: ${e}`,{hint:"Actions: list, create, revoke",code:"validation_error",json:t.json,fields:t.fields})}}async function Sc(e,t){let i=C(!e);i.start("Loading tokens");let s=await _("/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(`${w.success} ${n.tokens.length} token(s)`),e){y(n,t);return}if(n.tokens.length===0){c(),console.log(` ${Fe.default.dim("No tokens.")}`),c(),R("Create one:",'domani tokens create --name "My App"'),c();return}c(),j("API Tokens");let r=n.tokens.map(o=>{let a;o.expired?a=Fe.default.red("Expired"):o.expiresAt?a=Fe.default.dim(`Expires ${new Date(o.expiresAt).toLocaleDateString()}`):a=Fe.default.dim("No expiration");let l=o.scopes.includes("*")?Fe.default.dim("all"):Fe.default.dim(o.scopes.join(", "));return[Fe.default.dim(o.id),Fe.default.bold(o.name),o.agent_identity?Fe.default.dim(o.agent_identity.name||o.agent_identity.slug):Fe.default.dim("\u2014"),l,a]});B(["ID","Name","Agent","Scopes","Expiration"],r,[28,16,18,32,20]),c()}async function Cc(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=C(!e.json);i.start("Creating token");let s=await _("/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(`${w.success} Token created`),e.json){y(n,e.fields);return}c(),j("Token Created"),d("ID",n.id),d("Name",n.name),d("Scopes",n.scopes?.includes("*")?"All (full access)":n.scopes?.join(", ")||"All"),n.agent_identity&&d("Agent",n.agent_identity.name||n.agent_identity.slug),d("Expires",n.expiresAt?new Date(n.expiresAt).toLocaleString():"Never"),c(),console.log(` ${Fe.default.yellow("!")} ${Fe.default.bold("Key:")} ${n.key}`),console.log(` ${Fe.default.dim("Save this key - it will not be shown again.")}`),c()}async function Oc(e){e.tokenId||u("Token ID required",{hint:`Usage: domani tokens revoke --token-id <id>
195
- Run 'domani tokens list' to see your tokens.`,code:"validation_error",json:e.json,fields:e.fields});let t=C(!e.json);t.start("Revoking token");let i=await _(`/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(`${w.success} Token revoked`),e.json){y(s,e.fields);return}console.log(` ${Fe.default.dim("Any applications using this key will need a new one.")}`),c()}G();var Re=D(F(),1);L();we();Ze();async function Ko(e,t){e||(e=await he()),Y(e,t);let i=t.autoRenew!==void 0,s=t.whoisPrivacy!==void 0,n=t.securityLock!==void 0;if(!i&&!s&&!n)return Ic(e,t.json,t.fields);let r={};if(i){let f=Fn(t.autoRenew);f===null&&u("--auto-renew must be on or off",{code:"validation_error",json:t.json,fields:t.fields}),r.auto_renew=f}if(s){let f=Fn(t.whoisPrivacy);f===null&&u("--whois-privacy must be on or off",{code:"validation_error",json:t.json,fields:t.fields}),r.whois_privacy=f}if(n){let f=Fn(t.securityLock);f===null&&u("--security-lock must be on or off",{code:"validation_error",json:t.json,fields:t.fields}),r.security_lock=f}if(t.dryRun)return K("settings_update",{domain:e,...r},t.json,t.fields);let o=C(!t.json);o.start(`Updating ${v.domain(e)}`);let a=await _(`/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(`${w.success} Settings updated`),t.json){y(l,t.fields);return}j("Settings Updated"),d("Domain",v.domain(l.domain)),l.auto_renew!==void 0&&d("Auto-renew",l.auto_renew?Re.default.green("on"):Re.default.dim("off")),l.whois_privacy!==void 0&&d("WHOIS privacy",l.whois_privacy?Re.default.green("on"):Re.default.dim("off")),l.security_lock!==void 0&&d("Security lock",l.security_lock?Re.default.green("locked"):Re.default.dim("unlocked")),l.hint&&d("",Re.default.dim(l.hint)),c()}async function Ic(e,t,i){let s=C(!t);s.start(`Loading ${v.domain(e)}`);let n=await _(`/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(`${w.success} ${v.domain(e)}`),t){y(r,i);return}j("Domain Settings"),d("Domain",v.domain(r.domain)),d("Status",r.status==="active"?Re.default.green(r.status):Re.default.yellow(r.status)),d("Auto-renew",r.auto_renew?Re.default.green("on"):Re.default.dim("off")),r.registrar&&(d("WHOIS privacy",r.registrar.whois_privacy?Re.default.green("on"):Re.default.dim("off")),d("Security lock",r.registrar.security_lock?Re.default.green("locked"):Re.default.dim("unlocked"))),d("Expires",new Date(r.expires_at).toLocaleDateString()+Re.default.dim(` (${r.days_until_expiry} days)`)),c(),R("Toggle auto-renew:",`domani settings ${e} --auto-renew off`),R("Toggle WHOIS privacy:",`domani settings ${e} --whois-privacy off`),R("Toggle security lock:",`domani settings ${e} --security-lock off`),R("Get transfer auth code:",`domani auth-code ${e}`),c()}function Fn(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}G();var Jt=D(F(),1);L();we();Ze();async function zo(e,t){e||(e=await he()),Y(e,t);let i=C(!t.json);i.start(`Getting auth code for ${v.domain(e)}`);let s=await _(`/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(`${w.success} Auth code retrieved`),t.json){y(n,t.fields);return}if(j("Auth Code"),d("Domain",v.domain(n.domain)),d("Auth code",Jt.default.bold(Jt.default.green(n.auth_code))),n.was_unlocked&&d("",Jt.default.yellow("Domain was automatically unlocked to allow transfer.")),n.hint&&(c(),console.log(` ${Jt.default.dim(n.hint)}`)),n.next_steps?.length){c();for(let r of n.next_steps)console.log(` ${Jt.default.dim("\u2192")} ${Jt.default.dim(r)}`)}c(),R("Check transfer status:",`domani transfer-away ${e}`),R("Re-lock domain:",`domani settings ${e} --security-lock on`),c()}G();var _t=D(F(),1);L();we();Ze();var Rc={none:_t.default.dim,pending:_t.default.yellow,approved:_t.default.yellow,completed:_t.default.green,rejected:_t.default.red,expired:_t.default.red};async function Yo(e,t){e||(e=await he()),Y(e,t);let i=C(!t.json);i.start(`Checking transfer status for ${v.domain(e)}`);let s=await _(`/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(`${w.success} ${v.domain(e)}`),t.json){y(n,t.fields);return}j("Transfer Away Status"),d("Domain",v.domain(n.domain));let r=Rc[n.status]||_t.default.dim;d("Status",r(n.status)),n.gaining_registrar&&d("New registrar",n.gaining_registrar),n.request_date&&d("Requested",new Date(n.request_date).toLocaleDateString()),n.hint&&(c(),console.log(` ${_t.default.dim(n.hint)}`)),c(),n.status==="none"?R("Get auth code to start:",`domani auth-code ${e}`):n.status==="pending"||n.status==="approved"?R("Check again later:",`domani transfer-away ${e}`):n.status==="completed"?R("Search for a new domain:","domani search <name>"):(n.status==="rejected"||n.status==="expired")&&R("Retry with a new auth code:",`domani auth-code ${e}`),c()}G();Ue();var fs=D(F(),1);L();async function Xo(e,t){return e==="set"?Tc(t):Ac(t)}async function Ac(e){let t=C(!e.json);t.start("Loading contact info");let i=await _("/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(`${w.success} Contact info`),e.json){y(s,e.fields);return}if(j("Contact Info"),!s.has_contact){console.log(` ${w.warning} ${fs.default.yellow("No contact info set.")} Run ${fs.default.bold("domani contact set")} to add.`),c(),console.log(` ${fs.default.dim("Contact info is required before purchasing domains.")}`),c();return}let n=s.contact;d("Name",`${n.first_name} ${n.last_name}`),n.org_name&&d("Organization",n.org_name),d("Address",n.address1),n.address2&&d("",n.address2),d("",`${n.city}, ${n.state} ${n.postal_code}`),d("Country",n.country),d("Phone",n.phone),d("Email",n.email),c()}async function Tc(e){let t={},i=e.firstName||e.lastName||e.address1;if(!Ce&&!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"},f=a.filter(m=>!e[m]);f.length>0&&u(`Missing required flags: ${f.map(m=>`--${m.replace(/[A-Z]/g,h=>`-${h.toLowerCase()}`)}`).join(", ")}`,{code:"missing_argument",json:e.json});for(let[m,h]of Object.entries(l)){let b=e[m];b&&(t[h]=b)}}else{let a=await _("/api/me/contact"),f=(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 h of m){let b=f?.[h.key]||"",k=await Pe({message:h.message,placeholder:h.placeholder,defaultValue:b,validate:h.required?g=>g?.trim()?void 0:`${h.message} is required`:void 0});ce(k)&&process.exit(0);let $=k.trim();$&&(t[h.key]=$)}}if(e.dryRun)return K("contact_set",t,e.json,e.fields);let s=C(!e.json);s.start("Saving contact info");let n=await _("/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(`${w.success} Contact info saved`),e.json){y(r,e.fields);return}j("Contact Saved");let o=r.contact;d("Name",`${o.first_name} ${o.last_name}`),o.org_name&&d("Organization",o.org_name),d("Address",o.address1),o.address2&&d("",o.address2),d("",`${o.city}, ${o.state} ${o.postal_code}`),d("Country",o.country),d("Phone",o.phone),d("Email",o.email),c(),R("Search for a domain:","domani search <name>"),c()}G();var De=D(F(),1);L();we();Ze();async function ea(e,t,i,s){if(e||(e=await he()),Y(e,s),!t)return Ec(e,s.json,s.fields);switch(t){case"enable":case"on":return s.dryRun?K("parking_enable",{domain:e},s.json,s.fields):Zo(e,!0,s.json,s.fields);case"disable":case"off":return s.dryRun?K("parking_disable",{domain:e},s.json,s.fields):Zo(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?K("parking_price",{domain:e,price:n},s.json,s.fields):Qo(e,n,s.json,s.fields)}case"unprice":case"unlist":return s.dryRun?K("parking_unlist",{domain:e},s.json,s.fields):Qo(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 Ec(e,t,i){let s=C(!t);s.start(`Loading ${v.domain(e)}`);let n=await _(`/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(`${w.success} ${v.domain(e)}`),t){y({domain:r.domain,parking_enabled:r.parking_enabled,listing_price:r.listing_price},i);return}j("Parking"),d("Domain",v.domain(r.domain)),d("Parking",r.parking_enabled?De.default.green("enabled"):De.default.dim("disabled")),d("Listing",r.listing_price?`${v.price(r.listing_price)} ${De.default.dim("(for sale)")}`:De.default.dim("not listed")),c(),R("Enable parking:",`domani parking ${e} enable`),R("Set sale price:",`domani parking ${e} price 499`),R("View analytics:",`domani analytics ${e}`),c()}async function Zo(e,t,i,s){let n=C(!i);n.start(`${t?"Enabling":"Disabling"} parking for ${v.domain(e)}`);let r=await _(`/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(`${w.warning} DNS records will be replaced`),i){y(o,s);return}console.log(`
196
- ${De.default.yellow("Enabling parking will replace these DNS records:")}`);for(let a of o.existing_dns||[])console.log(` ${De.default.dim(a.type)} ${a.name} ${De.default.dim("\u2192")} ${a.value}`);console.log(`
197
- ${De.default.dim("Run again with --confirm to proceed (not implemented yet).")}`),console.log(` ${De.default.dim("Or use the dashboard to confirm.")}`),c();return}if(r.ok||(n.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:i,fields:s})),n.stop(`${w.success} Parking ${t?"enabled":"disabled"}`),i){y(o,s);return}j("Parking Updated"),d("Domain",v.domain(o.domain)),d("Parking",o.parking_enabled?De.default.green("enabled"):De.default.dim("disabled")),o.hint&&d("",De.default.dim(o.hint)),c()}async function Qo(e,t,i,s){let n=C(!i);n.start(t!==null?`Setting price for ${v.domain(e)} to ${v.price(t)}`:`Removing listing for ${v.domain(e)}`);let r=await _(`/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(`${w.success} ${t!==null?"Price set":"Listing removed"}`),i){y(o,s);return}j("Listing Updated"),d("Domain",v.domain(o.domain)),d("Listing",o.listing_price?`${v.price(o.listing_price)} ${De.default.dim("(for sale)")}`:De.default.dim("not listed")),o.hint&&d("",De.default.dim(o.hint)),c()}G();var Ke=D(F(),1);L();we();Ze();var Pc=" \u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588";function Dc(e){let t=Math.max(...e,1);return e.map(i=>Pc[Math.min(Math.round(i/t*8),8)]).join("")}async function ta(e,t){e||(e=await he()),Y(e,t);let i=C(!t.json);i.start(`Loading analytics for ${v.domain(e)}`);let s=await _(`/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){y(n,t.fields);return}if(c(),j(`Analytics: ${v.domain(e)}`),d("Views (7d)",Ke.default.cyan(n.views_7d.toLocaleString())),d("Views (30d)",Ke.default.cyan(n.views_30d.toLocaleString())),d("Inquiries",Ke.default.cyan(String(n.inquiries_30d))),d("Conversion",n.conversion_rate>0?Ke.default.green(`${n.conversion_rate}%`):Ke.default.dim("0%")),n.daily_views&&n.daily_views.length>0){let r=n.daily_views.map(f=>f.views),o=Dc(r),a=n.daily_views[0].date.slice(5),l=n.daily_views[n.daily_views.length-1].date.slice(5);c(),console.log(` ${Ke.default.dim(a)} ${Ke.default.cyan(o)} ${Ke.default.dim(l)}`)}if(n.recent_inquiries&&n.recent_inquiries.length>0){c(),console.log(` ${Ke.default.bold("Recent Inquiries")}`);let r=n.recent_inquiries.map(o=>[Ke.default.dim(o.email),o.offer?v.price(o.offer):Ke.default.dim("-"),Ke.default.dim(new Date(o.date).toLocaleDateString())]);B(["Email","Offer","Date"],r,[30,12,14])}c(),R("Set a listing price:",`domani parking ${e} price <amount>`),R("Set up email:",`domani email setup ${e}`),R("Domain settings:",`domani settings ${e}`),c()}G();var ge=D(F(),1);L();rs();async function ia(e,t){switch(e){case void 0:case"list":return Uc(t.json,t.fields);case"create":return qc(t);case"update":return Mc(t);case"delete":return Fc(t);case"deliveries":return Lc(t);case"replay":return Nc(t);case"events":return Vc(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 Nc(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=C(!e.json);t.start("Replaying webhook delivery");let i=await _(`/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(`${w.success} Webhook replay ${s.status}`),e.json)return y(s,e.fields);j("Webhook Replay Receipt"),d("Delivery",s.delivery_id),d("Original",s.original_delivery_id),d("Status",s.status),d("Attempts",s.attempts),d("Idempotent retry",s.idempotent_replay?"yes":"no"),c()}async function Uc(e,t){let i=C(!e);i.start("Loading webhooks");let s=await _("/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(`${w.success} ${n.webhooks.length} webhook(s)`),e){y(n,t);return}if(n.webhooks.length===0){c(),console.log(` ${ge.default.dim("No webhooks configured.")}`),c(),R("Create one:","domani webhooks create --url https://... --events domain.purchased,dns.updated"),R("List events:","domani webhooks events"),c();return}c(),j("Webhooks");let r=n.webhooks.map(o=>[ge.default.dim(o.id),v.url(o.url),o.events.length<=3?o.events.join(", "):`${o.events.length} events`,o.header_names?.join(", ")||ge.default.dim("none"),o.active?ge.default.green("active"):ge.default.dim("paused")]);B(["ID","URL","Events","Auth headers","Status"],r,[28,40,24,20,10]),c()}async function qc(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
198
- 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=Vt(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 K("webhook_create",{url:e.url,events:t,header_names:Wt(i)},e.json,e.fields);let s=C(!e.json);s.start("Creating webhook");let n=await _("/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(`${w.success} Webhook created`),e.json){y(r,e.fields);return}c(),j("Webhook Created"),d("ID",r.id),d("URL",v.url(r.url)),d("Events",r.events.join(", ")),d("Auth headers",r.header_names?.join(", ")||ge.default.dim("none")),d("Status",ge.default.green("active")),c(),console.log(` ${ge.default.yellow("!")} ${ge.default.bold("Secret:")} ${r.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.")}`),c()}async function Mc(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=Vt(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 K("webhook_update",{webhook_id:e.webhookId,...o,...r!==void 0?{header_names:Wt(r)}:{}},e.json,e.fields)}let i=C(!e.json);i.start("Updating webhook");let s=await _(`/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(`${w.success} Webhook updated`),e.json){y(n,e.fields);return}j("Webhook Updated"),d("ID",n.id),d("URL",v.url(n.url)),d("Events",n.events.join(", ")),d("Auth headers",n.header_names?.join(", ")||ge.default.dim("none")),d("Status",n.active?ge.default.green("active"):ge.default.dim("paused")),c()}async function Fc(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 K("webhook_delete",{webhook_id:e.webhookId},e.json,e.fields);let t=C(!e.json);t.start("Deleting webhook");let i=await _(`/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(`${w.success} Webhook deleted`),e.json){y(s,e.fields);return}console.log(` ${ge.default.dim("Pending deliveries have been cancelled.")}`),c()}async function Lc(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=C(!e.json);i.start("Loading deliveries");let s=await _(`/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(`${w.success} ${n.deliveries.length} delivery(ies)`),e.json){y(n,e.fields);return}if(n.deliveries.length===0){c(),console.log(` ${ge.default.dim("No deliveries yet.")}`),c();return}c(),j("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())]});B(["Event","Status","HTTP","Tries","Date"],r,[22,12,6,6,22]),c()}async function Vc(e,t){let i=C(!e);i.start("Loading event types");let s=await ve("/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(`${w.success} ${n.events.length} event type(s)`),e){y(n,t);return}c(),j("Webhook Event Types");let r=n.events.map(o=>[ge.default.cyan(o.type),ge.default.dim(o.description)]);B(["Event","Description"],r,[24,50]),c()}G();var _e=D(F(),1);L();we();async function sa(e,t){if(e||u("Domain is required",{hint:`Usage: domani sell <domain> --price <amount>
184
+ `),m=I.length}process.stdout.write(`${E.default.cyan("\u25C6")} Register a domain?
185
+ `),process.stdout.write("\x1B[?25l"),process.stdin.setRawMode(!0),process.stdin.resume();let le=I=>{let L=I.toString();if(L==="\x1B[A")d=Math.max(0,d-1),N();else if(L==="\x1B[B")d=Math.min(ee(),d+1),N();else if(L==="\r"){let te=H();if(f&&te.length===0)return;if(d<te.length)b=te[d]?.domain??null,k=!0;else{let ce=W()[d-te.length];ce==="more"?(a+=ze,r.length<a?y=!0:(d=Math.min(d,ee()),N())):(ce==="new"&&(b="__new__"),k=!0)}}else(L===""||L==="\x1B")&&(k=!0)};process.stdin.on("data",le),N();async function de(I){let L=new TextDecoder,te="",X="";for await(let ce of I){if(k)break;te+=L.decode(ce,{stream:!0});let ke=te.split(`
186
+ `);te=ke.pop()??"";for(let he of ke)if(he.startsWith("event: "))X=he.slice(7);else if(he.startsWith("data: ")){let ie=JSON.parse(he.slice(6));if(X==="error"&&(process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdout.write("\x1B[?25h"),u(ie.message||ie.error||"Search failed",{code:ie.code||"error"})),X==="result"){g=ie.domain,Gt(o,ie.domain);let be=Gt(r,ie.domain);be!==-1&&(be<d&&d--,d=Math.min(d,ee()),N())}if(X==="result"&&(ie.available||ie.for_sale||i)&&!lt(ie)){if(p===0){let be=r.findIndex(rt=>rt.price>ie.price);be===-1?r.push(ie):(r.splice(be,0,ie),be<=d&&d++)}else r.push(ie);N()}else if(X==="result"&&!ie.available&&!ie.error)o.length<8&&o.push(ie);else if(X==="done"){f=!1,d=Math.min(d,ee());let be=ze+p*ze;r.length<a&&n&&be<s.length&&(y=!0),y||N()}}}f=!1}for(await de(e);!k;)if(await new Promise(I=>{let L=setInterval(()=>{(k||y)&&(clearInterval(L),I())},16)}),y&&!k){y=!1;let I=ze+p*ze,L=s.slice(I,I+ze);p++,f=!0,d=Math.min(d,Math.max(0,r.length-1)),N();let te=new URLSearchParams;te.set("domains",L.map(X=>`${t}.${X}`).join(","));try{let X=await _e(`/api/domains/search?${te}`,{headers:{Accept:"text/event-stream"}});X.ok&&X.body?await de(X.body):(f=!1,N())}catch{f=!1,N()}}clearInterval(O),process.stdin.removeListener("data",le),process.stdin.isTTY&&process.stdin.setRawMode(!1),process.stdin.pause(),process.stdout.write("\x1B[?25h"),T();let P=b==="__new__",pe=P?null:b,ne=pe?r.find(I=>I.domain===pe)??null:null;return pe?process.stdout.write(`${E.default.dim("\u25C7")} Register a domain?
187
+ ${E.default.dim("\u2502")} ${E.default.bold(E.default.cyan(pe))}
188
+ ${E.default.dim("\u2514")}
189
+ `):process.stdout.write(`${E.default.dim("\u2514")}
190
+ `),{chosen:pe,chosenResult:ne,searchAgain:P,allTaken:r.length===0&&o.length>0,expanded:p>0}}async function Qo(e,t,i){if(!e){Re||u("Missing required argument: domain",{hint:"Usage: domani search <domain> [tlds...]",code:"missing_argument",json:i.json});let P=await De({message:"Search for a domain",placeholder:"e.g. myapp or myapp.dev"});(ae(P)||!P)&&process.exit(0),e=P}let n=t.map(P=>P.replace(/^\./,"")),s=i.tlds?.split(",").map(P=>P.trim())||[],r=[...new Set([...n,...s])];if(r.length>0&&bn(r,i),Y(e,i),e.includes(".")&&r.length===0){let P=C(!i.json);P.start(`Checking ${$.domain(e)}`);let[pe,ne]=await Promise.all([_e(`/api/domains/search?q=${encodeURIComponent(e)}`),_e(`/api/domains/${encodeURIComponent(e)}/og`).catch(()=>null)]),I=await pe.json();if(pe.ok||(P.stop("Search failed"),u(I.error||I.message,{hint:I.hint,status:pe.status,json:i.json,fields:i.fields})),i.json){let L=I.domain.split(".")[0];v({name:L,results:[I],total:1,available:I.available?1:0},i.fields);return}if(ci(I))P.stop(`${w.warning} ${$.domain(I.domain)} ${w.dot} ${E.default.yellow("not in public DNS")}`),c(),console.log(` ${er(I)}`),c();else if(lt(I))P.stop(`${w.warning} ${$.domain(I.domain)} ${w.dot} ${E.default.yellow(mi(I))}`),c(),console.log(` ${tr(I)}`),c();else if(I.available)if(P.stop(`${w.success} ${$.domain(I.domain)} ${w.dot} available ${w.dot} ${$.price(I.price)}/yr`),Re&&!i.json){let{buy:L}=await Promise.resolve().then(()=>(li(),Ri));await L([I.domain],{preChecked:{price:I.price,currency:I.currency}})}else c(),A("Register it:",`domani buy ${I.domain}`),c();else if(I.for_sale?.buyable)if(P.stop(`${w.info} ${$.domain(I.domain)} ${w.dot} ${E.default.cyan("for sale")} ${w.dot} ${$.price(I.for_sale.price)}`),Re&&!i.json){let{buy:L}=await Promise.resolve().then(()=>(li(),Ri));await L([I.domain],{preChecked:{price:I.for_sale.price,currency:I.for_sale.currency,marketplace:!0}})}else c(),A("Buy it:",`domani buy ${I.domain}`),c();else if(I.error)P.stop(`${E.default.dim("?")} ${$.domain(I.domain)} ${w.dot} ${E.default.dim("lookup failed")}`);else{let L;try{if(ne?.ok){let X=await ne.json();X?.title&&(L=X.title)}}catch{}let te=L?` ${w.dot} ${E.default.dim(`"${L}"`)}`:"";P.stop(`${w.error} ${$.domain(I.domain)} ${w.dot} ${E.default.red("taken")}${te}`)}return}let o=e.split(".")[0];if(Re&&!i.json&&r.length>0){let P=new URLSearchParams;P.set("domains",r.map(z=>`${o}.${z}`).join(",")),i.maxPrice&&P.set("max_price",i.maxPrice);let pe=await _e(`/api/domains/search?${P}`,{headers:{Accept:"text/event-stream"}});if(!pe.ok||!pe.body){u("Search failed",{json:i.json});return}let ne=[],I=new TextDecoder,L="",te="",X=C(!0);X.start(`Checking ${r.length} TLD${r.length>1?"s":""}`);for await(let z of pe.body){L+=I.decode(z,{stream:!0});let Zt=L.split(`
191
+ `);L=Zt.pop()??"";for(let Li of Zt)if(Li.startsWith("event: "))te=Li.slice(7);else if(Li.startsWith("data: ")&&te==="result"){let cr=JSON.parse(Li.slice(6));Gt(ne,cr.domain),ne.push(cr)}}X.stop("");let ce=Math.max(...r.map(z=>`${o}.${z}`.length))+2,ke=ne.filter(z=>z.available),he=ne.filter(ci),ie=ne.filter(lt),be=ne.filter(z=>!z.available&&!z.error&&!ci(z)&&!lt(z)),rt=ne.filter(z=>!z.available&&z.for_sale);for(let z of[...ke,...rt,...ie,...be.filter(Zt=>!Zt.for_sale),...he])ci(z)?console.log(` ${E.default.yellow("!")} ${E.default.dim(z.domain.padEnd(ce))} ${E.default.yellow("not in public DNS")}`):lt(z)?console.log(` ${E.default.yellow("!")} ${E.default.dim(z.domain.padEnd(ce))} ${E.default.yellow(mi(z))}`):z.available?console.log(` ${E.default.green("\u2713")} ${E.default.bold(E.default.white(z.domain.padEnd(ce)))} ${E.default.green($.price(z.price)+"/yr")}`):z.for_sale?console.log(` ${E.default.cyan("$")} ${E.default.bold(E.default.white(z.domain.padEnd(ce)))} ${E.default.cyan($.price(z.for_sale.price))} ${E.default.dim("(for sale)")}`):console.log(` ${E.default.dim("\u2717")} ${E.default.dim(z.domain.padEnd(ce))} ${E.default.dim("taken")}`);if(he.length>0||ie.length>0){c();for(let z of ie)console.log(` ${E.default.dim(tr(z))}`);for(let z of he)console.log(` ${E.default.dim(er(z))}`)}if(ke.length===0){console.log(` ${E.default.dim("No domains available")}`),c();return}let{buy:St}=await Promise.resolve().then(()=>(li(),Ri));if(ke.length===1){await St([ke[0].domain],{preChecked:{price:ke[0].price,currency:ke[0].currency}});return}let{select:hi,isCancel:gi}=await Promise.resolve().then(()=>(Ne(),Ts)),Fi=await hi({message:"Register one?",options:[...ke.map(z=>({value:z.domain,label:$.domain(z.domain),hint:$.price(z.price)+"/yr"})),{value:"__skip__",label:"Skip"}]});if(!gi(Fi)&&Fi!=="__skip__"){c();let z=ke.find(Zt=>Zt.domain===Fi);await St([Fi],{preChecked:z?{price:z.price,currency:z.currency}:void 0})}else c();return}if(Re&&!i.json){let P=await Zo();for(i.expand&&P.length>ui&&console.error(E.default.dim(` (--expand: checking the first ${ui} of ${P.length} TLDs - server limit per request)`));;){let pe=i.expand?P.slice(0,ui):P.slice(0,ze),ne=new URLSearchParams;ne.set("domains",pe.map(rt=>`${o}.${rt}`).join(",")),i.maxPrice&&ne.set("max_price",i.maxPrice);let I=C(!0);I.start(`Searching available domains for ${E.default.bold(o)}`);let L=await _e(`/api/domains/search?${ne}`,{headers:{Accept:"text/event-stream"}});if(!L.ok||!L.body){I.stop("Search failed");break}I.stop("");let te=!i.expand,{chosen:X,chosenResult:ce,searchAgain:ke}=await Wc(L.body,o,i.all??!1,te,P);if(X){c();let{buy:rt}=await Promise.resolve().then(()=>(li(),Ri)),St=ce?{price:ce.price,currency:ce.currency}:void 0;await rt([X],{preChecked:St});return}if(!ke)break;let{text:he,isCancel:ie}=await Promise.resolve().then(()=>(Ne(),Ts)),be=await he({message:"Search for a domain",placeholder:"e.g. myapp or myapp.dev"});if(ie(be)||!be)break;o=be.split(".")[0]}c();return}let a=o,d=await Zo(),f=r.length>0?r:i.expand?d.slice(0,ui):d.slice(0,ze);i.expand&&r.length===0&&d.length>ui&&console.error(`(--expand: checking the first ${ui} of ${d.length} TLDs - server limit per request; use --tlds to target others)`);let m=f.map(P=>`${a}.${P}`),p=new URLSearchParams;p.set("domains",m.join(",")),i.maxPrice&&p.set("max_price",i.maxPrice);let y=C(!i.json);y.start(`Searching available domains for ${E.default.bold(a)}`);let k=await _e(`/api/domains/search?${p}`,{headers:{Accept:"text/event-stream"}});if(!k.ok){y.stop("Search failed");try{let P=await k.json();u(P.error||P.message||`Server error (${k.status})`,{hint:P.hint,status:k.status,json:i.json,fields:i.fields})}catch{u(`Server error (${k.status})`,{status:k.status,json:i.json,fields:i.fields})}}let b=k.body;b||(y.stop("Search failed"),u("Empty response",{code:"error",json:i.json,fields:i.fields}));let g=[],S=!1,j=0,O=!1,T=new Set,W=i.all??!1;function H(){S||(S=!0,y.stop(`Checking TLDs for ${E.default.bold(a)}`),c())}function ee(P){H(),ci(P)?(console.log(` ${w.warning} ${E.default.dim(P.domain.padEnd(38))} ${E.default.yellow("not in public DNS")}`),console.log(` ${E.default.dim(er(P))}`)):lt(P)?(console.log(` ${w.warning} ${E.default.dim(P.domain.padEnd(38))} ${E.default.yellow(mi(P))}`),console.log(` ${E.default.dim(tr(P))}`)):P.available?console.log(` ${w.success} ${$.domain(P.domain).padEnd(37)} ${$.price(P.price)}${E.default.dim("/yr")}`):P.for_sale?console.log(` ${w.info} ${$.domain(P.domain).padEnd(37)} ${E.default.cyan($.price(P.for_sale.price))} ${E.default.dim("(for sale)")}`):P.error||console.log(` ${w.error} ${E.default.dim(P.domain.padEnd(38))} ${E.default.red("taken")}`)}function q(){S||y.message(`Checking TLDs for ${E.default.bold(a)} ${E.default.dim(`(${j} checked)`)}`)}let N=new TextDecoder,le="",de="";for await(let P of b){le+=N.decode(P,{stream:!0});let pe=le.split(`
192
+ `);le=pe.pop()??"";for(let ne of pe)if(ne.startsWith("event: "))de=ne.slice(7);else if(ne.startsWith("data: ")){let I=JSON.parse(ne.slice(6));if(de==="error")y.stop("Search failed"),u(I.message||I.error||"Search failed",{code:I.code||"error",json:i.json,fields:i.fields});else if(de==="result"){T.add(I.domain),j=T.size;let L=Gt(g,I.domain);(I.available||I.for_sale||W||ci(I)||lt(I))&&g.splice(L===-1?g.length:L,0,I),i.json||q()}else if(de==="done"){if(i.json){g.sort((ce,ke)=>ce.price-ke.price),v({name:a,results:g,total:I.total,available:I.available},i.fields);return}O=!0;for(let ce of g)ee(ce);S&&console.log(` ${E.default.dim("\u2500".repeat(50))}`);let L=I.total-I.available,te=I.total>=5&&L/I.total>=.5,X=`Checked ${I.total} TLDs \xB7 ${I.available} available${te?" \xB7 popular name":""}`;console.log(` ${E.default.dim(X)}`),I.available===0&&!i.expand&&r.length===0&&(c(),A("Try more TLDs:",`domani search ${a} --expand`))}}}if(!O&&!i.json)for(let P of g)ee(P);c()}li();G();var Ai=U(M(),1);F();$e();vn();function ea(e,t,i=process.env){let n=Jt(t,i);if(n!==void 0&&!e)throw new Error("--webhook is required when setting webhook authentication");return{request:{...e?{webhook_url:e}:{},...n!==void 0?{webhook_headers:n}:{}},preview:{...e?{webhook_url:e}:{},...n!==void 0?{webhook_header_names:Bt(n)}:{}}}}wn();async function ta(e,t){Y(e,t);let i={domain:e};t.slug&&(i.slug=t.slug),t.name&&(i.name=t.name);let n;try{n=ea(t.webhook,t)}catch(f){u(f instanceof Error?f.message:"Invalid webhook headers",{hint:"Set the named environment variable and retry.",code:"validation_error",json:t.json,fields:t.fields})}Object.assign(i,n.request),t.years&&(i.years=Number(t.years));let s=Ht(t.maxPrice,t);if(s!==void 0&&(i.max_price=s),t.paymentMethod&&(i.payment_method=t.paymentMethod),t.dryRun){let f={...i};delete f.webhook_headers,Object.assign(f,n.preview),K("POST /api/agents/provision",f,t.json,t.fields);return}let r=C(!t.json);r.start(`Provisioning ${$.domain(e)}`);let o=await _("/api/agents/provision",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(i)}),a=await o.json(),d=o.ok?void 0:At(a);if(d!==void 0&&(r.stop("Price changed - nothing was charged"),u(a.error,{code:"price_above_max",hint:Ms(d),data:{price:d},json:t.json,fields:t.fields})),o.ok||(r.stop("Provisioning failed"),u(a.error||"Provisioning failed",{hint:a.hint,status:o.status,json:t.json,fields:t.fields})),r.stop(`${$.domain(e)} is ready`),t.json){v(a,t.fields);return}if(c(),x("Agent identity"),l("Domain",`${a.domain} (${a.domain_status})`),l("Mailbox",a.mailbox?Ai.default.green(a.mailbox.address):Ai.default.yellow("pending DNS")),l("Webhook",a.webhook?a.webhook.url:Ai.default.dim("none")),a.webhook?.header_names.length&&l("Webhook auth",a.webhook.header_names.join(", ")),a.webhook?.secret&&l("Signing secret",a.webhook.secret),a.warnings?.length){c();for(let f of a.warnings)ve(Ai.default.yellow(f))}if(a.next_steps?.length){c(),x("Next");for(let f of a.next_steps)ve(f)}c()}G();var xt=U(M(),1);F();async function ia(e){let t=C(!e.json);t.start("Loading domains");let i=await _("/api/domains"),n=await i.json();if(i.ok||(t.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:i.status,json:e.json,fields:e.fields})),t.stop(`${n.domains.length} domain(s)`),e.json){v({...n,count:n.domains.length},e.fields);return}if(n.domains.length===0){c(),console.log(` ${xt.default.dim("No domains yet.")} Use: ${xt.default.cyan("domani buy <domain>")}`),c();return}let s=[30,12,12,14];x(`Your Domains (${n.domains.length})`,s.reduce((o,a)=>o+a,0)+s.length-1);let r=n.domains.map(o=>{let a=new Date(o.expiresAt).toLocaleDateString(),d=o.status==="active"?xt.default.green:o.status==="pending"?xt.default.yellow:xt.default.red,f=o.autoRenew?xt.default.green("on"):xt.default.dim("off");return[$.domain(o.domain),d(o.status),f,xt.default.dim(a)]});B(["Domain","Status","Auto-renew","Expires"],r,s),c()}zs();G();var ct=U(M(),1);F();function Hc(e){let t=new URLSearchParams;return e.kind&&t.set("kind",e.kind),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"),t.toString()}function na(e){return e==="second_level"?"second level":e==="alt_root"?"alt root, no public DNS":"tld"}async function sa(e){let t=C(!e.json);t.start("Loading TLDs");let i=await _e(`/api/tlds?${Hc(e)}`),n=await i.json();if(i.ok||(t.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:i.status,json:e.json,fields:e.fields})),t.stop(`${n.total} TLDs loaded`),e.json){v(n,e.fields);return}let s=n.tlds;if(s.length===0){c(),console.log(` ${ct.default.dim("No TLDs match your filters.")}`),c();return}x("TLD Pricing");let r=s.map(o=>[ct.default.bold(`.${o.tld}`),$.price(o.registration.toFixed(2))+ct.default.dim("/yr"),ct.default.dim("renew ")+$.price(o.renewal.toFixed(2))+ct.default.dim("/yr"),o.kind==="alt_root"?ct.default.yellow(na(o.kind)):ct.default.dim(na(o.kind))]);B(["TLD","Register","Renewal","Kind"],r,[22,16,20,24]),c(),console.log(` ${ct.default.dim(`${n.total} TLDs total`)}`),s.some(o=>o.kind==="alt_root")&&console.log(` ${w.warning} ${ct.default.yellow("alt root names are outside the IANA root zone: they do not resolve in public DNS, and Domani does not sell them.")}`),c()}G();var Te=U(M(),1);F();$e();async function ra(e,t){Y(e,t);let i=C(!t.json);i.start(`Looking up ${$.domain(e)}`);let[n,s]=await Promise.all([_e(`/api/domains/whois?q=${encodeURIComponent(e)}`),_e(`/api/domains/${encodeURIComponent(e)}/og`).catch(()=>null)]),r=await n.json(),o=null;try{s?.ok&&(o=await s.json())}catch{}if(n.ok||(i.stop("Lookup failed"),u(r.error||r.message,{hint:r.hint,status:n.status,json:t.json,fields:t.fields})),i.stop("WHOIS data retrieved"),t.json){v({...r,...o?{og:o}:{}},t.fields);return}if(x(`WHOIS ${$.domain(r.domain)}`),!r.registered){l("Status",`${w.success} ${Te.default.green("not registered")}`),c(),A("Register it:",`domani buy ${r.domain}`),c();return}if(l("Status",`${w.error} ${Te.default.red("registered")}`),(o?.title||o?.description)&&(c(),console.log(` ${Te.default.bold("Website preview")}`),console.log(` ${Te.default.dim("\u2500".repeat(50))}`),o.title&&l("Title",o.title),o.description&&l("Description",Te.default.dim(o.description.length>80?o.description.slice(0,80)+"\u2026":o.description)),c()),r.registrar&&l("Registrar",r.registrar),r.created&&l("Created",r.created),r.expires&&l("Expires",r.expires),r.days_until_expiry!=null){let d=r.days_until_expiry,f=d<30?Te.default.red:d<90?Te.default.yellow:Te.default.green;l("Days left",f(String(d)))}r.updated&&l("Updated",r.updated),l("DNSSEC",r.dnssec?Te.default.green("yes"):Te.default.dim("no")),r.nameservers?.length>0&&l("Nameservers",r.nameservers.map(d=>Te.default.cyan(d)).join(Te.default.dim(", "))),r.status?.length>0&&l("Status codes",Te.default.dim(r.status.join(", ")));let a=r.contacts?.registrant;a&&!r.redacted?(c(),console.log(` ${Te.default.bold("Registrant")}`),console.log(` ${Te.default.dim("\u2500".repeat(50))}`),a.name&&l("Name",a.name),a.organization&&l("Organization",a.organization),a.email&&l("Email",$.url(a.email)),a.country&&l("Country",a.country)):r.redacted&&l("Contact",Te.default.dim("redacted (WHOIS privacy)")),c()}G();Ne();var ut=U(M(),1);F();$e();async function oa(e,t){if(!e){Re||u("Missing required argument: prompt",{hint:'Usage: domani suggest "describe your project"',code:"missing_argument",json:t.json});let g=await De({message:"Describe your project or idea",placeholder:"e.g. AI coding assistant, pet food delivery..."});(ae(g)||!g)&&process.exit(0),e=g}let i=new URLSearchParams({prompt:e});if(t.count&&i.set("count",t.count),t.tlds&&i.set("tlds",t.tlds),t.tlds&&bn(t.tlds.split(",").map(g=>g.trim()),t),t.style&&i.set("style",t.style),t.lang&&i.set("lang",t.lang),t.json){let g=C(!1);g.start("Finding available domains");let S=t.timeout?parseInt(t.timeout,10)*1e3:6e4,j;try{j=await _e(`/api/domains/suggest?${i}`,{signal:AbortSignal.timeout(S)})}catch{g.stop("Failed"),u("Request timed out",{hint:"Suggest took too long. Try --timeout <seconds> to increase.",code:"timeout",json:t.json,fields:t.fields})}let O=await j.json();j.ok||(g.stop("Failed"),u(O.error||O.message,{hint:O.hint,status:j.status,json:t.json,fields:t.fields})),v(O,t.fields);return}let n=C(!0);n.start("Finding available domains");let s=t.timeout?parseInt(t.timeout,10)*1e3:6e4,r;try{r=await _e(`/api/domains/suggest?${i}`,{headers:{Accept:"text/event-stream"},signal:AbortSignal.timeout(s)})}catch{n.stop("Failed"),u("Request timed out",{hint:"Suggest took too long. Try --timeout <seconds> to increase.",code:"timeout"})}if(!r.ok){n.stop("Failed");try{let g=await r.json();u(g.error||g.message||`Server error (${r.status})`,{hint:g.hint,status:r.status})}catch{u(`Server error (${r.status})`,{status:r.status})}}let o=r.body;o||(n.stop("Failed"),u("Empty response"));let a=[],d=[],f=!1,m=0;function p(){f||(f=!0,n.stop("Finding available domains"),c())}let y=new TextDecoder,k="",b="";for await(let g of o){k+=y.decode(g,{stream:!0});let S=k.split(`
193
+ `);k=S.pop()??"";for(let j of S)if(j.startsWith("event: "))b=j.slice(7);else if(j.startsWith("data: "))try{let O=JSON.parse(j.slice(6));if(b==="result")Gt(a,O.domain)!==-1||Gt(d,O.domain)!==-1||m++,O.available?a.push(O):d.push(O),f||n.message(`Finding available domains ${ut.default.dim(`(${m} checked, ${a.length} available)`)}`);else if(b==="iteration")f||n.message(`Finding available domains ${ut.default.dim(`(round ${O.n})`)}`);else if(b==="done"){p();for(let T of a){let W=T.reason?` ${ut.default.dim(T.reason)}`:"";console.log(` ${w.success} ${$.domain(T.domain).padEnd(37)} ${$.price(T.price)}${ut.default.dim("/yr")}${W}`)}for(let T of d)console.log(` ${w.error} ${ut.default.dim(T.domain.padEnd(38))} ${lt(T)?ut.default.yellow(mi(T)):ut.default.red("taken")}`);console.log(` ${ut.default.dim("\u2500".repeat(50))}`),console.log(` ${ut.default.dim(`Found ${O.total} available \xB7 checked ${O.checked} \xB7 ${O.iterations} round${O.iterations>1?"s":""}`)}`)}else b==="error"&&(f||n.stop("Failed"),u(O.message))}catch{}}a.length===0&&d.length===0&&(f||n.stop("No results"),u("Could not find available domains for this prompt.")),c(),a.length>0&&(A("Register one:",`domani buy ${a[0].domain}`),c())}Vs();Xs();G();Ne();var mt=U(M(),1);F();$e();wi();async function aa(e){let t=e.maxConsecutiveFailures??10,i=0;for(let n=1;n<=e.maxAttempts;n++){let s=await e.fetchPlan().catch(()=>null);if(e.onTick?.(s,n),s!==null){if(i=0,e.isEligible(s))return{status:"eligible",plan:s}}else if(i++,i>=t)return{status:"unreachable",failures:i};n<e.maxAttempts&&await e.sleep(e.intervalMs)}return{status:"timeout",attempts:e.maxAttempts}}var Ti=U(M(),1);F();function Ei(e){if(e){c(),console.log(` ${Ti.default.bold(`Exit path (${e.managed_via})`)}`),console.log(` ${Ti.default.dim("Unlock:")} ${e.unlock}`),console.log(` ${Ti.default.dim("Auth code:")} ${e.auth_code}`);for(let t of e.notes||[])console.log(` ${Ti.default.yellow("!")} ${t}`)}}var Jc=6e4,Bc=1440;async function da(e,t){Y(e,t);let i=C(!t.json);i.start(`Planning safe adoption for ${$.domain(e)}`);let n=await _(`/api/domains/adoption-plan?domain=${encodeURIComponent(e)}`),s=await n.json();if(n.ok||(i.stop("Check failed"),u(s.error,{hint:s.hint,status:n.status,json:t.json,fields:t.fields})),s.options?.transfer?.eligible)i.stop(`${w.success} Eligible for transfer`);else{i.stop(`${w.error} Not eligible`);let a=s.options?.transfer;if(t.watch&&a?.eligible_at){let d=await _("/api/domains/transfer-watch",{method:"POST",body:JSON.stringify({domain:e})}),f=await d.json();if(d.ok||u(f.error||f.message,{hint:f.hint,status:d.status,json:t.json,fields:t.fields}),t.json){v(f,t.fields);return}x("Transfer Watch Registered"),l("Domain",$.domain(e)),l("Eligible from",f.eligible_at||a.eligible_at),f.hint&&(c(),console.log(` ${mt.default.dim(f.hint)}`)),c();return}if(t.watch){t.json||(console.log(` ${mt.default.dim(a?.reason||"Domain is not eligible for transfer yet.")}`),Ei(a?.guidance),c());let d=C(!t.json);d.start(`Watching ${$.domain(e)} until it becomes transferable (every 60s, Ctrl+C to stop)`);let f=await aa({fetchPlan:async()=>{let m=await _(`/api/domains/adoption-plan?domain=${encodeURIComponent(e)}`);return m.ok?m.json():null},isEligible:m=>!!m.options?.transfer?.eligible,sleep:m=>new Promise(p=>setTimeout(p,m)),intervalMs:Jc,maxAttempts:Bc});f.status!=="eligible"&&(d.stop(`${w.error} Watch ended`),u(f.status==="timeout"?"Domain did not become eligible within 24 hours.":"Gave up after repeated failures fetching the adoption plan.",{hint:"The transfer lock is disabled at the losing registrar; rerun with --watch once you have flipped it.",code:f.status==="timeout"?"watch_timeout":"watch_unreachable",json:t.json,fields:t.fields})),s=f.plan,d.stop(`${w.success} Now eligible for transfer`)}else{t.json||Ei(a?.guidance);let d=a?.eligible_at?`Eligible from ${a.eligible_at}. Rerun with --watch to register a server watch (email + webhook when the date arrives).`:"Fix the blocker above, then rerun - or rerun with --watch to poll until the domain becomes eligible and continue automatically.",f=t.json&&a?.guidance?` The registrar exit playbook is in the adoption plan (options.transfer.guidance, \`domani adopt ${e} --json\`).`:"";u(a?.reason||"Domain is not eligible for transfer.",{hint:[d+f,...s.warnings?.length?[s.warnings.join(" ")]:[]].join(" "),code:"not_eligible",json:t.json,fields:t.fields})}}if(t.dryRun)return K("transfer",{domain:e,eligible:!0,price:s.options.transfer.price,currency:s.options.transfer.currency||"USD",includes_renewal:!0,preserves_nameservers:!0,migrates_dns:!1,nameservers:s.current.nameservers,dns_provider:s.current.dns_provider,dnssec_enabled:s.current.dnssec_enabled},t.json,t.fields);if(!$t(t)){x("Transfer Safety Plan"),l("Registrar",s.current.registrar||"Unknown"),l("DNS provider",s.current.dns_provider),l("Nameservers",`${s.current.nameservers.length} preserved`),l("DNSSEC",s.current.dnssec_enabled?mt.default.yellow("Enabled, DS will be verified"):"Not enabled"),l("DNS migration","Not requested"),c();let a=s.options.transfer.price!=null?` for ${$.price(s.options.transfer.price.toFixed(2))}`:"",d=await Ve({message:`Transfer ${mt.default.bold(e)} to ${ei}${a}? Nameservers stay unchanged and 1 year is included.`});if(!d||typeof d=="symbol"){console.log(` ${mt.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}),s.options?.transfer?.guidance&&console.log(` ${mt.default.dim("Where to get it:")} ${s.options.transfer.guidance.auth_code}`);let a=await De({message:"Enter the EPP/auth code from your current registrar:",validate:d=>!d||d.trim().length===0?"Auth code is required":void 0});ae(a)&&process.exit(0),t.authCode=a}i.start(`Initiating transfer for ${$.domain(e)}`);let r=await _("/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(`${w.success} Transfer initiated`),t.json){v(o,t.fields);return}x("Transfer Initiated"),l("Domain",$.domain(o.domain)),l("Status",mt.default.yellow(o.status||"pending")),o.price&&l("Price",$.price(o.price)+mt.default.dim(` ${o.currency||"USD"}`)),o.payment_method&&l("Payment",o.payment_method),o.expires&&l("Expires",new Date(o.expires).toLocaleDateString()),o.hint&&(c(),console.log(` ${mt.default.dim(o.hint)}`)),c(),A("Check transfer progress:",`domani status ${o.domain}`),c()}G();var Pi=U(M(),1);F();$e();async function la(e,t){Y(e,t);let i=C(!t.json);i.start(`Inspecting ${$.domain(e)}`);let n=await _(`/api/domains/adoption-plan?domain=${encodeURIComponent(e)}`),s=await n.json();if(n.ok||(i.stop("Inspection failed"),u(s.error||s.message,{hint:s.hint,status:n.status,json:t.json,fields:t.fields})),i.stop(`${w.success} Adoption plan ready`),t.json){v(s,t.fields);return}if(x(`Adopt ${$.domain(s.domain)}`),l("Registrar",s.current.registrar||"Unknown"),l("DNS provider",s.current.dns_provider),l("Nameservers",s.current.nameservers.join(", ")||"None detected"),l("DNSSEC",s.current.dnssec_enabled?Pi.default.yellow("Enabled"):"Not enabled"),l("Account",s.account_state),l("Recommended",Pi.default.cyan(s.recommended_action)),c(),s.recommended_action==="connect"&&A("Connect free, without changing registrar or DNS:",`domani import ${s.domain}`),s.options.transfer.available){let r=s.options.transfer.price==null?"price unavailable":`$${s.options.transfer.price.toFixed(2)} ${s.options.transfer.currency}`;A(`Transfer registration for ${r}, preserving nameservers:`,`domani transfer ${s.domain}`),!s.options.transfer.eligible&&s.options.transfer.reason&&(console.log(` ${Pi.default.yellow("!")} ${s.options.transfer.reason}`),A("Wait for eligibility and transfer in one go:",`domani transfer ${s.domain} --watch`)),Ei(s.options.transfer.guidance)}for(let r of s.warnings||[])console.log(` ${Pi.default.yellow("!")} ${r}`);c()}G();Ne();var fi=U(M(),1);F();$e();Ze();wn();async function ca(e,t){e||(e=await ge()),Y(e,t);let i=t.years?parseInt(t.years,10):1;(isNaN(i)||i<1||i>10)&&u("--years must be between 1 and 10",{code:"validation_error",json:t.json,fields:t.fields});let n=Ht(t.maxPrice,t),s=`${i} year${i>1?"s":""}`,r=C(!t.json);r.start(`Checking ${$.domain(e)}`);let o=await _(`/api/domains/${encodeURIComponent(e)}`),a=await o.json();o.ok||(r.stop("Lookup failed"),u(a.error,{hint:a.hint,status:o.status,json:t.json,fields:t.fields}));let d=typeof a.renewal_price=="number"?a.renewal_price:void 0,f=d!==void 0?Ci(d*i):void 0;r.stop(d!==void 0?`${w.success} ${$.domain(e)} ${w.dot} renews at ${$.price(d.toFixed(2))}/yr`:`${$.domain(e)} ${w.dot} ${fi.default.dim("renewal price unknown")}`);let m=n??f;if(t.dryRun)return K("renew",{domain:e,years:i,price:f,currency:"USD",max_price:m},t.json,t.fields);if(!$t(t)){let b=await Ve({message:f!==void 0?`Renew ${fi.default.bold(e)} for ${s} for ${$.price(f.toFixed(2))}?`:`Renew ${fi.default.bold(e)} for ${s}? You will be charged.`});if(!b||typeof b=="symbol"){console.log(` ${fi.default.dim("Cancelled.")}`);return}}let p,y,k;for(;;){k=C(!t.json),k.start(`Renewing ${$.domain(e)}`),p=await _(`/api/domains/${encodeURIComponent(e)}/renew`,{method:"POST",body:JSON.stringify({years:i,...m!==void 0?{max_price:m}:{}})}),y=await p.json();let b=p.ok?void 0:At(y);if(b===void 0)break;k.stop("Price changed");let g=await Oi(b,m??b,y,"Renew",t);if(g===void 0)return;m=g}if(p.ok||(k.stop("Renewal failed"),u(y.error||y.message,{hint:y.hint,fixUrl:y.setup_url||y.payment_options?.card?.setup_url,status:p.status,json:t.json,fields:t.fields})),k.stop(`${w.success} Domain renewed`),t.json){v(y,t.fields);return}x("Renewal Complete"),l("Domain",$.domain(y.domain)),l("Years",String(y.renewed_years)),l("New expiry",new Date(y.new_expiry).toLocaleDateString()),y.price&&l("Price",$.price(y.price.toFixed(2))+fi.default.dim(` ${y.currency||"USD"}`)),y.payment_method&&l("Payment",y.payment_method),c(),A("Verify renewal:",`domani status ${y.domain}`),c()}G();var ft=U(M(),1);F();$e();async function ua(e,t){e||u("Domain is required",{hint:`Usage: domani import <domain>
194
+ domani import <domain> --verify`,code:"validation_error",json:t.json,fields:t.fields}),Y(e,t);let i=t.verify?"/api/domains/import/verify":"/api/domains/import",n=C(!t.json);n.start(t.verify?`Verifying ownership of ${$.domain(e)}`:`Initiating import for ${$.domain(e)}`);let s=await _(i,{method:"POST",body:JSON.stringify({domain:e})}),r=await s.json();if(s.ok||(n.stop(t.verify?"Verification failed":"Import failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:t.json,fields:t.fields})),t.json){n.stop(""),v(r,t.fields);return}t.verify?(n.stop(`${w.success} ${$.domain(e)} imported!`),x("Domain Imported"),l("Domain",$.domain(r.domain)),l("Status",ft.default.green(r.status||"active")),r.expires_at&&l("Expires",new Date(r.expires_at).toLocaleDateString()),r.registrar&&l("Registrar",r.registrar),c(),A("Check domain health:",`domani status ${r.domain}`),c()):(n.stop(`${w.success} Verification record ready`),x("Import Domain"),l("Domain",$.domain(r.domain)),l("Status",ft.default.yellow("pending verification")),c(),console.log(" Add this TXT record at your DNS provider:"),c(),console.log(` ${ft.default.dim("Type:")} ${ft.default.bold("TXT")}`),console.log(` ${ft.default.dim("Name:")} ${ft.default.bold(r.txt_record?.name||"@")}`),console.log(` ${ft.default.dim("Value:")} ${ft.default.bold(r.txt_record?.value||`domani-verify=${r.token}`)}`),c(),console.log(` ${ft.default.dim("DNS propagation may take a few minutes to 48 hours.")}`),c(),A("Once the record is set, verify:",`domani import ${e} --verify`),c())}Bs();wt();F();function ma(e){let t=Be();if(t||(c(),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?v({token:t}):console.log(t)}G();var Le=U(M(),1);F();async function fa(e,t){switch(e){case void 0:case"list":return Gc(t.json,t.fields);case"create":return Kc(t);case"revoke":return zc(t);default:u(`Unknown action: ${e}`,{hint:"Actions: list, create, revoke",code:"validation_error",json:t.json,fields:t.fields})}}async function Gc(e,t){let i=C(!e);i.start("Loading tokens");let n=await _("/api/tokens"),s=await n.json();if(n.ok||(i.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:n.status,json:e,fields:t})),i.stop(`${w.success} ${s.tokens.length} token(s)`),e){v(s,t);return}if(s.tokens.length===0){c(),console.log(` ${Le.default.dim("No tokens.")}`),c(),A("Create one:",'domani tokens create --name "My App"'),c();return}c(),x("API Tokens");let r=s.tokens.map(o=>{let a;o.expired?a=Le.default.red("Expired"):o.expiresAt?a=Le.default.dim(`Expires ${new Date(o.expiresAt).toLocaleDateString()}`):a=Le.default.dim("No expiration");let d=o.scopes.includes("*")?Le.default.dim("all"):Le.default.dim(o.scopes.join(", "));return[Le.default.dim(o.id),Le.default.bold(o.name),o.agent_identity?Le.default.dim(o.agent_identity.name||o.agent_identity.slug):Le.default.dim("\u2014"),d,a]});B(["ID","Name","Agent","Scopes","Expiration"],r,[28,16,18,32,20]),c()}async function Kc(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=C(!e.json);i.start("Creating token");let n=await _("/api/tokens",{method:"POST",body:JSON.stringify(t)}),s=await n.json();if(n.ok||(i.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:n.status,json:e.json,fields:e.fields})),i.stop(`${w.success} Token created`),e.json){v(s,e.fields);return}c(),x("Token Created"),l("ID",s.id),l("Name",s.name),l("Scopes",s.scopes?.includes("*")?"All (full access)":s.scopes?.join(", ")||"All"),s.agent_identity&&l("Agent",s.agent_identity.name||s.agent_identity.slug),l("Expires",s.expiresAt?new Date(s.expiresAt).toLocaleString():"Never"),c(),console.log(` ${Le.default.yellow("!")} ${Le.default.bold("Key:")} ${s.key}`),console.log(` ${Le.default.dim("Save this key - it will not be shown again.")}`),c()}async function zc(e){e.tokenId||u("Token ID required",{hint:`Usage: domani tokens revoke --token-id <id>
195
+ Run 'domani tokens list' to see your tokens.`,code:"validation_error",json:e.json,fields:e.fields});let t=C(!e.json);t.start("Revoking token");let i=await _(`/api/tokens/${encodeURIComponent(e.tokenId)}`,{method:"DELETE"}),n=await i.json();if(i.ok||(t.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:i.status,json:e.json,fields:e.fields})),t.stop(`${w.success} Token revoked`),e.json){v(n,e.fields);return}console.log(` ${Le.default.dim("Any applications using this key will need a new one.")}`),c()}G();var Ee=U(M(),1);F();$e();Ze();async function pa(e,t){e||(e=await ge()),Y(e,t);let i=t.autoRenew!==void 0,n=t.whoisPrivacy!==void 0,s=t.securityLock!==void 0;if(!i&&!n&&!s)return Yc(e,t.json,t.fields);let r={};if(i){let f=ir(t.autoRenew);f===null&&u("--auto-renew must be on or off",{code:"validation_error",json:t.json,fields:t.fields}),r.auto_renew=f}if(n){let f=ir(t.whoisPrivacy);f===null&&u("--whois-privacy must be on or off",{code:"validation_error",json:t.json,fields:t.fields}),r.whois_privacy=f}if(s){let f=ir(t.securityLock);f===null&&u("--security-lock must be on or off",{code:"validation_error",json:t.json,fields:t.fields}),r.security_lock=f}if(t.dryRun)return K("settings_update",{domain:e,...r},t.json,t.fields);let o=C(!t.json);o.start(`Updating ${$.domain(e)}`);let a=await _(`/api/domains/${encodeURIComponent(e)}/settings`,{method:"PUT",body:JSON.stringify(r)}),d=await a.json();if(a.ok||(o.stop("Failed"),u(d.error||d.message,{hint:d.hint,status:a.status,json:t.json,fields:t.fields})),o.stop(`${w.success} Settings updated`),t.json){v(d,t.fields);return}x("Settings Updated"),l("Domain",$.domain(d.domain)),d.auto_renew!==void 0&&l("Auto-renew",d.auto_renew?Ee.default.green("on"):Ee.default.dim("off")),d.whois_privacy!==void 0&&l("WHOIS privacy",d.whois_privacy?Ee.default.green("on"):Ee.default.dim("off")),d.security_lock!==void 0&&l("Security lock",d.security_lock?Ee.default.green("locked"):Ee.default.dim("unlocked")),d.hint&&l("",Ee.default.dim(d.hint)),c()}async function Yc(e,t,i){let n=C(!t);n.start(`Loading ${$.domain(e)}`);let s=await _(`/api/domains/${encodeURIComponent(e)}`),r=await s.json();if(s.ok||(n.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:t,fields:i})),n.stop(`${w.success} ${$.domain(e)}`),t){v(r,i);return}x("Domain Settings"),l("Domain",$.domain(r.domain)),l("Status",r.status==="active"?Ee.default.green(r.status):Ee.default.yellow(r.status)),l("Auto-renew",r.auto_renew?Ee.default.green("on"):Ee.default.dim("off")),r.registrar&&(l("WHOIS privacy",r.registrar.whois_privacy?Ee.default.green("on"):Ee.default.dim("off")),l("Security lock",r.registrar.security_lock?Ee.default.green("locked"):Ee.default.dim("unlocked"))),l("Expires",new Date(r.expires_at).toLocaleDateString()+Ee.default.dim(` (${r.days_until_expiry} days)`)),c(),A("Toggle auto-renew:",`domani settings ${e} --auto-renew off`),A("Toggle WHOIS privacy:",`domani settings ${e} --whois-privacy off`),A("Toggle security lock:",`domani settings ${e} --security-lock off`),A("Get transfer auth code:",`domani auth-code ${e}`),c()}function ir(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}G();var Kt=U(M(),1);F();$e();Ze();async function ha(e,t){e||(e=await ge()),Y(e,t);let i=C(!t.json);i.start(`Getting auth code for ${$.domain(e)}`);let n=await _(`/api/domains/${encodeURIComponent(e)}/auth-code`),s=await n.json();if(n.ok||(i.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:n.status,json:t.json,fields:t.fields})),i.stop(`${w.success} Auth code retrieved`),t.json){v(s,t.fields);return}if(x("Auth Code"),l("Domain",$.domain(s.domain)),l("Auth code",Kt.default.bold(Kt.default.green(s.auth_code))),s.was_unlocked&&l("",Kt.default.yellow("Domain was automatically unlocked to allow transfer.")),s.hint&&(c(),console.log(` ${Kt.default.dim(s.hint)}`)),s.next_steps?.length){c();for(let r of s.next_steps)console.log(` ${Kt.default.dim("\u2192")} ${Kt.default.dim(r)}`)}c(),A("Check transfer status:",`domani transfer-away ${e}`),A("Re-lock domain:",`domani settings ${e} --security-lock on`),c()}G();var jt=U(M(),1);F();$e();Ze();var Xc={none:jt.default.dim,pending:jt.default.yellow,approved:jt.default.yellow,completed:jt.default.green,rejected:jt.default.red,expired:jt.default.red};async function ga(e,t){e||(e=await ge()),Y(e,t);let i=C(!t.json);i.start(`Checking transfer status for ${$.domain(e)}`);let n=await _(`/api/domains/${encodeURIComponent(e)}/transfer-away`),s=await n.json();if(n.ok||(i.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:n.status,json:t.json,fields:t.fields})),i.stop(`${w.success} ${$.domain(e)}`),t.json){v(s,t.fields);return}x("Transfer Away Status"),l("Domain",$.domain(s.domain));let r=Xc[s.status]||jt.default.dim;l("Status",r(s.status)),s.gaining_registrar&&l("New registrar",s.gaining_registrar),s.request_date&&l("Requested",new Date(s.request_date).toLocaleDateString()),s.hint&&(c(),console.log(` ${jt.default.dim(s.hint)}`)),c(),s.status==="none"?A("Get auth code to start:",`domani auth-code ${e}`):s.status==="pending"||s.status==="approved"?A("Check again later:",`domani transfer-away ${e}`):s.status==="completed"?A("Search for a new domain:","domani search <name>"):(s.status==="rejected"||s.status==="expired")&&A("Retry with a new auth code:",`domani auth-code ${e}`),c()}G();Ne();var Cn=U(M(),1);F();async function ya(e,t){return e==="set"?Qc(t):Zc(t)}async function Zc(e){let t=C(!e.json);t.start("Loading contact info");let i=await _("/api/me/contact"),n=await i.json();if(i.ok||(t.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:i.status,json:e.json,fields:e.fields})),t.stop(`${w.success} Contact info`),e.json){v(n,e.fields);return}if(x("Contact Info"),!n.has_contact){console.log(` ${w.warning} ${Cn.default.yellow("No contact info set.")} Run ${Cn.default.bold("domani contact set")} to add.`),c(),console.log(` ${Cn.default.dim("Contact info is required before purchasing domains.")}`),c();return}let s=n.contact;l("Name",`${s.first_name} ${s.last_name}`),s.org_name&&l("Organization",s.org_name),l("Address",s.address1),s.address2&&l("",s.address2),l("",`${s.city}, ${s.state} ${s.postal_code}`),l("Country",s.country),l("Phone",s.phone),l("Email",s.email),c()}async function Qc(e){let t={},i=e.firstName||e.lastName||e.address1;if(!Re&&!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"],d={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"},f=a.filter(m=>!e[m]);f.length>0&&u(`Missing required flags: ${f.map(m=>`--${m.replace(/[A-Z]/g,p=>`-${p.toLowerCase()}`)}`).join(", ")}`,{code:"missing_argument",json:e.json});for(let[m,p]of Object.entries(d)){let y=e[m];y&&(t[p]=y)}}else{let a=await _("/api/me/contact"),f=(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 p of m){let y=f?.[p.key]||"",k=await De({message:p.message,placeholder:p.placeholder,defaultValue:y,validate:p.required?g=>g?.trim()?void 0:`${p.message} is required`:void 0});ae(k)&&process.exit(0);let b=k.trim();b&&(t[p.key]=b)}}if(e.dryRun)return K("contact_set",t,e.json,e.fields);let n=C(!e.json);n.start("Saving contact info");let s=await _("/api/me/contact",{method:"PUT",body:JSON.stringify(t)}),r=await s.json();if(s.ok||(n.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:e.json,fields:e.fields})),n.stop(`${w.success} Contact info saved`),e.json){v(r,e.fields);return}x("Contact Saved");let o=r.contact;l("Name",`${o.first_name} ${o.last_name}`),o.org_name&&l("Organization",o.org_name),l("Address",o.address1),o.address2&&l("",o.address2),l("",`${o.city}, ${o.state} ${o.postal_code}`),l("Country",o.country),l("Phone",o.phone),l("Email",o.email),c(),A("Search for a domain:","domani search <name>"),c()}G();var qe=U(M(),1);F();$e();Ze();async function va(e,t,i,n){if(e||(e=await ge()),Y(e,n),!t)return eu(e,n.json,n.fields);switch(t){case"enable":case"on":return n.dryRun?K("parking_enable",{domain:e},n.json,n.fields):ba(e,!0,n.json,n.fields);case"disable":case"off":return n.dryRun?K("parking_disable",{domain:e},n.json,n.fields):ba(e,!1,n.json,n.fields);case"price":{i||u("Price required",{hint:"Usage: domani parking <domain> price <amount>",code:"validation_error",json:n.json,fields:n.fields});let s=parseFloat(i);return(isNaN(s)||s<=0)&&u("Price must be a positive number",{hint:`Got: "${i}"`,code:"validation_error",json:n.json,fields:n.fields}),n.dryRun?K("parking_price",{domain:e,price:s},n.json,n.fields):wa(e,s,n.json,n.fields)}case"unprice":case"unlist":return n.dryRun?K("parking_unlist",{domain:e},n.json,n.fields):wa(e,null,n.json,n.fields);default:u(`Unknown action: ${t}`,{hint:"Actions: enable, disable, price <amount>, unprice",code:"validation_error",json:n.json,fields:n.fields})}}async function eu(e,t,i){let n=C(!t);n.start(`Loading ${$.domain(e)}`);let s=await _(`/api/domains/${encodeURIComponent(e)}`),r=await s.json();if(s.ok||(n.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:t,fields:i})),n.stop(`${w.success} ${$.domain(e)}`),t){v({domain:r.domain,parking_enabled:r.parking_enabled,listing_price:r.listing_price},i);return}x("Parking"),l("Domain",$.domain(r.domain)),l("Parking",r.parking_enabled?qe.default.green("enabled"):qe.default.dim("disabled")),l("Listing",r.listing_price?`${$.price(r.listing_price)} ${qe.default.dim("(for sale)")}`:qe.default.dim("not listed")),c(),A("Enable parking:",`domani parking ${e} enable`),A("Set sale price:",`domani parking ${e} price 499`),A("View analytics:",`domani analytics ${e}`),c()}async function ba(e,t,i,n){let s=C(!i);s.start(`${t?"Enabling":"Disabling"} parking for ${$.domain(e)}`);let r=await _(`/api/domains/${encodeURIComponent(e)}/parking`,{method:"PUT",body:JSON.stringify({enabled:t})}),o=await r.json();if(r.status===409&&o.requires_confirmation){if(s.stop(`${w.warning} DNS records will be replaced`),i){v(o,n);return}console.log(`
196
+ ${qe.default.yellow("Enabling parking will replace these DNS records:")}`);for(let a of o.existing_dns||[])console.log(` ${qe.default.dim(a.type)} ${a.name} ${qe.default.dim("\u2192")} ${a.value}`);console.log(`
197
+ ${qe.default.dim("Run again with --confirm to proceed (not implemented yet).")}`),console.log(` ${qe.default.dim("Or use the dashboard to confirm.")}`),c();return}if(r.ok||(s.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:i,fields:n})),s.stop(`${w.success} Parking ${t?"enabled":"disabled"}`),i){v(o,n);return}x("Parking Updated"),l("Domain",$.domain(o.domain)),l("Parking",o.parking_enabled?qe.default.green("enabled"):qe.default.dim("disabled")),o.hint&&l("",qe.default.dim(o.hint)),c()}async function wa(e,t,i,n){let s=C(!i);s.start(t!==null?`Setting price for ${$.domain(e)} to ${$.price(t)}`:`Removing listing for ${$.domain(e)}`);let r=await _(`/api/domains/${encodeURIComponent(e)}/parking`,{method:"PUT",body:JSON.stringify({listing_price:t})}),o=await r.json();if(r.ok||(s.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:i,fields:n})),s.stop(`${w.success} ${t!==null?"Price set":"Listing removed"}`),i){v(o,n);return}x("Listing Updated"),l("Domain",$.domain(o.domain)),l("Listing",o.listing_price?`${$.price(o.listing_price)} ${qe.default.dim("(for sale)")}`:qe.default.dim("not listed")),o.hint&&l("",qe.default.dim(o.hint)),c()}G();var Ye=U(M(),1);F();$e();Ze();var tu=" \u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588";function iu(e){let t=Math.max(...e,1);return e.map(i=>tu[Math.min(Math.round(i/t*8),8)]).join("")}async function $a(e,t){e||(e=await ge()),Y(e,t);let i=C(!t.json);i.start(`Loading analytics for ${$.domain(e)}`);let n=await _(`/api/domains/${encodeURIComponent(e)}/analytics`),s=await n.json();if(n.ok||(i.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:n.status,json:t.json,fields:t.fields})),i.stop("Analytics loaded"),t.json){v(s,t.fields);return}if(c(),x(`Analytics: ${$.domain(e)}`),l("Views (7d)",Ye.default.cyan(s.views_7d.toLocaleString())),l("Views (30d)",Ye.default.cyan(s.views_30d.toLocaleString())),l("Inquiries",Ye.default.cyan(String(s.inquiries_30d))),l("Conversion",s.conversion_rate>0?Ye.default.green(`${s.conversion_rate}%`):Ye.default.dim("0%")),s.daily_views&&s.daily_views.length>0){let r=s.daily_views.map(f=>f.views),o=iu(r),a=s.daily_views[0].date.slice(5),d=s.daily_views[s.daily_views.length-1].date.slice(5);c(),console.log(` ${Ye.default.dim(a)} ${Ye.default.cyan(o)} ${Ye.default.dim(d)}`)}if(s.recent_inquiries&&s.recent_inquiries.length>0){c(),console.log(` ${Ye.default.bold("Recent Inquiries")}`);let r=s.recent_inquiries.map(o=>[Ye.default.dim(o.email),o.offer?$.price(o.offer):Ye.default.dim("-"),Ye.default.dim(new Date(o.date).toLocaleDateString())]);B(["Email","Offer","Date"],r,[30,12,14])}c(),A("Set a listing price:",`domani parking ${e} price <amount>`),A("Set up email:",`domani email setup ${e}`),A("Domain settings:",`domani settings ${e}`),c()}G();var ye=U(M(),1);F();vn();async function ka(e,t){switch(e){case void 0:case"list":return su(t.json,t.fields);case"create":return ru(t);case"update":return ou(t);case"delete":return au(t);case"deliveries":return du(t);case"replay":return nu(t);case"events":return lu(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 nu(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=C(!e.json);t.start("Replaying webhook delivery");let i=await _(`/api/webhooks/${encodeURIComponent(e.webhookId)}/deliveries/${encodeURIComponent(e.deliveryId)}/replay`,{method:"POST",body:JSON.stringify({idempotency_key:e.idempotencyKey})}),n=await i.json();if(i.ok||(t.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:i.status,json:e.json,fields:e.fields})),t.stop(`${w.success} Webhook replay ${n.status}`),e.json)return v(n,e.fields);x("Webhook Replay Receipt"),l("Delivery",n.delivery_id),l("Original",n.original_delivery_id),l("Status",n.status),l("Attempts",n.attempts),l("Idempotent retry",n.idempotent_replay?"yes":"no"),c()}async function su(e,t){let i=C(!e);i.start("Loading webhooks");let n=await _("/api/webhooks"),s=await n.json();if(n.ok||(i.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:n.status,json:e,fields:t})),i.stop(`${w.success} ${s.webhooks.length} webhook(s)`),e){v(s,t);return}if(s.webhooks.length===0){c(),console.log(` ${ye.default.dim("No webhooks configured.")}`),c(),A("Create one:","domani webhooks create --url https://... --events domain.purchased,dns.updated"),A("List events:","domani webhooks events"),c();return}c(),x("Webhooks");let r=s.webhooks.map(o=>[ye.default.dim(o.id),$.url(o.url),o.events.length<=3?o.events.join(", "):`${o.events.length} events`,o.header_names?.join(", ")||ye.default.dim("none"),o.active?ye.default.green("active"):ye.default.dim("paused")]);B(["ID","URL","Events","Auth headers","Status"],r,[28,40,24,20,10]),c()}async function ru(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
198
+ 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=Jt(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 K("webhook_create",{url:e.url,events:t,header_names:Bt(i)},e.json,e.fields);let n=C(!e.json);n.start("Creating webhook");let s=await _("/api/webhooks",{method:"POST",body:JSON.stringify({url:e.url,events:t,...i!==void 0?{headers:i}:{}})}),r=await s.json();if(s.ok||(n.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:e.json,fields:e.fields})),n.stop(`${w.success} Webhook created`),e.json){v(r,e.fields);return}c(),x("Webhook Created"),l("ID",r.id),l("URL",$.url(r.url)),l("Events",r.events.join(", ")),l("Auth headers",r.header_names?.join(", ")||ye.default.dim("none")),l("Status",ye.default.green("active")),c(),console.log(` ${ye.default.yellow("!")} ${ye.default.bold("Secret:")} ${r.secret}`),console.log(` ${ye.default.dim("Save this secret - it won't be shown again.")}`),console.log(` ${ye.default.dim("Use it to verify payloads with HMAC-SHA256.")}`),c()}async function ou(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=Jt(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 K("webhook_update",{webhook_id:e.webhookId,...o,...r!==void 0?{header_names:Bt(r)}:{}},e.json,e.fields)}let i=C(!e.json);i.start("Updating webhook");let n=await _(`/api/webhooks/${encodeURIComponent(e.webhookId)}`,{method:"PATCH",body:JSON.stringify(t)}),s=await n.json();if(n.ok||(i.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:n.status,json:e.json,fields:e.fields})),i.stop(`${w.success} Webhook updated`),e.json){v(s,e.fields);return}x("Webhook Updated"),l("ID",s.id),l("URL",$.url(s.url)),l("Events",s.events.join(", ")),l("Auth headers",s.header_names?.join(", ")||ye.default.dim("none")),l("Status",s.active?ye.default.green("active"):ye.default.dim("paused")),c()}async function au(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 K("webhook_delete",{webhook_id:e.webhookId},e.json,e.fields);let t=C(!e.json);t.start("Deleting webhook");let i=await _(`/api/webhooks/${encodeURIComponent(e.webhookId)}`,{method:"DELETE"}),n=await i.json();if(i.ok||(t.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:i.status,json:e.json,fields:e.fields})),t.stop(`${w.success} Webhook deleted`),e.json){v(n,e.fields);return}console.log(` ${ye.default.dim("Pending deliveries have been cancelled.")}`),c()}async function du(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=C(!e.json);i.start("Loading deliveries");let n=await _(`/api/webhooks/${encodeURIComponent(e.webhookId)}/deliveries${t}`),s=await n.json();if(n.ok||(i.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:n.status,json:e.json,fields:e.fields})),i.stop(`${w.success} ${s.deliveries.length} delivery(ies)`),e.json){v(s,e.fields);return}if(s.deliveries.length===0){c(),console.log(` ${ye.default.dim("No deliveries yet.")}`),c();return}c(),x("Deliveries");let r=s.deliveries.map(o=>{let a=o.status==="delivered"?ye.default.green("delivered"):o.status==="failed"?ye.default.red("failed"):ye.default.yellow("pending");return[o.event_type,a,o.http_status?String(o.http_status):ye.default.dim("-"),String(o.attempts),ye.default.dim(new Date(o.created_at).toLocaleString())]});B(["Event","Status","HTTP","Tries","Date"],r,[22,12,6,6,22]),c()}async function lu(e,t){let i=C(!e);i.start("Loading event types");let n=await _e("/api/webhooks/events"),s=await n.json();if(n.ok||(i.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:n.status,json:e,fields:t})),i.stop(`${w.success} ${s.events.length} event type(s)`),e){v(s,t);return}c(),x("Webhook Event Types");let r=s.events.map(o=>[ye.default.cyan(o.type),ye.default.dim(o.description)]);B(["Event","Description"],r,[24,50]),c()}G();var Se=U(M(),1);F();$e();async function _a(e,t){if(e||u("Domain is required",{hint:`Usage: domani sell <domain> --price <amount>
199
199
  domani sell <domain> --verify
200
200
  domani sell <domain> --status
201
- domani sell <domain> --cancel`,code:"validation_error",json:t.json,fields:t.fields}),Y(e,t),t.status)return Jc(e,t);if(t.verify)return Hc(e,t);if(t.cancel)return Bc(e,t);if(t.transferCode)return Gc(e,t.transferCode,t);if(t.price)return Wc(e,t);u("No action specified",{hint:`Usage: domani sell <domain> --price <amount>
201
+ domani sell <domain> --cancel`,code:"validation_error",json:t.json,fields:t.fields}),Y(e,t),t.status)return mu(e,t);if(t.verify)return uu(e,t);if(t.cancel)return fu(e,t);if(t.transferCode)return pu(e,t.transferCode,t);if(t.price)return cu(e,t);u("No action specified",{hint:`Usage: domani sell <domain> --price <amount>
202
202
  domani sell <domain> --verify
203
203
  domani sell <domain> --status
204
204
  domani sell <domain> --cancel
205
- domani sell <domain> --transfer-code <code>`,code:"validation_error",json:t.json,fields:t.fields})}async function Wc(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=C(!t.json);s.start(`Listing ${v.domain(e)} for sale`);let n={domain:e,price:i};t.description&&(n.description=t.description);let r=await _("/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(""),y(o,t.fields);return}(o.listing?.status??"pending_verification")==="active"?(s.stop(`${w.success} Listed for sale`),j("Sell Domain"),d("Domain",v.domain(o.listing?.domain||e)),d("Price",v.price(i)),d("Status",_e.default.green("active")),c(),console.log(` ${_e.default.dim("Your listing is live on the marketplace.")}`),c()):(s.stop(`${w.success} Verification record ready`),j("Sell Domain"),d("Domain",v.domain(o.listing?.domain||e)),d("Price",v.price(i)),d("Status",_e.default.yellow("pending verification")),c(),console.log(" Add this TXT record at your DNS provider:"),c(),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}`)}`),c(),console.log(` ${_e.default.dim("DNS propagation may take a few minutes to 48 hours.")}`),c(),R("Once the record is set, verify:",`domani sell ${e} --verify`),c())}async function Hc(e,t){let i=C(!t.json);i.start(`Verifying ownership of ${v.domain(e)}`);let s=await _("/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(""),y(n,t.fields);return}i.stop(`${w.success} ${v.domain(e)} is now listed for sale!`),j("Domain Listed"),d("Domain",v.domain(n.domain||e)),d("Status",_e.default.green(n.status||"active")),n.price&&d("Price",v.price(n.price)),c(),R("Check listing status:",`domani sell ${e} --status`),R("View your deals:","domani deals"),c()}async function Jc(e,t){let i=C(!t.json);i.start(`Checking listing status for ${v.domain(e)}`);let s=await _(`/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(`${w.success} Listing status loaded`),t.json){y(n,t.fields);return}let r=n.listing;if(j("Listing Status"),d("Domain",v.domain(n.domain||e)),r){let o=r.status;d("Status",o==="active"?_e.default.green(o):_e.default.yellow(o||"unknown")),r.price&&d("Price",v.price(r.price)),r.description&&d("Description",r.description),r.created_at&&d("Listed",_e.default.dim(new Date(r.created_at).toLocaleDateString()))}else d("Status",_e.default.dim("No listing found"));n.deal&&d("Deal",`${n.deal.status} ($${n.deal.price})`),c()}async function Bc(e,t){let i=C(!t.json);i.start(`Removing ${v.domain(e)} from sale`);let s=await _(`/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(""),y(n,t.fields);return}i.stop(`${w.success} ${v.domain(e)} removed from sale`),c()}async function Gc(e,t,i){let s=C(!i.json);s.start(`Looking up active deal for ${v.domain(e)}`);let n=await _(`/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(h=>h.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.
206
- 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 f=await _(`/api/deals/${encodeURIComponent(l)}`,{method:"PATCH",body:JSON.stringify({auth_code:t})}),m=await f.json();if(f.ok||(s.stop("Failed"),u(m.error||m.message,{hint:m.hint,status:f.status,json:i.json,fields:i.fields})),i.json){s.stop(""),y(m,i.fields);return}s.stop(`${w.success} Transfer code submitted for ${v.domain(e)}`),j("Transfer Code Submitted"),d("Domain",v.domain(e)),d("Deal",_e.default.dim(l)),d("Status",_e.default.green(m.status||"code_submitted")),c(),R("Track the deal:",`domani deals ${l}`),c()}G();var $e=D(F(),1);L();async function na(e,t){return e?Yc(e,t):zc(t)}function Kc(e){let t=new URLSearchParams;e.role&&t.set("role",e.role),e.status&&t.set("status",e.status),e.limit&&t.set("limit",e.limit),e.cursor&&t.set("cursor",e.cursor);let i=t.toString();return i?`?${i}`:""}async function zc(e){let t=C(!e.json);t.start("Loading deals");let i=Kc(e),s=await _(`/api/deals${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.deals||n.data||[];if(t.stop(`${w.success} ${r.length} deal(s)`),e.json){y(n,e.fields);return}if(r.length===0){c(),console.log(` ${$e.default.dim("No deals found.")}`),c(),R("List a domain for sale:","domani sell <domain> --price <amount>"),c();return}c(),j("Deals");let o=r.map(a=>{let l=a.status==="completed"?$e.default.green:a.status==="active"?$e.default.cyan:a.status==="cancelled"?$e.default.red:$e.default.yellow;return[v.domain(a.domain),v.price(a.price),l(a.status),$e.default.dim(a.role||"-"),$e.default.dim(new Date(a.created_at).toLocaleDateString())]});B(["Domain","Price","Status","Role","Created"],o,[28,12,14,10,14]),c(),n.next_cursor&&(console.log(` ${$e.default.dim(`More: --cursor ${n.next_cursor}`)}`),c())}async function Yc(e,t){let i=C(!t.json);i.start(`Loading deal ${$e.default.dim(e)}`);let s=await _(`/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(`${w.success} Deal loaded`),t.json){y(n,t.fields);return}let r=n.deal||n;j("Deal Details"),d("ID",$e.default.dim(r.id)),d("Domain",v.domain(r.domain)),d("Price",v.price(r.price));let o=r.status==="completed"?$e.default.green:r.status==="active"?$e.default.cyan:r.status==="cancelled"?$e.default.red:$e.default.yellow;d("Status",o(r.status)),r.role&&d("Your Role",r.role),r.buyer&&d("Buyer",$e.default.dim(r.buyer)),r.seller&&d("Seller",$e.default.dim(r.seller)),r.created_at&&d("Created",$e.default.dim(new Date(r.created_at).toLocaleDateString())),r.updated_at&&d("Updated",$e.default.dim(new Date(r.updated_at).toLocaleDateString())),c();let a=r.events||[];if(a.length>0){j("Timeline");for(let l of a){let f=$e.default.dim(new Date(l.created_at).toLocaleString()),m=l.status==="completed"?w.success:l.status==="expired"||l.status==="refunded"?w.error:w.info;console.log(` ${m} ${f} ${l.detail||l.status}`)}c()}(r.status==="escrow_held"||r.status==="epp_pending")&&r.role==="seller"&&(R("Submit transfer code:",`domani sell ${r.domain} --transfer-code <code>`),c())}G();var Le=D(F(),1);L();we();async function aa(e,t,i){switch(e){case void 0:case"list":case"ls":return Xc(i);case"request":case"acquire":case"new":return ra(t,i);case"status":case"get":return oa(t,i);case"cancel":case"rm":return Zc(t,i);default:return e.includes(".")?ra(e,i):oa(e,i)}}async function ra(e,t){e||u("A domain is required.",{hint:"domani broker request dream.com --max-budget 5000",json:t.json}),Y(e,{json:t.json});let i=C(!t.json);i.start(`Requesting acquisition of ${v.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 _("/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(`${w.success} Acquisition requested`),t.json)return y(r,t.fields);j("Broker request"),d("Domain",v.domain(o.domain)),d("Status",Ln(o.status)),o.max_budget!=null&&d("Max budget",v.price(o.max_budget)),d("ID",Le.default.dim(o.id)),c(),console.log(` ${Le.default.dim("We'll source the owner and reach out anonymously. Commission-only - you pay nothing unless a deal closes.")}`),c(),R("Check progress:",`domani broker status ${o.id}`),c()}async function Xc(e){let t=C(!e.json);t.start("Loading broker requests");let i=e.status?`?status=${encodeURIComponent(e.status)}`:"",s=await _(`/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(`${w.success} ${r.length} request(s)`),e.json)return y(n,e.fields);if(r.length===0){c(),console.log(` ${Le.default.dim("No broker requests yet.")}`),c(),R("Acquire a taken domain:","domani broker request <domain> --max-budget <amount>"),c();return}c(),j("Broker requests"),B(["Domain","Status","Budget","ID"],r.map(o=>[v.domain(o.domain),Ln(o.status),o.max_budget!=null?v.price(o.max_budget):Le.default.dim("-"),Le.default.dim(o.id)])),c()}async function oa(e,t){e||u("A request ID is required.",{hint:"domani broker status <id> (list with: domani broker)",json:t.json});let i=C(!t.json);i.start("Loading request");let s=await _(`/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(`${w.success} ${v.domain(r.domain)}`),t.json)return y(n,t.fields);j("Broker request"),d("Domain",v.domain(r.domain)),d("Status",Ln(r.status)),r.max_budget!=null&&d("Max budget",v.price(r.max_budget)),d("Contacted",r.contacted?Le.default.green("yes"):Le.default.dim("not yet")),r.failure_reason&&d("Reason",Le.default.yellow(r.failure_reason)),d("ID",Le.default.dim(r.id)),c(),r.negotiation_id?(console.log(` ${Le.default.dim("The owner responded - an anonymous negotiation is open.")}`),c(),R("Review the offer:","domani deals"),c()):["sourcing","contacted","negotiating"].includes(r.status)&&(R("Cancel this request:",`domani broker cancel ${r.id}`),c())}async function Zc(e,t){e||u("A request ID is required.",{hint:"domani broker cancel <id>",json:t.json});let i=C(!t.json);i.start("Cancelling request");let s=await _(`/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(`${w.success} Request cancelled`),t.json)return y(n,t.fields);c()}function Ln(e){return["completed","agreed"].includes(e)?Le.default.green(e):["negotiating","contacted","sourcing"].includes(e)?Le.default.cyan(e):["declined","no_contact","failed","expired","cancelled"].includes(e)?Le.default.dim(e):e}G();var ye=D(F(),1);L();async function da(e){return e.read?tu(e):eu(e)}function Qc(e){let t=new URLSearchParams;e.unread&&t.set("unread","true"),e.limit&&t.set("limit",e.limit),e.cursor&&t.set("cursor",e.cursor);let i=t.toString();return i?`?${i}`:""}async function eu(e){let t=C(!e.json);t.start("Loading notifications");let i=Qc(e),s=await _(`/api/notifications${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.notifications||n.data||[],o=n.unread_count??r.filter(l=>!l.read).length;if(t.stop(`${w.success} ${r.length} notification(s)${o>0?` ${w.dot} ${ye.default.yellow(`${o} unread`)}`:""}`),e.json){y(n,e.fields);return}if(r.length===0){c(),console.log(` ${ye.default.dim("No notifications.")}`),c();return}c(),j("Notifications");let a=r.map(l=>{let f=l.read?ye.default.dim(w.dot):ye.default.cyan(w.info),m=iu(l.type),h=l.read?ye.default.dim(l.title):ye.default.white(l.title),b=l.body?l.read?ye.default.dim(la(l.body,40)):ye.default.dim(la(l.body,40)):ye.default.dim("-"),k=ye.default.dim(new Date(l.created_at).toLocaleDateString());return[f,m,h,b,k]});B(["","Type","Title","Body","Date"],a,[3,16,28,42,14]),c(),n.next_cursor&&(console.log(` ${ye.default.dim(`More: --cursor ${n.next_cursor}`)}`),c()),o>0&&(console.log(` ${ye.default.dim("Mark all as read:")} ${ye.default.cyan("domani notifications --read")}`),c())}async function tu(e){let t=C(!e.json);t.start("Marking all notifications as read");let i=await _("/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(""),y(s,e.fields);return}let n=s.count??0;t.stop(`${w.success} ${n} notification(s) marked as read`),c()}function iu(e){let t={deal:ye.default.cyan,sale:ye.default.green,purchase:ye.default.green,transfer:ye.default.yellow,expiry:ye.default.red,security:ye.default.red,billing:ye.default.yellow,email:ye.default.blue},i=e.split(".")[0].split("_")[0];return(t[i]||ye.default.dim)(e)}function la(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}G();var Rt=D(F(),1);L();async function ca(e){let t=e.limit?Number(e.limit):20,i=await _(`/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){y({...s,count:s.invoices.length},e.fields);return}if(s.invoices.length===0){console.log(` ${Rt.default.dim("No invoices yet.")}`);return}j(`Invoices (${s.invoices.length})`),c();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(` ${w.success} ${Rt.default.bold(a)} ${Rt.default.green(r)} ${Rt.default.dim(o)}`),n.description&&console.log(` ${Rt.default.dim(n.description)}`),n.hosted_invoice_url&&console.log(` ${Rt.default.dim(n.hosted_invoice_url)}`)}c(),s.has_more&&(console.log(` ${Rt.default.dim(`Showing ${s.invoices.length} most recent. Use --limit to see more.`)}`),c())}G();var xi=D(F(),1);L();async function ua(e){let t=C(!e?.json);t.start("Setting up billing session");let i=await _("/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){y({url:s.url});return}c(),console.log(` ${xi.default.dim("Opening browser")} ${w.arrow} ${v.url(s.url)}`),c(),qe(s.url),console.log(` ${w.info} ${xi.default.dim("Complete payment setup in your browser.")}`),console.log(` ${xi.default.dim(" After setup, you can purchase domains with")} ${xi.default.cyan("domani buy")}`),c()}G();var Vn=D(F(),1);L();async function ma(e){let t=C(!e?.json);t.start("Creating upgrade session");let i=await _("/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){y({url:s.url},e?.fields);return}c(),console.log(` ${Vn.default.dim("Opening browser")} ${w.arrow} ${v.url(s.url)}`),c(),qe(s.url),console.log(` ${w.info} ${Vn.default.dim("Complete your plan upgrade in the browser.")}`),c()}G();var Wn=D(F(),1);L();async function fa(e){let t=C(!e?.json);t.start("Cancelling subscription");let i=await _("/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){y(s,e?.fields);return}c();let n=s.cancel_at?new Date(s.cancel_at).toLocaleDateString():"end of billing period";console.log(` ${w.success} ${Wn.default.dim("Subscription cancelled.")} Access continues until ${Wn.default.cyan(n)}.`),c()}G();var nt=D(F(),1);L();we();Ze();async function pa(e,t,i){e||(e=await he()),Y(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 nu(e,s,i);return}await su(e,i)}async function su(e,t){let i=C(!t.json);i.start(`Fetching nameservers for ${v.domain(e)}`);let s=await _(`/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 ${v.domain(e)}`),t.json){y(n,t.fields);return}if(c(),n.nameservers.length===0)console.log(` ${w.warning} ${nt.default.yellow("No nameservers configured.")}`),console.log(` ${nt.default.dim("DNS operations (parking, email, connect) will not work.")}`),c(),R("Set default nameservers:",`domani nameservers ${e} --reset`);else{j("Nameservers");for(let r of n.nameservers)console.log(` ${w.success} ${nt.default.cyan(r)}`);n.default_nameservers&&n.nameservers.length===n.default_nameservers.length&&n.nameservers.every(o=>n.default_nameservers.includes(o))&&(c(),console.log(` ${nt.default.dim("Using default nameservers.")}`))}n.default_nameservers?.length&&(c(),d("Defaults",n.default_nameservers.map(r=>nt.default.dim(r)).join(nt.default.dim(", ")))),c()}async function nu(e,t,i){let s=C(!i.json);if(i.reset){s.start(`Fetching default nameservers for ${v.domain(e)}`);let o=await _(`/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=>nt.default.cyan(l)).join(nt.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 K("nameservers_set",{domain:e,nameservers:t},i.json,i.fields);s.start(`Setting nameservers for ${v.domain(e)}`);let n=await _(`/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(`${w.success} Nameservers updated`),i.json){y(r,i.fields);return}c();for(let o of r.nameservers)console.log(` ${w.success} ${nt.default.cyan(o)}`);c(),console.log(` ${nt.default.dim("Changes may take up to 48 hours to propagate.")}`),c(),R("Check propagation:",`domani status ${e}`),c()}var ha=require("crypto"),ps=D(require("fs"),1);yt();var ji=D(F(),1);L();function ru(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 ga(e){let t=!!e?.json,i=C(!t);i.start("Checking for updates");let s=We();try{let n=await fetch(`${s}/api/cli/version`);n.ok||(i.stop("Failed"),u("Could not check for updates"));let r=await n.json(),o=r.version,a=r.sha256;if(ru(o,je)<=0){i.stop(`${w.success} Already up to date (v${je})`),t&&y({current:je,latest:o,up_to_date:!0});return}if(t&&!e?.yes){i.stop(""),y({current:je,latest:o,up_to_date:!1,hint:"Run `domani update --yes` to upgrade non-interactively, or `domani update` in an interactive terminal."});return}i.stop(t?"":`New version available: ${ji.default.cyan(je)} ${w.arrow} ${ji.default.green(o)}`);let l=C(!t);l.start("Downloading update");let f=`${s}/cli/domani.js`,m=await fetch(f);m.ok||(l.stop("Download failed"),u(`Failed to download from ${f}`));let h=await m.text();a&&(0,ha.createHash)("sha256").update(h).digest("hex")!==a&&(l.stop("Integrity check failed"),u("Downloaded file does not match expected hash - update aborted"));let b=process.argv[1];b||(l.stop("Failed"),u("Could not determine binary path"));let k=ps.default.realpathSync(b),$=k+".tmp";if(ps.default.writeFileSync($,h,{mode:493}),ps.default.renameSync($,k),l.stop(`${w.success} Updated to v${o}`),t){y({updated:!0,from:je,to:o});return}c(),console.log(` ${ji.default.dim("Restart your terminal or run")} domani --version ${ji.default.dim("to verify")}`),c()}catch(n){u(`Update failed: ${n instanceof Error?n.message:String(n)}`)}}var hs=D(require("fs"),1),ya=D(require("path"),1),ba=D(require("os"),1);Ue();var Si=D(F(),1);L();async function wa(){let e=process.argv[1],t=e?hs.default.realpathSync(e):null,i=ya.default.join(ba.default.homedir(),".domani");if(c(),console.log(` ${Si.default.bold("This will remove:")}`),t&&console.log(` ${w.dot} CLI binary: ${Si.default.dim(t)}`),console.log(` ${w.dot} Config dir: ${Si.default.dim(i)}`),c(),await Xe({message:"Uninstall domani?"})!==!0){console.log(` ${Si.default.dim("Cancelled.")}`);return}hs.default.rmSync(i,{recursive:!0,force:!0}),t&&hs.default.unlinkSync(t),c(),console.log(` ${w.success} domani uninstalled.`),c()}G();var ae=D(F(),1);L();async function $a(e,t){let i=t?.json,s=t?.fields,n=e?`/api/schema?command=${encodeURIComponent(e)}`:"/api/schema",r=C(!i);r.start("Loading schema");let o=await ve(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){y(a,s);return}e?au(e,a):ou(a.commands)}function ou(e){j("Commands");let t=Object.entries(e).map(([i,s])=>[ae.default.bold(ae.default.cyan(i)),s.description]);B(["Command","Description"],t,[20,50]),c(),console.log(` ${ae.default.dim("Run")} ${ae.default.cyan("domani schema <command>")} ${ae.default.dim("for full details")}`),c()}function au(e,t){if(j(`domani ${e}`),console.log(` ${t.description}`),c(),console.log(` ${v.label("Usage:")} ${ae.default.cyan(t.usage)}`),t.arguments&&Object.keys(t.arguments).length>0){c(),console.log(` ${ae.default.bold("Arguments")}`);for(let[i,s]of Object.entries(t.arguments)){let n=s.required?ae.default.red("*"):"",r=ae.default.dim(`(${s.type}${s.variadic?", variadic":""})`);console.log(` ${ae.default.cyan(i)}${n} ${r}`),s.description&&console.log(` ${ae.default.dim(s.description)}`)}}if(t.options&&Object.keys(t.options).length>0){c(),console.log(` ${ae.default.bold("Options")}`);for(let[i,s]of Object.entries(t.options)){let n=s.required?ae.default.red("*"):"",r=ae.default.dim(`(${s.type})`),o=s.choices?ae.default.dim(` [${s.choices.join(", ")}]`):"";console.log(` ${ae.default.cyan(`--${i}`)}${n} ${r}${o}`),console.log(` ${ae.default.dim(s.description)}`)}}if(t.api)if(c(),console.log(` ${ae.default.bold("API")}`),lu(t.api))va(t.api);else for(let[i,s]of Object.entries(t.api))console.log(` ${ae.default.bold(ae.default.yellow(i))}`),va(s,6);t.errors&&t.errors.length>0&&(c(),console.log(` ${ae.default.bold("Errors")}`),console.log(` ${t.errors.map(i=>ae.default.dim(i)).join(ae.default.dim(", "))}`)),c()}function lu(e){return typeof e=="object"&&e!==null&&"method"in e&&"path"in e}function va(e,t=4){let i=" ".repeat(t);if(console.log(`${i}${ae.default.green(e.method)} ${ae.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?ae.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=ae.default.dim(`(${o.join(", ")})`);console.log(`${i} ${ae.default.cyan(s)}${r} ${a}`),n.description&&console.log(`${i} ${ae.default.dim(n.description)}`)}}G();var Ve=D(F(),1);Ue();L();async function ka(e){let t=C(!e.json);t.start("Loading payment method");let i=await _("/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(""),y(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"),c(),console.log(` ${Ve.default.dim("Add a card with")} ${Ve.default.cyan("domani card add")}`),c();return}let{brand:n,last4:r,exp_month:o,exp_year:a}=s.card,l=`${String(o).padStart(2,"0")}/${a}`,f=n.charAt(0).toUpperCase()+n.slice(1);t.stop("Payment method loaded"),j("Payment method"),d("Card",`${Ve.default.bold(f)} \u2022\u2022\u2022\u2022 ${Ve.default.bold(r)}`),d("Expires",l),c(),console.log(` ${Ve.default.dim("Update with")} ${Ve.default.cyan("domani card add")}`),c()}async function _a(e){let t=C(!e?.json);t.start("Setting up payment session");let i=await _("/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){y({url:s.url},e?.fields);return}c(),console.log(` ${Ve.default.dim("Opening browser")} ${w.arrow} ${v.url(s.url)}`),c(),qe(s.url),console.log(` ${w.info} ${Ve.default.dim("Complete payment setup in your browser.")}`),console.log(` ${Ve.default.dim(" After setup, you can purchase domains with")} ${Ve.default.cyan("domani buy")}`),c()}async function xa(e){if(!e?.yes&&!e?.json){let n=await Xe({message:"Remove your saved payment method?"});if(ce(n)||!n){console.log(` ${Ve.default.dim("Cancelled.")}`);return}}let t=C(!e?.json);t.start("Removing payment method");let i=await _("/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(`${w.success} Payment method removed`),e?.json){y({removed:!0},e?.fields);return}c(),console.log(` ${Ve.default.dim("Add a new card with")} ${Ve.default.cyan("domani card add")}`),c()}var Hn=D(F(),1);G();L();async function pe(e,t,i,s){let n=C(!i.json);n.start(s);let r=await _(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(`${w.success} Done`),o}async function ja(e,t){if(!e||e==="list"){let i=await pe("/api/workspaces",void 0,t,"Loading workspaces");if(t.json)return y(i,t.fields);if(c(),j("Workspaces"),!i.workspaces.length){console.log(` ${Hn.default.dim("No workspaces yet.")}`),R("Create one:","domani workspace create --name Acme");return}B(["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]),c();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 pe("/api/workspaces",{method:"POST",body:JSON.stringify({name:t.name})},t,"Creating workspace");if(t.json)return y(i,t.fields);c(),j("Workspace Created"),d("ID",i.id),d("Name",i.name),c();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 pe(`/api/workspaces/${encodeURIComponent(t.id)}`,void 0,t,"Loading workspace");if(t.json)return y(i,t.fields);c(),j(i.name),d("Role",i.role),d("Mailboxes",i.mailboxes.length),d("Members",i.members.length),c(),B(["Email","Role","Mailbox grants"],i.members.map(s=>[s.email,s.role,String(s.mailbox_grants.length)]),[42,12,16]),c();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 pe(`/api/workspaces/${encodeURIComponent(t.id)}/access`,void 0,t,"Loading access graph");if(t.json)return y(a,t.fields);c(),j("Access Graph"),d("Principals",a.principals.length),d("Mailboxes",a.mailboxes.length),d("Groups",a.groups.length),d("Collections",a.collections.length),d("Active grants",a.grants.length),d("Pending offers",a.offers.length),c();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 pe(`/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 y(o,t.fields);c(),j(t.apply?"Access Applied":"Access Plan"),d("Action",o.action),d("Changed",String(o.changed)),o.grant_id&&d("Grant",o.grant_id),c();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 pe(`/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 y(s,t.fields);c(),j("Access Group Synced"),d("ID",s.id),d("Principals",s.principal_count),c();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 pe(`/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 y(i,t.fields);c(),j("Mailbox Collection Synced"),d("ID",i.id),d("Mailboxes",i.mailbox_count),c();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 pe(`/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 y(s,t.fields);c(),j("Access Offered"),d("Email",s.email),d("Expires",s.expires_at),c();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 pe("/api/workspaces/access/offers/accept",{method:"POST",body:JSON.stringify({token:t.token})},t,"Accepting access offer");if(t.json)return y(i,t.fields);c(),j("Access Accepted"),d("Workspace",i.workspace_name),d("Ownership",i.ownership),c();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 pe(`/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 y(i,t.fields);c(),j("Access Revoked"),d("Grant",i.grant_id),d("Version",i.version),c();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 pe(`/api/workspaces/${encodeURIComponent(t.id)}`,{method:"PATCH",body:JSON.stringify({name:t.name})},t,"Renaming workspace");if(t.json)return y(i,t.fields);c(),j("Workspace Renamed"),d("ID",i.id),d("Name",i.name),c();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 pe(`/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 y(i,t.fields);c(),j("Invitation Sent"),d("Email",i.email),d("Role",i.role),d("Expires",i.expires_at),c();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 pe("/api/workspaces/invitations/accept",{method:"POST",body:JSON.stringify({token:t.token})},t,"Accepting invitation");if(t.json)return y(i,t.fields);c(),j("Workspace Joined"),d("Workspace",i.workspace_name),d("Role",i.role),c();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 pe(`/api/workspaces/${encodeURIComponent(t.id)}/invitations/${encodeURIComponent(t.invitationId)}`,{method:"DELETE"},t,"Revoking invitation");if(t.json)return y(i,t.fields);c(),j("Invitation Revoked"),d("Invitation",i.invitation_id),c();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 pe(`/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 y(i,t.fields);c(),j("Member Updated"),d("Membership",i.id),d("Role",i.role),c();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 pe(`/api/workspaces/${encodeURIComponent(t.id)}/members/${encodeURIComponent(t.membershipId)}`,{method:"DELETE"},t,"Removing member and revoking access");if(t.json)return y(i,t.fields);c(),j("Member Removed"),d("Membership",i.membership_id),c();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 pe(`/api/workspaces/${encodeURIComponent(t.id)}/members/me`,{method:"DELETE"},t,"Leaving workspace and revoking access");if(t.json)return y(i,t.fields);c(),j("Workspace Left"),d("Workspace",i.workspace_id),c();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 pe(`/api/workspaces/${encodeURIComponent(t.id)}/ownership-transfer`,{method:"POST",body:JSON.stringify({membership_id:t.membershipId})},t,"Requesting ownership transfer");if(t.json)return y(i,t.fields);c(),j("Ownership Transfer Requested"),d("To",i.to_email),d("Expires",i.expires_at),d("Billing",i.billing),c();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 pe("/api/workspaces/ownership-transfers/accept",{method:"POST",body:JSON.stringify({token:t.token})},t,"Accepting ownership");if(t.json)return y(i,t.fields);c(),j("Ownership Transferred"),d("Workspace",i.workspace_id),d("Domains",i.domains_transferred),d("Mailboxes",i.mailboxes_transferred),d("Previous owner",i.previous_owner_role),c();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 pe(`/api/workspaces/${encodeURIComponent(t.id)}/ownership-transfer/${encodeURIComponent(t.transferId)}`,{method:"DELETE"},t,"Revoking ownership transfer");if(t.json)return y(i,t.fields);c(),j("Ownership Transfer Revoked"),d("Transfer",i.transfer_id),c();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 pe(`/api/workspaces/${encodeURIComponent(t.id)}/mailboxes`,{method:"POST",body:JSON.stringify({mailbox_id:t.mailboxId})},t,"Adopting mailbox boundary");if(t.json)return y(i,t.fields);c(),j(i.adopted?"Mailbox Boundary Adopted":"Already in Workspace"),d("Address",i.address),d("Mailboxes",i.mailbox_ids?.length??1),c();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 pe(`/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 y(i,t.fields);c(),j("Mailbox Access Granted"),d("Membership",i.membership_id),d("Mailbox",i.mailbox_id),d("Role",i.role),c();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 pe(`/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 y(i,t.fields);c(),j("Mailbox Access Revoked"),d("Membership",i.membership_id),d("Mailbox",i.mailbox_id),c();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 pe(`/api/workspaces/${encodeURIComponent(t.id)}/billing/checkout`,{method:"POST",body:JSON.stringify({plan:t.plan})},t,"Creating secure checkout");if(t.json)return y(i,t.fields);c(),j("Workspace Checkout"),d("Plan",i.plan),d("URL",i.url),c(),i.url&&t.open!==!1&&(console.log(` ${Hn.default.dim("Opening browser")} ${w.arrow} ${v.url(i.url)}`),qe(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 pe(`/api/workspaces/${encodeURIComponent(t.id)}/billing/cancel`,{method:"POST"},t,"Scheduling cancellation");if(t.json)return y(i,t.fields);c(),j("Cancellation Scheduled"),d("Message",i.message),i.cancel_at&&d("Cancels",i.cancel_at),c();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 Ci=D(F(),1);G();var gs=D(require("node:crypto"),1),ai=D(require("node:fs"),1),Sa=D(require("node:os"),1),ys=D(require("node:path"),1),du=process.env.DOMANI_CONFIG_DIR||ys.default.join(Sa.default.homedir(),".domani"),Ca=ys.default.join(du,"mutations");function cu(e){return ys.default.join(Ca,`${gs.default.createHash("sha256").update(e).digest("hex")}.json`)}function ut(e,t,i){let s=cu(e),n=gs.default.createHash("sha256").update(JSON.stringify(t)).digest("hex");if(!i)try{let o=JSON.parse(ai.default.readFileSync(s,"utf8"));if(o.key&&o.fingerprint===n)return{key:o.key,complete:()=>{try{ai.default.unlinkSync(s)}catch{}}}}catch{}let r=i||`cli-${gs.default.randomUUID()}`;return ai.default.mkdirSync(Ca,{recursive:!0,mode:448}),ai.default.writeFileSync(s,JSON.stringify({key:r,fingerprint:n}),{mode:384}),{key:r,complete:()=>{try{ai.default.unlinkSync(s)}catch{}}}}L();function Oa(e){if(e.clearUpstreamHeaders)return{};let t={};for(let[i,s]of[["Authorization",e.upstreamAuthorizationEnv],["X-Api-Key",e.upstreamApiKeyEnv]]){if(!s)continue;let n=process.env[s];n||u(`Environment variable ${s} is empty`,{code:"validation_error",json:e.json}),t[i]=n}return Object.keys(t).length?t:void 0}async function Bt(e,t){let i=await e.json();return e.ok||u(i.error||i.message,{hint:i.hint,status:e.status,json:t.json,fields:t.fields}),i}function bs(e,t){if(t.json)return y(e,t.fields);let i=e.http_route||e;c(),j("HTTP Route"),d("ID",i.id),d("URL",i.url),d("Upstream",i.upstream),d("Status",i.status),d("Expires",i.expires_at),d("Browser mode",i.browser_mode||"stateless"),i.upstream_verification?.secret&&(d("Verification secret",Ci.default.yellow(i.upstream_verification.secret)),console.log(Ci.default.dim(" Save this secret now. It will not be shown again after this receipt."))),c()}function uu(e){let t=new URLSearchParams;e.domain&&t.set("domain",e.domain),e.hostname&&t.set("hostname",e.hostname),e.status&&t.set("status",e.status),e.limit&&t.set("limit",e.limit),e.cursor&&t.set("cursor",e.cursor);let i=t.toString();return i?`?${i}`:""}async function Ia(e,t,i){if(!e||e==="list"){let s=await Bt(await _(`/api/http-routes${uu(i)}`),i);if(i.json)return y(s,i.fields);c(),j("HTTP Routes");for(let n of s.http_routes)console.log(` ${Ci.default.dim(n.id)} ${n.hostname} ${n.status} ${n.upstream}`);c(),s.next_cursor&&(console.log(` ${Ci.default.dim(`More: --cursor ${s.next_cursor}`)}`),c());return}if(e==="create"){i.upstream||u("--upstream is required",{code:"validation_error",json:i.json});let s=Oa(i),n={...i.hostname?{hostname:i.hostname}:{},upstream:i.upstream,...i.expiresIn?{expires_in:Number(i.expiresIn)}:{},...i.hostHeader?{host_header:i.hostHeader}:{},...i.upstreamVerification?{upstream_verification:i.upstreamVerification}:{},...s?{upstream_headers:s}:{}},r=ut(`route:create:${i.hostname||"auto"}`,n,i.idempotencyKey),o=C(!i.json);o.start("Creating HTTP route");let a=await Bt(await _("/api/http-routes",{method:"POST",headers:{"Idempotency-Key":r.key},body:JSON.stringify(n)}),i);return r.complete(),o.stop(`${w.success} HTTP route created`),bs(a,i)}if(t||u("Route ID is required",{hint:`Usage: domani route ${e} <id>`,code:"validation_error",json:i.json}),e==="get")return bs(await Bt(await _(`/api/http-routes/${encodeURIComponent(t)}`),i),i);if(e==="delete"){let s=await _(`/api/http-routes/${encodeURIComponent(t)}`,{method:"DELETE"});if(s.ok||await Bt(s,i),i.json)return y({deleted:!0,id:t},i.fields);console.log(`${w.success} HTTP route deleted`);return}if(e==="refresh"){i.expiresIn||u("--expires-in is required",{code:"validation_error",json:i.json});let s={expires_in:Number(i.expiresIn)},n=ut(`route:refresh:${t}`,s,i.idempotencyKey),r=await Bt(await _(`/api/http-routes/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Idempotency-Key":n.key},body:JSON.stringify(s)}),i);return n.complete(),bs(r,i)}if(e==="rotate-verification"){let s=ut(`route:rotate-verification:${t}`,{},i.idempotencyKey),n=await Bt(await _(`/api/http-routes/${encodeURIComponent(t)}/upstream-verification/rotate`,{method:"POST",headers:{"Idempotency-Key":s.key}}),i);return s.complete(),i.json?y(n,i.fields):bs(n,i)}if(e==="rotate-headers"){let s=Oa(i);s||u("Provide an upstream header environment variable or --clear-upstream-headers",{code:"validation_error",json:i.json});let n=ut(`route:rotate-headers:${t}`,{upstream_headers:s},i.idempotencyKey),r=await Bt(await _(`/api/http-routes/${encodeURIComponent(t)}/upstream-headers`,{method:"PUT",headers:{"Idempotency-Key":n.key},body:JSON.stringify({upstream_headers:s})}),i);if(n.complete(),i.json)return y(r,i.fields);console.log(`${w.success} Upstream headers replaced: ${r.upstream_header_names.join(", ")||"none"}`);return}u(`Unknown action: ${e}`,{hint:"Actions: create, list, get, refresh, rotate-verification, rotate-headers, delete",code:"validation_error",json:i.json})}var ee=D(F(),1),Ta=require("node:fs");G();L();var Bn="mailzero-personal-ai.v1",Q=class extends Error{constructor(i,s){super(i);this.hint=s;this.name="AssistantUsageError"}},mu={choose:"choose",instruct:"instruct","take-over":"take_over",snooze:"snooze",ignore:"ignore",correct:"correct",approve:"approve",reject:"reject",tag:"tag"},fu=["today","settings","set","preview","backfill","retry","item","choose","instruct","snooze","ignore","take-over","correct","approve","reject","tag","plan","activity","export","delete","brief","facts","sender","task","lease","release","effects","escalate","report","rules","approvals","suggestions","metrics"];function Jn(e,t,i){if(!e)throw new Q(`${t} is required`,i);try{return JSON.parse(e)}catch{throw new Q(`${t} must be valid JSON`,i)}}function ws(e){return(e||"").split(",").map(t=>t.trim()).filter(Boolean)}function Ra(e){return(e||"").split(",").map(t=>t.trim()).filter(Boolean)}function Gt(e,t,i){let s=Number(e);if(!Number.isInteger(s)||s<i)throw new Q(`${t} must be an integer of at least ${i}`);return s}function pu(e,t,i){let s=e||"today";switch(s){case"today":{let n=new URLSearchParams;i.category&&n.set("category",i.category.trim().toLowerCase()),i.tag&&n.set("tag",i.tag.trim().toLowerCase());let r=n.toString();return{method:"GET",path:r?`/api/assistant/today?${r}`:"/api/assistant/today"}}case"settings":return{method:"GET",path:"/api/assistant/settings"};case"set":{let n={};if(i.enable&&i.disable)throw new Q("Use either --enable or --disable");if(i.pause&&i.resume)throw new Q("Use either --pause or --resume");if(i.enable&&(n.enabled=!0),i.disable&&(n.enabled=!1),i.shadow!==void 0&&(n.shadow_enabled=i.shadow),i.pause&&(n.paused=!0),i.resume&&(n.paused=!1),i.none?n.mailbox_ids=[]:i.mailboxes!==void 0&&(n.mailbox_ids=Ra(i.mailboxes)),i.days!==void 0&&(n.history_window_days=Gt(i.days,"--days",1)),i.attachmentVision!==void 0){if(!["on","off"].includes(i.attachmentVision))throw new Q("--attachment-vision must be on or off");n.attachment_vision=i.attachmentVision==="on"}if(!Object.keys(n).length)throw new Q("Provide at least one setting","Options: --enable, --disable, --shadow, --no-shadow, --pause, --resume, --mailboxes <ids>, --none, --days <n>, --attachment-vision <on|off>");return{method:"PUT",path:"/api/assistant/settings",body:n}}case"preview":{if(!i.consent)throw new Q("--consent is required to start the assistant",`Consent means Domani may read the selected mailboxes and send bounded, minimized message content to the approved private model route (version ${Bn}). Nothing is ever sent on your behalf. You can pause or delete derived data at any time.`);let n=Ra(i.mailboxes);if(!n.length)throw new Q("--mailboxes is required","Pass owned mailbox IDs, comma-separated. List them with: domani assistant settings");return{method:"POST",path:"/api/assistant/preview",body:{mailbox_ids:n,history_window_days:i.days===void 0?30:Gt(i.days,"--days",1),consent:!0,consent_version:Bn}}}case"backfill":return{method:"GET",path:"/api/assistant/backfill"};case"retry":return{method:"POST",path:"/api/assistant/backfill",idempotency:"assistant:retry"};case"item":if(!t)throw new Q("Work item ID is required","Usage: domani assistant item <id>");return{method:"GET",path:`/api/assistant/work-items/${encodeURIComponent(t)}`};case"brief":{if(t)return{method:"GET",path:`/api/assistant/work-items/${encodeURIComponent(t)}/brief`};if(!i.correspondent)throw new Q("Work item ID or --correspondent is required","Usage: domani assistant brief <id> | domani assistant brief --correspondent ada@example.com [--mailbox hi@myapp.dev]");let n=new URLSearchParams({correspondent:i.correspondent});return i.mailbox&&n.set("mailbox",i.mailbox),{method:"GET",path:`/api/assistant/brief?${n}`}}case"facts":if(!t)throw new Q("Work item ID is required","Usage: domani assistant facts <id>");return{method:"GET",path:`/api/assistant/work-items/${encodeURIComponent(t)}/facts`};case"sender":if(!t)throw new Q("Work item ID is required","Usage: domani assistant sender <id>");return{method:"GET",path:`/api/assistant/work-items/${encodeURIComponent(t)}/sender`};case"plan":if(!t)throw new Q("Action plan ID is required","Usage: domani assistant plan <id>");return{method:"GET",path:`/api/assistant/action-plans/${encodeURIComponent(t)}`};case"activity":return{method:"GET",path:`/api/assistant/activity${i.limit!==void 0?`?limit=${Gt(i.limit,"--limit",1)}`:""}`};case"rules":return{method:"GET",path:"/api/assistant/rules"};case"approvals":return{method:"GET",path:"/api/assistant/approvals"};case"suggestions":return{method:"GET",path:"/api/assistant/suggestions"};case"metrics":return{method:"GET",path:`/api/assistant/metrics${i.days!==void 0?`?window_days=${Gt(i.days,"--days",1)}`:""}`};case"export":return{method:"GET",path:"/api/assistant/data"};case"delete":if(!i.yes)throw new Q("Deleting derived assistant data requires --yes","This removes analyses, Decisions, plans, receipts, imports, and settings. Source mail is never touched.");return{method:"DELETE",path:"/api/assistant/data"};case"task":if(!t)throw new Q("Task ID is required","Usage: domani assistant task <work item id>");return{method:"GET",path:`/api/assistant/tasks/${encodeURIComponent(t)}`};case"lease":{if(!t)throw new Q("Task ID is required","Usage: domani assistant lease <id> [--ttl <seconds>]");let n={};return i.ttl!==void 0&&(n.ttl_seconds=Gt(i.ttl,"--ttl",30)),{method:"POST",path:`/api/assistant/tasks/${encodeURIComponent(t)}/lease`,body:n}}case"release":if(!t)throw new Q("Task ID is required","Usage: domani assistant release <id>");return{method:"DELETE",path:`/api/assistant/tasks/${encodeURIComponent(t)}/lease`};case"effects":{if(!t)throw new Q("Task ID is required","Usage: domani assistant effects <id> --effects '<json array>'");let n=Jn(i.effects,"--effects",`A JSON array of effects, for example: --effects '[{"kind":"label","mailbox_id":"mbx_1","add":["finance"]}]'`);if(!Array.isArray(n)||!n.length)throw new Q("--effects must be a non-empty JSON array","Kinds: reply, forward, label, snooze, resolve, note, request");let r={effects:n};return i.text&&(r.note=i.text),{method:"POST",path:`/api/assistant/tasks/${encodeURIComponent(t)}/effects`,body:r,idempotency:`assistant:effects:${t}`}}case"escalate":{if(!t)throw new Q("Task ID is required","Usage: domani assistant escalate <id> --question '<text>' [--options '<json>'] [--evidence <refs>]");if(!i.question)throw new Q("--question is required","What the owner must decide, with the evidence in --evidence");let n={question:i.question};i.options&&(n.options=Jn(i.options,"--options","A JSON array of { key, label, outcome }"));let r=ws(i.evidence);return r.length&&(n.evidence_refs=r),{method:"POST",path:`/api/assistant/tasks/${encodeURIComponent(t)}/escalate`,body:n}}case"report":{if(!t)throw new Q("Task ID is required","Usage: domani assistant report <id> --outcome done|blocked|handed_back --summary '<text>' [--claims '<json>'] [--evidence <refs>]");if(!i.outcome||!["done","blocked","handed_back"].includes(i.outcome))throw new Q("--outcome must be done, blocked or handed_back");if(!i.summary)throw new Q("--summary is required","What was done and how it ended, in a few lines");let n={outcome:i.outcome,summary:i.summary};i.claims&&(n.claims=Jn(i.claims,"--claims","A JSON array of { kind, ref } the platform reconciles with its receipts"));let r=ws(i.evidence);return r.length&&(n.evidence_refs=r),{method:"POST",path:`/api/assistant/tasks/${encodeURIComponent(t)}/report`,body:n}}case"choose":case"instruct":case"snooze":case"ignore":case"take-over":case"correct":case"approve":case"reject":case"tag":{if(!t)throw new Q("Work item ID is required",`Usage: domani assistant ${s} <id> --item-version <work_item_version>`);if(i.itemVersion===void 0)throw new Q("--item-version is required","Pass the work_item_version shown by: domani assistant item <id>");let n=mu[s],r={type:n,work_item_version:Gt(i.itemVersion,"--item-version",1)};if(n==="ignore"&&i.scope){if(!["item","sender","sender_domain","situation"].includes(i.scope))throw new Q("--scope must be item, sender, sender_domain or situation","Example: domani assistant ignore <id> --item-version 3 --scope sender");r.scope=i.scope}if(n==="choose"){if(!i.option||!i.decision||i.decisionVersion===void 0)throw new Q("--option, --decision and --decision-version are required","They come from the Decision shown by: domani assistant item <id>");r.decision_id=i.decision,r.decision_version=Gt(i.decisionVersion,"--decision-version",1),r.option_id=i.option}if(n==="instruct"){if(!i.text)throw new Q("--text is required","The instruction the assistant should follow when preparing the draft");r.instruction=i.text}if(n==="snooze"){if(!i.until)throw new Q("--until is required","ISO 8601 date-time, for example 2026-09-03T09:00:00Z");r.until=i.until}if(n==="correct"){if(!i.field||!i.text)throw new Q("--field and --text are required","Name the analysis field to correct and the correct value");r.field=i.field,r.correction=i.text}if(n==="tag"){let o=ws(i.add),a=ws(i.remove);if(!o.length&&!a.length)throw new Q("--add or --remove is required","Example: domani assistant tag <id> --item-version 3 --add lumenworks --remove draft");o.length&&(r.add=o),a.length&&(r.remove=a)}if(n==="approve"||n==="reject"){if(!i.plan)throw new Q("--plan is required","The waiting action plan shown by: domani assistant task <id>");r.plan_id=i.plan,n==="reject"&&i.text&&(r.reason=i.text)}return{method:"POST",path:`/api/assistant/work-items/${encodeURIComponent(t)}/interactions`,body:r,idempotency:`assistant:${n}:${t}`}}default:throw new Q(`Unknown action: ${s}`,`Actions: ${fu.join(", ")}`)}}async function hu(e,t){let i=await e.json();if(e.ok)return i;i.code==="NOT_AVAILABLE"&&u("The Mailzero assistant is in private preview",{hint:"It is enabled per account during the private beta. Ask for access at https://domani.run/support or wait for general availability.",code:"not_available",status:e.status,json:t.json,fields:t.fields}),i.code==="INSUFFICIENT_SCOPE"&&u(i.error||"Missing assistant scope",{hint:"This token needs the assistant:read scope for reads and assistant:write for changes. Create one with: domani tokens create --scopes assistant:read,assistant:write",code:"insufficient_scope",status:e.status,json:t.json,fields:t.fields}),u(i.error||i.message,{hint:i.hint,status:e.status,json:t.json,fields:t.fields})}function gu(e){let t=e.sender?.name||e.sender?.address?.split("@")[0]||e.mailbox?.name||e.mailbox?.address||"",i=e.recurrence?.count&&e.recurrence.count>1?ee.default.dim(`x${e.recurrence.count}`):"",s=[e.category?e.category.replace(/_/g," "):"",...(e.tags??[]).map(n=>`#${n}`)].filter(Boolean).join(" ");return[ee.default.dim(e.id),t,s,`${(e.title||e.summary||"").slice(0,60)} ${i}`.trim(),e.ask?e.ask.slice(0,50):e.attention?.deadline||""]}function yu(e,t){if(t.json)return y(e,t.fields);c(),j("Today");let i=[["now","Now"],["needs_you","Needs you"],["waiting","Waiting"],["upcoming","Upcoming"],["handled","Handled"]],s=0;for(let[a,l]of i){let f=e.sections&&typeof e.sections=="object"?e.sections:e,m=Array.isArray(f[a])?f[a]:[];m.length&&(s+=m.length,console.log(` ${ee.default.bold(l)} ${ee.default.dim(`(${m.length})`)}`),B(["ID","Who","Kind","Summary","Deadline"],m.map(gu)),c())}s||console.log(ee.default.dim(t.tag?` Nothing tagged ${t.tag} right now.`:t.category?` Nothing of the kind ${t.category} right now.`:" Nothing needs you right now."));let n=e.categories&&typeof e.categories=="object"?Object.entries(e.categories).sort((a,l)=>l[1]-a[1]):[];n.length>1&&console.log(ee.default.dim(` Kinds: ${n.map(([a,l])=>`${a} ${l}`).join(", ")} (narrow with --category)`));let r=e.tags&&typeof e.tags=="object"?Object.entries(e.tags).sort((a,l)=>l[1]-a[1]):[];r.length&&console.log(ee.default.dim(` Tags: ${r.map(([a,l])=>`${a} ${l}`).join(", ")} (narrow with --tag)`));let o=typeof e.as_of=="string"?e.as_of:void 0;o&&console.log(ee.default.dim(` As of ${o}`)),c()}function bu(e,t){if(t.json)return y(e,t.fields);let i=e.brief??e;if(e.correspondent&&!e.brief){c(),j(`Brief for ${e.correspondent}`),console.log(` ${ee.default.dim("Nothing analysed from this person yet.")}`);for(let s of e.recent_mail||[])d(s.received_at.slice(0,10),`${s.subject||""} (${s.mailbox})`);return}c(),j(i.title||"Brief"),i.situation&&d("Status",`${i.situation.status||""}${i.situation.attention?.level?` \xB7 ${i.situation.attention.level}`:""}${i.situation.occurrences&&i.situation.occurrences>1?` \xB7 ${i.situation.occurrences} messages`:""}`),i.situation?.sender?.address&&d("With",`${i.situation.sender.name?`${i.situation.sender.name} `:""}<${i.situation.sender.address}>`),i.summary&&d("Summary",i.summary),i.ask&&d("Ask",i.ask);for(let s of i.story||[])d(s.occurred_at.slice(0,10),`${s.title}${s.analysed?"":ee.default.dim(" (not analysed)")}`);for(let s of i.facts||[])d("Fact",`${s.subject||""} ${s.predicate||""} ${s.value?.value??s.object??""}${s.value?.currency?` ${s.value.currency}`:""}`.trim());for(let s of i.awaiting||[])d(s.overdue?ee.default.red("Awaited"):"Awaited",`${s.who}: ${s.what} (since ${s.since.slice(0,10)})`);for(let s of i.commitments||[])d(s.overdue?ee.default.red("Promised"):"Promised",`${s.who}: ${s.what}`);for(let s of(i.settled||[]).slice(0,5))d("Settled",`${s.what} (${s.status}, ${s.at.slice(0,10)})`);i.decision?.question&&d("Decision",`${i.decision.question} ${(i.decision.options||[]).map(s=>`${s.recommended?"\u2605 ":""}${s.label}`).join(" / ")}`),i.suggested_next&&d("Next",`${i.suggested_next.action} ${ee.default.dim(`(${i.suggested_next.reason})`)}`),e.related&&e.related.length&&d("Also",`${e.related.length} other item(s) from this person`)}function wu(e,t){if(t.json)return y(e,t.fields);let i=e;c(),j(i.sender?`${i.sender.name?`${i.sender.name} `:""}<${i.sender.address}>`:"Sender"),i.organisation?(d("Organisation",`${i.organisation.name||i.sender?.domain||""}${i.organisation.legal_name&&i.organisation.legal_name!==i.organisation.name?` (${i.organisation.legal_name})`:""}${i.organisation.fresh?"":ee.default.dim(" (profile ageing)")}`),i.organisation.pitch&&d("About",i.organisation.pitch),i.organisation.registered_at&&d("Domain since",i.organisation.registered_at.slice(0,10)),d("Mail",`${i.organisation.mail.provider||"unknown provider"} \xB7 spf ${i.organisation.mail.spf===null?"?":i.organisation.mail.spf?"yes":"no"} \xB7 dmarc ${i.organisation.mail.dmarc}`)):i.sender?.shared_domain?d("Organisation",ee.default.dim(`${i.sender.domain} is a shared mail domain`)):i.sender?.domain&&d("Organisation",ee.default.dim(`${i.sender.domain} not analysed yet`));let s=i.relationship;if(s){let n=s.first_received_at&&s.last_received_at?` between ${s.first_received_at.slice(0,10)} and ${s.last_received_at.slice(0,10)}`:"";d("Received",s.received?`${s.received_capped?"50+":s.received} message(s)${n}`:"nothing before this");for(let r of s.matters.slice(0,5))d(r.last_seen_at.slice(0,10),`${r.title} ${ee.default.dim(`(${r.status}, ${r.id})`)}`);s.organisation?.matters.length&&d("Colleagues",`${s.organisation.other_senders.join(", ")}: ${s.organisation.matters.slice(0,3).map(r=>r.title).join(" / ")}`)}for(let n of i.participants||[])d(n.roles.join("+"),`${n.name?`${n.name} `:""}<${n.address}>${n.messages>1?ee.default.dim(` \xD7${n.messages}`):""}${n.same_organisation?"":ee.default.dim(" (outside)")}`)}function Aa(e,t){if(t.json)return y(e,t.fields);let i=e.work_item||e;if(c(),j("Work item"),d("ID",i.id),d("Version",String(i.version??"")),d("Status",i.status||""),d("Mailbox",i.mailbox?.name?`${i.mailbox.name} <${i.mailbox.address||""}>`:i.mailbox?.address||""),i.title&&d("Title",i.title),i.sender?.address&&d("From",`${i.sender.name?`${i.sender.name} `:""}<${i.sender.address}>${i.sender.kind&&i.sender.kind!=="human"?` (${i.sender.kind})`:""}`),i.ask&&d("Ask",i.ask),i.recurrence?.count&&i.recurrence.count>1&&d("Recurrence",`${i.recurrence.count} messages since ${(i.recurrence.first_seen_at||"").slice(0,10)}`),d("Summary",i.summary||""),i.attention?.reason&&d("Why",i.attention.reason),i.attention?.deadline&&d("Deadline",i.attention.deadline),i.source?.event_id&&d("Source",`${i.source.type||"mail"} ${i.source.event_id}`),i.decision?.options?.length){c(),console.log(` ${ee.default.bold("Decision")} ${ee.default.dim(`${i.decision.id} v${i.decision.version??1}`)}`);for(let s of i.decision.options)console.log(` ${ee.default.dim(s.id)} ${s.label}${s.recommended?ee.default.green(" recommended"):""}`);console.log(ee.default.dim(` Choose with: domani assistant choose ${i.id} --version ${i.version??1} --decision ${i.decision.id} --decision-version ${i.decision.version??1} --option <id>`))}i.plan?.id&&d("Plan",`${i.plan.id} (preview with: domani assistant plan ${i.plan.id})`),c()}function vu(e,t){if(t.json)return y(e,t.fields);c(),j("Mailzero assistant"),d("Enabled",e.enabled?"yes":"no"),d("Shadow",e.shadow_enabled?"yes":"no"),d("Paused",e.paused?"yes":"no"),d("History window",`${e.history_window_days} days`),d("Privacy route",String(e.privacy_route||"")),d("Consent",e.consent?.accepted_version?`${e.consent.accepted_version} at ${e.consent.accepted_at}`:`none (required: ${e.consent?.required_version||Bn})`),c();let i=new Set(e.mailbox_ids||[]),s=e.mailboxes||[];s.length&&B(["ID","Address","AI"],s.map(n=>[ee.default.dim(n.id),n.address,i.has(n.id)?ee.default.green("on"):ee.default.dim("off")])),c()}function $u(e,t){if(t.json)return y(e,t.fields);let i=e.backfill;if(c(),j("History import"),!i){console.log(ee.default.dim(" No import has run yet.")),c();return}d("Status",`${i.status} (${i.phase})`),d("Progress",`${i.processed}/${i.total}${i.percent===null||i.percent===void 0?"":` (${i.percent}%)`}`),d("Failed",String(i.failed??0)),d("Paused",i.paused?"yes":"no"),i.estimated_completion_at&&d("ETA",i.estimated_completion_at),i.can_close_app&&console.log(ee.default.dim(" The import continues in the background.")),c()}function ku(e,t){if(t.json)return y(e,t.fields);let i=e.action_plan||e.plan||e;c(),j("Action preview"),d("ID",i.id),d("Status",i.status||""),i.expires_at&&d("Expires",i.expires_at);for(let s of i.effects||[])c(),console.log(` ${ee.default.bold(s.kind||"effect")} ${ee.default.dim(`mailbox ${s.mailbox_id||""}`)}${s.reply_to_message_id?ee.default.dim(` in reply to ${s.reply_to_message_id}`):""}`),s.body&&console.log(`
207
- ${String(s.body).split(`
208
- `).map(n=>` ${n}`).join(`
205
+ domani sell <domain> --transfer-code <code>`,code:"validation_error",json:t.json,fields:t.fields})}async function cu(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 n=C(!t.json);n.start(`Listing ${$.domain(e)} for sale`);let s={domain:e,price:i};t.description&&(s.description=t.description);let r=await _("/api/domains/sell",{method:"POST",body:JSON.stringify(s)}),o=await r.json();if(r.ok||(n.stop("Listing failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:t.json,fields:t.fields})),t.json){n.stop(""),v(o,t.fields);return}(o.listing?.status??"pending_verification")==="active"?(n.stop(`${w.success} Listed for sale`),x("Sell Domain"),l("Domain",$.domain(o.listing?.domain||e)),l("Price",$.price(i)),l("Status",Se.default.green("active")),c(),console.log(` ${Se.default.dim("Your listing is live on the marketplace.")}`),c()):(n.stop(`${w.success} Verification record ready`),x("Sell Domain"),l("Domain",$.domain(o.listing?.domain||e)),l("Price",$.price(i)),l("Status",Se.default.yellow("pending verification")),c(),console.log(" Add this TXT record at your DNS provider:"),c(),console.log(` ${Se.default.dim("Type:")} ${Se.default.bold("TXT")}`),console.log(` ${Se.default.dim("Name:")} ${Se.default.bold(o.txt_record?.name||"@")}`),console.log(` ${Se.default.dim("Value:")} ${Se.default.bold(o.txt_record?.value||`domani-verify=${o.token}`)}`),c(),console.log(` ${Se.default.dim("DNS propagation may take a few minutes to 48 hours.")}`),c(),A("Once the record is set, verify:",`domani sell ${e} --verify`),c())}async function uu(e,t){let i=C(!t.json);i.start(`Verifying ownership of ${$.domain(e)}`);let n=await _("/api/domains/sell/verify",{method:"POST",body:JSON.stringify({domain:e})}),s=await n.json();if(n.ok||(i.stop("Verification failed"),u(s.error||s.message,{hint:s.hint,status:n.status,json:t.json,fields:t.fields})),t.json){i.stop(""),v(s,t.fields);return}i.stop(`${w.success} ${$.domain(e)} is now listed for sale!`),x("Domain Listed"),l("Domain",$.domain(s.domain||e)),l("Status",Se.default.green(s.status||"active")),s.price&&l("Price",$.price(s.price)),c(),A("Check listing status:",`domani sell ${e} --status`),A("View your deals:","domani deals"),c()}async function mu(e,t){let i=C(!t.json);i.start(`Checking listing status for ${$.domain(e)}`);let n=await _(`/api/domains/sell/status?domain=${encodeURIComponent(e)}`),s=await n.json();if(n.ok||(i.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:n.status,json:t.json,fields:t.fields})),i.stop(`${w.success} Listing status loaded`),t.json){v(s,t.fields);return}let r=s.listing;if(x("Listing Status"),l("Domain",$.domain(s.domain||e)),r){let o=r.status;l("Status",o==="active"?Se.default.green(o):Se.default.yellow(o||"unknown")),r.price&&l("Price",$.price(r.price)),r.description&&l("Description",r.description),r.created_at&&l("Listed",Se.default.dim(new Date(r.created_at).toLocaleDateString()))}else l("Status",Se.default.dim("No listing found"));s.deal&&l("Deal",`${s.deal.status} ($${s.deal.price})`),c()}async function fu(e,t){let i=C(!t.json);i.start(`Removing ${$.domain(e)} from sale`);let n=await _(`/api/domains/sell?domain=${encodeURIComponent(e)}`,{method:"DELETE"}),s=await n.json();if(n.ok||(i.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:n.status,json:t.json,fields:t.fields})),t.json){i.stop(""),v(s,t.fields);return}i.stop(`${w.success} ${$.domain(e)} removed from sale`),c()}async function pu(e,t,i){let n=C(!i.json);n.start(`Looking up active deal for ${$.domain(e)}`);let s=await _(`/api/deals?role=seller&domain=${encodeURIComponent(e)}&status=active`),r=await s.json();s.ok||(n.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:i.json,fields:i.fields}));let a=(r.deals||r.data||[]).filter(p=>p.domain.toLowerCase()===e.toLowerCase());a.length===0&&(n.stop("No active deal found"),u(`No active deal found for ${e}`,{hint:`Make sure you have an active sale for this domain.
206
+ Run 'domani deals --role seller' to see your deals.`,code:"not_found",json:i.json,fields:i.fields}));let d=a[0].id;n.message(`Submitting transfer code for deal ${Se.default.dim(d)}`);let f=await _(`/api/deals/${encodeURIComponent(d)}`,{method:"PATCH",body:JSON.stringify({auth_code:t})}),m=await f.json();if(f.ok||(n.stop("Failed"),u(m.error||m.message,{hint:m.hint,status:f.status,json:i.json,fields:i.fields})),i.json){n.stop(""),v(m,i.fields);return}n.stop(`${w.success} Transfer code submitted for ${$.domain(e)}`),x("Transfer Code Submitted"),l("Domain",$.domain(e)),l("Deal",Se.default.dim(d)),l("Status",Se.default.green(m.status||"code_submitted")),c(),A("Track the deal:",`domani deals ${d}`),c()}G();var xe=U(M(),1);F();async function xa(e,t){return e?yu(e,t):gu(t)}function hu(e){let t=new URLSearchParams;e.role&&t.set("role",e.role),e.status&&t.set("status",e.status),e.limit&&t.set("limit",e.limit),e.cursor&&t.set("cursor",e.cursor);let i=t.toString();return i?`?${i}`:""}async function gu(e){let t=C(!e.json);t.start("Loading deals");let i=hu(e),n=await _(`/api/deals${i}`),s=await n.json();n.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:n.status,json:e.json,fields:e.fields}));let r=s.deals||s.data||[];if(t.stop(`${w.success} ${r.length} deal(s)`),e.json){v(s,e.fields);return}if(r.length===0){c(),console.log(` ${xe.default.dim("No deals found.")}`),c(),A("List a domain for sale:","domani sell <domain> --price <amount>"),c();return}c(),x("Deals");let o=r.map(a=>{let d=a.status==="completed"?xe.default.green:a.status==="active"?xe.default.cyan:a.status==="cancelled"?xe.default.red:xe.default.yellow;return[$.domain(a.domain),$.price(a.price),d(a.status),xe.default.dim(a.role||"-"),xe.default.dim(new Date(a.created_at).toLocaleDateString())]});B(["Domain","Price","Status","Role","Created"],o,[28,12,14,10,14]),c(),s.next_cursor&&(console.log(` ${xe.default.dim(`More: --cursor ${s.next_cursor}`)}`),c())}async function yu(e,t){let i=C(!t.json);i.start(`Loading deal ${xe.default.dim(e)}`);let n=await _(`/api/deals/${encodeURIComponent(e)}`),s=await n.json();if(n.ok||(i.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:n.status,json:t.json,fields:t.fields})),i.stop(`${w.success} Deal loaded`),t.json){v(s,t.fields);return}let r=s.deal||s;x("Deal Details"),l("ID",xe.default.dim(r.id)),l("Domain",$.domain(r.domain)),l("Price",$.price(r.price));let o=r.status==="completed"?xe.default.green:r.status==="active"?xe.default.cyan:r.status==="cancelled"?xe.default.red:xe.default.yellow;l("Status",o(r.status)),r.role&&l("Your Role",r.role),r.buyer&&l("Buyer",xe.default.dim(r.buyer)),r.seller&&l("Seller",xe.default.dim(r.seller)),r.created_at&&l("Created",xe.default.dim(new Date(r.created_at).toLocaleDateString())),r.updated_at&&l("Updated",xe.default.dim(new Date(r.updated_at).toLocaleDateString())),c();let a=r.events||[];if(a.length>0){x("Timeline");for(let d of a){let f=xe.default.dim(new Date(d.created_at).toLocaleString()),m=d.status==="completed"?w.success:d.status==="expired"||d.status==="refunded"?w.error:w.info;console.log(` ${m} ${f} ${d.detail||d.status}`)}c()}(r.status==="escrow_held"||r.status==="epp_pending")&&r.role==="seller"&&(A("Submit transfer code:",`domani sell ${r.domain} --transfer-code <code>`),c())}G();var We=U(M(),1);F();$e();async function Ca(e,t,i){switch(e){case void 0:case"list":case"ls":return bu(i);case"request":case"acquire":case"new":return ja(t,i);case"status":case"get":return Sa(t,i);case"cancel":case"rm":return wu(t,i);default:return e.includes(".")?ja(e,i):Sa(e,i)}}async function ja(e,t){e||u("A domain is required.",{hint:"domani broker request dream.com --max-budget 5000",json:t.json}),Y(e,{json:t.json});let i=C(!t.json);i.start(`Requesting acquisition of ${$.domain(e)}`);let n={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}),n.max_budget=a}let s=await _("/api/broker",{method:"POST",body:JSON.stringify(n)}),r=await s.json();s.ok||(i.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:t.json,fields:t.fields}));let o=r.request||r;if(i.stop(`${w.success} Acquisition requested`),t.json)return v(r,t.fields);x("Broker request"),l("Domain",$.domain(o.domain)),l("Status",nr(o.status)),o.max_budget!=null&&l("Max budget",$.price(o.max_budget)),l("ID",We.default.dim(o.id)),c(),console.log(` ${We.default.dim("We'll source the owner and reach out anonymously. Commission-only - you pay nothing unless a deal closes.")}`),c(),A("Check progress:",`domani broker status ${o.id}`),c()}async function bu(e){let t=C(!e.json);t.start("Loading broker requests");let i=e.status?`?status=${encodeURIComponent(e.status)}`:"",n=await _(`/api/broker${i}`),s=await n.json();n.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:n.status,json:e.json,fields:e.fields}));let r=s.requests||s.data||[];if(t.stop(`${w.success} ${r.length} request(s)`),e.json)return v(s,e.fields);if(r.length===0){c(),console.log(` ${We.default.dim("No broker requests yet.")}`),c(),A("Acquire a taken domain:","domani broker request <domain> --max-budget <amount>"),c();return}c(),x("Broker requests"),B(["Domain","Status","Budget","ID"],r.map(o=>[$.domain(o.domain),nr(o.status),o.max_budget!=null?$.price(o.max_budget):We.default.dim("-"),We.default.dim(o.id)])),c()}async function Sa(e,t){e||u("A request ID is required.",{hint:"domani broker status <id> (list with: domani broker)",json:t.json});let i=C(!t.json);i.start("Loading request");let n=await _(`/api/broker/${encodeURIComponent(e)}`),s=await n.json();n.ok||(i.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:n.status,json:t.json,fields:t.fields}));let r=s.request||s;if(i.stop(`${w.success} ${$.domain(r.domain)}`),t.json)return v(s,t.fields);x("Broker request"),l("Domain",$.domain(r.domain)),l("Status",nr(r.status)),r.max_budget!=null&&l("Max budget",$.price(r.max_budget)),l("Contacted",r.contacted?We.default.green("yes"):We.default.dim("not yet")),r.failure_reason&&l("Reason",We.default.yellow(r.failure_reason)),l("ID",We.default.dim(r.id)),c(),r.negotiation_id?(console.log(` ${We.default.dim("The owner responded - an anonymous negotiation is open.")}`),c(),A("Review the offer:","domani deals"),c()):["sourcing","contacted","negotiating"].includes(r.status)&&(A("Cancel this request:",`domani broker cancel ${r.id}`),c())}async function wu(e,t){e||u("A request ID is required.",{hint:"domani broker cancel <id>",json:t.json});let i=C(!t.json);i.start("Cancelling request");let n=await _(`/api/broker/${encodeURIComponent(e)}`,{method:"DELETE"}),s=await n.json();if(n.ok||(i.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:n.status,json:t.json,fields:t.fields})),i.stop(`${w.success} Request cancelled`),t.json)return v(s,t.fields);c()}function nr(e){return["completed","agreed"].includes(e)?We.default.green(e):["negotiating","contacted","sourcing"].includes(e)?We.default.cyan(e):["declined","no_contact","failed","expired","cancelled"].includes(e)?We.default.dim(e):e}G();var we=U(M(),1);F();async function Ia(e){return e.read?ku(e):$u(e)}function vu(e){let t=new URLSearchParams;e.unread&&t.set("unread","true"),e.limit&&t.set("limit",e.limit),e.cursor&&t.set("cursor",e.cursor);let i=t.toString();return i?`?${i}`:""}async function $u(e){let t=C(!e.json);t.start("Loading notifications");let i=vu(e),n=await _(`/api/notifications${i}`),s=await n.json();n.ok||(t.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:n.status,json:e.json,fields:e.fields}));let r=s.notifications||s.data||[],o=s.unread_count??r.filter(d=>!d.read).length;if(t.stop(`${w.success} ${r.length} notification(s)${o>0?` ${w.dot} ${we.default.yellow(`${o} unread`)}`:""}`),e.json){v(s,e.fields);return}if(r.length===0){c(),console.log(` ${we.default.dim("No notifications.")}`),c();return}c(),x("Notifications");let a=r.map(d=>{let f=d.read?we.default.dim(w.dot):we.default.cyan(w.info),m=_u(d.type),p=d.read?we.default.dim(d.title):we.default.white(d.title),y=d.body?d.read?we.default.dim(Oa(d.body,40)):we.default.dim(Oa(d.body,40)):we.default.dim("-"),k=we.default.dim(new Date(d.created_at).toLocaleDateString());return[f,m,p,y,k]});B(["","Type","Title","Body","Date"],a,[3,16,28,42,14]),c(),s.next_cursor&&(console.log(` ${we.default.dim(`More: --cursor ${s.next_cursor}`)}`),c()),o>0&&(console.log(` ${we.default.dim("Mark all as read:")} ${we.default.cyan("domani notifications --read")}`),c())}async function ku(e){let t=C(!e.json);t.start("Marking all notifications as read");let i=await _("/api/notifications/read-all",{method:"POST"}),n=await i.json();if(i.ok||(t.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:i.status,json:e.json,fields:e.fields})),e.json){t.stop(""),v(n,e.fields);return}let s=n.count??0;t.stop(`${w.success} ${s} notification(s) marked as read`),c()}function _u(e){let t={deal:we.default.cyan,sale:we.default.green,purchase:we.default.green,transfer:we.default.yellow,expiry:we.default.red,security:we.default.red,billing:we.default.yellow,email:we.default.blue},i=e.split(".")[0].split("_")[0];return(t[i]||we.default.dim)(e)}function Oa(e,t){return e.length<=t?e:e.slice(0,t-1)+"\u2026"}G();var Et=U(M(),1);F();async function Ra(e){let t=e.limit?Number(e.limit):20,i=await _(`/api/billing/invoices?limit=${t}`),n=await i.json();if(i.ok||u(n.error||n.message,{hint:n.hint,status:i.status,json:e.json,fields:e.fields}),e.json){v({...n,count:n.invoices.length},e.fields);return}if(n.invoices.length===0){console.log(` ${Et.default.dim("No invoices yet.")}`);return}x(`Invoices (${n.invoices.length})`),c();for(let s of n.invoices){let r=`$${(s.amount_paid/100).toFixed(2)}`,o=new Date(s.created).toLocaleDateString(),a=s.number||s.id;console.log(` ${w.success} ${Et.default.bold(a)} ${Et.default.green(r)} ${Et.default.dim(o)}`),s.description&&console.log(` ${Et.default.dim(s.description)}`),s.hosted_invoice_url&&console.log(` ${Et.default.dim(s.hosted_invoice_url)}`)}c(),n.has_more&&(console.log(` ${Et.default.dim(`Showing ${n.invoices.length} most recent. Use --limit to see more.`)}`),c())}G();var Di=U(M(),1);F();async function Aa(e){let t=C(!e?.json);t.start("Setting up billing session");let i=await _("/api/billing/setup",{method:"POST",body:JSON.stringify({mode:"checkout"})}),n=await i.json();if(i.ok||(t.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:i.status,json:e?.json})),n.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){v({url:n.url});return}c(),console.log(` ${Di.default.dim("Opening browser")} ${w.arrow} ${$.url(n.url)}`),c(),Fe(n.url),console.log(` ${w.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")}`),c()}G();var sr=U(M(),1);F();async function Ta(e){let t=C(!e?.json);t.start("Creating upgrade session");let i=await _("/api/billing/subscribe",{method:"POST"}),n=await i.json();if(!i.ok){t.stop("Failed"),n.code==="ALREADY_SUBSCRIBED"||n.code==="ALREADY_PRO"?u("You're already on a paid plan.",{json:e?.json}):u(n.error||n.message,{hint:n.hint,status:i.status,json:e?.json});return}if(t.stop("Ready"),e?.json){v({url:n.url},e?.fields);return}c(),console.log(` ${sr.default.dim("Opening browser")} ${w.arrow} ${$.url(n.url)}`),c(),Fe(n.url),console.log(` ${w.info} ${sr.default.dim("Complete your plan upgrade in the browser.")}`),c()}G();var rr=U(M(),1);F();async function Ea(e){let t=C(!e?.json);t.start("Cancelling subscription");let i=await _("/api/billing/cancel",{method:"POST"}),n=await i.json();if(!i.ok){t.stop("Failed"),n.code==="NOT_PAID"||n.code==="NOT_PRO"?u("You're not on a paid plan.",{json:e?.json}):u(n.error||n.message,{hint:n.hint,status:i.status,json:e?.json});return}if(t.stop("Done"),e?.json){v(n,e?.fields);return}c();let s=n.cancel_at?new Date(n.cancel_at).toLocaleDateString():"end of billing period";console.log(` ${w.success} ${rr.default.dim("Subscription cancelled.")} Access continues until ${rr.default.cyan(s)}.`),c()}G();var st=U(M(),1);F();$e();Ze();async function Pa(e,t,i){e||(e=await ge()),Y(e,i);let n=[];if(t?.length&&n.push(...t),i.set&&n.push(...i.set.split(",").map(s=>s.trim()).filter(Boolean)),n.length>0||i.reset){await ju(e,n,i);return}await xu(e,i)}async function xu(e,t){let i=C(!t.json);i.start(`Fetching nameservers for ${$.domain(e)}`);let n=await _(`/api/domains/${encodeURIComponent(e)}/nameservers`),s=await n.json();if(n.ok||(i.stop("Failed"),u(s.error||s.message,{hint:s.hint,status:n.status,json:t.json,fields:t.fields})),i.stop(`Nameservers for ${$.domain(e)}`),t.json){v(s,t.fields);return}if(c(),s.nameservers.length===0)console.log(` ${w.warning} ${st.default.yellow("No nameservers configured.")}`),console.log(` ${st.default.dim("DNS operations (parking, email, connect) will not work.")}`),c(),A("Set default nameservers:",`domani nameservers ${e} --reset`);else{x("Nameservers");for(let r of s.nameservers)console.log(` ${w.success} ${st.default.cyan(r)}`);s.default_nameservers&&s.nameservers.length===s.default_nameservers.length&&s.nameservers.every(o=>s.default_nameservers.includes(o))&&(c(),console.log(` ${st.default.dim("Using default nameservers.")}`))}s.default_nameservers?.length&&(c(),l("Defaults",s.default_nameservers.map(r=>st.default.dim(r)).join(st.default.dim(", ")))),c()}async function ju(e,t,i){let n=C(!i.json);if(i.reset){n.start(`Fetching default nameservers for ${$.domain(e)}`);let o=await _(`/api/domains/${encodeURIComponent(e)}/nameservers`),a=await o.json();o.ok||(n.stop("Failed"),u(a.error,{hint:a.hint,status:o.status,json:i.json,fields:i.fields})),a.default_nameservers?.length||(n.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,n.stop(`Using defaults: ${t.map(d=>st.default.cyan(d)).join(st.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 K("nameservers_set",{domain:e,nameservers:t},i.json,i.fields);n.start(`Setting nameservers for ${$.domain(e)}`);let s=await _(`/api/domains/${encodeURIComponent(e)}/nameservers`,{method:"PUT",body:JSON.stringify({nameservers:t})}),r=await s.json();if(s.ok||(n.stop("Failed"),u(r.error||r.message,{hint:r.hint,status:s.status,json:i.json,fields:i.fields})),n.stop(`${w.success} Nameservers updated`),i.json){v(r,i.fields);return}c();for(let o of r.nameservers)console.log(` ${w.success} ${st.default.cyan(o)}`);c(),console.log(` ${st.default.dim("Changes may take up to 48 hours to propagate.")}`),c(),A("Check propagation:",`domani status ${e}`),c()}var Da=require("crypto"),On=U(require("fs"),1);wt();var Ni=U(M(),1);F();function Su(e,t){let i=e.split(".").map(Number),n=t.split(".").map(Number);for(let s=0;s<3;s++){if((i[s]||0)>(n[s]||0))return 1;if((i[s]||0)<(n[s]||0))return-1}return 0}async function Na(e){let t=!!e?.json,i=C(!t);i.start("Checking for updates");let n=Je();try{let s=await fetch(`${n}/api/cli/version`);s.ok||(i.stop("Failed"),u("Could not check for updates"));let r=await s.json(),o=r.version,a=r.sha256;if(Su(o,Ce)<=0){i.stop(`${w.success} Already up to date (v${Ce})`),t&&v({current:Ce,latest:o,up_to_date:!0});return}if(t&&!e?.yes){i.stop(""),v({current:Ce,latest:o,up_to_date:!1,hint:"Run `domani update --yes` to upgrade non-interactively, or `domani update` in an interactive terminal."});return}i.stop(t?"":`New version available: ${Ni.default.cyan(Ce)} ${w.arrow} ${Ni.default.green(o)}`);let d=C(!t);d.start("Downloading update");let f=`${n}/cli/domani.js`,m=await fetch(f);m.ok||(d.stop("Download failed"),u(`Failed to download from ${f}`));let p=await m.text();a&&(0,Da.createHash)("sha256").update(p).digest("hex")!==a&&(d.stop("Integrity check failed"),u("Downloaded file does not match expected hash - update aborted"));let y=process.argv[1];y||(d.stop("Failed"),u("Could not determine binary path"));let k=On.default.realpathSync(y),b=k+".tmp";if(On.default.writeFileSync(b,p,{mode:493}),On.default.renameSync(b,k),d.stop(`${w.success} Updated to v${o}`),t){v({updated:!0,from:Ce,to:o});return}c(),console.log(` ${Ni.default.dim("Restart your terminal or run")} domani --version ${Ni.default.dim("to verify")}`),c()}catch(s){u(`Update failed: ${s instanceof Error?s.message:String(s)}`)}}var In=U(require("fs"),1),Ua=U(require("path"),1),qa=U(require("os"),1);Ne();var Ui=U(M(),1);F();async function Ma(){let e=process.argv[1],t=e?In.default.realpathSync(e):null,i=Ua.default.join(qa.default.homedir(),".domani");if(c(),console.log(` ${Ui.default.bold("This will remove:")}`),t&&console.log(` ${w.dot} CLI binary: ${Ui.default.dim(t)}`),console.log(` ${w.dot} Config dir: ${Ui.default.dim(i)}`),c(),await Ve({message:"Uninstall domani?"})!==!0){console.log(` ${Ui.default.dim("Cancelled.")}`);return}In.default.rmSync(i,{recursive:!0,force:!0}),t&&In.default.unlinkSync(t),c(),console.log(` ${w.success} domani uninstalled.`),c()}G();var re=U(M(),1);F();async function La(e,t){let i=t?.json,n=t?.fields,s=e?`/api/schema?command=${encodeURIComponent(e)}`:"/api/schema",r=C(!i);r.start("Loading schema");let o=await _e(s),a=await o.json();if(o.ok||(r.stop("Failed"),u(a.error||a.message,{hint:a.hint,status:o.status,json:i,fields:n})),r.stop("Schema loaded"),i){v(a,n);return}e?Ou(e,a):Cu(a.commands)}function Cu(e){x("Commands");let t=Object.entries(e).map(([i,n])=>[re.default.bold(re.default.cyan(i)),n.description]);B(["Command","Description"],t,[20,50]),c(),console.log(` ${re.default.dim("Run")} ${re.default.cyan("domani schema <command>")} ${re.default.dim("for full details")}`),c()}function Ou(e,t){if(x(`domani ${e}`),console.log(` ${t.description}`),c(),console.log(` ${$.label("Usage:")} ${re.default.cyan(t.usage)}`),t.arguments&&Object.keys(t.arguments).length>0){c(),console.log(` ${re.default.bold("Arguments")}`);for(let[i,n]of Object.entries(t.arguments)){let s=n.required?re.default.red("*"):"",r=re.default.dim(`(${n.type}${n.variadic?", variadic":""})`);console.log(` ${re.default.cyan(i)}${s} ${r}`),n.description&&console.log(` ${re.default.dim(n.description)}`)}}if(t.options&&Object.keys(t.options).length>0){c(),console.log(` ${re.default.bold("Options")}`);for(let[i,n]of Object.entries(t.options)){let s=n.required?re.default.red("*"):"",r=re.default.dim(`(${n.type})`),o=n.choices?re.default.dim(` [${n.choices.join(", ")}]`):"";console.log(` ${re.default.cyan(`--${i}`)}${s} ${r}${o}`),console.log(` ${re.default.dim(n.description)}`)}}if(t.api)if(c(),console.log(` ${re.default.bold("API")}`),Iu(t.api))Fa(t.api);else for(let[i,n]of Object.entries(t.api))console.log(` ${re.default.bold(re.default.yellow(i))}`),Fa(n,6);t.errors&&t.errors.length>0&&(c(),console.log(` ${re.default.bold("Errors")}`),console.log(` ${t.errors.map(i=>re.default.dim(i)).join(re.default.dim(", "))}`)),c()}function Iu(e){return typeof e=="object"&&e!==null&&"method"in e&&"path"in e}function Fa(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[n,s]of Object.entries(e.parameters)){let r=s.required?re.default.red("*"):"",o=[s.type];s.enum&&o.push(`enum: ${s.enum.join(", ")}`),s.minimum!==void 0&&o.push(`min: ${s.minimum}`),s.maximum!==void 0&&o.push(`max: ${s.maximum}`),s.maxItems!==void 0&&o.push(`maxItems: ${s.maxItems}`),s.items&&o.push(`items: ${s.items}`),s.in==="path"&&o.push("in: path");let a=re.default.dim(`(${o.join(", ")})`);console.log(`${i} ${re.default.cyan(n)}${r} ${a}`),s.description&&console.log(`${i} ${re.default.dim(s.description)}`)}}G();var He=U(M(),1);Ne();F();async function Va(e){let t=C(!e.json);t.start("Loading payment method");let i=await _("/api/me"),n=await i.json();if(i.ok||(t.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:i.status,json:e.json,fields:e.fields})),e.json){t.stop(""),v(n.card?{has_payment_method:n.has_payment_method,card:n.card}:{has_payment_method:!1},e.fields);return}if(!n.has_payment_method||!n.card){t.stop("No payment method on file"),c(),console.log(` ${He.default.dim("Add a card with")} ${He.default.cyan("domani card add")}`),c();return}let{brand:s,last4:r,exp_month:o,exp_year:a}=n.card,d=`${String(o).padStart(2,"0")}/${a}`,f=s.charAt(0).toUpperCase()+s.slice(1);t.stop("Payment method loaded"),x("Payment method"),l("Card",`${He.default.bold(f)} \u2022\u2022\u2022\u2022 ${He.default.bold(r)}`),l("Expires",d),c(),console.log(` ${He.default.dim("Update with")} ${He.default.cyan("domani card add")}`),c()}async function Wa(e){let t=C(!e?.json);t.start("Setting up payment session");let i=await _("/api/billing/setup",{method:"POST",body:JSON.stringify({mode:"checkout"})}),n=await i.json();if(i.ok||(t.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:i.status,json:e?.json})),n.url||(t.stop("Failed"),u("No checkout URL returned",{json:e?.json})),t.stop("Checkout ready"),e?.json){v({url:n.url},e?.fields);return}c(),console.log(` ${He.default.dim("Opening browser")} ${w.arrow} ${$.url(n.url)}`),c(),Fe(n.url),console.log(` ${w.info} ${He.default.dim("Complete payment setup in your browser.")}`),console.log(` ${He.default.dim(" After setup, you can purchase domains with")} ${He.default.cyan("domani buy")}`),c()}async function Ha(e){if(!e?.yes&&!e?.json){let s=await Ve({message:"Remove your saved payment method?"});if(ae(s)||!s){console.log(` ${He.default.dim("Cancelled.")}`);return}}let t=C(!e?.json);t.start("Removing payment method");let i=await _("/api/billing/card",{method:"DELETE"}),n=await i.json();if(i.ok||(t.stop("Failed"),u(n.error||n.message,{hint:n.hint,status:i.status,json:e?.json})),t.stop(`${w.success} Payment method removed`),e?.json){v({removed:!0},e?.fields);return}c(),console.log(` ${He.default.dim("Add a new card with")} ${He.default.cyan("domani card add")}`),c()}var or=U(M(),1);G();F();async function fe(e,t,i,n){let s=C(!i.json);s.start(n);let r=await _(e,t),o=await r.json();return r.ok||(s.stop("Failed"),u(o.error||o.message,{hint:o.hint,status:r.status,json:i.json,fields:i.fields})),s.stop(`${w.success} Done`),o}async function Ja(e,t){if(!e||e==="list"){let i=await fe("/api/workspaces",void 0,t,"Loading workspaces");if(t.json)return v(i,t.fields);if(c(),x("Workspaces"),!i.workspaces.length){console.log(` ${or.default.dim("No workspaces yet.")}`),A("Create one:","domani workspace create --name Acme");return}B(["ID","Name","Role","Mailboxes","Members"],i.workspaces.map(n=>[n.id,n.name,n.role,String(n.mailbox_count),String(n.member_count)]),[28,28,10,10,8]),c();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 fe("/api/workspaces",{method:"POST",body:JSON.stringify({name:t.name})},t,"Creating workspace");if(t.json)return v(i,t.fields);c(),x("Workspace Created"),l("ID",i.id),l("Name",i.name),c();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 fe(`/api/workspaces/${encodeURIComponent(t.id)}`,void 0,t,"Loading workspace");if(t.json)return v(i,t.fields);c(),x(i.name),l("Role",i.role),l("Mailboxes",i.mailboxes.length),l("Members",i.members.length),c(),B(["Email","Role","Mailbox grants"],i.members.map(n=>[n.email,n.role,String(n.mailbox_grants.length)]),[42,12,16]),c();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 fe(`/api/workspaces/${encodeURIComponent(t.id)}/access`,void 0,t,"Loading access graph");if(t.json)return v(a,t.fields);c(),x("Access Graph"),l("Principals",a.principals.length),l("Mailboxes",a.mailboxes.length),l("Groups",a.groups.length),l("Collections",a.collections.length),l("Active grants",a.grants.length),l("Pending offers",a.offers.length),c();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,n]=t.subject.split(":",2),[s,r]=t.resource.split(":",2);(!n||!["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(s))&&u("Invalid --resource",{hint:"Use mailbox:<id> or collection:<id>",json:t.json});let o=await fe(`/api/workspaces/${encodeURIComponent(t.id)}/access`,{method:"PUT",body:JSON.stringify({mode:t.apply?"apply":"plan",subject:i==="group"?{type:"group",id:n}:{type:"principal",principal:{type:i,id:n}},resource:{type:s,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 v(o,t.fields);c(),x(t.apply?"Access Applied":"Access Plan"),l("Action",o.action),l("Changed",String(o.changed)),o.grant_id&&l("Grant",o.grant_id),c();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(s=>s.trim()).filter(Boolean).map(s=>{let[r,o]=s.split(":",2);return o||u(`Invalid principal: ${s}`,{hint:"Use type:id",json:t.json}),{type:r,id:o,label:o}}),n=await fe(`/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 v(n,t.fields);c(),x("Access Group Synced"),l("ID",n.id),l("Principals",n.principal_count),c();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 fe(`/api/workspaces/${encodeURIComponent(t.id)}/access/collections`,{method:"PUT",body:JSON.stringify({id:t.collectionId,name:t.name,mailbox_ids:t.mailboxes?.split(",").map(n=>n.trim()).filter(Boolean)??[]})},t,"Syncing mailbox collection");if(t.json)return v(i,t.fields);c(),x("Mailbox Collection Synced"),l("ID",i.id),l("Mailboxes",i.mailbox_count),c();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(s=>s.trim()).filter(Boolean).map(s=>({resource:{type:"mailbox",id:s},profile:t.profile||"responder"})),n=await fe(`/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 v(n,t.fields);c(),x("Access Offered"),l("Email",n.email),l("Expires",n.expires_at),c();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 fe("/api/workspaces/access/offers/accept",{method:"POST",body:JSON.stringify({token:t.token})},t,"Accepting access offer");if(t.json)return v(i,t.fields);c(),x("Access Accepted"),l("Workspace",i.workspace_name),l("Ownership",i.ownership),c();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 fe(`/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 v(i,t.fields);c(),x("Access Revoked"),l("Grant",i.grant_id),l("Version",i.version),c();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 fe(`/api/workspaces/${encodeURIComponent(t.id)}`,{method:"PATCH",body:JSON.stringify({name:t.name})},t,"Renaming workspace");if(t.json)return v(i,t.fields);c(),x("Workspace Renamed"),l("ID",i.id),l("Name",i.name),c();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 fe(`/api/workspaces/${encodeURIComponent(t.id)}/invitations`,{method:"POST",body:JSON.stringify({email:t.email,role:t.role,mailbox_ids:t.mailboxes?.split(",").map(n=>n.trim()).filter(Boolean),mailbox_role:t.mailboxRole})},t,"Sending invitation");if(t.json)return v(i,t.fields);c(),x("Invitation Sent"),l("Email",i.email),l("Role",i.role),l("Expires",i.expires_at),c();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 fe("/api/workspaces/invitations/accept",{method:"POST",body:JSON.stringify({token:t.token})},t,"Accepting invitation");if(t.json)return v(i,t.fields);c(),x("Workspace Joined"),l("Workspace",i.workspace_name),l("Role",i.role),c();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 fe(`/api/workspaces/${encodeURIComponent(t.id)}/invitations/${encodeURIComponent(t.invitationId)}`,{method:"DELETE"},t,"Revoking invitation");if(t.json)return v(i,t.fields);c(),x("Invitation Revoked"),l("Invitation",i.invitation_id),c();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 fe(`/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 v(i,t.fields);c(),x("Member Updated"),l("Membership",i.id),l("Role",i.role),c();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 fe(`/api/workspaces/${encodeURIComponent(t.id)}/members/${encodeURIComponent(t.membershipId)}`,{method:"DELETE"},t,"Removing member and revoking access");if(t.json)return v(i,t.fields);c(),x("Member Removed"),l("Membership",i.membership_id),c();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 fe(`/api/workspaces/${encodeURIComponent(t.id)}/members/me`,{method:"DELETE"},t,"Leaving workspace and revoking access");if(t.json)return v(i,t.fields);c(),x("Workspace Left"),l("Workspace",i.workspace_id),c();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 fe(`/api/workspaces/${encodeURIComponent(t.id)}/ownership-transfer`,{method:"POST",body:JSON.stringify({membership_id:t.membershipId})},t,"Requesting ownership transfer");if(t.json)return v(i,t.fields);c(),x("Ownership Transfer Requested"),l("To",i.to_email),l("Expires",i.expires_at),l("Billing",i.billing),c();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 fe("/api/workspaces/ownership-transfers/accept",{method:"POST",body:JSON.stringify({token:t.token})},t,"Accepting ownership");if(t.json)return v(i,t.fields);c(),x("Ownership Transferred"),l("Workspace",i.workspace_id),l("Domains",i.domains_transferred),l("Mailboxes",i.mailboxes_transferred),l("Previous owner",i.previous_owner_role),c();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 fe(`/api/workspaces/${encodeURIComponent(t.id)}/ownership-transfer/${encodeURIComponent(t.transferId)}`,{method:"DELETE"},t,"Revoking ownership transfer");if(t.json)return v(i,t.fields);c(),x("Ownership Transfer Revoked"),l("Transfer",i.transfer_id),c();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 fe(`/api/workspaces/${encodeURIComponent(t.id)}/mailboxes`,{method:"POST",body:JSON.stringify({mailbox_id:t.mailboxId})},t,"Adopting mailbox boundary");if(t.json)return v(i,t.fields);c(),x(i.adopted?"Mailbox Boundary Adopted":"Already in Workspace"),l("Address",i.address),l("Mailboxes",i.mailbox_ids?.length??1),c();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 fe(`/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 v(i,t.fields);c(),x("Mailbox Access Granted"),l("Membership",i.membership_id),l("Mailbox",i.mailbox_id),l("Role",i.role),c();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 fe(`/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 v(i,t.fields);c(),x("Mailbox Access Revoked"),l("Membership",i.membership_id),l("Mailbox",i.mailbox_id),c();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 fe(`/api/workspaces/${encodeURIComponent(t.id)}/billing/checkout`,{method:"POST",body:JSON.stringify({plan:t.plan})},t,"Creating secure checkout");if(t.json)return v(i,t.fields);c(),x("Workspace Checkout"),l("Plan",i.plan),l("URL",i.url),c(),i.url&&t.open!==!1&&(console.log(` ${or.default.dim("Opening browser")} ${w.arrow} ${$.url(i.url)}`),Fe(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 fe(`/api/workspaces/${encodeURIComponent(t.id)}/billing/cancel`,{method:"POST"},t,"Scheduling cancellation");if(t.json)return v(i,t.fields);c(),x("Cancellation Scheduled"),l("Message",i.message),i.cancel_at&&l("Cancels",i.cancel_at),c();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 qi=U(M(),1);G();var Rn=U(require("node:crypto"),1),pi=U(require("node:fs"),1),Ba=U(require("node:os"),1),An=U(require("node:path"),1),Ru=process.env.DOMANI_CONFIG_DIR||An.default.join(Ba.default.homedir(),".domani"),Ga=An.default.join(Ru,"mutations");function Au(e){return An.default.join(Ga,`${Rn.default.createHash("sha256").update(e).digest("hex")}.json`)}function pt(e,t,i){let n=Au(e),s=Rn.default.createHash("sha256").update(JSON.stringify(t)).digest("hex");if(!i)try{let o=JSON.parse(pi.default.readFileSync(n,"utf8"));if(o.key&&o.fingerprint===s)return{key:o.key,complete:()=>{try{pi.default.unlinkSync(n)}catch{}}}}catch{}let r=i||`cli-${Rn.default.randomUUID()}`;return pi.default.mkdirSync(Ga,{recursive:!0,mode:448}),pi.default.writeFileSync(n,JSON.stringify({key:r,fingerprint:s}),{mode:384}),{key:r,complete:()=>{try{pi.default.unlinkSync(n)}catch{}}}}F();function Ka(e){if(e.clearUpstreamHeaders)return{};let t={};for(let[i,n]of[["Authorization",e.upstreamAuthorizationEnv],["X-Api-Key",e.upstreamApiKeyEnv]]){if(!n)continue;let s=process.env[n];s||u(`Environment variable ${n} is empty`,{code:"validation_error",json:e.json}),t[i]=s}return Object.keys(t).length?t:void 0}async function zt(e,t){let i=await e.json();return e.ok||u(i.error||i.message,{hint:i.hint,status:e.status,json:t.json,fields:t.fields}),i}function Tn(e,t){if(t.json)return v(e,t.fields);let i=e.http_route||e;c(),x("HTTP Route"),l("ID",i.id),l("URL",i.url),l("Upstream",i.upstream),l("Status",i.status),l("Expires",i.expires_at),l("Browser mode",i.browser_mode||"stateless"),i.upstream_verification?.secret&&(l("Verification secret",qi.default.yellow(i.upstream_verification.secret)),console.log(qi.default.dim(" Save this secret now. It will not be shown again after this receipt."))),c()}function Tu(e){let t=new URLSearchParams;e.domain&&t.set("domain",e.domain),e.hostname&&t.set("hostname",e.hostname),e.status&&t.set("status",e.status),e.limit&&t.set("limit",e.limit),e.cursor&&t.set("cursor",e.cursor);let i=t.toString();return i?`?${i}`:""}async function za(e,t,i){if(!e||e==="list"){let n=await zt(await _(`/api/http-routes${Tu(i)}`),i);if(i.json)return v(n,i.fields);c(),x("HTTP Routes");for(let s of n.http_routes)console.log(` ${qi.default.dim(s.id)} ${s.hostname} ${s.status} ${s.upstream}`);c(),n.next_cursor&&(console.log(` ${qi.default.dim(`More: --cursor ${n.next_cursor}`)}`),c());return}if(e==="create"){i.upstream||u("--upstream is required",{code:"validation_error",json:i.json});let n=Ka(i),s={...i.hostname?{hostname:i.hostname}:{},upstream:i.upstream,...i.expiresIn?{expires_in:Number(i.expiresIn)}:{},...i.hostHeader?{host_header:i.hostHeader}:{},...i.upstreamVerification?{upstream_verification:i.upstreamVerification}:{},...n?{upstream_headers:n}:{}},r=pt(`route:create:${i.hostname||"auto"}`,s,i.idempotencyKey),o=C(!i.json);o.start("Creating HTTP route");let a=await zt(await _("/api/http-routes",{method:"POST",headers:{"Idempotency-Key":r.key},body:JSON.stringify(s)}),i);return r.complete(),o.stop(`${w.success} HTTP route created`),Tn(a,i)}if(t||u("Route ID is required",{hint:`Usage: domani route ${e} <id>`,code:"validation_error",json:i.json}),e==="get")return Tn(await zt(await _(`/api/http-routes/${encodeURIComponent(t)}`),i),i);if(e==="delete"){let n=await _(`/api/http-routes/${encodeURIComponent(t)}`,{method:"DELETE"});if(n.ok||await zt(n,i),i.json)return v({deleted:!0,id:t},i.fields);console.log(`${w.success} HTTP route deleted`);return}if(e==="refresh"){i.expiresIn||u("--expires-in is required",{code:"validation_error",json:i.json});let n={expires_in:Number(i.expiresIn)},s=pt(`route:refresh:${t}`,n,i.idempotencyKey),r=await zt(await _(`/api/http-routes/${encodeURIComponent(t)}`,{method:"PATCH",headers:{"Idempotency-Key":s.key},body:JSON.stringify(n)}),i);return s.complete(),Tn(r,i)}if(e==="rotate-verification"){let n=pt(`route:rotate-verification:${t}`,{},i.idempotencyKey),s=await zt(await _(`/api/http-routes/${encodeURIComponent(t)}/upstream-verification/rotate`,{method:"POST",headers:{"Idempotency-Key":n.key}}),i);return n.complete(),i.json?v(s,i.fields):Tn(s,i)}if(e==="rotate-headers"){let n=Ka(i);n||u("Provide an upstream header environment variable or --clear-upstream-headers",{code:"validation_error",json:i.json});let s=pt(`route:rotate-headers:${t}`,{upstream_headers:n},i.idempotencyKey),r=await zt(await _(`/api/http-routes/${encodeURIComponent(t)}/upstream-headers`,{method:"PUT",headers:{"Idempotency-Key":s.key},body:JSON.stringify({upstream_headers:n})}),i);if(s.complete(),i.json)return v(r,i.fields);console.log(`${w.success} Upstream headers replaced: ${r.upstream_header_names.join(", ")||"none"}`);return}u(`Unknown action: ${e}`,{hint:"Actions: create, list, get, refresh, rotate-verification, rotate-headers, delete",code:"validation_error",json:i.json})}var Q=U(M(),1),Za=require("node:fs");G();F();var dr="mailzero-personal-ai.v1",Z=class extends Error{constructor(i,n){super(i);this.hint=n;this.name="AssistantUsageError"}},Eu={choose:"choose",instruct:"instruct","take-over":"take_over",snooze:"snooze",ignore:"ignore",correct:"correct",approve:"approve",reject:"reject",tag:"tag"},Pu=["today","settings","set","preview","backfill","retry","item","choose","instruct","snooze","ignore","take-over","correct","approve","reject","tag","plan","activity","export","delete","brief","facts","sender","task","lease","release","effects","escalate","report","rules","approvals","suggestions","metrics"];function ar(e,t,i){if(!e)throw new Z(`${t} is required`,i);try{return JSON.parse(e)}catch{throw new Z(`${t} must be valid JSON`,i)}}function En(e){return(e||"").split(",").map(t=>t.trim()).filter(Boolean)}function Ya(e){return(e||"").split(",").map(t=>t.trim()).filter(Boolean)}function Yt(e,t,i){let n=Number(e);if(!Number.isInteger(n)||n<i)throw new Z(`${t} must be an integer of at least ${i}`);return n}function Du(e,t,i){let n=e||"today";switch(n){case"today":{let s=new URLSearchParams;i.category&&s.set("category",i.category.trim().toLowerCase()),i.tag&&s.set("tag",i.tag.trim().toLowerCase());let r=s.toString();return{method:"GET",path:r?`/api/assistant/today?${r}`:"/api/assistant/today"}}case"settings":return{method:"GET",path:"/api/assistant/settings"};case"set":{let s={};if(i.enable&&i.disable)throw new Z("Use either --enable or --disable");if(i.pause&&i.resume)throw new Z("Use either --pause or --resume");if(i.enable&&(s.enabled=!0),i.disable&&(s.enabled=!1),i.shadow!==void 0&&(s.shadow_enabled=i.shadow),i.pause&&(s.paused=!0),i.resume&&(s.paused=!1),i.none?s.mailbox_ids=[]:i.mailboxes!==void 0&&(s.mailbox_ids=Ya(i.mailboxes)),i.days!==void 0&&(s.history_window_days=Yt(i.days,"--days",1)),i.attachmentVision!==void 0){if(!["on","off"].includes(i.attachmentVision))throw new Z("--attachment-vision must be on or off");s.attachment_vision=i.attachmentVision==="on"}if(!Object.keys(s).length)throw new Z("Provide at least one setting","Options: --enable, --disable, --shadow, --no-shadow, --pause, --resume, --mailboxes <ids>, --none, --days <n>, --attachment-vision <on|off>");return{method:"PUT",path:"/api/assistant/settings",body:s}}case"preview":{if(!i.consent)throw new Z("--consent is required to start the assistant",`Consent means Domani may read the selected mailboxes and send bounded, minimized message content to the approved private model route (version ${dr}). Nothing is ever sent on your behalf. You can pause or delete derived data at any time.`);let s=Ya(i.mailboxes);if(!s.length)throw new Z("--mailboxes is required","Pass owned mailbox IDs, comma-separated. List them with: domani assistant settings");return{method:"POST",path:"/api/assistant/preview",body:{mailbox_ids:s,history_window_days:i.days===void 0?30:Yt(i.days,"--days",1),consent:!0,consent_version:dr}}}case"backfill":return{method:"GET",path:"/api/assistant/backfill"};case"retry":return{method:"POST",path:"/api/assistant/backfill",idempotency:"assistant:retry"};case"item":if(!t)throw new Z("Work item ID is required","Usage: domani assistant item <id>");return{method:"GET",path:`/api/assistant/work-items/${encodeURIComponent(t)}`};case"brief":{if(t)return{method:"GET",path:`/api/assistant/work-items/${encodeURIComponent(t)}/brief`};if(!i.correspondent)throw new Z("Work item ID or --correspondent is required","Usage: domani assistant brief <id> | domani assistant brief --correspondent ada@example.com [--mailbox hi@myapp.dev]");let s=new URLSearchParams({correspondent:i.correspondent});return i.mailbox&&s.set("mailbox",i.mailbox),{method:"GET",path:`/api/assistant/brief?${s}`}}case"facts":if(!t)throw new Z("Work item ID is required","Usage: domani assistant facts <id>");return{method:"GET",path:`/api/assistant/work-items/${encodeURIComponent(t)}/facts`};case"sender":if(!t)throw new Z("Work item ID is required","Usage: domani assistant sender <id>");return{method:"GET",path:`/api/assistant/work-items/${encodeURIComponent(t)}/sender`};case"plan":if(!t)throw new Z("Action plan ID is required","Usage: domani assistant plan <id>");return{method:"GET",path:`/api/assistant/action-plans/${encodeURIComponent(t)}`};case"activity":return{method:"GET",path:`/api/assistant/activity${i.limit!==void 0?`?limit=${Yt(i.limit,"--limit",1)}`:""}`};case"rules":return{method:"GET",path:"/api/assistant/rules"};case"approvals":return{method:"GET",path:"/api/assistant/approvals"};case"suggestions":return{method:"GET",path:"/api/assistant/suggestions"};case"metrics":return{method:"GET",path:`/api/assistant/metrics${i.days!==void 0?`?window_days=${Yt(i.days,"--days",1)}`:""}`};case"export":return{method:"GET",path:"/api/assistant/data"};case"delete":if(!i.yes)throw new Z("Deleting derived assistant data requires --yes","This removes analyses, Decisions, plans, receipts, imports, and settings. Source mail is never touched.");return{method:"DELETE",path:"/api/assistant/data"};case"task":if(!t)throw new Z("Task ID is required","Usage: domani assistant task <work item id>");return{method:"GET",path:`/api/assistant/tasks/${encodeURIComponent(t)}`};case"lease":{if(!t)throw new Z("Task ID is required","Usage: domani assistant lease <id> [--ttl <seconds>]");let s={};return i.ttl!==void 0&&(s.ttl_seconds=Yt(i.ttl,"--ttl",30)),{method:"POST",path:`/api/assistant/tasks/${encodeURIComponent(t)}/lease`,body:s}}case"release":if(!t)throw new Z("Task ID is required","Usage: domani assistant release <id>");return{method:"DELETE",path:`/api/assistant/tasks/${encodeURIComponent(t)}/lease`};case"effects":{if(!t)throw new Z("Task ID is required","Usage: domani assistant effects <id> --effects '<json array>'");let s=ar(i.effects,"--effects",`A JSON array of effects, for example: --effects '[{"kind":"label","mailbox_id":"mbx_1","add":["finance"]}]'`);if(!Array.isArray(s)||!s.length)throw new Z("--effects must be a non-empty JSON array","Kinds: reply, forward, label, snooze, resolve, note, request");let r={effects:s};return i.text&&(r.note=i.text),{method:"POST",path:`/api/assistant/tasks/${encodeURIComponent(t)}/effects`,body:r,idempotency:`assistant:effects:${t}`}}case"escalate":{if(!t)throw new Z("Task ID is required","Usage: domani assistant escalate <id> --question '<text>' [--options '<json>'] [--evidence <refs>]");if(!i.question)throw new Z("--question is required","What the owner must decide, with the evidence in --evidence");let s={question:i.question};i.options&&(s.options=ar(i.options,"--options","A JSON array of { key, label, outcome }"));let r=En(i.evidence);return r.length&&(s.evidence_refs=r),{method:"POST",path:`/api/assistant/tasks/${encodeURIComponent(t)}/escalate`,body:s}}case"report":{if(!t)throw new Z("Task ID is required","Usage: domani assistant report <id> --outcome done|blocked|handed_back --summary '<text>' [--claims '<json>'] [--evidence <refs>]");if(!i.outcome||!["done","blocked","handed_back"].includes(i.outcome))throw new Z("--outcome must be done, blocked or handed_back");if(!i.summary)throw new Z("--summary is required","What was done and how it ended, in a few lines");let s={outcome:i.outcome,summary:i.summary};i.claims&&(s.claims=ar(i.claims,"--claims","A JSON array of { kind, ref } the platform reconciles with its receipts"));let r=En(i.evidence);return r.length&&(s.evidence_refs=r),{method:"POST",path:`/api/assistant/tasks/${encodeURIComponent(t)}/report`,body:s}}case"choose":case"instruct":case"snooze":case"ignore":case"take-over":case"correct":case"approve":case"reject":case"tag":{if(!t)throw new Z("Work item ID is required",`Usage: domani assistant ${n} <id> --item-version <work_item_version>`);if(i.itemVersion===void 0)throw new Z("--item-version is required","Pass the work_item_version shown by: domani assistant item <id>");let s=Eu[n],r={type:s,work_item_version:Yt(i.itemVersion,"--item-version",1)};if(s==="ignore"&&i.scope){if(!["item","sender","sender_domain","situation"].includes(i.scope))throw new Z("--scope must be item, sender, sender_domain or situation","Example: domani assistant ignore <id> --item-version 3 --scope sender");r.scope=i.scope}if(s==="choose"){if(!i.option||!i.decision||i.decisionVersion===void 0)throw new Z("--option, --decision and --decision-version are required","They come from the Decision shown by: domani assistant item <id>");r.decision_id=i.decision,r.decision_version=Yt(i.decisionVersion,"--decision-version",1),r.option_id=i.option}if(s==="instruct"){if(!i.text)throw new Z("--text is required","The instruction the assistant should follow when preparing the draft");r.instruction=i.text}if(s==="snooze"){if(!i.until)throw new Z("--until is required","ISO 8601 date-time, for example 2026-09-03T09:00:00Z");r.until=i.until}if(s==="correct"){if(!i.field||!i.text)throw new Z("--field and --text are required","Name the analysis field to correct and the correct value");r.field=i.field,r.correction=i.text}if(s==="tag"){let o=En(i.add),a=En(i.remove);if(!o.length&&!a.length)throw new Z("--add or --remove is required","Example: domani assistant tag <id> --item-version 3 --add lumenworks --remove draft");o.length&&(r.add=o),a.length&&(r.remove=a)}if(s==="approve"||s==="reject"){if(!i.plan)throw new Z("--plan is required","The waiting action plan shown by: domani assistant task <id>");r.plan_id=i.plan,s==="reject"&&i.text&&(r.reason=i.text)}return{method:"POST",path:`/api/assistant/work-items/${encodeURIComponent(t)}/interactions`,body:r,idempotency:`assistant:${s}:${t}`}}default:throw new Z(`Unknown action: ${n}`,`Actions: ${Pu.join(", ")}`)}}async function Nu(e,t){let i=await e.json();if(e.ok)return i;i.code==="NOT_AVAILABLE"&&u("The Mailzero assistant is in private preview",{hint:"It is enabled per account during the private beta. Ask for access at https://domani.run/support or wait for general availability.",code:"not_available",status:e.status,json:t.json,fields:t.fields}),i.code==="INSUFFICIENT_SCOPE"&&u(i.error||"Missing assistant scope",{hint:"This token needs the assistant:read scope for reads and assistant:write for changes. Create one with: domani tokens create --scopes assistant:read,assistant:write",code:"insufficient_scope",status:e.status,json:t.json,fields:t.fields}),u(i.error||i.message,{hint:i.hint,status:e.status,json:t.json,fields:t.fields})}function Uu(e){let t=e.sender?.name||e.sender?.address?.split("@")[0]||e.mailbox?.name||e.mailbox?.address||"",i=e.recurrence?.count&&e.recurrence.count>1?Q.default.dim(`x${e.recurrence.count}`):"",n=[e.category?e.category.replace(/_/g," "):"",...(e.tags??[]).map(s=>`#${s}`)].filter(Boolean).join(" ");return[Q.default.dim(e.id),t,n,`${(e.title||e.summary||"").slice(0,60)} ${i}`.trim(),e.ask?e.ask.slice(0,50):e.attention?.deadline||""]}function qu(e,t){if(t.json)return v(e,t.fields);c(),x("Today");let i=[["now","Now"],["needs_you","Needs you"],["waiting","Waiting"],["upcoming","Upcoming"],["handled","Handled"]],n=0;for(let[a,d]of i){let f=e.sections&&typeof e.sections=="object"?e.sections:e,m=Array.isArray(f[a])?f[a]:[];m.length&&(n+=m.length,console.log(` ${Q.default.bold(d)} ${Q.default.dim(`(${m.length})`)}`),B(["ID","Who","Kind","Summary","Deadline"],m.map(Uu)),c())}n||console.log(Q.default.dim(t.tag?` Nothing tagged ${t.tag} right now.`:t.category?` Nothing of the kind ${t.category} right now.`:" Nothing needs you right now."));let s=e.categories&&typeof e.categories=="object"?Object.entries(e.categories).sort((a,d)=>d[1]-a[1]):[];s.length>1&&console.log(Q.default.dim(` Kinds: ${s.map(([a,d])=>`${a} ${d}`).join(", ")} (narrow with --category)`));let r=e.tags&&typeof e.tags=="object"?Object.entries(e.tags).sort((a,d)=>d[1]-a[1]):[];r.length&&console.log(Q.default.dim(` Tags: ${r.map(([a,d])=>`${a} ${d}`).join(", ")} (narrow with --tag)`));let o=typeof e.as_of=="string"?e.as_of:void 0;o&&console.log(Q.default.dim(` As of ${o}`)),c()}function Mu(e,t){if(t.json)return v(e,t.fields);let i=e.brief??e;if(e.correspondent&&!e.brief){c(),x(`Brief for ${e.correspondent}`),console.log(` ${Q.default.dim("Nothing analysed from this person yet.")}`);for(let n of e.recent_mail||[])l(n.received_at.slice(0,10),`${n.subject||""} (${n.mailbox})`);return}c(),x(i.title||"Brief"),i.situation&&l("Status",`${i.situation.status||""}${i.situation.attention?.level?` \xB7 ${i.situation.attention.level}`:""}${i.situation.occurrences&&i.situation.occurrences>1?` \xB7 ${i.situation.occurrences} messages`:""}`),i.situation?.sender?.address&&l("With",`${i.situation.sender.name?`${i.situation.sender.name} `:""}<${i.situation.sender.address}>`),i.summary&&l("Summary",i.summary),i.ask&&l("Ask",i.ask);for(let n of i.story||[])l(n.occurred_at.slice(0,10),`${n.title}${n.analysed?"":Q.default.dim(" (not analysed)")}`);for(let n of i.facts||[])l("Fact",`${n.subject||""} ${n.predicate||""} ${n.value?.value??n.object??""}${n.value?.currency?` ${n.value.currency}`:""}`.trim());for(let n of i.awaiting||[])l(n.overdue?Q.default.red("Awaited"):"Awaited",`${n.who}: ${n.what} (since ${n.since.slice(0,10)})`);for(let n of i.commitments||[])l(n.overdue?Q.default.red("Promised"):"Promised",`${n.who}: ${n.what}`);for(let n of(i.settled||[]).slice(0,5))l("Settled",`${n.what} (${n.status}, ${n.at.slice(0,10)})`);i.decision?.question&&l("Decision",`${i.decision.question} ${(i.decision.options||[]).map(n=>`${n.recommended?"\u2605 ":""}${n.label}`).join(" / ")}`),i.suggested_next&&l("Next",`${i.suggested_next.action} ${Q.default.dim(`(${i.suggested_next.reason})`)}`),e.related&&e.related.length&&l("Also",`${e.related.length} other item(s) from this person`)}function Fu(e,t){if(t.json)return v(e,t.fields);let i=e;c(),x(i.sender?`${i.sender.name?`${i.sender.name} `:""}<${i.sender.address}>`:"Sender"),i.organisation?(l("Organisation",`${i.organisation.name||i.sender?.domain||""}${i.organisation.legal_name&&i.organisation.legal_name!==i.organisation.name?` (${i.organisation.legal_name})`:""}${i.organisation.fresh?"":Q.default.dim(" (profile ageing)")}`),i.organisation.pitch&&l("About",i.organisation.pitch),i.organisation.registered_at&&l("Domain since",i.organisation.registered_at.slice(0,10)),l("Mail",`${i.organisation.mail.provider||"unknown provider"} \xB7 spf ${i.organisation.mail.spf===null?"?":i.organisation.mail.spf?"yes":"no"} \xB7 dmarc ${i.organisation.mail.dmarc}`)):i.sender?.shared_domain?l("Organisation",Q.default.dim(`${i.sender.domain} is a shared mail domain`)):i.sender?.domain&&l("Organisation",Q.default.dim(`${i.sender.domain} not analysed yet`));let n=i.relationship;if(n){let s=n.first_received_at&&n.last_received_at?` between ${n.first_received_at.slice(0,10)} and ${n.last_received_at.slice(0,10)}`:"";l("Received",n.received?`${n.received_capped?"50+":n.received} message(s)${s}`:"nothing before this");for(let r of n.matters.slice(0,5))l(r.last_seen_at.slice(0,10),`${r.title} ${Q.default.dim(`(${r.status}, ${r.id})`)}`);n.organisation?.matters.length&&l("Colleagues",`${n.organisation.other_senders.join(", ")}: ${n.organisation.matters.slice(0,3).map(r=>r.title).join(" / ")}`)}for(let s of i.participants||[])l(s.roles.join("+"),`${s.name?`${s.name} `:""}<${s.address}>${s.messages>1?Q.default.dim(` \xD7${s.messages}`):""}${s.same_organisation?"":Q.default.dim(" (outside)")}`)}function Xa(e,t){if(t.json)return v(e,t.fields);let i=e.work_item||e;if(c(),x("Work item"),l("ID",i.id),l("Version",String(i.version??"")),l("Status",i.status||""),l("Mailbox",i.mailbox?.name?`${i.mailbox.name} <${i.mailbox.address||""}>`:i.mailbox?.address||""),i.title&&l("Title",i.title),i.sender?.address&&l("From",`${i.sender.name?`${i.sender.name} `:""}<${i.sender.address}>${i.sender.kind&&i.sender.kind!=="human"?` (${i.sender.kind})`:""}`),i.ask&&l("Ask",i.ask),i.recurrence?.count&&i.recurrence.count>1&&l("Recurrence",`${i.recurrence.count} messages since ${(i.recurrence.first_seen_at||"").slice(0,10)}`),l("Summary",i.summary||""),i.attention?.reason&&l("Why",i.attention.reason),i.attention?.deadline&&l("Deadline",i.attention.deadline),i.source?.event_id&&l("Source",`${i.source.type||"mail"} ${i.source.event_id}`),i.decision?.options?.length){c(),console.log(` ${Q.default.bold("Decision")} ${Q.default.dim(`${i.decision.id} v${i.decision.version??1}`)}`);for(let n of i.decision.options)console.log(` ${Q.default.dim(n.id)} ${n.label}${n.recommended?Q.default.green(" recommended"):""}`);console.log(Q.default.dim(` Choose with: domani assistant choose ${i.id} --version ${i.version??1} --decision ${i.decision.id} --decision-version ${i.decision.version??1} --option <id>`))}i.plan?.id&&l("Plan",`${i.plan.id} (preview with: domani assistant plan ${i.plan.id})`),c()}function Lu(e,t){if(t.json)return v(e,t.fields);c(),x("Mailzero assistant"),l("Enabled",e.enabled?"yes":"no"),l("Shadow",e.shadow_enabled?"yes":"no"),l("Paused",e.paused?"yes":"no"),l("History window",`${e.history_window_days} days`),l("Privacy route",String(e.privacy_route||"")),l("Consent",e.consent?.accepted_version?`${e.consent.accepted_version} at ${e.consent.accepted_at}`:`none (required: ${e.consent?.required_version||dr})`),c();let i=new Set(e.mailbox_ids||[]),n=e.mailboxes||[];n.length&&B(["ID","Address","AI"],n.map(s=>[Q.default.dim(s.id),s.address,i.has(s.id)?Q.default.green("on"):Q.default.dim("off")])),c()}function Vu(e,t){if(t.json)return v(e,t.fields);let i=e.backfill;if(c(),x("History import"),!i){console.log(Q.default.dim(" No import has run yet.")),c();return}l("Status",`${i.status} (${i.phase})`),l("Progress",`${i.processed}/${i.total}${i.percent===null||i.percent===void 0?"":` (${i.percent}%)`}`),l("Failed",String(i.failed??0)),l("Paused",i.paused?"yes":"no"),i.estimated_completion_at&&l("ETA",i.estimated_completion_at),i.can_close_app&&console.log(Q.default.dim(" The import continues in the background.")),c()}function Wu(e,t){if(t.json)return v(e,t.fields);let i=e.action_plan||e.plan||e;c(),x("Action preview"),l("ID",i.id),l("Status",i.status||""),i.expires_at&&l("Expires",i.expires_at);for(let n of i.effects||[])c(),console.log(` ${Q.default.bold(n.kind||"effect")} ${Q.default.dim(`mailbox ${n.mailbox_id||""}`)}${n.reply_to_message_id?Q.default.dim(` in reply to ${n.reply_to_message_id}`):""}`),n.body&&console.log(`
207
+ ${String(n.body).split(`
208
+ `).map(s=>` ${s}`).join(`
209
209
  `)}
210
- `);console.log(ee.default.dim(` Nothing is sent by this command. Send through the reply endpoint with assistant_plan_id=${i.id} or from the app.`)),c()}function _u(e,t){if(t.json)return y(e,t.fields);let i=e.events||[];c(),j("Assistant activity"),i.length?B(["When","Kind","Action","Work item"],i.map(s=>[s.occurred_at||"",s.kind||"",s.action||s.type||"",ee.default.dim(s.work_item?.id||s.work_item_id||"")])):console.log(ee.default.dim(" No activity yet.")),c()}async function Ea(e,t,i){let s;try{s=pu(e,t,i)}catch(h){throw h instanceof Q&&u(h.message,{hint:h.hint,code:"validation_error",json:i.json}),h}let n=e||"today",r={},o;s.idempotency&&(o=ut(s.idempotency,s.body||{},i.idempotencyKey),r["Idempotency-Key"]=o.key,s.body&&s.path.endsWith("/interactions")&&(s.body.idempotency_key=o.key));let a={set:"Updating assistant settings",preview:"Recording consent and starting the history import",retry:"Requeuing failed messages",delete:"Deleting derived assistant data"}[n]||(s.method!=="GET"?"Recording your decision":void 0),l=C(!i.json&&!!a);a&&l.start(a);let f=await _(s.path,{method:s.method,headers:r,...s.body?{body:JSON.stringify(s.body)}:{}}),m=await hu(f,i);switch(o?.complete(),a&&l.stop(`${w.success} Done`),n){case"today":return yu(m,i);case"settings":return vu(m,i);case"backfill":return $u(m,i);case"item":return Aa(m,i);case"brief":return bu(m,i);case"facts":return y(m,i.fields);case"sender":return wu(m,i);case"plan":return ku(m,i);case"activity":return _u(m,i);case"export":{let h=`${JSON.stringify(m,null,2)}
211
- `;if(i.out){if((0,Ta.writeFileSync)(i.out,h,"utf8"),i.json)return y({exported:!0,path:i.out},i.fields);console.log(`${w.success} Derived assistant data exported to ${i.out}`);return}process.stdout.write(h);return}case"delete":if(i.json)return y(m,i.fields);console.log(`${w.success} Derived assistant data deleted. Source mail is untouched.`);return;default:if(i.json)return y(m,i.fields);if(n==="set"||n==="preview"||n==="retry"){n==="preview"&&console.log(ee.default.dim(` Import ${m.preview?.backfill_id||""} runs in the background. Follow it with: domani assistant backfill`)),n==="retry"&&console.log(` Requeued ${m.retried??m.requeued??0} messages`),n==="set"&&console.log(` enabled=${m.enabled?"yes":"no"} shadow=${m.shadow_enabled?"yes":"no"} paused=${m.paused?"yes":"no"} mailboxes=${(m.mailbox_ids||[]).length}`);return}return m.work_item?Aa(m,i):y(m,i.fields)}}G();var vs=D(F(),1);L();var xu=["list","token","tokens","revoke-token"],Kt=class extends Error{constructor(i,s){super(i);this.hint=s;this.name="AgentsUsageError"}};function ju(e,t,i){switch(e||"list"){case"list":return{method:"GET",path:"/api/agents/identity"};case"token":{if(!t)throw new Kt("Agent handle is required",'Usage: domani agents token <slug> [--name "Dave on the pod"] [--mailboxes mb_1,mb_2]');let s=(i.mailboxes||"").split(",").map(n=>n.trim()).filter(Boolean);return{method:"POST",path:`/api/agents/identity/${encodeURIComponent(t)}/tokens`,body:{...i.name?{name:i.name}:{},...s.length?{mailbox_ids:s}:{}}}}case"tokens":if(!t)throw new Kt("Agent handle is required","Usage: domani agents tokens <slug>");return{method:"GET",path:`/api/agents/identity/${encodeURIComponent(t)}/tokens`};case"revoke-token":if(!t||!i.tokenId)throw new Kt("Agent handle and --token-id are required","Usage: domani agents revoke-token <slug> --token-id <id>");return{method:"DELETE",path:`/api/agents/identity/${encodeURIComponent(t)}/tokens/${encodeURIComponent(i.tokenId)}`};default:throw new Kt(`Unknown action: ${e}`,`Actions: ${xu.join(", ")}`)}}async function Pa(e,t,i){let s;try{s=ju(e,t,i)}catch(o){if(o instanceof Kt)return u(o.message,{hint:o.hint,code:"validation_error",json:i.json,fields:i.fields});throw o}let n=await _(s.path,{method:s.method,...s.body?{headers:{"Content-Type":"application/json"},body:JSON.stringify(s.body)}:{}}),r=await n.json().catch(()=>({}));if(!n.ok)return u(r.error||r.message||"Request failed",{hint:r.hint,status:n.status,json:i.json,fields:i.fields});if(i.json)return y(r,i.fields);switch(e||"list"){case"list":{let o=r.identities||r.items||[];if(j("Agent identities"),!o.length){console.log(` ${vs.default.dim("No agent identity yet. Claim one: domani agents claim is on the web at /agents")}`);return}B(["Handle","Name","Email"],o.map(a=>[a.slug,a.name||"",a.email||""]),[24,30,40]);return}case"token":{j("Agent API key"),d("Key",r.key||r.token||""),r.scopes&&d("Scopes",r.scopes.join(", ")),r.mailbox_ids?.length&&d("Mailboxes",r.mailbox_ids.join(", ")),be("Shown once. The key sees only this agent's mailboxes and the items handed to it.");return}case"tokens":{let o=r.tokens||[];if(j("Agent API keys"),!o.length){console.log(` ${vs.default.dim("No key yet: domani agents token <slug>")}`);return}B(["ID","Name","Scopes","Last used"],o.map(a=>[a.id,a.name||"",(a.scopes||[]).join(","),a.last_used_at||"never"]),[28,24,40,20]);return}case"revoke-token":console.log(`${vs.default.green("\u2713")} Token revoked`);return}}G();var At=D(F(),1);L();var Su=["providers","connect","connector","import","verify","disconnect"],et=class extends Error{constructor(i,s){super(i);this.hint=s;this.name="MailboxUsageError"}};function Cu(e,t,i){switch(e){case"providers":return{path:"/api/emails/connect/providers",method:"GET"};case"connect":{if(t==="forwarding"){if(!i.address)throw new et("--address is required.","domani mailbox connect forwarding --address someone@gmail.com");return{path:"/api/emails/connect/forwarding",method:"POST",body:{address:i.address,...i.workspace?{workspace_id:i.workspace}:{}}}}let s=t??"gmail";if(s!=="gmail"&&s!=="outlook")throw new et(`Unknown provider "${t}".`,"gmail or outlook (the APIs), or forwarding (a rule at any provider).");if(i.since&&i.window)throw new et("Use --since or --window, not both.");return{path:`/api/emails/connect/${s}`,method:"POST",body:{...i.since?{since:i.since}:{},...i.window?{window:i.window}:{},...i.workspace?{workspace_id:i.workspace}:{}}}}case"connector":if(!t)throw new et("Address required.","domani mailbox connector someone@gmail.com");return{path:`/api/emails/${encodeURIComponent(t.toLowerCase())}/connector`,method:"GET"};case"import":if(!t)throw new et("Address required.","domani mailbox import someone@gmail.com --since 2026-06-01");if(!i.since)throw new et("--since is required.","The date the import should reach back to, for example --since 2026-06-01.");return{path:`/api/emails/${encodeURIComponent(t.toLowerCase())}/import`,method:"POST",body:{since:i.since}};case"verify":if(!t)throw new et("Address required.","domani mailbox verify someone@gmail.com");return{path:`/api/emails/${encodeURIComponent(t.toLowerCase())}/connector/verify`,method:"POST"};case"disconnect":if(!t)throw new et("Address required.","domani mailbox disconnect someone@gmail.com");return{path:`/api/emails/${encodeURIComponent(t.toLowerCase())}/connector`,method:"DELETE"};default:throw new et(`Unknown action "${e??""}".`,`Actions: ${Su.join(", ")}.`)}}function Ou(e){j(`${e.address} (${e.kind})`),d("Status",String(e.status)),d("Phase",String(e.phase)+(e.paused_reason?` (${e.paused_reason})`:"")),d("Imported since",e.import_since?new Date(String(e.import_since)).toLocaleString():"-");let t=e.forwarding;if(t){d("Forward to",String(t.address??"-")),d("Forwarded",`${t.forwarded??0}${t.last_forwarded_at?`, last ${new Date(t.last_forwarded_at).toLocaleString()}`:""}`),t.confirmation&&d("Gmail confirmation",`${At.default.bold(t.confirmation.code)}${t.confirmation.url?` ${t.confirmation.url}`:""}`);let s=t.guide;s&&d("Provider",`${s.name??"unknown"}${s.settings_url?` ${s.settings_url}`:""}${s.limits?.includes("paid_plan")?" (forwarding needs a paid plan there)":""}`),t.probe&&d("Probe",t.probe.returned_at?`came back ${new Date(t.probe.returned_at).toLocaleString()}`:`sent ${new Date(t.probe.sent_at).toLocaleString()}, not back yet`)}let i=e.import_run;i&&d("Import",`${i.status}: ${i.copied} copied, ${i.analysed}/${i.to_analyse} analysed${i.listing_done?"":", still listing"}`),e.source_messages_total&&d("In the source",`${e.source_messages_total} messages`),d("Last sync",e.last_sync_at?new Date(String(e.last_sync_at)).toLocaleString():"never"),e.last_error&&d("Last error",At.default.yellow(String(e.last_error)))}async function Da(e,t,i){let s;try{s=Cu(e,t,i)}catch(o){if(o instanceof et)return u(o.message,{hint:o.hint,code:"validation_error",json:i.json});throw o}let n=await _(s.path,{method:s.method,...s.body?{headers:{"Content-Type":"application/json"},body:JSON.stringify(s.body)}:{}}),r=await n.json().catch(()=>({}));if(!n.ok)return u(r.error||r.message||"Request failed",{hint:r.hint,status:n.status,json:i.json,code:String(r.code??"request_failed")});if(e==="connect"&&t==="forwarding"){if(i.json)return y(r,i.fields);j("Connect your inbox by forwarding"),d("Inbox",String(r.address)),d("Forward to",At.default.cyan(String(r.forwarding_address))),d("Status",String(r.status));let o=r.instructions;for(let[a,l]of Object.entries(o??{}))console.log(`
212
- ${At.default.bold(a==="gmail"?"Gmail":a==="outlook"?"Outlook":"Any provider")}`),l.forEach((f,m)=>console.log(` ${m+1}. ${f}`));be(`Then: domani mailbox verify ${r.address} sends a probe; domani mailbox connector ${r.address} shows the confirmation code and the status.`);return}if(e==="connect"){if(i.json&&!i.wait)return y(r,i.fields);if(j("Connect your Gmail inbox"),d("Import since",new Date(String(r.import_since)).toLocaleString()),console.log(`
210
+ `);console.log(Q.default.dim(` Nothing is sent by this command. Send through the reply endpoint with assistant_plan_id=${i.id} or from the app.`)),c()}function Hu(e,t){if(t.json)return v(e,t.fields);let i=e.events||[];c(),x("Assistant activity"),i.length?B(["When","Kind","Action","Work item"],i.map(n=>[n.occurred_at||"",n.kind||"",n.action||n.type||"",Q.default.dim(n.work_item?.id||n.work_item_id||"")])):console.log(Q.default.dim(" No activity yet.")),c()}async function Qa(e,t,i){let n;try{n=Du(e,t,i)}catch(p){throw p instanceof Z&&u(p.message,{hint:p.hint,code:"validation_error",json:i.json}),p}let s=e||"today",r={},o;n.idempotency&&(o=pt(n.idempotency,n.body||{},i.idempotencyKey),r["Idempotency-Key"]=o.key,n.body&&n.path.endsWith("/interactions")&&(n.body.idempotency_key=o.key));let a={set:"Updating assistant settings",preview:"Recording consent and starting the history import",retry:"Requeuing failed messages",delete:"Deleting derived assistant data"}[s]||(n.method!=="GET"?"Recording your decision":void 0),d=C(!i.json&&!!a);a&&d.start(a);let f=await _(n.path,{method:n.method,headers:r,...n.body?{body:JSON.stringify(n.body)}:{}}),m=await Nu(f,i);switch(o?.complete(),a&&d.stop(`${w.success} Done`),s){case"today":return qu(m,i);case"settings":return Lu(m,i);case"backfill":return Vu(m,i);case"item":return Xa(m,i);case"brief":return Mu(m,i);case"facts":return v(m,i.fields);case"sender":return Fu(m,i);case"plan":return Wu(m,i);case"activity":return Hu(m,i);case"export":{let p=`${JSON.stringify(m,null,2)}
211
+ `;if(i.out){if((0,Za.writeFileSync)(i.out,p,"utf8"),i.json)return v({exported:!0,path:i.out},i.fields);console.log(`${w.success} Derived assistant data exported to ${i.out}`);return}process.stdout.write(p);return}case"delete":if(i.json)return v(m,i.fields);console.log(`${w.success} Derived assistant data deleted. Source mail is untouched.`);return;default:if(i.json)return v(m,i.fields);if(s==="set"||s==="preview"||s==="retry"){s==="preview"&&console.log(Q.default.dim(` Import ${m.preview?.backfill_id||""} runs in the background. Follow it with: domani assistant backfill`)),s==="retry"&&console.log(` Requeued ${m.retried??m.requeued??0} messages`),s==="set"&&console.log(` enabled=${m.enabled?"yes":"no"} shadow=${m.shadow_enabled?"yes":"no"} paused=${m.paused?"yes":"no"} mailboxes=${(m.mailbox_ids||[]).length}`);return}return m.work_item?Xa(m,i):v(m,i.fields)}}G();var Pn=U(M(),1);F();var Ju=["list","token","tokens","revoke-token"],Xt=class extends Error{constructor(i,n){super(i);this.hint=n;this.name="AgentsUsageError"}};function Bu(e,t,i){switch(e||"list"){case"list":return{method:"GET",path:"/api/agents/identity"};case"token":{if(!t)throw new Xt("Agent handle is required",'Usage: domani agents token <slug> [--name "Dave on the pod"] [--mailboxes mb_1,mb_2]');let n=(i.mailboxes||"").split(",").map(s=>s.trim()).filter(Boolean);return{method:"POST",path:`/api/agents/identity/${encodeURIComponent(t)}/tokens`,body:{...i.name?{name:i.name}:{},...n.length?{mailbox_ids:n}:{}}}}case"tokens":if(!t)throw new Xt("Agent handle is required","Usage: domani agents tokens <slug>");return{method:"GET",path:`/api/agents/identity/${encodeURIComponent(t)}/tokens`};case"revoke-token":if(!t||!i.tokenId)throw new Xt("Agent handle and --token-id are required","Usage: domani agents revoke-token <slug> --token-id <id>");return{method:"DELETE",path:`/api/agents/identity/${encodeURIComponent(t)}/tokens/${encodeURIComponent(i.tokenId)}`};default:throw new Xt(`Unknown action: ${e}`,`Actions: ${Ju.join(", ")}`)}}async function ed(e,t,i){let n;try{n=Bu(e,t,i)}catch(o){if(o instanceof Xt)return u(o.message,{hint:o.hint,code:"validation_error",json:i.json,fields:i.fields});throw o}let s=await _(n.path,{method:n.method,...n.body?{headers:{"Content-Type":"application/json"},body:JSON.stringify(n.body)}:{}}),r=await s.json().catch(()=>({}));if(!s.ok)return u(r.error||r.message||"Request failed",{hint:r.hint,status:s.status,json:i.json,fields:i.fields});if(i.json)return v(r,i.fields);switch(e||"list"){case"list":{let o=r.identities||r.items||[];if(x("Agent identities"),!o.length){console.log(` ${Pn.default.dim("No agent identity yet. Claim one: domani agents claim is on the web at /agents")}`);return}B(["Handle","Name","Email"],o.map(a=>[a.slug,a.name||"",a.email||""]),[24,30,40]);return}case"token":{x("Agent API key"),l("Key",r.key||r.token||""),r.scopes&&l("Scopes",r.scopes.join(", ")),r.mailbox_ids?.length&&l("Mailboxes",r.mailbox_ids.join(", ")),ve("Shown once. The key sees only this agent's mailboxes and the items handed to it.");return}case"tokens":{let o=r.tokens||[];if(x("Agent API keys"),!o.length){console.log(` ${Pn.default.dim("No key yet: domani agents token <slug>")}`);return}B(["ID","Name","Scopes","Last used"],o.map(a=>[a.id,a.name||"",(a.scopes||[]).join(","),a.last_used_at||"never"]),[28,24,40,20]);return}case"revoke-token":console.log(`${Pn.default.green("\u2713")} Token revoked`);return}}G();var Pt=U(M(),1);F();var Gu=["providers","connect","connector","import","verify","disconnect"],et=class extends Error{constructor(i,n){super(i);this.hint=n;this.name="MailboxUsageError"}};function Ku(e,t,i){switch(e){case"providers":return{path:"/api/emails/connect/providers",method:"GET"};case"connect":{if(t==="forwarding"){if(!i.address)throw new et("--address is required.","domani mailbox connect forwarding --address someone@gmail.com");return{path:"/api/emails/connect/forwarding",method:"POST",body:{address:i.address,...i.workspace?{workspace_id:i.workspace}:{}}}}let n=t??"gmail";if(n!=="gmail"&&n!=="outlook")throw new et(`Unknown provider "${t}".`,"gmail or outlook (the APIs), or forwarding (a rule at any provider).");if(i.since&&i.window)throw new et("Use --since or --window, not both.");return{path:`/api/emails/connect/${n}`,method:"POST",body:{...i.since?{since:i.since}:{},...i.window?{window:i.window}:{},...i.workspace?{workspace_id:i.workspace}:{}}}}case"connector":if(!t)throw new et("Address required.","domani mailbox connector someone@gmail.com");return{path:`/api/emails/${encodeURIComponent(t.toLowerCase())}/connector`,method:"GET"};case"import":if(!t)throw new et("Address required.","domani mailbox import someone@gmail.com --since 2026-06-01");if(!i.since)throw new et("--since is required.","The date the import should reach back to, for example --since 2026-06-01.");return{path:`/api/emails/${encodeURIComponent(t.toLowerCase())}/import`,method:"POST",body:{since:i.since}};case"verify":if(!t)throw new et("Address required.","domani mailbox verify someone@gmail.com");return{path:`/api/emails/${encodeURIComponent(t.toLowerCase())}/connector/verify`,method:"POST"};case"disconnect":if(!t)throw new et("Address required.","domani mailbox disconnect someone@gmail.com");return{path:`/api/emails/${encodeURIComponent(t.toLowerCase())}/connector`,method:"DELETE"};default:throw new et(`Unknown action "${e??""}".`,`Actions: ${Gu.join(", ")}.`)}}function zu(e){x(`${e.address} (${e.kind})`),l("Status",String(e.status)),l("Phase",String(e.phase)+(e.paused_reason?` (${e.paused_reason})`:"")),l("Imported since",e.import_since?new Date(String(e.import_since)).toLocaleString():"-");let t=e.forwarding;if(t){l("Forward to",String(t.address??"-")),l("Forwarded",`${t.forwarded??0}${t.last_forwarded_at?`, last ${new Date(t.last_forwarded_at).toLocaleString()}`:""}`),t.confirmation&&l("Gmail confirmation",`${Pt.default.bold(t.confirmation.code)}${t.confirmation.url?` ${t.confirmation.url}`:""}`);let n=t.guide;n&&l("Provider",`${n.name??"unknown"}${n.settings_url?` ${n.settings_url}`:""}${n.limits?.includes("paid_plan")?" (forwarding needs a paid plan there)":""}`),t.probe&&l("Probe",t.probe.returned_at?`came back ${new Date(t.probe.returned_at).toLocaleString()}`:`sent ${new Date(t.probe.sent_at).toLocaleString()}, not back yet`)}let i=e.import_run;i&&l("Import",`${i.status}: ${i.copied} copied, ${i.analysed}/${i.to_analyse} analysed${i.listing_done?"":", still listing"}`),e.source_messages_total&&l("In the source",`${e.source_messages_total} messages`),l("Last sync",e.last_sync_at?new Date(String(e.last_sync_at)).toLocaleString():"never"),e.last_error&&l("Last error",Pt.default.yellow(String(e.last_error)))}async function td(e,t,i){let n;try{n=Ku(e,t,i)}catch(o){if(o instanceof et)return u(o.message,{hint:o.hint,code:"validation_error",json:i.json});throw o}let s=await _(n.path,{method:n.method,...n.body?{headers:{"Content-Type":"application/json"},body:JSON.stringify(n.body)}:{}}),r=await s.json().catch(()=>({}));if(!s.ok)return u(r.error||r.message||"Request failed",{hint:r.hint,status:s.status,json:i.json,code:String(r.code??"request_failed")});if(e==="connect"&&t==="forwarding"){if(i.json)return v(r,i.fields);x("Connect your inbox by forwarding"),l("Inbox",String(r.address)),l("Forward to",Pt.default.cyan(String(r.forwarding_address))),l("Status",String(r.status));let o=r.instructions;for(let[a,d]of Object.entries(o??{}))console.log(`
212
+ ${Pt.default.bold(a==="gmail"?"Gmail":a==="outlook"?"Outlook":"Any provider")}`),d.forEach((f,m)=>console.log(` ${m+1}. ${f}`));ve(`Then: domani mailbox verify ${r.address} sends a probe; domani mailbox connector ${r.address} shows the confirmation code and the status.`);return}if(e==="connect"){if(i.json&&!i.wait)return v(r,i.fields);if(x("Connect your Gmail inbox"),l("Import since",new Date(String(r.import_since)).toLocaleString()),console.log(`
213
213
  Open this link in your browser and choose the Google account:
214
- ${At.default.cyan(String(r.auth_url))}
215
- `),i.open!==!1&&qe(String(r.auth_url)),be("After consent, the inbox appears as a connected mailbox at its own address; check it with: domani mailbox connector <address>"),i.wait){let o=Date.now();for(let a=0;a<180;a+=1){await wt(5e3);let m=((await(await _("/api/emails?limit=50")).json().catch(()=>({}))).mailboxes??[]).find(h=>h.kind==="connected"&&h.created_at&&Date.parse(h.created_at)>=o-6e4);if(m){let h=m.address??m.email;if(i.json)return y({status:"connected",address:h},i.fields);console.log(`
216
- ${At.default.green("Connected")} ${h}`);return}}return u("No inbox was connected within 15 minutes.",{code:"connect_timeout",json:i.json})}return}if(i.json)return y(r,i.fields);if(e==="providers"){j("Mailbox providers");for(let o of r.providers??[])d(String(o.name),o.configured?`ready (${o.access.join(", ")}${o.imports_history?", imports older mail":""})`:At.default.yellow(`not set up: ${o.reason}`));be("domani mailbox connect gmail | outlook | forwarding --address me@company.com");return}if(e==="connector")return Ou(r);if(e==="verify"){j("Probe sent"),d("To",String(r.sent_to)),d("Comes back through",String(r.forwarding_address)),be("When the rule brings it back, the connection is active: domani mailbox connector <address>");return}if(e==="import"){j("Importing older mail"),d("From",new Date(String(r.import_since)).toLocaleString()),d("To",new Date(String(r.import_until)).toLocaleString()),be(`Progress: domani mailbox connector ${t}`);return}e==="disconnect"&&(j("Disconnected"),d("Address",String(r.address)),d("Removed",`${r.removed_messages} messages, ${r.removed_attachments} attachments`))}var Na=D(F(),1);G();L();async function Iu(e,t){let i=await e.json();return e.ok||u(i.error||i.message,{hint:i.hint,status:e.status,json:t.json,fields:t.fields}),i}async function Ua(e,t,i,s){let n=`/api/domains/${encodeURIComponent(e)}/hostname-bindings`,r;if(!t||t==="list")r=await _(n);else if(t==="plan")s.hostname||u("--hostname is required",{code:"validation_error",json:s.json}),r=await _(`${n}/plan`,{method:"POST",body:JSON.stringify({hostname:s.hostname,browser_mode:s.browserMode})});else if(t==="create"){s.hostname||u("--hostname is required",{code:"validation_error",json:s.json});let l={hostname:s.hostname,browser_mode:s.browserMode,expected_zone_version:s.expectedZoneVersion,acknowledgements:s.acknowledgements?.split(",").map(m=>m.trim())},f=ut(`binding:create:${e}:${s.hostname}`,l);r=await _(n,{method:"POST",headers:{"Idempotency-Key":f.key},body:JSON.stringify(l)}),r.ok&&f.complete()}else{i||u("Binding ID is required",{hint:`Usage: domani binding ${e} ${t} <id>`,code:"validation_error",json:s.json});let l=`${n}/${encodeURIComponent(i)}`;if(t==="get")r=await _(l);else if(t==="verify")r=await _(`${l}/verify`,{method:"POST"});else if(t==="delete")r=await _(l,{method:"DELETE"});else if(t==="update"){s.browserMode||u("--browser-mode is required",{code:"validation_error",json:s.json});let f={browser_mode:s.browserMode,acknowledgements:s.acknowledgements?.split(",").map(h=>h.trim())},m=ut(`binding:update:${e}:${i}`,f);r=await _(l,{method:"PATCH",headers:{"Idempotency-Key":m.key},body:JSON.stringify(f)}),r.ok&&m.complete()}else return u(`Unknown action: ${t}`,{hint:"Actions: list, plan, create, get, update, verify, delete",code:"validation_error",json:s.json})}if(r.status===204){if(s.json)return y({disabled:!0,id:i},s.fields);console.log("Hostname binding disabled");return}let o=await Iu(r,s);if(s.json)return y(o,s.fields);c(),j(t==="plan"?"Hostname Binding Plan":"Hostname Bindings");let a=o.hostname_bindings||(o.hostname_binding?[o.hostname_binding]:[]);if(a.length)for(let l of a)console.log(` ${Na.default.dim(l.id)} ${l.hostname_pattern} ${l.status} ${l.browser_mode}`);else console.log(JSON.stringify(o,null,2));c()}var qa=D(require("node:readline"),1);yt();function Ru(e){return(Array.isArray(e)?e:[e]).filter(i=>!!i&&typeof i=="object")}function Gn(e,t,i,s){return{jsonrpc:"2.0",id:e,error:{code:t,message:i,...s?{data:s}:{}}}}function Oi(e,t,i,s){let n=Ru(e).filter(r=>Object.prototype.hasOwnProperty.call(r,"id")).map(r=>Gn(r.id??null,t,i,s));if(n.length!==0)return Array.isArray(e)?n:n[0]}function Au(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 Tu(e,t={}){let i=t.fetchImpl??fetch,s=t.getAuthToken?t.getAuthToken():He(),n=(t.apiUrl??We()).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 h=m instanceof Error?m.message:"Unknown network error",b=Oi(e,-32002,"Domani MCP is unreachable",{code:"MCP_NETWORK_ERROR",hint:`Check your connection and that ${n} is reachable.`,detail:h});return b===void 0?[]:[b]}if(a.status===401){let m=t.refreshAuthToken?t.refreshAuthToken():t.getAuthToken?void 0:He({refreshKeychain:!0});if(m&&m!==s){await a.body?.cancel(),s=m,r.Authorization=`Bearer ${s}`;try{a=await o()}catch(h){let b=h instanceof Error?h.message:"Unknown network error",k=Oi(e,-32002,"Domani MCP is unreachable",{code:"MCP_NETWORK_ERROR",hint:`Check your connection and that ${n} is reachable.`,detail:b});return k===void 0?[]:[k]}}}if(a.status===202||a.status===204)return[];let l=await a.text();if(a.status===401){let m=Oi(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=Oi(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 Au(l);try{return[JSON.parse(l)]}catch{let m=Oi(e,-32700,"Domani MCP returned invalid JSON",{code:"MCP_INVALID_RESPONSE"});return m===void 0?[]:[m]}}async function Ma(e={}){let t=e.stderr??process.stderr,i=qa.default.createInterface({input:process.stdin,crlfDelay:1/0}),s=new Set;e.verbose&&t.write(`domani MCP bridge ready
217
- `);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(Gn(null,-32700,"Parse error"))}
218
- `);return}let a=await Tu(o,e);for(let l of a)process.stdout.write(`${JSON.stringify(l)}
214
+ ${Pt.default.cyan(String(r.auth_url))}
215
+ `),i.open!==!1&&Fe(String(r.auth_url)),ve("After consent, the inbox appears as a connected mailbox at its own address; check it with: domani mailbox connector <address>"),i.wait){let o=Date.now();for(let a=0;a<180;a+=1){await kt(5e3);let m=((await(await _("/api/emails?limit=50")).json().catch(()=>({}))).mailboxes??[]).find(p=>p.kind==="connected"&&p.created_at&&Date.parse(p.created_at)>=o-6e4);if(m){let p=m.address??m.email;if(i.json)return v({status:"connected",address:p},i.fields);console.log(`
216
+ ${Pt.default.green("Connected")} ${p}`);return}}return u("No inbox was connected within 15 minutes.",{code:"connect_timeout",json:i.json})}return}if(i.json)return v(r,i.fields);if(e==="providers"){x("Mailbox providers");for(let o of r.providers??[])l(String(o.name),o.configured?`ready (${o.access.join(", ")}${o.imports_history?", imports older mail":""})`:Pt.default.yellow(`not set up: ${o.reason}`));ve("domani mailbox connect gmail | outlook | forwarding --address me@company.com");return}if(e==="connector")return zu(r);if(e==="verify"){x("Probe sent"),l("To",String(r.sent_to)),l("Comes back through",String(r.forwarding_address)),ve("When the rule brings it back, the connection is active: domani mailbox connector <address>");return}if(e==="import"){x("Importing older mail"),l("From",new Date(String(r.import_since)).toLocaleString()),l("To",new Date(String(r.import_until)).toLocaleString()),ve(`Progress: domani mailbox connector ${t}`);return}e==="disconnect"&&(x("Disconnected"),l("Address",String(r.address)),l("Removed",`${r.removed_messages} messages, ${r.removed_attachments} attachments`))}var id=U(M(),1);G();F();async function Yu(e,t){let i=await e.json();return e.ok||u(i.error||i.message,{hint:i.hint,status:e.status,json:t.json,fields:t.fields}),i}async function nd(e,t,i,n){let s=`/api/domains/${encodeURIComponent(e)}/hostname-bindings`,r;if(!t||t==="list")r=await _(s);else if(t==="plan")n.hostname||u("--hostname is required",{code:"validation_error",json:n.json}),r=await _(`${s}/plan`,{method:"POST",body:JSON.stringify({hostname:n.hostname,browser_mode:n.browserMode})});else if(t==="create"){n.hostname||u("--hostname is required",{code:"validation_error",json:n.json});let d={hostname:n.hostname,browser_mode:n.browserMode,expected_zone_version:n.expectedZoneVersion,acknowledgements:n.acknowledgements?.split(",").map(m=>m.trim())},f=pt(`binding:create:${e}:${n.hostname}`,d);r=await _(s,{method:"POST",headers:{"Idempotency-Key":f.key},body:JSON.stringify(d)}),r.ok&&f.complete()}else{i||u("Binding ID is required",{hint:`Usage: domani binding ${e} ${t} <id>`,code:"validation_error",json:n.json});let d=`${s}/${encodeURIComponent(i)}`;if(t==="get")r=await _(d);else if(t==="verify")r=await _(`${d}/verify`,{method:"POST"});else if(t==="delete")r=await _(d,{method:"DELETE"});else if(t==="update"){n.browserMode||u("--browser-mode is required",{code:"validation_error",json:n.json});let f={browser_mode:n.browserMode,acknowledgements:n.acknowledgements?.split(",").map(p=>p.trim())},m=pt(`binding:update:${e}:${i}`,f);r=await _(d,{method:"PATCH",headers:{"Idempotency-Key":m.key},body:JSON.stringify(f)}),r.ok&&m.complete()}else return u(`Unknown action: ${t}`,{hint:"Actions: list, plan, create, get, update, verify, delete",code:"validation_error",json:n.json})}if(r.status===204){if(n.json)return v({disabled:!0,id:i},n.fields);console.log("Hostname binding disabled");return}let o=await Yu(r,n);if(n.json)return v(o,n.fields);c(),x(t==="plan"?"Hostname Binding Plan":"Hostname Bindings");let a=o.hostname_bindings||(o.hostname_binding?[o.hostname_binding]:[]);if(a.length)for(let d of a)console.log(` ${id.default.dim(d.id)} ${d.hostname_pattern} ${d.status} ${d.browser_mode}`);else console.log(JSON.stringify(o,null,2));c()}var sd=U(require("node:readline"),1);wt();function Xu(e){return(Array.isArray(e)?e:[e]).filter(i=>!!i&&typeof i=="object")}function lr(e,t,i,n){return{jsonrpc:"2.0",id:e,error:{code:t,message:i,...n?{data:n}:{}}}}function Mi(e,t,i,n){let s=Xu(e).filter(r=>Object.prototype.hasOwnProperty.call(r,"id")).map(r=>lr(r.id??null,t,i,n));if(s.length!==0)return Array.isArray(e)?s:s[0]}function Zu(e){let t=[];for(let i of e.split(/\r?\n/)){if(!i.startsWith("data:"))continue;let n=i.slice(5).trim();if(!(!n||n==="[DONE]"))try{t.push(JSON.parse(n))}catch{}}return t}async function Qu(e,t={}){let i=t.fetchImpl??fetch,n=t.getAuthToken?t.getAuthToken():Be(),s=(t.apiUrl??Je()).replace(/\/$/,""),r={"Content-Type":"application/json",Accept:"application/json, text/event-stream"};n&&(r.Authorization=`Bearer ${n}`);let o=()=>i(`${s}/mcp`,{method:"POST",headers:r,body:JSON.stringify(e)}),a;try{a=await o()}catch(m){let p=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 ${s} is reachable.`,detail:p});return y===void 0?[]:[y]}if(a.status===401){let m=t.refreshAuthToken?t.refreshAuthToken():t.getAuthToken?void 0:Be({refreshKeychain:!0});if(m&&m!==n){await a.body?.cancel(),n=m,r.Authorization=`Bearer ${n}`;try{a=await o()}catch(p){let y=p instanceof Error?p.message:"Unknown network error",k=Mi(e,-32002,"Domani MCP is unreachable",{code:"MCP_NETWORK_ERROR",hint:`Check your connection and that ${s} is reachable.`,detail:y});return k===void 0?[]:[k]}}}if(a.status===202||a.status===204)return[];let d=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(!d.trim())return[];if((a.headers.get("content-type")??"").includes("text/event-stream"))return Zu(d);try{return[JSON.parse(d)]}catch{let m=Mi(e,-32700,"Domani MCP returned invalid JSON",{code:"MCP_INVALID_RESPONSE"});return m===void 0?[]:[m]}}async function rd(e={}){let t=e.stderr??process.stderr,i=sd.default.createInterface({input:process.stdin,crlfDelay:1/0}),n=new Set;e.verbose&&t.write(`domani MCP bridge ready
217
+ `);for await(let s of i){if(!s.trim())continue;let r=(async()=>{let o;try{o=JSON.parse(s)}catch{process.stdout.write(`${JSON.stringify(lr(null,-32700,"Parse error"))}
218
+ `);return}let a=await Qu(o,e);for(let d of a)process.stdout.write(`${JSON.stringify(d)}
219
219
  `)})().catch(o=>{if(e.verbose){let a=o instanceof Error?o.message:String(o);t.write(`domani MCP bridge internal error: ${a}
220
- `)}process.stdout.write(`${JSON.stringify(Gn(null,-32603,"Domani MCP bridge internal error"))}
221
- `)});s.add(r),r.then(()=>s.delete(r))}await Promise.all(s)}process.stdin.setMaxListeners(50);var V=new ar;V.name("domani").description(`Domain names for developers and AI agents - ${Yt}`).version(je).option("--api-url <url>","Override API base URL").configureOutput({outputError:(e,t)=>{let i=e.replace(/^error:\s*/i,"").trimEnd();if(t(`${mt.default.red("\u2717")} ${i}
222
- `),/unknown option|missing required|expected argument/i.test(i)){let s=process.argv[2],n=s&&!s.startsWith("-")?`domani ${s} --help`:"domani --help";t(`${mt.default.dim(` Run \`${n}\` to see available options.`)}
223
- `)}}}).hook("preAction",async(e,t)=>{let i=e.opts();i.apiUrl&&br(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 lo()});V.command("login").description(`Log in to ${Yt} (opens browser)`).option("--json","Output as JSON (returns auth_url for non-interactive approval)").option("--no-open","Don't open browser (print URL instead)").option("--scopes <scopes>","Request a comma-separated, least-privilege scope set").option("--mailboxes <addresses>","Confine the credential to these comma-separated mailbox addresses").option("--label <label>","Human-readable label shown on the approval screen").option("--expires-in <seconds>","Delegated credential lifetime in seconds (3600-31536000)").option("--surface <surface>","Attribute onboarding: cli, mcp, plugin, skill, or api","cli").addHelpText("after",`
220
+ `)}process.stdout.write(`${JSON.stringify(lr(null,-32603,"Domani MCP bridge internal error"))}
221
+ `)});n.add(r),r.then(()=>n.delete(r))}await Promise.all(n)}process.stdin.setMaxListeners(50);var V=new xr;V.name("domani").description(`Domain names for developers and AI agents - ${ei}`).version(Ce).option("--api-url <url>","Override API base URL").configureOutput({outputError:(e,t)=>{let i=e.replace(/^error:\s*/i,"").trimEnd();if(t(`${ht.default.red("\u2717")} ${i}
222
+ `),/unknown option|missing required|expected argument/i.test(i)){let n=process.argv[2],s=n&&!n.startsWith("-")?`domani ${n} --help`:"domani --help";t(`${ht.default.dim(` Run \`${s}\` to see available options.`)}
223
+ `)}}}).hook("preAction",async(e,t)=>{let i=e.opts();i.apiUrl&&Dr(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 So()});V.command("login").description(`Log in to ${ei} (opens browser)`).option("--json","Output as JSON (returns auth_url for non-interactive approval)").option("--no-open","Don't open browser (print URL instead)").option("--scopes <scopes>","Request a comma-separated, least-privilege scope set").option("--mailboxes <addresses>","Confine the credential to these comma-separated mailbox addresses").option("--label <label>","Human-readable label shown on the approval screen").option("--expires-in <seconds>","Delegated credential lifetime in seconds (3600-31536000)").option("--surface <surface>","Attribute onboarding: cli, mcp, plugin, skill, or api","cli").addHelpText("after",`
224
224
  Examples:
225
225
  domani login # interactive login (opens browser)
226
226
  domani login --scopes domains:read,search --label "Project agent" --expires-in 86400
@@ -229,54 +229,59 @@ Examples:
229
229
  domani login --surface plugin # authenticate the Domani agent plugin
230
230
  domani login --json # non-interactive (returns auth_url)
231
231
  domani login --no-open # print login URL without opening browser
232
- DOMANI_API_KEY=domani_sk_xxx domani list # skip login, use env var`).action(co);V.command("logout").description("Clear saved credentials").option("--yes","Skip confirmation").option("--json","Output as JSON").action(uo);V.command("me").description("Show account info").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
232
+ DOMANI_API_KEY=domani_sk_xxx domani list # skip login, use env var`).action(Co);V.command("logout").description("Clear saved credentials").option("--yes","Skip confirmation").option("--json","Output as JSON").action(Oo);V.command("me").description("Show account info").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
233
233
  Examples:
234
234
  domani me # show account overview
235
235
  domani me --json # machine-readable account info
236
- domani me --json --fields email,plan # just email and plan`).action(fo);V.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(ca);V.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 ka(t);if(e==="add")return _a(t);if(e==="remove")return xa(t);u(`Unknown action: ${e}`,{hint:"Use: domani card list, domani card add, or domani card remove"})});V.command("upgrade").description("Upgrade to Agent ($19/month)").option("--json","Output as JSON (returns checkout URL)").action(ma);V.command("cancel").description("Cancel your paid subscription (access continues until end of billing period)").option("--json","Output as JSON").action(fa);V.command("billing",{hidden:!0}).option("--json","Output as JSON (returns checkout URL)").action(ua);V.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);V.command("mcp [action]").description("Run the secure local MCP bridge (stdio)").option("--verbose","Write bridge lifecycle messages to stderr").addHelpText("after",`
236
+ domani me --json --fields email,plan # just email and plan`).action(Ro);V.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(Ra);V.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 Va(t);if(e==="add")return Wa(t);if(e==="remove")return Ha(t);u(`Unknown action: ${e}`,{hint:"Use: domani card list, domani card add, or domani card remove"})});V.command("upgrade").description("Upgrade to Agent ($19/month)").option("--json","Output as JSON (returns checkout URL)").action(Ta);V.command("cancel").description("Cancel your paid subscription (access continues until end of billing period)").option("--json","Output as JSON").action(Ea);V.command("billing",{hidden:!0}).option("--json","Output as JSON (returns checkout URL)").action(Aa);V.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(ma);V.command("mcp [action]").description("Run the secure local MCP bridge (stdio)").option("--verbose","Write bridge lifecycle messages to stderr").addHelpText("after",`
237
237
  Examples:
238
238
  domani login # authenticate once in your browser
239
239
  domani mcp serve # stdio bridge for agent plugins
240
240
 
241
241
  The bridge reads the API token from the OS keychain. It never prints the token
242
- 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 Ma({verbose:t.verbose})});V.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",`
242
+ 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 rd({verbose:t.verbose})});V.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",`
243
243
  Examples:
244
244
  domani tokens list # list all tokens
245
245
  domani tokens create --name "CI" --scopes "domains:read,search"
246
246
  domani tokens create --name "Support agent" --agent-identity agent_abc123
247
- domani tokens revoke --token-id tok_abc123`).action(Go);V.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",`
247
+ domani tokens revoke --token-id tok_abc123`).action(fa);V.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",`
248
248
  Examples:
249
249
  domani search myapp # check popular TLDs
250
250
  domani search myapp .io .fm .xyz # specific TLDs
251
251
  domani search myapp --expand # check 30+ TLDs
252
252
  domani search myapp --max-price 20 # only affordable options
253
- domani search myapp --json # machine-readable output`).action(Po);V.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(qo);V.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);V.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",`
253
+ domani search myapp --json # machine-readable output`).action(Qo);V.command("tlds").description("List the TLDs Domani sells, with pricing").option("--kind <kinds>","Kinds to show, comma-separated: tld, second_level, alt_root (default: tld,second_level; alt_root does not resolve in public DNS)").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(sa);V.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(ra);V.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",`
254
254
  Examples:
255
255
  domani suggest "cat sitting marketplace"
256
256
  domani suggest "AI code editor" --style creative --tlds ai,dev
257
- domani suggest "meditation app" --lang japanese --count 5`).action(Fo);V.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",`
257
+ domani suggest "meditation app" --lang japanese --count 5`).action(oa);V.command("buy [domains...]").description("Purchase one or more domains").option("--max-price <usd>","Ceiling for the total charge (default: the price shown)").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 buy myapp.dev # buy one domain
260
260
  domani buy myapp.dev myapp.com myapp.ai # buy multiple
261
261
  domani buy myapp.dev --dry-run # preview without buying
262
262
  domani buy myapp.dev --yes # skip confirmation
263
- domani buy myapp.dev --json # machine-readable output`).action(Mn);V.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("--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("--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",`
263
+ domani buy myapp.dev --yes --max-price 15 # never pay more than $15
264
+ domani buy myapp.dev --json # machine-readable output`).action(Qs);V.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("--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("--years <n>","Registration years (1-10, default 1)").option("--max-price <usd>","Ceiling for the domain charge (default: the listed price)").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",`
264
265
  Examples:
265
266
  domani provision myagent.run # domain + hi@ mailbox
266
267
  domani provision myagent.run --slug hey --name "My Agent" # custom mailbox
267
268
  DOMANI_SENDER_AUTH="Bearer secret" domani provision myagent.run --webhook https://me.dev/inbox --authorization-env DOMANI_SENDER_AUTH
268
- domani provision myagent.run --dry-run # preview`).action(No);V.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",`
269
+ domani provision myagent.run --dry-run # preview`).action(ta);V.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",`
269
270
  Examples:
270
271
  domani adopt myapp.com
271
- domani adopt myapp.com --json`).action(Wo);V.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("--watch","If not eligible: poll until the lock lifts and continue, or register a server watch (email + webhook) for a dated wait").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",`
272
+ domani adopt myapp.com --json`).action(la);V.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("--watch","If not eligible: poll until the lock lifts and continue, or register a server watch (email + webhook) for a dated wait").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",`
272
273
  Examples:
273
274
  domani transfer myapp.com --auth-code ABC123XYZ
274
275
  domani transfer myapp.com --auth-code ABC123XYZ --dry-run
275
276
  domani transfer myapp.com --auth-code ABC123XYZ --yes
276
- domani transfer myapp.com --watch --auth-code ABC123XYZ --yes # park it: waits for the unlock, then completes`).action(Vo);V.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(Ho);V.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",`
277
+ domani transfer myapp.com --watch --auth-code ABC123XYZ --yes # park it: waits for the unlock, then completes`).action(da);V.command("renew [domain]").description("Renew a domain").option("--years <n>","Number of years (1-10, default: 1)").option("--max-price <usd>","Ceiling for the renewal charge (default: the price shown)").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",`
278
+ Examples:
279
+ domani renew myapp.dev # renew one year at the price shown
280
+ domani renew myapp.dev --years 3 --dry-run # preview the total without renewing
281
+ domani renew myapp.dev --yes --max-price 40 # never pay more than $40`).action(ca);V.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",`
277
282
  Examples:
278
283
  domani import myapp.com # start import (shows TXT record to add)
279
- domani import myapp.com --verify # verify TXT record and complete import`).action(Jo);V.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",`
284
+ domani import myapp.com --verify # verify TXT record and complete import`).action(ua);V.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",`
280
285
  Examples:
281
286
  domani sell myapp.dev --price 5000 # list for $5,000
282
287
  domani sell myapp.dev --price 5000 --description "Great brand name"
@@ -284,7 +289,7 @@ Examples:
284
289
  domani sell external.com --verify # verify TXT record
285
290
  domani sell myapp.dev --status # check listing status
286
291
  domani sell myapp.dev --cancel # remove from sale
287
- domani sell myapp.dev --transfer-code ABC123 # provide EPP code for a deal`).action(sa);V.command("route [action] [id]").description("Manage short-lived HTTP routes").option("--hostname <hostname>","Public hostname; omitted only when token policy can auto-assign").option("--upstream <url>","HTTP or HTTPS upstream origin").option("--domain <domain>","Filter routes by owned domain").option("--status <status>","Filter: active, expired, deleted, suspended, all").option("--limit <n>","Routes per page for list (default 50, max 100)").option("--cursor <cursor>","Page cursor from the previous list (printed as More: --cursor ...)").option("--expires-in <seconds>","Lease duration in seconds (60-86400)").option("--host-header <mode>","Host header mode: public or upstream").option("--upstream-verification <mode>","Verification mode: none or signed_headers").option("--upstream-authorization-env <name>","Read a write-only upstream Authorization value from this environment variable").option("--upstream-api-key-env <name>","Read a write-only upstream X-Api-Key value from this environment variable").option("--clear-upstream-headers","Clear stored write-only upstream authentication headers").option("--idempotency-key <key>","Stable retry key; generated and persisted by default").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
292
+ domani sell myapp.dev --transfer-code ABC123 # provide EPP code for a deal`).action(_a);V.command("route [action] [id]").description("Manage short-lived HTTP routes").option("--hostname <hostname>","Public hostname; omitted only when token policy can auto-assign").option("--upstream <url>","HTTP or HTTPS upstream origin").option("--domain <domain>","Filter routes by owned domain").option("--status <status>","Filter: active, expired, deleted, suspended, all").option("--limit <n>","Routes per page for list (default 50, max 100)").option("--cursor <cursor>","Page cursor from the previous list (printed as More: --cursor ...)").option("--expires-in <seconds>","Lease duration in seconds (60-86400)").option("--host-header <mode>","Host header mode: public or upstream").option("--upstream-verification <mode>","Verification mode: none or signed_headers").option("--upstream-authorization-env <name>","Read a write-only upstream Authorization value from this environment variable").option("--upstream-api-key-env <name>","Read a write-only upstream X-Api-Key value from this environment variable").option("--clear-upstream-headers","Clear stored write-only upstream authentication headers").option("--idempotency-key <key>","Stable retry key; generated and persisted by default").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
288
293
  Examples:
289
294
  domani route create --hostname preview.example.com --upstream http://bore.pub:45255
290
295
  domani route list --domain example.com --status active
@@ -292,7 +297,7 @@ Examples:
292
297
  domani route refresh route_123 --expires-in 3600
293
298
  domani route rotate-verification route_123
294
299
  domani route rotate-headers route_123 --upstream-authorization-env SPRITES_AUTH
295
- domani route delete route_123`).action(Ia);V.command("assistant [action] [id]").description("Mailzero assistant: Today decisions, settings, consent, history import, activity (private preview)").option("--enable","Show Today decisions and prepare drafts on demand (for set)").option("--disable","Stop surfacing decisions; shadow analysis may continue (for set)").option("--shadow","Analyze mail without surfacing decisions (for set)").option("--no-shadow","Stop shadow analysis (for set)").option("--pause","Pause every kind of processing (for set)").option("--resume","Resume processing (for set)").option("--mailboxes <ids>","Comma-separated owned mailbox IDs to process (for set, preview)").option("--none","Disable every mailbox; cancels a running import (for set)").option("--days <n>","History window in days (for set, preview; default 30)").option("--attachment-vision <mode>","on or off: let the model read images in attachments (for set)").option("--consent","Record explicit AI consent (required for preview)").option("--option <id>","Decision option to choose (for choose)").option("--decision <id>","Decision ID (for choose)").option("--decision-version <n>","Decision version (for choose)").option("--item-version <n>","Work item version fence (for choose, instruct, snooze, ignore, take-over, correct)").option("--scope <scope>","With ignore: also mute the sender, sender_domain or situation (default item)").option("--text <text>","Instruction or corrected value (for instruct, correct)").option("--until <iso>","Snooze until this ISO 8601 date-time (for snooze)").option("--field <name>","Analysis field to correct (for correct)").option("--limit <n>","Number of activity entries (for activity)").option("--out <file>","Write the export to a file instead of stdout (for export)").option("--correspondent <email>","The person you are about to answer (for brief)").option("--mailbox <address>","Restrict the correspondent brief to one mailbox (for brief)").option("--category <kind>","Only one kind of matter: invoice, meeting_request, newsletter... (for today)").option("--tag <name>","Only the matters carrying this tag (for today)").option("--add <tags>","Tags to put on the matter, comma separated (for tag)").option("--remove <tags>","Tags to take off the matter, comma separated (for tag)").option("--yes","Confirm deletion of derived data (for delete)").option("--plan <id>","Action plan to approve or reject (for approve, reject)").option("--ttl <seconds>","How long to hold the task lease, 30 to 3600 (for lease)").option("--effects <json>","JSON array of effects to ask for (for effects)").option("--question <text>","The question for the owner (for escalate)").option("--options <json>","JSON array of { key, label, outcome } the owner may pick (for escalate)").option("--outcome <outcome>","done, blocked or handed_back (for report)").option("--summary <text>","What was done and how it ended (for report)").option("--claims <json>","JSON array of { kind, ref } reconciled with the receipts (for report)").option("--evidence <refs>","Comma-separated evidence refs (for escalate, report)").option("--idempotency-key <key>","Stable retry key; generated and persisted by default").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
300
+ domani route delete route_123`).action(za);V.command("assistant [action] [id]").description("Mailzero assistant: Today decisions, settings, consent, history import, activity (private preview)").option("--enable","Show Today decisions and prepare drafts on demand (for set)").option("--disable","Stop surfacing decisions; shadow analysis may continue (for set)").option("--shadow","Analyze mail without surfacing decisions (for set)").option("--no-shadow","Stop shadow analysis (for set)").option("--pause","Pause every kind of processing (for set)").option("--resume","Resume processing (for set)").option("--mailboxes <ids>","Comma-separated owned mailbox IDs to process (for set, preview)").option("--none","Disable every mailbox; cancels a running import (for set)").option("--days <n>","History window in days (for set, preview; default 30)").option("--attachment-vision <mode>","on or off: let the model read images in attachments (for set)").option("--consent","Record explicit AI consent (required for preview)").option("--option <id>","Decision option to choose (for choose)").option("--decision <id>","Decision ID (for choose)").option("--decision-version <n>","Decision version (for choose)").option("--item-version <n>","Work item version fence (for choose, instruct, snooze, ignore, take-over, correct)").option("--scope <scope>","With ignore: also mute the sender, sender_domain or situation (default item)").option("--text <text>","Instruction or corrected value (for instruct, correct)").option("--until <iso>","Snooze until this ISO 8601 date-time (for snooze)").option("--field <name>","Analysis field to correct (for correct)").option("--limit <n>","Number of activity entries (for activity)").option("--out <file>","Write the export to a file instead of stdout (for export)").option("--correspondent <email>","The person you are about to answer (for brief)").option("--mailbox <address>","Restrict the correspondent brief to one mailbox (for brief)").option("--category <kind>","Only one kind of matter: invoice, meeting_request, newsletter... (for today)").option("--tag <name>","Only the matters carrying this tag (for today)").option("--add <tags>","Tags to put on the matter, comma separated (for tag)").option("--remove <tags>","Tags to take off the matter, comma separated (for tag)").option("--yes","Confirm deletion of derived data (for delete)").option("--plan <id>","Action plan to approve or reject (for approve, reject)").option("--ttl <seconds>","How long to hold the task lease, 30 to 3600 (for lease)").option("--effects <json>","JSON array of effects to ask for (for effects)").option("--question <text>","The question for the owner (for escalate)").option("--options <json>","JSON array of { key, label, outcome } the owner may pick (for escalate)").option("--outcome <outcome>","done, blocked or handed_back (for report)").option("--summary <text>","What was done and how it ended (for report)").option("--claims <json>","JSON array of { kind, ref } reconciled with the receipts (for report)").option("--evidence <refs>","Comma-separated evidence refs (for escalate, report)").option("--idempotency-key <key>","Stable retry key; generated and persisted by default").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
296
301
  Actions:
297
302
  today Now, Needs you, Waiting, Upcoming, Handled (--category keeps one kind, --tag one tag)
298
303
  settings Opt-in state, consent, and mailbox scope
@@ -340,21 +345,21 @@ Examples:
340
345
  This command never sends mail. Choosing an option prepares an exact draft; review it
341
346
  with "assistant plan" and send it through the normal reply endpoint
342
347
  (POST /api/emails/{address}/messages/{id}/reply with assistant_plan_id) or from the app.
343
- Tokens need the assistant:read scope for reads and assistant:write for changes.`).action(Ea);V.command("binding [action] <domain> [id]").description("Manage HTTP edge hostname bindings and certificates").option("--hostname <hostname>","Exact hostname, wildcard, or apex").option("--browser-mode <mode>","stateless, dedicated_site, or trusted_same_site").option("--expected-zone-version <version>","Zone version returned by binding plan").option("--acknowledgements <values>","Comma-separated acknowledgement identifiers").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
348
+ Tokens need the assistant:read scope for reads and assistant:write for changes.`).action(Qa);V.command("binding [action] <domain> [id]").description("Manage HTTP edge hostname bindings and certificates").option("--hostname <hostname>","Exact hostname, wildcard, or apex").option("--browser-mode <mode>","stateless, dedicated_site, or trusted_same_site").option("--expected-zone-version <version>","Zone version returned by binding plan").option("--acknowledgements <values>","Comma-separated acknowledgement identifiers").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
344
349
  Examples:
345
350
  domani binding list example.com
346
351
  domani binding plan example.com --hostname '*.example.com' --browser-mode stateless
347
352
  domani binding create example.com --hostname '*.example.com' --expected-zone-version <version>
348
- domani binding verify example.com binding_123`).action((e,t,i,s)=>Ua(t,e,i,s));V.command("list").alias("domains").description("List your domains").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
353
+ domani binding verify example.com binding_123`).action((e,t,i,n)=>nd(t,e,i,n));V.command("list").alias("domains").description("List your domains").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
349
354
  Examples:
350
355
  domani list # list all domains
351
356
  domani domains # alias for list
352
- domani list --json --fields domain,expires_at`).action(Uo);V.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(Nn);V.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",`
357
+ domani list --json --fields domain,expires_at`).action(ia);V.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(Ys);V.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",`
353
358
  Examples:
354
359
  domani connect --list # list providers
355
360
  domani connect myapp.dev vercel # connect to Vercel
356
361
  domani connect myapp.dev --provider google-workspace # connect Google Workspace
357
- domani connect myapp.dev vercel --dry-run # preview DNS changes`).action(Cn);V.command("email [action] [arg2]").description("Manage email: inbox lifecycle, mailboxes, send, forwarding, webhooks and setup").addHelpText("after",`
362
+ domani connect myapp.dev vercel --dry-run # preview DNS changes`).action(Ls);V.command("email [action] [arg2]").description("Manage email: inbox lifecycle, mailboxes, send, forwarding, webhooks and setup").addHelpText("after",`
358
363
  Examples:
359
364
  domani email list # list all mailboxes
360
365
  domani email create --domain myapp.dev --slug hi # create hi@myapp.dev
@@ -378,7 +383,7 @@ Examples:
378
383
  domani email thread THREAD --from hi@myapp.dev # one conversation, oldest first
379
384
  domani email label --from hi@myapp.dev --message-ids m1 --add billing,urgent
380
385
  domani email facts MSG --from hi@myapp.dev # what the assistant established
381
- domani email extract MSG --from hi@myapp.dev --schema '{"type":"object","properties":{"total":{"type":"number"}}}'`).option("--domain <domain>","Domain name").option("--slug <slug>","Mailbox slug (local part before @)").option("--query <text>","Search text (for search; or pass it as the argument; --mode hybrid|semantic|keyword picks the ranking)").option("--since <iso>","Only mail or threads after this time (for search, threads, inbox)").option("--until <iso>","Only mail before this time (for search, inbox)").option("--label <labels>","Comma-separated labels, any of (for search, threads, inbox)").option("--add <labels>","Labels to add (for label)").option("--remove <labels>","Labels to remove (for label; --set <labels> replaces every label)").option("--schema <json>","JSON schema of the fields to extract, inline or @file (for extract)").option("--instructions <text>","Guidance for the extraction (for extract)").option("--thread-id <id>","Thread ID (for thread; or pass it as the argument)").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("--send-at <iso>","Schedule the send (ISO 8601, 30s to 30 days out); trash the message to cancel").option("--message-id <id>","Message ID (for escalate/remind)").option("--reason <text>","Why the human is needed (for escalate)").option("--at <iso>","Reminder time, ISO 8601 (for remind)").option("--clear","Clear the escalation flag, reminder, or tone notes").option("--q <query>","Filter contacts by address or name").option("--order <order>","Contacts order: recent (default) or created (stable, for a full sync with --cursor)").option("--name <name>","Contact display name (for contact-add)").option("--notes <text>","Contact notes (for contact-add)").option("--set <text>","Tone notes to set on the mailbox (for tone)").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("--events <list>","Comma-separated webhook events: email.received plus delivery verdicts on outbound mail (email.delivered, email.bounced, email.failed, email.suppressed, email.complained, email.delayed); omit to keep the current subscription").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, all, or needs_human").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(bi);V.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",`
386
+ domani email extract MSG --from hi@myapp.dev --schema '{"type":"object","properties":{"total":{"type":"number"}}}'`).option("--domain <domain>","Domain name").option("--slug <slug>","Mailbox slug (local part before @)").option("--query <text>","Search text (for search; or pass it as the argument; --mode hybrid|semantic|keyword picks the ranking)").option("--since <iso>","Only mail or threads after this time (for search, threads, inbox)").option("--until <iso>","Only mail before this time (for search, inbox)").option("--label <labels>","Comma-separated labels, any of (for search, threads, inbox)").option("--add <labels>","Labels to add (for label)").option("--remove <labels>","Labels to remove (for label; --set <labels> replaces every label)").option("--schema <json>","JSON schema of the fields to extract, inline or @file (for extract)").option("--instructions <text>","Guidance for the extraction (for extract)").option("--thread-id <id>","Thread ID (for thread; or pass it as the argument)").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("--send-at <iso>","Schedule the send (ISO 8601, 30s to 30 days out); trash the message to cancel").option("--message-id <id>","Message ID (for escalate/remind)").option("--reason <text>","Why the human is needed (for escalate)").option("--at <iso>","Reminder time, ISO 8601 (for remind)").option("--clear","Clear the escalation flag, reminder, or tone notes").option("--q <query>","Filter contacts by address or name").option("--order <order>","Contacts order: recent (default) or created (stable, for a full sync with --cursor)").option("--name <name>","Contact display name (for contact-add)").option("--notes <text>","Contact notes (for contact-add)").option("--set <text>","Tone notes to set on the mailbox (for tone)").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("--events <list>","Comma-separated webhook events: email.received plus delivery verdicts on outbound mail (email.delivered, email.bounced, email.failed, email.suppressed, email.complained, email.delayed); omit to keep the current subscription").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, all, or needs_human").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(Ii);V.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",`
382
387
  Examples:
383
388
  domani workspace list
384
389
  domani workspace create --name Acme
@@ -395,28 +400,28 @@ Examples:
395
400
  domani workspace transfer --id ws_123 --membership-id mem_123
396
401
  domani workspace accept-ownership --token <ownership-token>
397
402
  domani workspace adopt-mailbox --id ws_123 --mailbox-id mb_123
398
- domani workspace checkout --id ws_123 --plan mail_team`).action(ja);V.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",`
403
+ domani workspace checkout --id ws_123 --plan mail_team`).action(Ja);V.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",`
399
404
  Examples:
400
405
  domani dns myapp.dev get # list all records
401
406
  domani dns myapp.dev set --type A --name @ --value 76.76.21.21 # add A record
402
407
  domani dns myapp.dev set --type CNAME --name www --value cname.vercel-dns.com
403
408
  domani dns myapp.dev delete --type A --name @
404
409
  domani dns myapp.dev snapshot # export DNS as JSON
405
- domani dns myapp.dev restore --file dns-backup.json # restore from snapshot`).action(Pn);V.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(pa);V.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",`
410
+ domani dns myapp.dev restore --file dns-backup.json # restore from snapshot`).action(Ks);V.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(Pa);V.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",`
406
411
  Examples:
407
412
  domani settings myapp.dev # view current settings
408
413
  domani settings myapp.dev --auto-renew on # enable auto-renew
409
414
  domani settings myapp.dev --whois-privacy on # enable WHOIS privacy
410
- domani settings myapp.dev --security-lock off # unlock for transfer`).action(Ko);V.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(zo);V.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);V.command("contact [action]").description("View or set WHOIS contact info (required for purchases)").addHelpText("after",`
415
+ domani settings myapp.dev --security-lock off # unlock for transfer`).action(pa);V.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(ha);V.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(ga);V.command("contact [action]").description("View or set WHOIS contact info (required for purchases)").addHelpText("after",`
411
416
  Examples:
412
417
  domani contact # view current contact info
413
418
  domani contact set --first-name John --last-name Doe --address1 "123 Main St" \\
414
- --city "San Francisco" --state CA --postal-code 94102 --country US --phone +1.5551234567 --email john@example.com`).option("--first-name <name>","First name (for set)").option("--last-name <name>","Last name (for set)").option("--org-name <name>","Organization name (for set, optional)").option("--address1 <addr>","Address line 1 (for set)").option("--address2 <addr>","Address line 2 (for set, optional)").option("--city <city>","City (for set)").option("--state <state>","State/Province (for set)").option("--postal-code <code>","Postal/ZIP code (for set)").option("--country <code>","Country code ISO 3166-1 alpha-2 (for set)").option("--phone <phone>","Phone +CC.NUMBER (for set)").option("--email <email>","Contact email (for set)").option("--dry-run","Show what would happen without executing").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action(Xo);V.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",`
419
+ --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(ya);V.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",`
415
420
  Examples:
416
421
  domani parking myapp.dev # view parking status
417
422
  domani parking myapp.dev enable # enable parking page
418
423
  domani parking myapp.dev disable # disable parking page
419
- domani parking myapp.dev price 500 # set for-sale price to $500`).action(ea);V.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(ta);V.command("webhooks [action]").alias("webhook").description("Manage webhook endpoints (list/create/update/delete/deliveries/replay/events)").addHelpText("after",`
424
+ domani parking myapp.dev price 500 # set for-sale price to $500`).action(va);V.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($a);V.command("webhooks [action]").alias("webhook").description("Manage webhook endpoints (list/create/update/delete/deliveries/replay/events)").addHelpText("after",`
420
425
  Examples:
421
426
  domani webhooks list
422
427
  domani webhooks create --url https://example.com/hook --events domain.purchased,domain.expiring
@@ -426,13 +431,13 @@ Examples:
426
431
  domani webhooks delete --webhook-id wh_abc
427
432
  domani webhooks deliveries --webhook-id wh_abc
428
433
  domani webhooks replay --webhook-id wh_abc --delivery-id del_abc --idempotency-key incident-2026-07-25
429
- 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(ia);V.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("--limit <n>","Deals per page (default 50, max 100)").option("--cursor <cursor>","Page cursor from the previous list (printed as More: --cursor ...)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
434
+ 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(ka);V.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("--limit <n>","Deals per page (default 50, max 100)").option("--cursor <cursor>","Page cursor from the previous list (printed as More: --cursor ...)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
430
435
  Examples:
431
436
  domani deals # list all your deals
432
437
  domani deals --role seller --status active # your active sales
433
438
  domani deals --cursor <next_cursor> # next page
434
439
  domani deals deal_abc123 # view specific deal
435
- domani deals --json # machine-readable output`).action(na);V.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",`
440
+ domani deals --json # machine-readable output`).action(xa);V.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",`
436
441
  Actions:
437
442
  request <domain> ask domani to acquire a taken domain (commission-only)
438
443
  list (default) list your acquisition requests
@@ -443,15 +448,15 @@ Examples:
443
448
  domani broker request dream.com --max-budget 5000
444
449
  domani broker # list your requests
445
450
  domani broker status brq_abc123
446
- domani broker cancel brq_abc123`).action((e,t,i)=>aa(e,t,i));V.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("--cursor <cursor>","Page cursor from the previous list (printed as More: --cursor ...)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
451
+ domani broker cancel brq_abc123`).action((e,t,i)=>Ca(e,t,i));V.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("--cursor <cursor>","Page cursor from the previous list (printed as More: --cursor ...)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").addHelpText("after",`
447
452
  Examples:
448
453
  domani notifications --unread # what is new
449
- domani notifications --cursor <next_cursor> # next page`).action(da);V.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)=>bi("send",e,t));V.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)=>bi("inbox",e,t));V.command("agents [action] [slug]").description("Agent identities: give an agent its own API key, list or revoke its keys").addHelpText("after",`
454
+ domani notifications --cursor <next_cursor> # next page`).action(Ia);V.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)=>Ii("send",e,t));V.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)=>Ii("inbox",e,t));V.command("agents [action] [slug]").description("Agent identities: give an agent its own API key, list or revoke its keys").addHelpText("after",`
450
455
  Examples:
451
456
  domani agents list # your agent identities
452
457
  domani agents token dave --name "Dave on the pod" # mint a confined key for dave.domani.run
453
458
  domani agents tokens dave # the keys of dave
454
- domani agents revoke-token dave --token-id tok_1 # revoke one`).option("--name <name>","Key name (for token)").option("--mailboxes <ids>","Comma-separated mailbox IDs the key is confined to (for token)").option("--token-id <id>","Token ID (for revoke-token)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action((e,t,i)=>Pa(e,t,i));V.command("mailbox [action] [target]").description("Connected inboxes: connect Gmail or any inbox by forwarding, read the connection, import older mail, disconnect").addHelpText("after",`
459
+ domani agents revoke-token dave --token-id tok_1 # revoke one`).option("--name <name>","Key name (for token)").option("--mailboxes <ids>","Comma-separated mailbox IDs the key is confined to (for token)").option("--token-id <id>","Token ID (for revoke-token)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action((e,t,i)=>ed(e,t,i));V.command("mailbox [action] [target]").description("Connected inboxes: connect Gmail or any inbox by forwarding, read the connection, import older mail, disconnect").addHelpText("after",`
455
460
  Examples:
456
461
  domani mailbox providers # which providers this server can connect
457
462
  domani mailbox connect gmail # the last 24 hours, then new mail as it arrives
@@ -461,8 +466,8 @@ Examples:
461
466
  domani mailbox verify me@outlook.com # send a probe through the rule
462
467
  domani mailbox connector someone@gmail.com # status, import progress, the Gmail confirmation code
463
468
  domani mailbox import someone@gmail.com --since 2026-01-01 # widen the import
464
- domani mailbox disconnect someone@gmail.com # remove your copies and the credential`).option("--address <address>","The inbox to connect by forwarding (for connect forwarding)").option("--since <date>","Import the mail received after this ISO date").option("--window <window>","A preset instead of --since: 24h (default), 7d, 30d, 1y").option("--workspace <id>","Workspace the mailbox belongs to (for connect)").option("--no-open","Do not open the browser (for connect)").option("--wait","Wait until the inbox is connected (for connect)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action((e,t,i)=>Da(e,t,i));V.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($a);V.command("update").description("Update domani CLI to the latest version").option("--json","Output as JSON (check version without updating)").option("--yes","Perform the update even in JSON/non-interactive mode").action(ga);V.command("uninstall").description("Remove domani CLI and config from this machine").action(wa);(async()=>{let e=$r();await V.parseAsync();let t=await e,i=process.stdout.isTTY?"domani update":"domani update --yes";t?.forced?(console.error(`
465
- ${mt.default.red("!")} CLI v${je} is no longer supported. Run ${mt.default.bold(i)} to upgrade to v${t.update}
469
+ domani mailbox disconnect someone@gmail.com # remove your copies and the credential`).option("--address <address>","The inbox to connect by forwarding (for connect forwarding)").option("--since <date>","Import the mail received after this ISO date").option("--window <window>","A preset instead of --since: 24h (default), 7d, 30d, 1y").option("--workspace <id>","Workspace the mailbox belongs to (for connect)").option("--no-open","Do not open the browser (for connect)").option("--wait","Wait until the inbox is connected (for connect)").option("--json","Output as JSON").option("--fields <fields>","Filter JSON output fields (comma-separated)").action((e,t,i)=>td(e,t,i));V.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(La);V.command("update").description("Update domani CLI to the latest version").option("--json","Output as JSON (check version without updating)").option("--yes","Perform the update even in JSON/non-interactive mode").action(Na);V.command("uninstall").description("Remove domani CLI and config from this machine").action(Ma);(async()=>{let e=qr();await V.parseAsync();let t=await e,i=process.stdout.isTTY?"domani update":"domani update --yes";t?.forced?(console.error(`
470
+ ${ht.default.red("!")} CLI v${Ce} is no longer supported. Run ${ht.default.bold(i)} to upgrade to v${t.update}
466
471
  `),process.exit(1)):t?.update&&console.error(`
467
- ${mt.default.yellow("!")} Update available: ${mt.default.dim(je)} ${mt.default.dim("\u2192")} ${mt.default.green(t.update)} Run ${mt.default.bold(i)}
472
+ ${ht.default.yellow("!")} Update available: ${ht.default.dim(Ce)} ${ht.default.dim("\u2192")} ${ht.default.green(t.update)} Run ${ht.default.bold(i)}
468
473
  `)})();