nipa-cli 0.1.7 → 0.1.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +2 -1
  2. package/dist/nipa.js +110 -102
  3. package/package.json +2 -3
package/dist/nipa.js CHANGED
@@ -1,71 +1,75 @@
1
1
  #!/usr/bin/env node
2
- import{createRequire as Cy}from"node:module";var by=Object.create;var{getPrototypeOf:xy,defineProperty:Yo,getOwnPropertyNames:wy}=Object;var ic=Object.prototype.hasOwnProperty;function _y(e){return this[e]}var vy,$y,Gt=(e,t,r)=>{var n=e!=null&&typeof e==="object";if(n){var o=t?vy??=new WeakMap:$y??=new WeakMap,s=o.get(e);if(s)return s}r=e!=null?by(xy(e)):{};let i=t||!e||!e.__esModule||!ic.call(e,"default")?Yo(r,"default",{value:e,enumerable:!0}):r;if(e&&typeof e==="object"||typeof e==="function"){for(let a of wy(e))if(!ic.call(i,a))Yo(i,a,{get:_y.bind(e,a),enumerable:!0})}if(n)o.set(e,i);return i};var Xo=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Sy=(e)=>e;function ky(e,t){this[e]=Sy.bind(null,t)}var Py=(e,t)=>{for(var r in t)Yo(e,r,{get:t[r],enumerable:!0,configurable:!0,set:ky.bind(t,r)})};var ac=Cy(import.meta.url);var fr=Xo(function(eP,Qo){var gn=process||{},cc=gn.argv||[],hn=gn.env||{},zy=!(!!hn.NO_COLOR||cc.includes("--no-color"))&&(!!hn.FORCE_COLOR||cc.includes("--color")||gn.platform==="win32"||(gn.stdout||{}).isTTY&&hn.TERM!=="dumb"||!!hn.CI),Iy=(e,t,r=e)=>(n)=>{let o=""+n,s=o.indexOf(t,e.length);return~s?e+Ty(o,t,r,s)+t:e+o+t},Ty=(e,t,r,n)=>{let o="",s=0;do o+=e.substring(s,n)+r,s=n+t.length,n=e.indexOf(t,s);while(~n);return o+e.substring(s)},lc=(e=zy)=>{let t=e?Iy:()=>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")}};Qo.exports=lc();Qo.exports.createColors=lc});var Pc=Xo(function(DP,kc){kc.exports=eb;function Qy(e){let t={defaultWidth:0,output:process.stdout,tty:ac("tty")};if(!e)return t;return Object.keys(t).forEach(function(r){if(!e[r])e[r]=t[r]}),e}function eb(e){let t=Qy(e);if(t.output.getWindowSize)return t.output.getWindowSize()[0]||t.defaultWidth;if(t.tty.getWindowSize)return t.tty.getWindowSize()[1]||t.defaultWidth;if(t.output.columns)return t.output.columns;if(process.env.CLI_WIDTH){let r=parseInt(process.env.CLI_WIDTH,10);if(!isNaN(r)&&r!==0)return r}return t.defaultWidth}});var Kc=Xo(function(YP,Gc){var hb=ac("stream");class Bc extends hb{#r=null;constructor(e={}){super(e);this.writable=this.readable=!0,this.muted=!1,this.on("pipe",this._onpipe),this.replace=e.replace,this._prompt=e.prompt||null,this._hadControl=!1}#t(e,t){if(this._dest)return this._dest[e];if(this._src)return this._src[e];return t}#e(e,...t){if(typeof this._dest?.[e]==="function")this._dest[e](...t);if(typeof this._src?.[e]==="function")this._src[e](...t)}get isTTY(){if(this.#r!==null)return this.#r;return this.#t("isTTY",!1)}set isTTY(e){this.#r=e}get rows(){return this.#t("rows")}get columns(){return this.#t("columns")}mute(){this.muted=!0}unmute(){this.muted=!1}_onpipe(e){this._src=e}pipe(e,t){return this._dest=e,super.pipe(e,t)}pause(){if(this._src)return this._src.pause()}resume(){if(this._src)return this._src.resume()}write(e){if(this.muted){if(!this.replace)return!0;if(e.match(/^\u001b/)){if(e.indexOf(this._prompt)===0)e=e.slice(this._prompt.length),e=e.replace(/./g,this.replace),e=this._prompt+e;return this._hadControl=!0,this.emit("data",e)}else{if(this._prompt&&this._hadControl&&e.indexOf(this._prompt)===0)this._hadControl=!1,this.emit("data",this._prompt),e=e.slice(this._prompt.length);e=e.toString().replace(/./g,this.replace)}}this.emit("data",e)}end(e){if(this.muted)if(e&&this.replace)e=e.toString().replace(/./g,this.replace);else e=null;if(e)this.emit("data",e);this.emit("end")}destroy(...e){return this.#e("destroy",...e)}destroySoon(...e){return this.#e("destroySoon",...e)}close(...e){return this.#e("close",...e)}}Gc.exports=Bc});var ho={};Py(ho,{ZodISODate:()=>Gr,ZodISODateTime:()=>Br,ZodISODuration:()=>Vr,ZodISOTime:()=>Kr,date:()=>Zw,datetime:()=>Nw,duration:()=>Fw,time:()=>Uw});var mt={name:"nipa-cli",version:"0.1.7",description:"The command-line interface for Nipa Cloud",keywords:["cli","keystone","mfa","nipa-cloud","openstack","terraform","totp"],homepage:"https://github.com/PunGrumpy/nipa#readme",bugs:{url:"https://github.com/PunGrumpy/nipa/issues"},license:"MIT",author:{name:"Noppakorn Kaewsalabnil",url:"https://www.pungrumpy.com"},repository:{type:"git",url:"git+https://github.com/PunGrumpy/nipa.git",directory:"packages/cli"},bin:{nipa:"dist/nipa.js"},files:["dist/nipa.js","README.md","LICENSE"],type:"module",publishConfig:{access:"public"},scripts:{dev:"bun src/index.ts",build:"bun build src/index.ts --compile --minify --outfile dist/nipa","build:npm":"bun build src/index.ts --target=node --minify --outfile dist/nipa.js","build:release":"bun scripts/build-release.ts",test:"bun test",typecheck:"tsc --noEmit","check:package":"bun run build:npm && publint",prepack:"bun run build:npm"},devDependencies:{"@inquirer/confirm":"6.3.2","@inquirer/input":"5.1.6","@inquirer/password":"5.2.2","@inquirer/select":"5.2.5","@types/bun":"1.4.2",picocolors:"1.1.1",typescript:"6.0.3",zod:"4.6.5"},preferGlobal:!0,engines:{node:">=22.13.0"}};var Ye=Gt(fr(),1);var N={description:"Print JSON",long:"json",value:{kind:"none"}},hr={description:"Don't ask for confirmation",long:"yes",short:"y",value:{kind:"none"}},es={description:"Use this profile (or set NIPA_PROFILE)",long:"profile",short:"P",value:{kind:"profile"}},ts={description:"Show help",long:"help",short:"h",value:{kind:"none"}},$e=[es,{description:"Log each HTTP request (or set NIPA_DEBUG=1)",long:"debug",short:"d",value:{kind:"none"}},{description:"Turn off colors (or set NO_COLOR=1)",long:"no-color",value:{kind:"none"}},ts,{description:"Show the version",long:"version",short:"v",value:{kind:"none"}}];var uc=["servers","flavors","images","networks","volumes","security-groups","load-balancers","databases"],xe=(e)=>[e.name,...e.aliases??[]],Se=(e)=>e.short?[`--${e.long}`,`-${e.short}`]:[`--${e.long}`],gr=(e)=>{switch(e.kind){case"none":return"";case"text":return` <${e.name}>`;case"choice":return` <${e.choices.join("|")}>`;case"project":return" <project>";case"profile":return" <name>";default:return e}},rs=(e)=>e.length===1?e[0]:e[1],yr=(e)=>e.sections.flatMap((t)=>t.commands);var ns=" ",Ay=80,br=(e,t)=>e.map(([r,n])=>`${ns}${r.padEnd(t)} ${n}`).join(`
3
- `),pc=(e)=>Math.max(0,...e.map(([t])=>t.length)),dc=(e,t)=>{let r=[],n="";for(let o of e.split(" "))if(n&&t.length+n.length+1+o.length>Ay)r.push(n),n=o;else n=n?`${n} ${o}`:o;return r.push(n),r.map((o)=>`${t}${o}`).join(`
4
- `)},Ry=(e)=>{switch(e.arity){case"one":return`<${e.name}>`;case"optional":return`[${e.name}]`;case"rest":return`[${e.name}...]`;default:return e.arity}},jy=(e)=>{let[t,...r]=e;if(!t)return[];if(r.length===0&&t.value.kind==="none")return[`[--${t.long}]`];return["[options]"]},Oy=(e)=>{switch(e.kind){case"program":case"openstack":return"<args...>";case"command":return"<command> [args...]";default:return e}},mc=(e)=>{switch(e.kind){case"leaf":return[...e.args.map(Ry),...jy(e.flags)].join(" ");case"group":return`[${e.subcommands.map((t)=>t.name).join("|")}]`;case"passthrough":return Oy(e.target);default:return e}},yn=(e)=>`nipa ${e.map((t)=>t.name).join(" ")}`,xr=(e)=>{let t=mc(rs(e));return t?`${yn(e)} ${t}`:yn(e)},Ly=(e)=>{switch(e.kind){case"leaf":return e.flags;case"group":{let t=e.subcommands.flatMap((r)=>r.flags);return t.filter((r,n)=>t.findIndex((o)=>o.long===r.long)===n)}case"passthrough":return[];default:return e}},fc=(e)=>[`${e.short?`-${e.short}, `:" "}--${e.long}${gr(e.value)}`,e.description],os=(e)=>{let t=mc(e);return[t?`${e.name} ${t}`:e.name,e.summary]},Ct=(e,t)=>` ${Ye.default.dim(`${e}:`)}
2
+ import{createRequire as Yb}from"node:module";var Mb=Object.create;var{getPrototypeOf:Bb,defineProperty:ws,getOwnPropertyNames:Gb}=Object;var Yc=Object.prototype.hasOwnProperty;function Kb(e){return this[e]}var Vb,Wb,vs=(e,t,r)=>{var n=e!=null&&typeof e==="object";if(n){var o=t?Vb??=new WeakMap:Wb??=new WeakMap,s=o.get(e);if(s)return s}r=e!=null?Mb(Bb(e)):{};let i=t||!e||!e.__esModule||!Yc.call(e,"default")?ws(r,"default",{value:e,enumerable:!0}):r;if(e&&typeof e==="object"||typeof e==="function"){for(let a of Gb(e))if(!Yc.call(i,a))ws(i,a,{get:Kb.bind(e,a),enumerable:!0})}if(n)o.set(e,i);return i};var _s=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Jb=(e)=>e;function Hb(e,t){this[e]=Jb.bind(null,t)}var qb=(e,t)=>{for(var r in t)ws(e,r,{get:t[r],enumerable:!0,configurable:!0,set:Hb.bind(t,r)})};var Xc=Yb(import.meta.url);var rl=_s(function(CE,ks){var Rn=process||{},el=Rn.argv||[],An=Rn.env||{},ex=!(!!An.NO_COLOR||el.includes("--no-color"))&&(!!An.FORCE_COLOR||el.includes("--color")||Rn.platform==="win32"||(Rn.stdout||{}).isTTY&&An.TERM!=="dumb"||!!An.CI),tx=(e,t,r=e)=>(n)=>{let o=""+n,s=o.indexOf(t,e.length);return~s?e+rx(o,t,r,s)+t:e+o+t},rx=(e,t,r,n)=>{let o="",s=0;do o+=e.substring(s,n)+r,s=n+t.length,n=e.indexOf(t,s);while(~n);return o+e.substring(s)},tl=(e=ex)=>{let t=e?tx:()=>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")}};ks.exports=tl();ks.exports.createColors=tl});var xl=_s(function(u0,bl){bl.exports=Cx;function Px(e){let t={defaultWidth:0,output:process.stdout,tty:Xc("tty")};if(!e)return t;return Object.keys(t).forEach(function(r){if(!e[r])e[r]=t[r]}),e}function Cx(e){let t=Px(e);if(t.output.getWindowSize)return t.output.getWindowSize()[0]||t.defaultWidth;if(t.tty.getWindowSize)return t.tty.getWindowSize()[1]||t.defaultWidth;if(t.output.columns)return t.output.columns;if(process.env.CLI_WIDTH){let r=parseInt(process.env.CLI_WIDTH,10);if(!isNaN(r)&&r!==0)return r}return t.defaultWidth}});var Nl=_s(function($0,Dl){var Mx=Xc("stream");class Ll extends Mx{#r=null;constructor(e={}){super(e);this.writable=this.readable=!0,this.muted=!1,this.on("pipe",this._onpipe),this.replace=e.replace,this._prompt=e.prompt||null,this._hadControl=!1}#t(e,t){if(this._dest)return this._dest[e];if(this._src)return this._src[e];return t}#e(e,...t){if(typeof this._dest?.[e]==="function")this._dest[e](...t);if(typeof this._src?.[e]==="function")this._src[e](...t)}get isTTY(){if(this.#r!==null)return this.#r;return this.#t("isTTY",!1)}set isTTY(e){this.#r=e}get rows(){return this.#t("rows")}get columns(){return this.#t("columns")}mute(){this.muted=!0}unmute(){this.muted=!1}_onpipe(e){this._src=e}pipe(e,t){return this._dest=e,super.pipe(e,t)}pause(){if(this._src)return this._src.pause()}resume(){if(this._src)return this._src.resume()}write(e){if(this.muted){if(!this.replace)return!0;if(e.match(/^\u001b/)){if(e.indexOf(this._prompt)===0)e=e.slice(this._prompt.length),e=e.replace(/./g,this.replace),e=this._prompt+e;return this._hadControl=!0,this.emit("data",e)}else{if(this._prompt&&this._hadControl&&e.indexOf(this._prompt)===0)this._hadControl=!1,this.emit("data",this._prompt),e=e.slice(this._prompt.length);e=e.toString().replace(/./g,this.replace)}}this.emit("data",e)}end(e){if(this.muted)if(e&&this.replace)e=e.toString().replace(/./g,this.replace);else e=null;if(e)this.emit("data",e);this.emit("end")}destroy(...e){return this.#e("destroy",...e)}destroySoon(...e){return this.#e("destroySoon",...e)}close(...e){return this.#e("close",...e)}}Dl.exports=Ll});var Do={};qb(Do,{ZodISODate:()=>an,ZodISODateTime:()=>sn,ZodISODuration:()=>ln,ZodISOTime:()=>cn,date:()=>R_,datetime:()=>A_,duration:()=>T_,time:()=>I_});var ft={name:"nipa-cli",version:"0.1.8",description:"The command-line interface for Nipa Cloud",keywords:["cli","keystone","mfa","nipa-cloud","openstack","terraform","totp"],homepage:"https://github.com/PunGrumpy/nipa#readme",bugs:{url:"https://github.com/PunGrumpy/nipa/issues"},license:"MIT",author:{name:"Noppakorn Kaewsalabnil",url:"https://www.pungrumpy.com"},repository:{type:"git",url:"git+https://github.com/PunGrumpy/nipa.git",directory:"packages/cli"},bin:{nipa:"dist/nipa.js"},files:["dist/nipa.js","README.md","LICENSE"],type:"module",publishConfig:{access:"public"},scripts:{dev:"bun src/index.ts",build:"bun build src/index.ts --compile --minify --outfile dist/nipa","build:npm":"bun build src/index.ts --target=node --minify --outfile dist/nipa.js","build:release":"bun scripts/build-release.ts",test:"bun test",typecheck:"tsc-ts --noEmit","check:package":"bun run build:npm && publint",prepack:"bun run build:npm"},devDependencies:{"@inquirer/confirm":"6.3.2","@inquirer/input":"5.1.6","@inquirer/password":"5.2.2","@inquirer/select":"5.2.5","@types/bun":"1.4.2",picocolors:"1.1.1",zod:"4.6.5"},preferGlobal:!0,engines:{node:">=22.13.0"}};var D={description:"Print JSON",long:"json",value:{kind:"none"}},Cr={description:"Don't ask for confirmation",long:"yes",short:"y",value:{kind:"none"}},Qb={description:"Use this profile (or set NIPA_PROFILE)",long:"profile",short:"P",value:{kind:"profile"}},Ss={description:"Show help",long:"help",short:"h",value:{kind:"none"}},ke=[Qb,{description:"Use this project, by name or ID, for this run only; login saves it",long:"project",short:"p",value:{kind:"project"}},{description:"Log each HTTP request (or set NIPA_DEBUG=1)",long:"debug",short:"d",value:{kind:"none"}},{description:"Turn off colors (or set NO_COLOR=1)",long:"no-color",value:{kind:"none"}},{description:"Never prompt; fail with the flag to pass",long:"non-interactive",value:{kind:"none"}},Ss,{description:"Show the version",long:"version",short:"v",value:{kind:"none"}}];var Qc=["servers","flavors","images","networks","volumes","security-groups","load-balancers","databases"],me=(e)=>[e.name,...e.aliases??[]],fe=(e)=>e.short?[`--${e.long}`,`-${e.short}`]:[`--${e.long}`],Er=(e)=>{switch(e.kind){case"none":return"";case"text":return` <${e.name}>`;case"choice":return` <${e.choices.join("|")}>`;case"project":return" <project>";case"profile":return" <name>";default:return e}},jr=(e)=>{let[t,r]=e;return r?.usesProject??t.usesProject},jn=(e)=>{let[t,r]=e;return r?.usesProfile??t.usesProfile},$s=(e)=>e.length===1?e[0]:e[1],Ar=(e)=>e.sections.flatMap((t)=>t.commands);var Ps=vs(rl(),1),nx=new Set(["0","false"]),nl=(e)=>{let{argv:t,env:r,forceMayAdd:n,stream:o}=e,s=t.indexOf("--");if((s===-1?t:t.slice(0,s)).includes("--no-color"))return!1;if(r.NO_COLOR)return!1;let i=o.isTTY===!0&&r.TERM!=="dumb";if(r.FORCE_COLOR){let a=!nx.has(r.FORCE_COLOR.toLowerCase());return n?a:a&&i}return i},ox=(e)=>{let{argv:t,env:r}=e;return{stderr:Ps.createColors(nl({argv:t,env:r,forceMayAdd:!0,stream:e.stderr})),stdout:Ps.createColors(nl({argv:t,env:r,forceMayAdd:!1,stream:e.stdout}))}},Rr=ox({argv:process.argv.slice(2),env:process.env,stderr:process.stderr,stdout:process.stdout});var ht=Rr.stdout,Cs=" ",sx=80,Ir=(e,t)=>e.map(([r,n])=>`${Cs}${r.padEnd(t)} ${n}`).join(`
3
+ `),ol=(e)=>Math.max(0,...e.map(([t])=>t.length)),sl=(e,t)=>{let r=[],n="";for(let o of e.split(" "))if(n&&t.length+n.length+1+o.length>sx)r.push(n),n=o;else n=n?`${n} ${o}`:o;return r.push(n),r.map((o)=>`${t}${o}`).join(`
4
+ `)},ix=(e)=>{switch(e.arity){case"one":return`<${e.name}>`;case"optional":return`[${e.name}]`;case"rest":return`[${e.name}...]`;default:return e.arity}},ax=(e)=>{let[t,...r]=e;if(!t)return[];if(r.length===0&&t.value.kind==="none")return[`[--${t.long}]`];return["[options]"]},cx=(e)=>{switch(e.kind){case"program":case"openstack":return"<args...>";case"command":return"<command> [args...]";default:return e}},il=(e)=>{switch(e.kind){case"leaf":return[...e.args.map(ix),...ax(e.flags)].join(" ");case"group":return`[${e.subcommands.map((t)=>t.name).join("|")}]`;case"passthrough":return cx(e.target);default:return e}},Xt=(e)=>`nipa ${e.map((t)=>t.name).join(" ")}`,Rt=(e)=>{let t=il($s(e));return t?`${Xt(e)} ${t}`:Xt(e)},lx=(e)=>{switch(e.kind){case"leaf":return e.flags;case"group":{let t=e.subcommands.flatMap((r)=>r.flags);return t.filter((r,n)=>t.findIndex((o)=>o.long===r.long)===n)}case"passthrough":return[];default:return e}},al=(e)=>[`${e.short?`-${e.short}, `:" "}--${e.long}${Er(e.value)}`,e.description],Es=(e)=>{let t=il(e);return[t?`${e.name} ${t}`:e.name,e.summary]},At=(e,t)=>` ${ht.dim(`${e}:`)}
5
5
 
6
6
  ${t}
7
- `,hc=(e)=>e.map((t)=>`${ns}${Ye.default.dim(t.description)}
8
- ${ns}${Ye.default.cyan("$")} ${t.command}`).join(`
7
+ `,cl=(e)=>e.map((t)=>`${Cs}${ht.dim(t.description)}
8
+ ${Cs}${ht.cyan("$")} ${t.command}`).join(`
9
9
 
10
- `),bn=$e.map(fc),ss=(e)=>{let{program:t}=e,r=t.sections.flatMap((i)=>i.commands.map(os)),n=pc([...r,...bn]),o=t.sections.map((i)=>Ct(i.title,br(i.commands.map(os),n))),s=Ye.default.dim(`v${e.version}`);return["",` ${Ye.default.bold("nipa")} ${s}`,"",dc(t.summary," "),"",` ${Ye.default.dim("Usage:")} nipa [options] <command>`,"",...o,Ct("Global options",br(bn,n)),Ct("Examples",hc(t.examples)),` Run ${Ye.default.bold("nipa <command> --help")} for a command's options.`,""].join(`
11
- `)},xn=(e)=>{let t=rs(e),r=t.kind==="group"?t.subcommands.map(os):[],n=Ly(t).map(fc),o=pc([...r,...n,...bn]),s=["",` ${Ye.default.dim("Usage:")} ${xr(e)}`,"",dc(t.description??t.summary," "),""];if(r.length>0)s.push(Ct("Subcommands",br(r,o)));if(n.length>0)s.push(Ct("Options",br(n,o)));if(s.push(Ct("Global options",br(bn,o))),t.examples?.length)s.push(Ct("Examples",hc(t.examples)));return s.join(`
12
- `)};var Dy=["emacs","vim"],Ny=new Set(Dy);function Zy(e){return Ny.has(e)}function gc(){let e=process.env.INQUIRER_KEYBINDINGS;if(!e)return[];return Array.from(new Set(e.toLowerCase().split(/[\s,]+/).filter(Zy)))}var wr=(e,t=[])=>e.name==="up"||t.includes("vim")&&e.name==="k"||t.includes("emacs")&&e.ctrl&&e.name==="p",wn=(e,t=[])=>e.name==="down"||t.includes("vim")&&e.name==="j"||t.includes("emacs")&&e.ctrl&&e.name==="n";var _r=(e)=>e.name==="backspace",vr=(e)=>e.name==="tab",is=(e)=>"1234567890".includes(e.name),Xe=(e)=>e.name==="enter"||e.name==="return";class as extends Error{name="AbortPromptError";message="Prompt was aborted";constructor(e){super();this.cause=e?.cause}}class cs extends Error{name="CancelPromptError";message="Prompt was canceled"}class _n extends Error{name="ExitPromptError"}class ls extends Error{name="HookError"}class $r extends Error{name="ValidationError"}import{AsyncResource as By}from"node:async_hooks";import{AsyncLocalStorage as Uy,AsyncResource as Fy}from"node:async_hooks";var yc=new Uy;function My(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function bc(e,t){let r=My(e);return yc.run(r,()=>{function n(o){r.handleChange=()=>{r.index=0,o()},r.handleChange()}return t(n)})}function Et(){let e=yc.getStore();if(!e)throw new ls("[Inquirer] Hook functions can only be called from within a prompt");return e}function us(){return Et().rl}function ps(e){let t=(...r)=>{let n=Et(),o=!1,s=n.handleChange;n.handleChange=()=>{o=!0};let i=e(...r);if(o)s();return n.handleChange=s,i};return Fy.bind(t)}function Kt(e){let t=Et(),{index:r}=t,n={get(){return t.hooks[r]},set(s){t.hooks[r]=s},initialized:r in t.hooks},o=e(n);return t.index++,o}function xc(){Et().handleChange()}var Sr={queue(e){let t=Et(),{index:r}=t;t.hooksEffect.push(()=>{t.hooksCleanup[r]?.();let n=e(us());if(n!=null&&typeof n!=="function")throw new $r("useEffect return value must be a cleanup function or nothing.");t.hooksCleanup[r]=n})},run(){let e=Et();ps(()=>{e.hooksEffect.forEach((t)=>{t()}),e.hooksEffect.length=0})()},clearAll(){let e=Et();e.hooksCleanup.forEach((t)=>{t?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function Gy(e){return typeof e==="function"}function Ky(e){return typeof e==="function"}function H(e){return Kt((t)=>{let r=By.bind(function(s){let i=t.get(),a=Ky(s)?s(i):s;if(!Object.is(i,a))t.set(a),xc()});if(t.initialized)return[t.get(),r];let n=Gy(e)?e():e;return t.set(n),[n,r]})}function Qe(e,t){Kt((r)=>{let n=r.get();if(!Array.isArray(n)||t.some((s,i)=>!Object.is(s,n[i])))Sr.queue(e);r.set(t)})}import{styleText as je}from"node:util";import Re from"node:process";function Vy(){if(!Re.platform.startsWith("win"))return Re.env.TERM!=="linux";return Boolean(Re.env.CI)||Boolean(Re.env.WT_SESSION)||Boolean(Re.env.TERMINUS_SUBLIME)||Re.env.ConEmuTask==="{cmd::Cmder}"||Re.env.TERM_PROGRAM==="Terminus-Sublime"||Re.env.TERM_PROGRAM==="vscode"||Re.env.TERM==="xterm-256color"||Re.env.TERM==="alacritty"||Re.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var wc={circleQuestionMark:"(?)",questionMarkPrefix:"(?)",square:"█",squareDarkShade:"▓",squareMediumShade:"▒",squareLightShade:"░",squareTop:"▀",squareBottom:"▄",squareLeft:"▌",squareRight:"▐",squareCenter:"■",bullet:"●",dot:"․",ellipsis:"…",pointerSmall:"›",triangleUp:"▲",triangleUpSmall:"▴",triangleDown:"▼",triangleDownSmall:"▾",triangleLeftSmall:"◂",triangleRightSmall:"▸",home:"⌂",heart:"♥",musicNote:"♪",musicNoteBeamed:"♫",arrowUp:"↑",arrowDown:"↓",arrowLeft:"←",arrowRight:"→",arrowLeftRight:"↔",arrowUpDown:"↕",almostEqual:"≈",notEqual:"≠",lessOrEqual:"≤",greaterOrEqual:"≥",identical:"≡",infinity:"∞",subscriptZero:"₀",subscriptOne:"₁",subscriptTwo:"₂",subscriptThree:"₃",subscriptFour:"₄",subscriptFive:"₅",subscriptSix:"₆",subscriptSeven:"₇",subscriptEight:"₈",subscriptNine:"₉",oneHalf:"½",oneThird:"⅓",oneQuarter:"¼",oneFifth:"⅕",oneSixth:"⅙",oneEighth:"⅛",twoThirds:"⅔",twoFifths:"⅖",threeQuarters:"¾",threeFifths:"⅗",threeEighths:"⅜",fourFifths:"⅘",fiveSixths:"⅚",fiveEighths:"⅝",sevenEighths:"⅞",line:"─",lineBold:"━",lineDouble:"═",lineDashed0:"┄",lineDashed1:"┅",lineDashed2:"┈",lineDashed3:"┉",lineDashed4:"╌",lineDashed5:"╍",lineDashed6:"╴",lineDashed7:"╶",lineDashed8:"╸",lineDashed9:"╺",lineDashed10:"╼",lineDashed11:"╾",lineDashed12:"−",lineDashed13:"–",lineDashed14:"‐",lineDashed15:"⁃",lineVertical:"│",lineVerticalBold:"┃",lineVerticalDouble:"║",lineVerticalDashed0:"┆",lineVerticalDashed1:"┇",lineVerticalDashed2:"┊",lineVerticalDashed3:"┋",lineVerticalDashed4:"╎",lineVerticalDashed5:"╏",lineVerticalDashed6:"╵",lineVerticalDashed7:"╷",lineVerticalDashed8:"╹",lineVerticalDashed9:"╻",lineVerticalDashed10:"╽",lineVerticalDashed11:"╿",lineDownLeft:"┐",lineDownLeftArc:"╮",lineDownBoldLeftBold:"┓",lineDownBoldLeft:"┒",lineDownLeftBold:"┑",lineDownDoubleLeftDouble:"╗",lineDownDoubleLeft:"╖",lineDownLeftDouble:"╕",lineDownRight:"┌",lineDownRightArc:"╭",lineDownBoldRightBold:"┏",lineDownBoldRight:"┎",lineDownRightBold:"┍",lineDownDoubleRightDouble:"╔",lineDownDoubleRight:"╓",lineDownRightDouble:"╒",lineUpLeft:"┘",lineUpLeftArc:"╯",lineUpBoldLeftBold:"┛",lineUpBoldLeft:"┚",lineUpLeftBold:"┙",lineUpDoubleLeftDouble:"╝",lineUpDoubleLeft:"╜",lineUpLeftDouble:"╛",lineUpRight:"└",lineUpRightArc:"╰",lineUpBoldRightBold:"┗",lineUpBoldRight:"┖",lineUpRightBold:"┕",lineUpDoubleRightDouble:"╚",lineUpDoubleRight:"╙",lineUpRightDouble:"╘",lineUpDownLeft:"┤",lineUpBoldDownBoldLeftBold:"┫",lineUpBoldDownBoldLeft:"┨",lineUpDownLeftBold:"┥",lineUpBoldDownLeftBold:"┩",lineUpDownBoldLeftBold:"┪",lineUpDownBoldLeft:"┧",lineUpBoldDownLeft:"┦",lineUpDoubleDownDoubleLeftDouble:"╣",lineUpDoubleDownDoubleLeft:"╢",lineUpDownLeftDouble:"╡",lineUpDownRight:"├",lineUpBoldDownBoldRightBold:"┣",lineUpBoldDownBoldRight:"┠",lineUpDownRightBold:"┝",lineUpBoldDownRightBold:"┡",lineUpDownBoldRightBold:"┢",lineUpDownBoldRight:"┟",lineUpBoldDownRight:"┞",lineUpDoubleDownDoubleRightDouble:"╠",lineUpDoubleDownDoubleRight:"╟",lineUpDownRightDouble:"╞",lineDownLeftRight:"┬",lineDownBoldLeftBoldRightBold:"┳",lineDownLeftBoldRightBold:"┯",lineDownBoldLeftRight:"┰",lineDownBoldLeftBoldRight:"┱",lineDownBoldLeftRightBold:"┲",lineDownLeftRightBold:"┮",lineDownLeftBoldRight:"┭",lineDownDoubleLeftDoubleRightDouble:"╦",lineDownDoubleLeftRight:"╥",lineDownLeftDoubleRightDouble:"╤",lineUpLeftRight:"┴",lineUpBoldLeftBoldRightBold:"┻",lineUpLeftBoldRightBold:"┷",lineUpBoldLeftRight:"┸",lineUpBoldLeftBoldRight:"┹",lineUpBoldLeftRightBold:"┺",lineUpLeftRightBold:"┶",lineUpLeftBoldRight:"┵",lineUpDoubleLeftDoubleRightDouble:"╩",lineUpDoubleLeftRight:"╨",lineUpLeftDoubleRightDouble:"╧",lineUpDownLeftRight:"┼",lineUpBoldDownBoldLeftBoldRightBold:"╋",lineUpDownBoldLeftBoldRightBold:"╈",lineUpBoldDownLeftBoldRightBold:"╇",lineUpBoldDownBoldLeftRightBold:"╊",lineUpBoldDownBoldLeftBoldRight:"╉",lineUpBoldDownLeftRight:"╀",lineUpDownBoldLeftRight:"╁",lineUpDownLeftBoldRight:"┽",lineUpDownLeftRightBold:"┾",lineUpBoldDownBoldLeftRight:"╂",lineUpDownLeftBoldRightBold:"┿",lineUpBoldDownLeftBoldRight:"╃",lineUpBoldDownLeftRightBold:"╄",lineUpDownBoldLeftBoldRight:"╅",lineUpDownBoldLeftRightBold:"╆",lineUpDoubleDownDoubleLeftDoubleRightDouble:"╬",lineUpDoubleDownDoubleLeftRight:"╫",lineUpDownLeftDoubleRightDouble:"╪",lineCross:"╳",lineBackslash:"╲",lineSlash:"╱"},_c={tick:"✔",info:"ℹ",warning:"⚠",cross:"✘",squareSmall:"◻",squareSmallFilled:"◼",circle:"◯",circleFilled:"◉",circleDotted:"◌",circleDouble:"◎",circleCircle:"ⓞ",circleCross:"ⓧ",circlePipe:"Ⓘ",radioOn:"◉",radioOff:"◯",checkboxOn:"☒",checkboxOff:"☐",checkboxCircleOn:"ⓧ",checkboxCircleOff:"Ⓘ",pointer:"❯",triangleUpOutline:"△",triangleLeft:"◀",triangleRight:"▶",lozenge:"◆",lozengeOutline:"◇",hamburger:"☰",smiley:"㋡",mustache:"෴",star:"★",play:"▶",nodejs:"⬢",oneSeventh:"⅐",oneNinth:"⅑",oneTenth:"⅒"},Wy={tick:"√",info:"i",warning:"‼",cross:"×",squareSmall:"□",squareSmallFilled:"■",circle:"( )",circleFilled:"(*)",circleDotted:"( )",circleDouble:"( )",circleCircle:"(○)",circleCross:"(×)",circlePipe:"(│)",radioOn:"(*)",radioOff:"( )",checkboxOn:"[×]",checkboxOff:"[ ]",checkboxCircleOn:"(×)",checkboxCircleOff:"( )",pointer:">",triangleUpOutline:"∆",triangleLeft:"◄",triangleRight:"►",lozenge:"♦",lozengeOutline:"◊",hamburger:"≡",smiley:"☺",mustache:"┌─┐",star:"✶",play:"►",nodejs:"♦",oneSeventh:"1/7",oneNinth:"1/9",oneTenth:"1/10"},Jy={...wc,..._c},Hy={...wc,...Wy},qy=Vy(),Yy=qy?Jy:Hy,Vt=Yy,yP=Object.entries(_c);var Xy={prefix:{idle:je("blue","?"),done:je("green",Vt.tick)},spinner:{interval:80,frames:["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"].map((e)=>je("yellow",e))},keybindings:[],style:{answer:(e)=>je("cyan",e),message:(e)=>je("bold",e),error:(e)=>je("red",`> ${e}`),defaultAnswer:(e)=>je("dim",`(${e})`),help:(e)=>je("dim",e),highlight:(e)=>je("cyan",e),key:(e)=>je("cyan",je("bold",`<${e}>`))}};function vc(){return{...Xy,keybindings:gc()}}function $c(e){if(typeof e!=="object"||e===null)return!1;let t=e;while(Object.getPrototypeOf(t)!==null)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function Sc(...e){let t={};for(let r of e)for(let[n,o]of Object.entries(r)){let s=t[n];t[n]=$c(s)&&$c(o)?Sc(s,o):o}return t}function Oe(...e){let t=[vc(),...e.filter((r)=>r!=null)];return Sc(...t)}function et({status:e="idle",theme:t}){let[r,n]=H(!1),[o,s]=H(0),{prefix:i,spinner:a}=Oe(t);if(Qe(()=>{if(e==="loading"){let l,u=-1,p=setTimeout(()=>{n(!0),l=setInterval(()=>{u=u+1,s(u%a.frames.length)},a.interval)},300);return()=>{clearTimeout(p),clearInterval(l)}}else n(!1)},[e]),r)return a.frames[o];return typeof i==="string"?i:i[e==="loading"?"idle":e]??i.idle}function kr(e,t){return Kt((r)=>{let n=r.get();if(!r.initialized||n.dependencies.length!==t.length||n.dependencies.some((o,s)=>o!==t[s])){let o=e();return r.set({value:o,dependencies:t}),o}return n.value})}function zt(e){return H({current:e})[0]}function tt(e){let t=zt(e);t.current=e,Qe((r)=>{let n=!1,o=ps((s,i)=>{if(n)return;t.current(i,r)});return r.input.on("keypress",o),()=>{n=!0,r.input.removeListener("keypress",o)}},[])}var Mc=Gt(Pc(),1);var Cc=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(t)=>{let r=0;e.lastIndex=0;while(e.test(t))r+=1;return t.length-r}})(),Ec=(e)=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,zc=(e)=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||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>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141;var tb=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,rb=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Ic=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,nb=/\t{1,1000}/y,Tc=/[\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,ob=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,sb=/\p{M}+/gu,ib={limit:1/0,ellipsis:""},Ac=(e,t={},r={})=>{let n=t.limit??1/0,o=t.ellipsis??"",s=t?.ellipsisWidth??(o?Ac(o,ib,r).width:0),i=0,a=r.controlWidth??0,c=r.tabWidth??8,l=r.emojiWidth??2,u=2,p=r.regularWidth??1,d=r.wideWidth??2,m=[[ob,p],[tb,0],[rb,a],[nb,c],[Tc,l],[Ic,d]],h=0,y=0,b=e.length,_=0,P=!1,O=b,D=Math.max(0,n-s),S=0,A=0,U=0,ce=0;e:while(!0){if(A>S||y>=b&&y>h){let L=e.slice(S,A)||e.slice(h,y);_=0;for(let F of L.replaceAll(sb,"")){let ne=F.codePointAt(0)||0;if(Ec(ne))ce=2;else if(zc(ne))ce=d;else ce=p;if(U+ce>D)O=Math.min(O,Math.max(S,h)+_);if(U+ce>n){P=!0;break e}_+=F.length,U+=ce}S=A=0}if(y>=b)break e;for(let L=0,F=m.length;L<F;L++){let[ne,le]=m[L];if(ne.lastIndex=y,ne.test(e)){if(_=ne===Ic?Cc(e.slice(y,ne.lastIndex)):ne===Tc?1:ne.lastIndex-y,ce=_*le,U+ce>D)O=Math.min(O,y+Math.floor((D-U)/le));if(U+ce>n){P=!0;break e}U+=ce,S=h,A=y,y=h=ne.lastIndex;continue e}}y+=1}return{width:P?D:U,index:P?O:b,truncated:P,ellipsed:P&&n>=s}},Rc=Ac;var ab={limit:1/0,ellipsis:"",ellipsisWidth:0},cb=(e,t={})=>Rc(e,ab,t).width,rt=cb;var vn="\x1B",Nc="›",lb=39,ms="\x07",Zc="[",ub="]",Uc="m",fs=`${ub}8;;`,jc=new RegExp(`(?:\\${Zc}(?<code>\\d+)m|\\${fs}(?<uri>.*)${ms})`,"y"),Oc=(e)=>{if(e>=30&&e<=37)return 39;if(e>=90&&e<=97)return 39;if(e>=40&&e<=47)return 49;if(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;return},Lc=(e)=>`${vn}${Zc}${e}${Uc}`,Dc=(e)=>`${vn}${fs}${e}${ms}`,ds=(e,t,r)=>{let n=t[Symbol.iterator](),o=!1,s=!1,i=e.at(-1),a=i===void 0?0:rt(i),c=n.next(),l=n.next(),u=0;while(!c.done){let p=c.value,d=rt(p);if(a+d<=r)e[e.length-1]+=p;else e.push(p),a=0;if(p===vn||p===Nc)o=!0,s=t.startsWith(fs,u+1);if(o){if(s){if(p===ms)o=!1,s=!1}else if(p===Uc)o=!1}else if(a+=d,a===r&&!l.done)e.push(""),a=0;c=l,l=n.next(),u+=p.length}if(i=e.at(-1),!a&&i!==void 0&&i.length&&e.length>1)e[e.length-2]+=e.pop()},pb=(e)=>{let t=e.split(" "),r=t.length;while(r){if(rt(t[r-1]))break;r--}if(r===t.length)return e;return t.slice(0,r).join(" ")+t.slice(r).join("")},db=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let n="",o,s,i=e.split(" "),a=[""],c=0;for(let p=0;p<i.length;p++){let d=i[p];if(r.trim!==!1){let h=a.at(-1)??"",y=h.trimStart();if(h.length!==y.length)a[a.length-1]=y,c=rt(y)}if(p!==0){if(c>=t&&(r.wordWrap===!1||r.trim===!1))a.push(""),c=0;if(c||r.trim===!1)a[a.length-1]+=" ",c++}let m=rt(d);if(r.hard&&m>t){let h=t-c,y=1+Math.floor((m-h-1)/t);if(Math.floor((m-1)/t)<y)a.push("");ds(a,d,t),c=rt(a.at(-1)??"");continue}if(c+m>t&&c&&m){if(r.wordWrap===!1&&c<t){ds(a,d,t),c=rt(a.at(-1)??"");continue}a.push(""),c=0}if(c+m>t&&r.wordWrap===!1){ds(a,d,t),c=rt(a.at(-1)??"");continue}a[a.length-1]+=d,c+=m}if(r.trim!==!1)a=a.map((p)=>pb(p));let l=a.join(`
13
- `),u=!1;for(let p=0;p<l.length;p++){let d=l[p];if(n+=d,!u){if(u=d>="\uD800"&&d<="\uDBFF",u)continue}else u=!1;if(d===vn||d===Nc){jc.lastIndex=p+1;let h=jc.exec(l)?.groups;if(h?.code!==void 0){let y=Number.parseFloat(h.code);o=y===lb?void 0:y}else if(h?.uri!==void 0)s=h.uri.length===0?void 0:h.uri}if(l[p+1]===`
14
- `){if(s)n+=Dc("");let m=o?Oc(o):void 0;if(o&&m)n+=Lc(m)}else if(d===`
15
- `){if(o&&Oc(o))n+=Lc(o);if(s)n+=Dc(s)}}return n},mb=/\r?\n/;function Fc(e,t,r){return String(e).normalize().split(mb).map((n)=>db(n,t,r)).join(`
16
- `)}function Pr(e,t){return e.split(`
17
- `).flatMap((r)=>Fc(r,t,{trim:!1,wordWrap:!1}).split(`
10
+ `),In=ke.map(al),js=(e)=>{let{program:t}=e,r=t.sections.flatMap((i)=>i.commands.map(Es)),n=ol([...r,...In]),o=t.sections.map((i)=>At(i.title,Ir(i.commands.map(Es),n))),s=ht.dim(`v${e.version}`);return["",` ${ht.bold("nipa")} ${s}`,"",sl(t.summary," "),"",` ${ht.dim("Usage:")} nipa [options] <command>`,"",...o,At("Global options",Ir(In,n)),At("Examples",cl(t.examples)),` Run ${ht.bold("nipa <command> --help")} for a command's options.`,""].join(`
11
+ `)},Tn=(e)=>{let t=$s(e),r=t.kind==="group"?t.subcommands.map(Es):[],n=lx(t).map(al),o=ol([...r,...n,...In]),s=["",` ${ht.dim("Usage:")} ${Rt(e)}`,"",sl(t.description??t.summary," "),""];if(r.length>0)s.push(At("Subcommands",Ir(r,o)));if(n.length>0)s.push(At("Options",Ir(n,o)));if(s.push(At("Global options",Ir(In,o))),t.examples?.length)s.push(At("Examples",cl(t.examples)));return s.join(`
12
+ `)};var ux=["emacs","vim"],px=new Set(ux);function dx(e){return px.has(e)}function ll(){let e=process.env.INQUIRER_KEYBINDINGS;if(!e)return[];return Array.from(new Set(e.toLowerCase().split(/[\s,]+/).filter(dx)))}var Tr=(e,t=[])=>e.name==="up"||t.includes("vim")&&e.name==="k"||t.includes("emacs")&&e.ctrl&&e.name==="p",zn=(e,t=[])=>e.name==="down"||t.includes("vim")&&e.name==="j"||t.includes("emacs")&&e.ctrl&&e.name==="n";var zr=(e)=>e.name==="backspace",Or=(e)=>e.name==="tab",As=(e)=>"1234567890".includes(e.name),Qe=(e)=>e.name==="enter"||e.name==="return";class Rs extends Error{name="AbortPromptError";message="Prompt was aborted";constructor(e){super();this.cause=e?.cause}}class Is extends Error{name="CancelPromptError";message="Prompt was canceled"}class On extends Error{name="ExitPromptError"}class Ts extends Error{name="HookError"}class Lr extends Error{name="ValidationError"}import{AsyncResource as gx}from"node:async_hooks";import{AsyncLocalStorage as mx,AsyncResource as fx}from"node:async_hooks";var ul=new mx;function hx(e){return{rl:e,hooks:[],hooksCleanup:[],hooksEffect:[],index:0,handleChange(){}}}function pl(e,t){let r=hx(e);return ul.run(r,()=>{function n(o){r.handleChange=()=>{r.index=0,o()},r.handleChange()}return t(n)})}function It(){let e=ul.getStore();if(!e)throw new Ts("[Inquirer] Hook functions can only be called from within a prompt");return e}function zs(){return It().rl}function Os(e){let t=(...r)=>{let n=It(),o=!1,s=n.handleChange;n.handleChange=()=>{o=!0};let i=e(...r);if(o)s();return n.handleChange=s,i};return fx.bind(t)}function Qt(e){let t=It(),{index:r}=t,n={get(){return t.hooks[r]},set(s){t.hooks[r]=s},initialized:r in t.hooks},o=e(n);return t.index++,o}function dl(){It().handleChange()}var Dr={queue(e){let t=It(),{index:r}=t;t.hooksEffect.push(()=>{t.hooksCleanup[r]?.();let n=e(zs());if(n!=null&&typeof n!=="function")throw new Lr("useEffect return value must be a cleanup function or nothing.");t.hooksCleanup[r]=n})},run(){let e=It();Os(()=>{e.hooksEffect.forEach((t)=>{t()}),e.hooksEffect.length=0})()},clearAll(){let e=It();e.hooksCleanup.forEach((t)=>{t?.()}),e.hooksEffect.length=0,e.hooksCleanup.length=0}};function yx(e){return typeof e==="function"}function bx(e){return typeof e==="function"}function Y(e){return Qt((t)=>{let r=gx.bind(function(s){let i=t.get(),a=bx(s)?s(i):s;if(!Object.is(i,a))t.set(a),dl()});if(t.initialized)return[t.get(),r];let n=yx(e)?e():e;return t.set(n),[n,r]})}function et(e,t){Qt((r)=>{let n=r.get();if(!Array.isArray(n)||t.some((s,i)=>!Object.is(s,n[i])))Dr.queue(e);r.set(t)})}import{styleText as Ze}from"node:util";import Ne from"node:process";function xx(){if(!Ne.platform.startsWith("win"))return Ne.env.TERM!=="linux";return Boolean(Ne.env.CI)||Boolean(Ne.env.WT_SESSION)||Boolean(Ne.env.TERMINUS_SUBLIME)||Ne.env.ConEmuTask==="{cmd::Cmder}"||Ne.env.TERM_PROGRAM==="Terminus-Sublime"||Ne.env.TERM_PROGRAM==="vscode"||Ne.env.TERM==="xterm-256color"||Ne.env.TERM==="alacritty"||Ne.env.TERMINAL_EMULATOR==="JetBrains-JediTerm"}var ml={circleQuestionMark:"(?)",questionMarkPrefix:"(?)",square:"█",squareDarkShade:"▓",squareMediumShade:"▒",squareLightShade:"░",squareTop:"▀",squareBottom:"▄",squareLeft:"▌",squareRight:"▐",squareCenter:"■",bullet:"●",dot:"․",ellipsis:"…",pointerSmall:"›",triangleUp:"▲",triangleUpSmall:"▴",triangleDown:"▼",triangleDownSmall:"▾",triangleLeftSmall:"◂",triangleRightSmall:"▸",home:"⌂",heart:"♥",musicNote:"♪",musicNoteBeamed:"♫",arrowUp:"↑",arrowDown:"↓",arrowLeft:"←",arrowRight:"→",arrowLeftRight:"↔",arrowUpDown:"↕",almostEqual:"≈",notEqual:"≠",lessOrEqual:"≤",greaterOrEqual:"≥",identical:"≡",infinity:"∞",subscriptZero:"₀",subscriptOne:"₁",subscriptTwo:"₂",subscriptThree:"₃",subscriptFour:"₄",subscriptFive:"₅",subscriptSix:"₆",subscriptSeven:"₇",subscriptEight:"₈",subscriptNine:"₉",oneHalf:"½",oneThird:"⅓",oneQuarter:"¼",oneFifth:"⅕",oneSixth:"⅙",oneEighth:"⅛",twoThirds:"⅔",twoFifths:"⅖",threeQuarters:"¾",threeFifths:"⅗",threeEighths:"⅜",fourFifths:"⅘",fiveSixths:"⅚",fiveEighths:"⅝",sevenEighths:"⅞",line:"─",lineBold:"━",lineDouble:"═",lineDashed0:"┄",lineDashed1:"┅",lineDashed2:"┈",lineDashed3:"┉",lineDashed4:"╌",lineDashed5:"╍",lineDashed6:"╴",lineDashed7:"╶",lineDashed8:"╸",lineDashed9:"╺",lineDashed10:"╼",lineDashed11:"╾",lineDashed12:"−",lineDashed13:"–",lineDashed14:"‐",lineDashed15:"⁃",lineVertical:"│",lineVerticalBold:"┃",lineVerticalDouble:"║",lineVerticalDashed0:"┆",lineVerticalDashed1:"┇",lineVerticalDashed2:"┊",lineVerticalDashed3:"┋",lineVerticalDashed4:"╎",lineVerticalDashed5:"╏",lineVerticalDashed6:"╵",lineVerticalDashed7:"╷",lineVerticalDashed8:"╹",lineVerticalDashed9:"╻",lineVerticalDashed10:"╽",lineVerticalDashed11:"╿",lineDownLeft:"┐",lineDownLeftArc:"╮",lineDownBoldLeftBold:"┓",lineDownBoldLeft:"┒",lineDownLeftBold:"┑",lineDownDoubleLeftDouble:"╗",lineDownDoubleLeft:"╖",lineDownLeftDouble:"╕",lineDownRight:"┌",lineDownRightArc:"╭",lineDownBoldRightBold:"┏",lineDownBoldRight:"┎",lineDownRightBold:"┍",lineDownDoubleRightDouble:"╔",lineDownDoubleRight:"╓",lineDownRightDouble:"╒",lineUpLeft:"┘",lineUpLeftArc:"╯",lineUpBoldLeftBold:"┛",lineUpBoldLeft:"┚",lineUpLeftBold:"┙",lineUpDoubleLeftDouble:"╝",lineUpDoubleLeft:"╜",lineUpLeftDouble:"╛",lineUpRight:"└",lineUpRightArc:"╰",lineUpBoldRightBold:"┗",lineUpBoldRight:"┖",lineUpRightBold:"┕",lineUpDoubleRightDouble:"╚",lineUpDoubleRight:"╙",lineUpRightDouble:"╘",lineUpDownLeft:"┤",lineUpBoldDownBoldLeftBold:"┫",lineUpBoldDownBoldLeft:"┨",lineUpDownLeftBold:"┥",lineUpBoldDownLeftBold:"┩",lineUpDownBoldLeftBold:"┪",lineUpDownBoldLeft:"┧",lineUpBoldDownLeft:"┦",lineUpDoubleDownDoubleLeftDouble:"╣",lineUpDoubleDownDoubleLeft:"╢",lineUpDownLeftDouble:"╡",lineUpDownRight:"├",lineUpBoldDownBoldRightBold:"┣",lineUpBoldDownBoldRight:"┠",lineUpDownRightBold:"┝",lineUpBoldDownRightBold:"┡",lineUpDownBoldRightBold:"┢",lineUpDownBoldRight:"┟",lineUpBoldDownRight:"┞",lineUpDoubleDownDoubleRightDouble:"╠",lineUpDoubleDownDoubleRight:"╟",lineUpDownRightDouble:"╞",lineDownLeftRight:"┬",lineDownBoldLeftBoldRightBold:"┳",lineDownLeftBoldRightBold:"┯",lineDownBoldLeftRight:"┰",lineDownBoldLeftBoldRight:"┱",lineDownBoldLeftRightBold:"┲",lineDownLeftRightBold:"┮",lineDownLeftBoldRight:"┭",lineDownDoubleLeftDoubleRightDouble:"╦",lineDownDoubleLeftRight:"╥",lineDownLeftDoubleRightDouble:"╤",lineUpLeftRight:"┴",lineUpBoldLeftBoldRightBold:"┻",lineUpLeftBoldRightBold:"┷",lineUpBoldLeftRight:"┸",lineUpBoldLeftBoldRight:"┹",lineUpBoldLeftRightBold:"┺",lineUpLeftRightBold:"┶",lineUpLeftBoldRight:"┵",lineUpDoubleLeftDoubleRightDouble:"╩",lineUpDoubleLeftRight:"╨",lineUpLeftDoubleRightDouble:"╧",lineUpDownLeftRight:"┼",lineUpBoldDownBoldLeftBoldRightBold:"╋",lineUpDownBoldLeftBoldRightBold:"╈",lineUpBoldDownLeftBoldRightBold:"╇",lineUpBoldDownBoldLeftRightBold:"╊",lineUpBoldDownBoldLeftBoldRight:"╉",lineUpBoldDownLeftRight:"╀",lineUpDownBoldLeftRight:"╁",lineUpDownLeftBoldRight:"┽",lineUpDownLeftRightBold:"┾",lineUpBoldDownBoldLeftRight:"╂",lineUpDownLeftBoldRightBold:"┿",lineUpBoldDownLeftBoldRight:"╃",lineUpBoldDownLeftRightBold:"╄",lineUpDownBoldLeftBoldRight:"╅",lineUpDownBoldLeftRightBold:"╆",lineUpDoubleDownDoubleLeftDoubleRightDouble:"╬",lineUpDoubleDownDoubleLeftRight:"╫",lineUpDownLeftDoubleRightDouble:"╪",lineCross:"╳",lineBackslash:"╲",lineSlash:"╱"},fl={tick:"✔",info:"ℹ",warning:"⚠",cross:"✘",squareSmall:"◻",squareSmallFilled:"◼",circle:"◯",circleFilled:"◉",circleDotted:"◌",circleDouble:"◎",circleCircle:"ⓞ",circleCross:"ⓧ",circlePipe:"Ⓘ",radioOn:"◉",radioOff:"◯",checkboxOn:"☒",checkboxOff:"☐",checkboxCircleOn:"ⓧ",checkboxCircleOff:"Ⓘ",pointer:"❯",triangleUpOutline:"△",triangleLeft:"◀",triangleRight:"▶",lozenge:"◆",lozengeOutline:"◇",hamburger:"☰",smiley:"㋡",mustache:"෴",star:"★",play:"▶",nodejs:"⬢",oneSeventh:"⅐",oneNinth:"⅑",oneTenth:"⅒"},wx={tick:"√",info:"i",warning:"‼",cross:"×",squareSmall:"□",squareSmallFilled:"■",circle:"( )",circleFilled:"(*)",circleDotted:"( )",circleDouble:"( )",circleCircle:"(○)",circleCross:"(×)",circlePipe:"(│)",radioOn:"(*)",radioOff:"( )",checkboxOn:"[×]",checkboxOff:"[ ]",checkboxCircleOn:"(×)",checkboxCircleOff:"( )",pointer:">",triangleUpOutline:"∆",triangleLeft:"◄",triangleRight:"►",lozenge:"♦",lozengeOutline:"◊",hamburger:"≡",smiley:"☺",mustache:"┌─┐",star:"✶",play:"►",nodejs:"♦",oneSeventh:"1/7",oneNinth:"1/9",oneTenth:"1/10"},vx={...ml,...fl},_x={...ml,...wx},Sx=xx(),$x=Sx?vx:_x,er=$x,GE=Object.entries(fl);var kx={prefix:{idle:Ze("blue","?"),done:Ze("green",er.tick)},spinner:{interval:80,frames:["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"].map((e)=>Ze("yellow",e))},keybindings:[],style:{answer:(e)=>Ze("cyan",e),message:(e)=>Ze("bold",e),error:(e)=>Ze("red",`> ${e}`),defaultAnswer:(e)=>Ze("dim",`(${e})`),help:(e)=>Ze("dim",e),highlight:(e)=>Ze("cyan",e),key:(e)=>Ze("cyan",Ze("bold",`<${e}>`))}};function hl(){return{...kx,keybindings:ll()}}function gl(e){if(typeof e!=="object"||e===null)return!1;let t=e;while(Object.getPrototypeOf(t)!==null)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}function yl(...e){let t={};for(let r of e)for(let[n,o]of Object.entries(r)){let s=t[n];t[n]=gl(s)&&gl(o)?yl(s,o):o}return t}function Ue(...e){let t=[hl(),...e.filter((r)=>r!=null)];return yl(...t)}function tt({status:e="idle",theme:t}){let[r,n]=Y(!1),[o,s]=Y(0),{prefix:i,spinner:a}=Ue(t);if(et(()=>{if(e==="loading"){let l,u=-1,p=setTimeout(()=>{n(!0),l=setInterval(()=>{u=u+1,s(u%a.frames.length)},a.interval)},300);return()=>{clearTimeout(p),clearInterval(l)}}else n(!1)},[e]),r)return a.frames[o];return typeof i==="string"?i:i[e==="loading"?"idle":e]??i.idle}function Nr(e,t){return Qt((r)=>{let n=r.get();if(!r.initialized||n.dependencies.length!==t.length||n.dependencies.some((o,s)=>o!==t[s])){let o=e();return r.set({value:o,dependencies:t}),o}return n.value})}function Tt(e){return Y({current:e})[0]}function rt(e){let t=Tt(e);t.current=e,et((r)=>{let n=!1,o=Os((s,i)=>{if(n)return;t.current(i,r)});return r.input.on("keypress",o),()=>{n=!0,r.input.removeListener("keypress",o)}},[])}var Ol=vs(xl(),1);var wl=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return(t)=>{let r=0;e.lastIndex=0;while(e.test(t))r+=1;return t.length-r}})(),vl=(e)=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,_l=(e)=>e===8987||e===9001||e>=12272&&e<=12287||e>=12289&&e<=12350||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>=65040&&e<=65049||e>=65072&&e<=65106||e>=65108&&e<=65126||e>=65128&&e<=65131||e>=127488&&e<=127490||e>=127504&&e<=127547||e>=127552&&e<=127560||e>=131072&&e<=196605||e>=196608&&e<=262141;var Ex=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,jx=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,Sl=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/yu,Ax=/\t{1,1000}/y,$l=/[\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,Rx=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,Ix=/\p{M}+/gu,Tx={limit:1/0,ellipsis:""},kl=(e,t={},r={})=>{let n=t.limit??1/0,o=t.ellipsis??"",s=t?.ellipsisWidth??(o?kl(o,Tx,r).width:0),i=0,a=r.controlWidth??0,c=r.tabWidth??8,l=r.emojiWidth??2,u=2,p=r.regularWidth??1,d=r.wideWidth??2,m=[[Rx,p],[Ex,0],[jx,a],[Ax,c],[$l,l],[Sl,d]],h=0,y=0,b=e.length,v=0,E=!1,L=b,U=Math.max(0,n-s),k=0,I=0,M=0,pe=0;e:while(!0){if(I>k||y>=b&&y>h){let N=e.slice(k,I)||e.slice(h,y);v=0;for(let B of N.replaceAll(Ix,"")){let se=B.codePointAt(0)||0;if(vl(se))pe=2;else if(_l(se))pe=d;else pe=p;if(M+pe>U)L=Math.min(L,Math.max(k,h)+v);if(M+pe>n){E=!0;break e}v+=B.length,M+=pe}k=I=0}if(y>=b)break e;for(let N=0,B=m.length;N<B;N++){let[se,de]=m[N];if(se.lastIndex=y,se.test(e)){if(v=se===Sl?wl(e.slice(y,se.lastIndex)):se===$l?1:se.lastIndex-y,pe=v*de,M+pe>U)L=Math.min(L,y+Math.floor((U-M)/de));if(M+pe>n){E=!0;break e}M+=pe,k=h,I=y,y=h=se.lastIndex;continue e}}y+=1}return{width:E?U:M,index:E?L:b,truncated:E,ellipsed:E&&n>=s}},Pl=kl;var zx={limit:1/0,ellipsis:"",ellipsisWidth:0},Ox=(e,t={})=>Pl(e,zx,t).width,nt=Ox;var Ln="\x1B",Rl="›",Lx=39,Ds="\x07",Il="[",Dx="]",Tl="m",Ns=`${Dx}8;;`,Cl=new RegExp(`(?:\\${Il}(?<code>\\d+)m|\\${Ns}(?<uri>.*)${Ds})`,"y"),El=(e)=>{if(e>=30&&e<=37)return 39;if(e>=90&&e<=97)return 39;if(e>=40&&e<=47)return 49;if(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;return},jl=(e)=>`${Ln}${Il}${e}${Tl}`,Al=(e)=>`${Ln}${Ns}${e}${Ds}`,Ls=(e,t,r)=>{let n=t[Symbol.iterator](),o=!1,s=!1,i=e.at(-1),a=i===void 0?0:nt(i),c=n.next(),l=n.next(),u=0;while(!c.done){let p=c.value,d=nt(p);if(a+d<=r)e[e.length-1]+=p;else e.push(p),a=0;if(p===Ln||p===Rl)o=!0,s=t.startsWith(Ns,u+1);if(o){if(s){if(p===Ds)o=!1,s=!1}else if(p===Tl)o=!1}else if(a+=d,a===r&&!l.done)e.push(""),a=0;c=l,l=n.next(),u+=p.length}if(i=e.at(-1),!a&&i!==void 0&&i.length&&e.length>1)e[e.length-2]+=e.pop()},Nx=(e)=>{let t=e.split(" "),r=t.length;while(r){if(nt(t[r-1]))break;r--}if(r===t.length)return e;return t.slice(0,r).join(" ")+t.slice(r).join("")},Zx=(e,t,r={})=>{if(r.trim!==!1&&e.trim()==="")return"";let n="",o,s,i=e.split(" "),a=[""],c=0;for(let p=0;p<i.length;p++){let d=i[p];if(r.trim!==!1){let h=a.at(-1)??"",y=h.trimStart();if(h.length!==y.length)a[a.length-1]=y,c=nt(y)}if(p!==0){if(c>=t&&(r.wordWrap===!1||r.trim===!1))a.push(""),c=0;if(c||r.trim===!1)a[a.length-1]+=" ",c++}let m=nt(d);if(r.hard&&m>t){let h=t-c,y=1+Math.floor((m-h-1)/t);if(Math.floor((m-1)/t)<y)a.push("");Ls(a,d,t),c=nt(a.at(-1)??"");continue}if(c+m>t&&c&&m){if(r.wordWrap===!1&&c<t){Ls(a,d,t),c=nt(a.at(-1)??"");continue}a.push(""),c=0}if(c+m>t&&r.wordWrap===!1){Ls(a,d,t),c=nt(a.at(-1)??"");continue}a[a.length-1]+=d,c+=m}if(r.trim!==!1)a=a.map((p)=>Nx(p));let l=a.join(`
13
+ `),u=!1;for(let p=0;p<l.length;p++){let d=l[p];if(n+=d,!u){if(u=d>="\uD800"&&d<="\uDBFF",u)continue}else u=!1;if(d===Ln||d===Rl){Cl.lastIndex=p+1;let h=Cl.exec(l)?.groups;if(h?.code!==void 0){let y=Number.parseFloat(h.code);o=y===Lx?void 0:y}else if(h?.uri!==void 0)s=h.uri.length===0?void 0:h.uri}if(l[p+1]===`
14
+ `){if(s)n+=Al("");let m=o?El(o):void 0;if(o&&m)n+=jl(m)}else if(d===`
15
+ `){if(o&&El(o))n+=jl(o);if(s)n+=Al(s)}}return n},Ux=/\r?\n/;function zl(e,t,r){return String(e).normalize().split(Ux).map((n)=>Zx(n,t,r)).join(`
16
+ `)}function Zr(e,t){return e.split(`
17
+ `).flatMap((r)=>zl(r,t,{trim:!1,wordWrap:!1}).split(`
18
18
  `).map((n)=>n.trimEnd())).join(`
19
- `)}function $n(){return Mc.default({defaultWidth:80,output:us().output})}function fb({active:e,renderedItems:t,pageSize:r,loop:n}){let o=zt({lastPointer:e,lastActive:void 0}),{lastPointer:s,lastActive:i}=o.current,a=Math.floor(r/2),c=t.reduce((p,d)=>p+d.length,0),l=t.slice(0,e).reduce((p,d)=>p+d.length,0),u=l;if(c>r)if(n){if(u=s,i!=null&&i<e&&e-i<r)u=Math.min(a,Math.abs(e-i)===1?Math.min(s+(t[i]?.length??0),Math.max(l,s)):s+e-i)}else{let p=t.slice(e).reduce((d,m)=>d+m.length,0);u=p<r-a?r-p:Math.min(l,a)}return o.current.lastPointer=u,o.current.lastActive=e,u}function hs({items:e,active:t,renderItem:r,pageSize:n,loop:o=!0}){let s=$n(),i=(_)=>(_%e.length+e.length)%e.length,a=e.map((_,P)=>{if(_==null)return[];return Pr(r({item:_,index:P,isActive:P===t}),s).split(`
20
- `)}),c=a.reduce((_,P)=>_+P.length,0),l=(_)=>a[_]??[],u=fb({active:t,renderedItems:a,pageSize:n,loop:o}),p=l(t).slice(0,n),d=u+p.length<=n?u:n-p.length,m=Array.from({length:n});m.splice(d,p.length,...p);let h=new Set([t]),y=d+p.length,b=i(t+1);while(y<n&&!h.has(b)&&(o&&c>n?b!==t:b>t)){let P=l(b).slice(0,n-y);m.splice(y,P.length,...P),h.add(b),y+=P.length,b=i(b+1)}y=d-1,b=i(t-1);while(y>=0&&!h.has(b)&&(o&&c>n?b!==t:b<t)){let _=l(b),P=_.slice(Math.max(0,_.length-y-1));m.splice(y-P.length+1,P.length,...P),h.add(b),y-=P.length,b=i(b-1)}return m.filter((_)=>typeof _==="string").join(`
21
- `)}var el=Gt(Kc(),1);import*as Qc from"node:readline";import{AsyncResource as wb}from"node:async_hooks";var It=[];It.push("SIGHUP","SIGINT","SIGTERM");if(process.platform!=="win32")It.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")It.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var Sn=(e)=>!!e&&typeof e==="object"&&typeof e.removeListener==="function"&&typeof e.emit==="function"&&typeof e.reallyExit==="function"&&typeof e.listeners==="function"&&typeof e.kill==="function"&&typeof e.pid==="number"&&typeof e.on==="function",gs=Symbol.for("signal-exit emitter"),ys=globalThis,gb=Object.defineProperty.bind(Object);class Vc{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(ys[gs])return ys[gs];gb(ys,gs,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,t){this.listeners[e].push(t)}removeListener(e,t){let r=this.listeners[e],n=r.indexOf(t);if(n===-1)return;if(n===0&&r.length===1)r.length=0;else r.splice(n,1)}emit(e,t,r){if(this.emitted[e])return!1;this.emitted[e]=!0;let n=!1;for(let o of this.listeners[e])n=o(t,r)===!0||n;if(e==="exit")n=this.emit("afterExit",t,r)||n;return n}}class xs{}var yb=(e)=>({onExit(t,r){return e.onExit(t,r)},load(){return e.load()},unload(){return e.unload()}});class Wc extends xs{onExit(){return()=>{}}load(){}unload(){}}class Jc extends xs{#r=bs.platform==="win32"?"SIGINT":"SIGHUP";#t=new Vc;#e;#s;#i;#o={};#n=!1;constructor(e){super();this.#e=e,this.#o={};for(let t of It)this.#o[t]=()=>{let r=this.#e.listeners(t),{count:n}=this.#t,o=e;if(typeof o.__signal_exit_emitter__==="object"&&typeof o.__signal_exit_emitter__.count==="number")n+=o.__signal_exit_emitter__.count;if(r.length===n){this.unload();let s=this.#t.emit("exit",null,t),i=t==="SIGHUP"?this.#r:t;if(!s)e.kill(e.pid,i)}};this.#i=e.reallyExit,this.#s=e.emit}onExit(e,t){if(!Sn(this.#e))return()=>{};if(this.#n===!1)this.load();let r=t?.alwaysLast?"afterExit":"exit";return this.#t.on(r,e),()=>{if(this.#t.removeListener(r,e),this.#t.listeners.exit.length===0&&this.#t.listeners.afterExit.length===0)this.unload()}}load(){if(this.#n)return;this.#n=!0,this.#t.count+=1;for(let e of It)try{let t=this.#o[e];if(t)this.#e.on(e,t)}catch(t){}this.#e.emit=(e,...t)=>this.#c(e,...t),this.#e.reallyExit=(e)=>this.#a(e)}unload(){if(!this.#n)return;this.#n=!1,It.forEach((e)=>{let t=this.#o[e];if(!t)throw Error("Listener not defined for signal: "+e);try{this.#e.removeListener(e,t)}catch(r){}}),this.#e.emit=this.#s,this.#e.reallyExit=this.#i,this.#t.count-=1}#a(e){if(!Sn(this.#e))return 0;return this.#e.exitCode=e||0,this.#t.emit("exit",this.#e.exitCode,null),this.#i.call(this.#e,this.#e.exitCode)}#c(e,...t){let r=this.#s;if(e==="exit"&&Sn(this.#e)){if(typeof t[0]==="number")this.#e.exitCode=t[0];let n=r.call(this.#e,e,...t);return this.#t.emit("exit",this.#e.exitCode,null),n}else return r.call(this.#e,e,...t)}}var bs=globalThis.process,{onExit:Hc,load:eC,unload:tC}=yb(Sn(bs)?new Jc(bs):new Wc);import{stripVTControlCharacters as bb}from"node:util";var ws="\x1B[G",kn="\x1B[?25l",Yc="\x1B[?25h",_s=(e=1)=>e>0?`\x1B[${e}A`:"",vs=(e=1)=>e>0?`\x1B[${e}B`:"",$s=(e,t)=>{if(typeof t==="number"&&!Number.isNaN(t))return`\x1B[${t+1};${e+1}H`;return`\x1B[${e+1}G`},qc="\x1B[2K",Ss=(e)=>e>0?(qc+_s(1)).repeat(e-1)+qc+ws:"";var Xc=(e)=>e.split(`
22
- `).length,xb=(e)=>e.split(`
23
- `).pop()??"";class Pn{height=0;extraLinesUnderPrompt=0;cursorPos;rl;constructor(e){this.rl=e,this.cursorPos=e.getCursorPos()}write(e){this.rl.output.unmute(),this.rl.output.write(e),this.rl.output.mute()}render(e,t=""){let r=xb(e),n=bb(r),o=n;if(this.rl.line.length>0)o=o.slice(0,-this.rl.line.length);this.rl.setPrompt(o),this.cursorPos=this.rl.getCursorPos();let s=$n();if(e=Pr(e,s),t=Pr(t,s),n.length%s===0)e+=`
19
+ `)}function Dn(){return Ol.default({defaultWidth:80,output:zs().output})}function Fx({active:e,renderedItems:t,pageSize:r,loop:n}){let o=Tt({lastPointer:e,lastActive:void 0}),{lastPointer:s,lastActive:i}=o.current,a=Math.floor(r/2),c=t.reduce((p,d)=>p+d.length,0),l=t.slice(0,e).reduce((p,d)=>p+d.length,0),u=l;if(c>r)if(n){if(u=s,i!=null&&i<e&&e-i<r)u=Math.min(a,Math.abs(e-i)===1?Math.min(s+(t[i]?.length??0),Math.max(l,s)):s+e-i)}else{let p=t.slice(e).reduce((d,m)=>d+m.length,0);u=p<r-a?r-p:Math.min(l,a)}return o.current.lastPointer=u,o.current.lastActive=e,u}function Zs({items:e,active:t,renderItem:r,pageSize:n,loop:o=!0}){let s=Dn(),i=(v)=>(v%e.length+e.length)%e.length,a=e.map((v,E)=>{if(v==null)return[];return Zr(r({item:v,index:E,isActive:E===t}),s).split(`
20
+ `)}),c=a.reduce((v,E)=>v+E.length,0),l=(v)=>a[v]??[],u=Fx({active:t,renderedItems:a,pageSize:n,loop:o}),p=l(t).slice(0,n),d=u+p.length<=n?u:n-p.length,m=Array.from({length:n});m.splice(d,p.length,...p);let h=new Set([t]),y=d+p.length,b=i(t+1);while(y<n&&!h.has(b)&&(o&&c>n?b!==t:b>t)){let E=l(b).slice(0,n-y);m.splice(y,E.length,...E),h.add(b),y+=E.length,b=i(b+1)}y=d-1,b=i(t-1);while(y>=0&&!h.has(b)&&(o&&c>n?b!==t:b<t)){let v=l(b),E=v.slice(Math.max(0,v.length-y-1));m.splice(y-E.length+1,E.length,...E),h.add(b),y-=E.length,b=i(b-1)}return m.filter((v)=>typeof v==="string").join(`
21
+ `)}var Wl=vs(Nl(),1);import*as Vl from"node:readline";import{AsyncResource as Wx}from"node:async_hooks";var zt=[];zt.push("SIGHUP","SIGINT","SIGTERM");if(process.platform!=="win32")zt.push("SIGALRM","SIGABRT","SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")zt.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT");var Nn=(e)=>!!e&&typeof e==="object"&&typeof e.removeListener==="function"&&typeof e.emit==="function"&&typeof e.reallyExit==="function"&&typeof e.listeners==="function"&&typeof e.kill==="function"&&typeof e.pid==="number"&&typeof e.on==="function",Us=Symbol.for("signal-exit emitter"),Fs=globalThis,Bx=Object.defineProperty.bind(Object);class Zl{emitted={afterExit:!1,exit:!1};listeners={afterExit:[],exit:[]};count=0;id=Math.random();constructor(){if(Fs[Us])return Fs[Us];Bx(Fs,Us,{value:this,writable:!1,enumerable:!1,configurable:!1})}on(e,t){this.listeners[e].push(t)}removeListener(e,t){let r=this.listeners[e],n=r.indexOf(t);if(n===-1)return;if(n===0&&r.length===1)r.length=0;else r.splice(n,1)}emit(e,t,r){if(this.emitted[e])return!1;this.emitted[e]=!0;let n=!1;for(let o of this.listeners[e])n=o(t,r)===!0||n;if(e==="exit")n=this.emit("afterExit",t,r)||n;return n}}class Bs{}var Gx=(e)=>({onExit(t,r){return e.onExit(t,r)},load(){return e.load()},unload(){return e.unload()}});class Ul extends Bs{onExit(){return()=>{}}load(){}unload(){}}class Fl extends Bs{#r=Ms.platform==="win32"?"SIGINT":"SIGHUP";#t=new Zl;#e;#s;#i;#o={};#n=!1;constructor(e){super();this.#e=e,this.#o={};for(let t of zt)this.#o[t]=()=>{let r=this.#e.listeners(t),{count:n}=this.#t,o=e;if(typeof o.__signal_exit_emitter__==="object"&&typeof o.__signal_exit_emitter__.count==="number")n+=o.__signal_exit_emitter__.count;if(r.length===n){this.unload();let s=this.#t.emit("exit",null,t),i=t==="SIGHUP"?this.#r:t;if(!s)e.kill(e.pid,i)}};this.#i=e.reallyExit,this.#s=e.emit}onExit(e,t){if(!Nn(this.#e))return()=>{};if(this.#n===!1)this.load();let r=t?.alwaysLast?"afterExit":"exit";return this.#t.on(r,e),()=>{if(this.#t.removeListener(r,e),this.#t.listeners.exit.length===0&&this.#t.listeners.afterExit.length===0)this.unload()}}load(){if(this.#n)return;this.#n=!0,this.#t.count+=1;for(let e of zt)try{let t=this.#o[e];if(t)this.#e.on(e,t)}catch(t){}this.#e.emit=(e,...t)=>this.#c(e,...t),this.#e.reallyExit=(e)=>this.#a(e)}unload(){if(!this.#n)return;this.#n=!1,zt.forEach((e)=>{let t=this.#o[e];if(!t)throw Error("Listener not defined for signal: "+e);try{this.#e.removeListener(e,t)}catch(r){}}),this.#e.emit=this.#s,this.#e.reallyExit=this.#i,this.#t.count-=1}#a(e){if(!Nn(this.#e))return 0;return this.#e.exitCode=e||0,this.#t.emit("exit",this.#e.exitCode,null),this.#i.call(this.#e,this.#e.exitCode)}#c(e,...t){let r=this.#s;if(e==="exit"&&Nn(this.#e)){if(typeof t[0]==="number")this.#e.exitCode=t[0];let n=r.call(this.#e,e,...t);return this.#t.emit("exit",this.#e.exitCode,null),n}else return r.call(this.#e,e,...t)}}var Ms=globalThis.process,{onExit:Ml,load:C0,unload:E0}=Gx(Nn(Ms)?new Fl(Ms):new Ul);import{stripVTControlCharacters as Kx}from"node:util";var Gs="\x1B[G",Zn="\x1B[?25l",Gl="\x1B[?25h",Ks=(e=1)=>e>0?`\x1B[${e}A`:"",Vs=(e=1)=>e>0?`\x1B[${e}B`:"",Ws=(e,t)=>{if(typeof t==="number"&&!Number.isNaN(t))return`\x1B[${t+1};${e+1}H`;return`\x1B[${e+1}G`},Bl="\x1B[2K",Js=(e)=>e>0?(Bl+Ks(1)).repeat(e-1)+Bl+Gs:"";var Kl=(e)=>e.split(`
22
+ `).length,Vx=(e)=>e.split(`
23
+ `).pop()??"";class Un{height=0;extraLinesUnderPrompt=0;cursorPos;rl;constructor(e){this.rl=e,this.cursorPos=e.getCursorPos()}write(e){this.rl.output.unmute(),this.rl.output.write(e),this.rl.output.mute()}render(e,t=""){let r=Vx(e),n=Kx(r),o=n;if(this.rl.line.length>0)o=o.slice(0,-this.rl.line.length);this.rl.setPrompt(o),this.cursorPos=this.rl.getCursorPos();let s=Dn();if(e=Zr(e,s),t=Zr(t,s),n.length%s===0)e+=`
24
24
  `;let i=e+(t?`
25
- `+t:""),c=Math.floor(n.length/s)-this.cursorPos.rows+(t?Xc(t):0);if(c>0)i+=_s(c);i+=$s(this.cursorPos.cols),this.write(vs(this.extraLinesUnderPrompt)+Ss(this.height)+i),this.extraLinesUnderPrompt=c,this.height=Xc(i)}checkCursorPos(){let e=this.rl.getCursorPos();if(e.cols!==this.cursorPos.cols)this.write($s(e.cols)),this.cursorPos=e}done({clearContent:e}){this.rl.setPrompt("");let t=vs(this.extraLinesUnderPrompt);t+=e?Ss(this.height):`
26
- `,t+=ws,t+=Yc,this.write(t),this.rl.close()}}class ks extends Promise{static withResolver(){let e,t;return{promise:new Promise((n,o)=>{e=n,t=o}),resolve:e,reject:t}}}import _b from"node:path";var vb=globalThis.setImmediate;function Cn(e,t,r){if("on"in e)return e.on(t,r),()=>e.removeListener(t,r);return e.addEventListener(t,r),()=>e.removeEventListener(t,r)}function $b(){let e=Error.prepareStackTrace,t=[];try{Error.prepareStackTrace=(r,n)=>{let o=n.slice(1);return t=o,o},Error().stack}catch{return t}return Error.prepareStackTrace=e,t}function nt(e){let t=$b();return(n,o={})=>{let{input:s=process.stdin,signal:i}=o,a=new Set,c=new el.default;c.pipe(o.output??process.stdout);let l=Qc.createInterface({terminal:!0,input:s,output:c});c.mute();let u=new Pn(l),{promise:p,resolve:d,reject:m}=ks.withResolver();return bc(l,(h)=>{let y=wb.bind(()=>Sr.clearAll()),b=(S)=>{try{y(),S()}catch(A){m(A)}},_=(S)=>b(()=>d(S)),P=(S)=>b(()=>m(S)),O=Object.assign(p.finally(()=>{a.forEach((S)=>S()),u.done({clearContent:Boolean(o.clearPromptOnDone)}),c.end()}).then(()=>p),{cancel:()=>P(new cs)});if(i){let S=()=>P(new as({cause:i.reason}));if(i.aborted)return S(),O;a.add(Cn(i,"abort",S))}a.add(Hc((S,A)=>{P(new _n(`User force closed the prompt with ${S} ${A}`))})),a.add(Cn(l,"SIGINT",()=>P(new _n("User force closed the prompt with SIGINT")))),a.add(Cn(l,"close",y));let D=()=>{a.add(Cn(l.input,"keypress",()=>u.checkCursorPos()));let S=null;h(()=>{let A=!1;try{let U=e(n,(F)=>{if(A)_(F);else S={value:F}});if(U===void 0){let F=t[1]?.getFileName();if(F&&!F.startsWith("file://"))F=_b.resolve(F);throw Error(`Prompt functions must return a string.
27
- at ${F}`)}let[ce,L]=typeof U==="string"?[U]:U;u.render(ce,L),Sr.run()}catch(U){P(U)}if(A=!0,S!==null){let{value:U}=S;S=null,_(U)}})};if("readableFlowing"in s)vb(D);else D();return O})}}import{styleText as Sb}from"node:util";class Me{separator=Sb("dim",Array.from({length:15}).join(Vt.line));type="separator";constructor(e){if(e)this.separator=e}static isSeparator(e){return Boolean(e&&typeof e==="object"&&"type"in e&&e.type==="separator")}}import{styleText as kb}from"node:util";var Pb={keywords:{yes:"Yes",no:"No"},style:{confirmDefault:(e)=>{let t=e[0]??"";if(t.toLowerCase()===t.toUpperCase())return kb("cyan",e);return t.toUpperCase()+e.slice(1)}}},tl=nt((e,t)=>{let[r,n]=H("idle"),[o,s]=H(""),i=Oe(Pb,e.theme),a=et({status:r,theme:i}),{yes:c,no:l}=i.keywords,u=(c[0]??"").toLowerCase(),p=(l[0]??"").toLowerCase(),d=e.default===!1?`${u}/${i.style.confirmDefault(p)}`:`${i.style.confirmDefault(u)}/${p}`;function m(O){return O?c:l}let{transformer:h=m}=e;function y(O,D){let S=O.trim().toLowerCase();if(S==="")return D!==!1;if(c.toLowerCase().startsWith(S))return!0;if(l.toLowerCase().startsWith(S))return!1;return D!==!1}tt((O,D)=>{if(r!=="idle")return;if(Xe(O)){let S=y(o,e.default);s(h(S)),n("done"),t(S)}else if(vr(O)){let S=m(!y(o,e.default));D.clearLine(0),D.write(S),s(S)}else s(D.line)});let b=o,_="";if(r==="done")b=i.style.answer(o);else _=` ${i.style.defaultAnswer(d)}`;let P=i.style.message(e.message,r);return`${a} ${P}${_} ${b}`});var Cb={validationFailureMode:"keep"},rl=nt((e,t)=>{let{prefill:r="tab"}=e,n=Oe(Cb,e.theme),[o,s]=H("idle"),[i,a]=H(String(e.default??"")),[c,l]=H(),[u,p]=H(""),d=et({status:o,theme:n});async function m(P){let{required:O,pattern:D,patternError:S="Invalid input"}=e;if(O&&!P)return"You must provide a value";if(D&&!D.test(P))return S;if(typeof e.validate==="function")return await e.validate(P)||"You must provide a valid value";return!0}tt(async(P,O)=>{if(o!=="idle")return;if(Xe(P)){let D=u||i;s("loading");let S=await m(D);if(S===!0)p(D),s("done"),t(D);else{if(n.validationFailureMode==="clear")p("");else O.write(u);l(S),s("idle")}}else if(_r(P)&&!u)a("");else if(vr(P)&&!u)a(""),O.clearLine(0),O.write(i),p(i);else p(O.line),l(void 0)}),Qe((P)=>{if(r==="editable"&&i)P.write(i),p(i)},[]);let h=n.style.message(e.message,o),y=u;if(typeof e.transformer==="function")y=e.transformer(u,{isFinal:o==="done"});else if(o==="done")y=n.style.answer(u);let b;if(i&&o!=="done"&&!u)b=n.style.defaultAnswer(i);let _="";if(c)_=n.style.error(c);return[[d,h,b,y].filter((P)=>P!==void 0).join(" "),_]});import{styleText as Ps}from"node:util";var Eb={style:{maskedText:"[input is masked]",keysHelpTip:(e)=>e.map(([t,r])=>`${Ps("bold",t)} ${Ps("dim",r)}`).join(Ps("dim"," • "))}},nl=nt((e,t)=>{let{toggleMask:r=!0,validate:n=()=>!0}=e,o=Oe(Eb,e.theme),[s,i]=H("idle"),[a,c]=H(),[l,u]=H(""),[p,d]=H(!1),m=et({status:s,theme:o});tt(async(O,D)=>{if(s!=="idle")return;if(Xe(O)){let S=l;i("loading");let A=await n(S);if(A===!0)u(S),i("done"),t(S);else D.write(l),c(A||"You must provide a valid value"),i("idle")}else if(r&&O.ctrl&&O.name==="t")d((S)=>!S);else u(D.line),c(void 0)});let h=o.style.message(e.message,s),y=r&&p&&s==="idle",b="";if(y)b=l;else if(e.mask)b=(typeof e.mask==="string"?e.mask:"*").repeat(l.length);else if(s!=="done")b=o.style.help(o.style.maskedText);if(s==="done")b=o.style.answer(b);else if(!e.mask)b+=kn;let _=[m,h,b].filter(Boolean).join(" "),P=[a?o.style.error(a):"",r&&s==="idle"?o.style.keysHelpTip([["ctrl+t","toggle visibility"]]):""].filter(Boolean).join(`
28
- `);return[_,P]});import{styleText as Cr}from"node:util";var zb={icon:{cursor:Vt.pointer},style:{disabled:(e)=>Cr("dim",e),description:(e)=>Cr("cyan",e),keysHelpTip:(e)=>e.map(([t,r])=>`${Cr("bold",t)} ${Cr("dim",r)}`).join(Cr("dim"," • "))},i18n:{disabledError:"This option is disabled and cannot be selected."},indexMode:"hidden"};function Cs(e){return!Me.isSeparator(e)&&!e.disabled}function Es(e){return!Me.isSeparator(e)}function Ib(e){return e.map((t)=>{if(Me.isSeparator(t))return t;if(typeof t!=="object"||t===null||!("value"in t)){let o=String(t);return{value:t,name:o,short:o,disabled:!1}}let r=t.name??String(t.value),n={value:t.value,name:r,short:t.short??r,disabled:t.disabled??!1};if(t.description)n.description=t.description;return n})}var ol=nt((e,t)=>{let{loop:r=!0,pageSize:n=7}=e,o=Oe(zb,e.theme),{keybindings:s}=o,[i,a]=H("idle"),c=et({status:i,theme:o}),l=zt(),u=!s.includes("vim"),p=kr(()=>Ib(e.choices),[e.choices]),d=kr(()=>{let L=p.findIndex(Es),F=p.findLastIndex(Es);if(L===-1)throw new $r("[select prompt] No selectable choices. All choices are disabled.");return{first:L,last:F}},[p]),m=kr(()=>{if(!("default"in e))return-1;return p.findIndex((L)=>Cs(L)&&L.value===e.default)},[e.default,p]),[h,y]=H(m===-1?d.first:m),b=p[h];if(b==null||Me.isSeparator(b))throw Error("Active index does not point to a choice");let[_,P]=H();tt((L,F)=>{if(clearTimeout(l.current),_)P(void 0);if(Xe(L))if(b.disabled)P(o.i18n.disabledError);else a("done"),t(b.value);else if(wr(L,s)||wn(L,s)){if(F.clearLine(0),r||wr(L,s)&&h!==d.first||wn(L,s)&&h!==d.last){let ne=wr(L,s)?-1:1,le=h;do le=(le+ne+p.length)%p.length;while(!Es(p[le]));y(le)}}else if(is(L)&&!Number.isNaN(Number(F.line))){let ne=Number(F.line)-1,le=-1,Ae=p.findIndex((mr)=>{if(Me.isSeparator(mr))return!1;return le++,le===ne}),qo=p[Ae];if(qo!=null&&Cs(qo))y(Ae);l.current=setTimeout(()=>{F.clearLine(0)},700)}else if(_r(L))F.clearLine(0);else if(u){let ne=F.line.toLowerCase(),le=p.findIndex((Ae)=>{if(Me.isSeparator(Ae)||!Cs(Ae))return!1;return Ae.name.toLowerCase().startsWith(ne)});if(le!==-1)y(le);l.current=setTimeout(()=>{F.clearLine(0)},700)}}),Qe(()=>()=>{clearTimeout(l.current)},[]);let O=o.style.message(e.message,i),D=o.style.keysHelpTip([["↑↓","navigate"],["⏎","select"]]),S=0,A=hs({items:p,active:h,renderItem({item:L,isActive:F,index:ne}){if(Me.isSeparator(L))return S++,` ${L.separator}`;let le=F?o.icon.cursor:" ",Ae=o.indexMode==="number"?`${ne+1-S}. `:"";if(L.disabled){let mr=typeof L.disabled==="string"?L.disabled:"(disabled)",yy=F?o.icon.cursor:"-";return o.style.disabled(`${yy} ${Ae}${L.name} ${mr}`)}return(F?o.style.highlight:(mr)=>mr)(`${le} ${Ae}${L.name}`)},pageSize:n,loop:r});if(i==="done")return[c,O,o.style.answer(b.short)].filter(Boolean).join(" ");let{description:U}=b;return`${[[c,O].filter(Boolean).join(" "),A," ",U?o.style.description(U):"",_?o.style.error(_):"",D].filter(Boolean).join(`
29
- `).trimEnd()}${kn}`});var Le=Gt(fr(),1);class E extends Error{hint;exitCode;constructor(e,t={}){super(e);this.name="CliError",this.hint=t.hint,this.exitCode=t.exitCode??1}}var Z=(e,t)=>new E(e,{exitCode:2,hint:t}),R=(e)=>e<1000?`${Math.round(e)}ms`:`${Math.round(e/1000)}s`,Tb=[["d",86400000],["h",3600000],["m",60000],["s",1000]],V=(e)=>{let t=Math.max(0,e);for(let[r,n]of Tb)if(t>=n)return`${Math.round(t/n)}${r}`;return`${Math.round(t)}ms`},Er=(e)=>`${Number((e/1024).toFixed(1))} GB`,ke=(e,t)=>`${e} ${t}${e===1?"":"s"}`,al=(e)=>e.charAt(0).toUpperCase()+e.slice(1),Tt=(e)=>{let t=e.at(-1)??"",r=e.slice(0,-1);return r.length===0?t:`${r.join(", ")} and ${t}`},Wt=(e)=>{let t=Math.max(0,Math.floor(e/60000)),r=Math.floor(t/60);return r>0?`${r}h ${t%60}m`:`${t}m`},oe=(e)=>{process.stderr.write(`${e}
30
- `)},w=(e)=>{oe(`${Le.default.dim(">")} ${e}`)},Q=(e,t)=>{let r=t===void 0?"":`[${R(t)}]`,n=r?` ${Le.default.dim(r)}`:"";oe(`${Le.default.cyan("> Success!")} ${e}${n}`)},G=(e)=>{oe(`${Le.default.bold(Le.default.yellow("> NOTE:"))} ${e}`)},cl=(e)=>{if(oe(`${Le.default.bold(Le.default.red("Error:"))} ${e.message}`),e.hint)oe(`${Le.default.dim(">")} ${e.hint}`)},sl=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],Ab=300,Rb="\r\x1B[2K",I=async(e,t)=>{if(!process.stderr.isTTY)return t();let r=0,n=!1,o,s=()=>{n=!0;let a=sl[r%sl.length]??"";r+=1,process.stderr.write(`\r${Le.default.dim(a)} ${e}`)},i=setTimeout(()=>{s(),o=setInterval(s,80)},Ab);try{return await t()}finally{if(clearTimeout(i),clearInterval(o),n)process.stderr.write(Rb)}},En=async(e)=>{try{return await e()}catch(t){if(t instanceof Error&&t.name==="ExitPromptError")throw new E("Canceled",{exitCode:130});throw t}},ll=(e)=>{let t={output:e.stderr};return{choice:(r)=>En(()=>ol(r,t)),confirm:(r)=>En(()=>tl(r,t)),interactive:e.stdin.isTTY===!0&&e.stderr.isTTY===!0,secret:(r)=>En(()=>nl({mask:"*",message:r},t)),text:(r)=>En(()=>rl({...r,required:r.required??!0},t))}},ul=(e)=>({isTTY:e.isTTY===!0,json:(t)=>{e.write(`${JSON.stringify(t,null,2)}
25
+ `+t:""),c=Math.floor(n.length/s)-this.cursorPos.rows+(t?Kl(t):0);if(c>0)i+=Ks(c);i+=Ws(this.cursorPos.cols),this.write(Vs(this.extraLinesUnderPrompt)+Js(this.height)+i),this.extraLinesUnderPrompt=c,this.height=Kl(i)}checkCursorPos(){let e=this.rl.getCursorPos();if(e.cols!==this.cursorPos.cols)this.write(Ws(e.cols)),this.cursorPos=e}done({clearContent:e}){this.rl.setPrompt("");let t=Vs(this.extraLinesUnderPrompt);t+=e?Js(this.height):`
26
+ `,t+=Gs,t+=Gl,this.write(t),this.rl.close()}}class Hs extends Promise{static withResolver(){let e,t;return{promise:new Promise((n,o)=>{e=n,t=o}),resolve:e,reject:t}}}import Jx from"node:path";var Hx=globalThis.setImmediate;function Fn(e,t,r){if("on"in e)return e.on(t,r),()=>e.removeListener(t,r);return e.addEventListener(t,r),()=>e.removeEventListener(t,r)}function qx(){let e=Error.prepareStackTrace,t=[];try{Error.prepareStackTrace=(r,n)=>{let o=n.slice(1);return t=o,o},Error().stack}catch{return t}return Error.prepareStackTrace=e,t}function ot(e){let t=qx();return(n,o={})=>{let{input:s=process.stdin,signal:i}=o,a=new Set,c=new Wl.default;c.pipe(o.output??process.stdout);let l=Vl.createInterface({terminal:!0,input:s,output:c});c.mute();let u=new Un(l),{promise:p,resolve:d,reject:m}=Hs.withResolver();return pl(l,(h)=>{let y=Wx.bind(()=>Dr.clearAll()),b=(k)=>{try{y(),k()}catch(I){m(I)}},v=(k)=>b(()=>d(k)),E=(k)=>b(()=>m(k)),L=Object.assign(p.finally(()=>{a.forEach((k)=>k()),u.done({clearContent:Boolean(o.clearPromptOnDone)}),c.end()}).then(()=>p),{cancel:()=>E(new Is)});if(i){let k=()=>E(new Rs({cause:i.reason}));if(i.aborted)return k(),L;a.add(Fn(i,"abort",k))}a.add(Ml((k,I)=>{E(new On(`User force closed the prompt with ${k} ${I}`))})),a.add(Fn(l,"SIGINT",()=>E(new On("User force closed the prompt with SIGINT")))),a.add(Fn(l,"close",y));let U=()=>{a.add(Fn(l.input,"keypress",()=>u.checkCursorPos()));let k=null;h(()=>{let I=!1;try{let M=e(n,(B)=>{if(I)v(B);else k={value:B}});if(M===void 0){let B=t[1]?.getFileName();if(B&&!B.startsWith("file://"))B=Jx.resolve(B);throw Error(`Prompt functions must return a string.
27
+ at ${B}`)}let[pe,N]=typeof M==="string"?[M]:M;u.render(pe,N),Dr.run()}catch(M){E(M)}if(I=!0,k!==null){let{value:M}=k;k=null,v(M)}})};if("readableFlowing"in s)Hx(U);else U();return L})}}import{styleText as Yx}from"node:util";class Ke{separator=Yx("dim",Array.from({length:15}).join(er.line));type="separator";constructor(e){if(e)this.separator=e}static isSeparator(e){return Boolean(e&&typeof e==="object"&&"type"in e&&e.type==="separator")}}import{styleText as Xx}from"node:util";var Qx={keywords:{yes:"Yes",no:"No"},style:{confirmDefault:(e)=>{let t=e[0]??"";if(t.toLowerCase()===t.toUpperCase())return Xx("cyan",e);return t.toUpperCase()+e.slice(1)}}},Jl=ot((e,t)=>{let[r,n]=Y("idle"),[o,s]=Y(""),i=Ue(Qx,e.theme),a=tt({status:r,theme:i}),{yes:c,no:l}=i.keywords,u=(c[0]??"").toLowerCase(),p=(l[0]??"").toLowerCase(),d=e.default===!1?`${u}/${i.style.confirmDefault(p)}`:`${i.style.confirmDefault(u)}/${p}`;function m(L){return L?c:l}let{transformer:h=m}=e;function y(L,U){let k=L.trim().toLowerCase();if(k==="")return U!==!1;if(c.toLowerCase().startsWith(k))return!0;if(l.toLowerCase().startsWith(k))return!1;return U!==!1}rt((L,U)=>{if(r!=="idle")return;if(Qe(L)){let k=y(o,e.default);s(h(k)),n("done"),t(k)}else if(Or(L)){let k=m(!y(o,e.default));U.clearLine(0),U.write(k),s(k)}else s(U.line)});let b=o,v="";if(r==="done")b=i.style.answer(o);else v=` ${i.style.defaultAnswer(d)}`;let E=i.style.message(e.message,r);return`${a} ${E}${v} ${b}`});var ew={validationFailureMode:"keep"},Hl=ot((e,t)=>{let{prefill:r="tab"}=e,n=Ue(ew,e.theme),[o,s]=Y("idle"),[i,a]=Y(String(e.default??"")),[c,l]=Y(),[u,p]=Y(""),d=tt({status:o,theme:n});async function m(E){let{required:L,pattern:U,patternError:k="Invalid input"}=e;if(L&&!E)return"You must provide a value";if(U&&!U.test(E))return k;if(typeof e.validate==="function")return await e.validate(E)||"You must provide a valid value";return!0}rt(async(E,L)=>{if(o!=="idle")return;if(Qe(E)){let U=u||i;s("loading");let k=await m(U);if(k===!0)p(U),s("done"),t(U);else{if(n.validationFailureMode==="clear")p("");else L.write(u);l(k),s("idle")}}else if(zr(E)&&!u)a("");else if(Or(E)&&!u)a(""),L.clearLine(0),L.write(i),p(i);else p(L.line),l(void 0)}),et((E)=>{if(r==="editable"&&i)E.write(i),p(i)},[]);let h=n.style.message(e.message,o),y=u;if(typeof e.transformer==="function")y=e.transformer(u,{isFinal:o==="done"});else if(o==="done")y=n.style.answer(u);let b;if(i&&o!=="done"&&!u)b=n.style.defaultAnswer(i);let v="";if(c)v=n.style.error(c);return[[d,h,b,y].filter((E)=>E!==void 0).join(" "),v]});import{styleText as qs}from"node:util";var tw={style:{maskedText:"[input is masked]",keysHelpTip:(e)=>e.map(([t,r])=>`${qs("bold",t)} ${qs("dim",r)}`).join(qs("dim"," • "))}},ql=ot((e,t)=>{let{toggleMask:r=!0,validate:n=()=>!0}=e,o=Ue(tw,e.theme),[s,i]=Y("idle"),[a,c]=Y(),[l,u]=Y(""),[p,d]=Y(!1),m=tt({status:s,theme:o});rt(async(L,U)=>{if(s!=="idle")return;if(Qe(L)){let k=l;i("loading");let I=await n(k);if(I===!0)u(k),i("done"),t(k);else U.write(l),c(I||"You must provide a valid value"),i("idle")}else if(r&&L.ctrl&&L.name==="t")d((k)=>!k);else u(U.line),c(void 0)});let h=o.style.message(e.message,s),y=r&&p&&s==="idle",b="";if(y)b=l;else if(e.mask)b=(typeof e.mask==="string"?e.mask:"*").repeat(l.length);else if(s!=="done")b=o.style.help(o.style.maskedText);if(s==="done")b=o.style.answer(b);else if(!e.mask)b+=Zn;let v=[m,h,b].filter(Boolean).join(" "),E=[a?o.style.error(a):"",r&&s==="idle"?o.style.keysHelpTip([["ctrl+t","toggle visibility"]]):""].filter(Boolean).join(`
28
+ `);return[v,E]});import{styleText as Ur}from"node:util";var rw={icon:{cursor:er.pointer},style:{disabled:(e)=>Ur("dim",e),description:(e)=>Ur("cyan",e),keysHelpTip:(e)=>e.map(([t,r])=>`${Ur("bold",t)} ${Ur("dim",r)}`).join(Ur("dim"," • "))},i18n:{disabledError:"This option is disabled and cannot be selected."},indexMode:"hidden"};function Ys(e){return!Ke.isSeparator(e)&&!e.disabled}function Xs(e){return!Ke.isSeparator(e)}function nw(e){return e.map((t)=>{if(Ke.isSeparator(t))return t;if(typeof t!=="object"||t===null||!("value"in t)){let o=String(t);return{value:t,name:o,short:o,disabled:!1}}let r=t.name??String(t.value),n={value:t.value,name:r,short:t.short??r,disabled:t.disabled??!1};if(t.description)n.description=t.description;return n})}var Yl=ot((e,t)=>{let{loop:r=!0,pageSize:n=7}=e,o=Ue(rw,e.theme),{keybindings:s}=o,[i,a]=Y("idle"),c=tt({status:i,theme:o}),l=Tt(),u=!s.includes("vim"),p=Nr(()=>nw(e.choices),[e.choices]),d=Nr(()=>{let N=p.findIndex(Xs),B=p.findLastIndex(Xs);if(N===-1)throw new Lr("[select prompt] No selectable choices. All choices are disabled.");return{first:N,last:B}},[p]),m=Nr(()=>{if(!("default"in e))return-1;return p.findIndex((N)=>Ys(N)&&N.value===e.default)},[e.default,p]),[h,y]=Y(m===-1?d.first:m),b=p[h];if(b==null||Ke.isSeparator(b))throw Error("Active index does not point to a choice");let[v,E]=Y();rt((N,B)=>{if(clearTimeout(l.current),v)E(void 0);if(Qe(N))if(b.disabled)E(o.i18n.disabledError);else a("done"),t(b.value);else if(Tr(N,s)||zn(N,s)){if(B.clearLine(0),r||Tr(N,s)&&h!==d.first||zn(N,s)&&h!==d.last){let se=Tr(N,s)?-1:1,de=h;do de=(de+se+p.length)%p.length;while(!Xs(p[de]));y(de)}}else if(As(N)&&!Number.isNaN(Number(B.line))){let se=Number(B.line)-1,de=-1,De=p.findIndex((Pr)=>{if(Ke.isSeparator(Pr))return!1;return de++,de===se}),xs=p[De];if(xs!=null&&Ys(xs))y(De);l.current=setTimeout(()=>{B.clearLine(0)},700)}else if(zr(N))B.clearLine(0);else if(u){let se=B.line.toLowerCase(),de=p.findIndex((De)=>{if(Ke.isSeparator(De)||!Ys(De))return!1;return De.name.toLowerCase().startsWith(se)});if(de!==-1)y(de);l.current=setTimeout(()=>{B.clearLine(0)},700)}}),et(()=>()=>{clearTimeout(l.current)},[]);let L=o.style.message(e.message,i),U=o.style.keysHelpTip([["↑↓","navigate"],["⏎","select"]]),k=0,I=Zs({items:p,active:h,renderItem({item:N,isActive:B,index:se}){if(Ke.isSeparator(N))return k++,` ${N.separator}`;let de=B?o.icon.cursor:" ",De=o.indexMode==="number"?`${se+1-k}. `:"";if(N.disabled){let Pr=typeof N.disabled==="string"?N.disabled:"(disabled)",Fb=B?o.icon.cursor:"-";return o.style.disabled(`${Fb} ${De}${N.name} ${Pr}`)}return(B?o.style.highlight:(Pr)=>Pr)(`${de} ${De}${N.name}`)},pageSize:n,loop:r});if(i==="done")return[c,L,o.style.answer(b.short)].filter(Boolean).join(" ");let{description:M}=b;return`${[[c,L].filter(Boolean).join(" "),I," ",M?o.style.description(M):"",v?o.style.error(v):"",U].filter(Boolean).join(`
29
+ `).trimEnd()}${Zn}`});var ti,tr=(e)=>{ti=e},Fr=()=>ti,ow=/^[\w%+,./:=@-]+$/u,sw=(e)=>e.replaceAll("\r",String.raw`\r`).replaceAll(`
30
+ `,String.raw`\n`).replaceAll("\t",String.raw`\t`),ri=(e,t=process.platform)=>{if(ow.test(e))return e;let r=sw(e);return`'${t==="win32"?r.replaceAll("'","''"):r.replaceAll("'",String.raw`'\''`)}'`},Qs=new Set(["-P","--profile"]),ei=new Set(["-p","--project"]),eu=(e,t)=>{for(let[r,n]of e.entries()){if(n==="--")return;if(t.has(n))return e[r+1];let o=n.indexOf("=");if(o!==-1&&t.has(n.slice(0,o)))return n.slice(o+1)}return},tu=(e)=>eu(e,Qs),ru=(e)=>eu(e,ei),iw=(e,t)=>[...e.sections.flatMap((r)=>r.commands),...e.hidden].find((r)=>t!==void 0&&me(r).includes(t)),Xl=(e,t)=>t.has(e.split("=")[0]??""),aw=(e,t)=>{let r=0;while(t[r]?.startsWith("-")){let c=t[r]??"",l=(Qs.has(c)||ei.has(c))&&!c.includes("=");r+=l?2:1}let n=iw(e,t[r]),o=n?.kind==="passthrough"?r:t.length,s=t.slice(0,o),i={profile:s.some((c)=>Xl(c,Qs)),project:s.some((c)=>Xl(c,ei))};if(!n)return{path:null,...i};if(n.kind!=="group")return{path:[n],...i};let a=n.subcommands.find((c)=>me(c).includes(t[r+1]??""));return{path:a?[n,a]:[n],...i}},Ql=(e,t,r)=>r.startsWith("-")?[`${t}=${r}`]:[e,r],cw=(e,t)=>{let{path:r,profile:n,project:o}=aw(e.program,t);if(!r)return[];let s=[];if(e.profile!==void 0&&!n&&jn(r)!==!1)s.push(...Ql("-P","--profile",e.profile));if(e.project!==void 0&&!o&&jr(r)===void 0)s.push(...Ql("-p","--project",e.project));return s},Mr=(e,t)=>{let[r,...n]=e.split(" "),o=t&&r==="nipa"?cw(t,n):[];return{argv:[r??"",...o,...n],command:[r,...o.map((s)=>ri(s)),...n].join(" ")}},lw=/`nipa(?: [^\n`]*)?`/gu,ni=(e,t)=>t?e.replaceAll(lw,(r)=>`\`${Mr(r.slice(1,-1),t).command}\``):e,Mn=(e)=>ni(e,ti);var{bold:x,cyan:Ot,dim:P,gray:W,green:Lt,red:xe,yellow:Ve}=Rr.stderr;class C extends Error{hint;data;exitCode;reason;next;constructor(e,t={}){super(e);this.name="CliError",this.hint=t.hint,this.data=t.data,this.exitCode=t.exitCode??1,this.reason=t.reason??(this.exitCode===2?"invalid_arguments":"failed"),this.next=t.next}}var Z=(e,t,r)=>new C(e,{exitCode:2,hint:t,reason:r}),T=(e)=>e<1000?`${Math.round(e)}ms`:`${Math.round(e/1000)}s`,uw=[["d",86400000],["h",3600000],["m",60000],["s",1000]],H=(e)=>{let t=Math.max(0,e);for(let[r,n]of uw)if(t>=n)return`${Math.round(t/n)}${r}`;return`${Math.round(t)}ms`},Br=(e)=>`${Number((e/1024).toFixed(1))} GB`,le=(e,t)=>`${e} ${t}${e===1?"":"s"}`,ou=(e)=>e.charAt(0).toUpperCase()+e.slice(1),Dt=(e)=>{let t=e.at(-1)??"",r=e.slice(0,-1);return r.length===0?t:`${r.join(", ")} and ${t}`},nr=(e)=>{let t=Math.max(0,Math.floor(e/60000)),r=Math.floor(t/60);return r>0?`${r}h ${t%60}m`:`${t}m`},oi="\x1B",pw="\x07",dw=new Set(["1m","2m","22m","31m","32m","33m","36m","39m","90m"]),mw=/^[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]$/u,fw=(e)=>e>="0"&&e<="?",su=(e)=>e>=" "&&e<="/",iu=(e)=>e>="@"&&e<="~",si=(e,t,r)=>{let n=t;while(n<e.length&&r(e[n]??""))n+=1;return n},hw=(e,t)=>{let r=si(e,si(e,t+2,fw),su);return iu(e[r]??"")?r+1:t+1},gw=(e,t)=>{for(let r=t+2;r<e.length;r+=1){if(e[r]===pw)return r+1;if(e[r]===oi&&e[r+1]==="\\")return r+2}return t+1},yw=(e,t)=>{let r=si(e,t+1,su);return iu(e[r]??"")?r+1:t+1},bw=(e,t)=>{let r=e[t+1]??"";if(r==="[")return hw(e,t);return"]PX^_".includes(r)&&r!==""?gw(e,t):yw(e,t)},Wn=(e,t)=>{let r=[...e],n="",o=0;while(o<r.length){let s=r[o]??"";if(s===oi){let i=bw(r,o),a=r.slice(o,i).join("");if(t.sgr&&a.startsWith(`${oi}[`)&&dw.has(a.slice(2)))n+=a;o=i}else{if(!mw.test(s)||t.newline&&s===`
31
+ `)n+=s;o+=1}}return n},xw=(e)=>Wn(e,{newline:!0,sgr:!0}),z=(e)=>Wn(e.replaceAll(`
32
+ `,String.raw`\n`).replaceAll("\r",String.raw`\r`).replaceAll("\t",String.raw`\t`),{newline:!1,sgr:!1}),gt=!1,ai=(e)=>{gt=e},au=()=>gt,V=(e)=>{process.stderr.write(`${xw(e)}
33
+ `)},Jn=()=>process.stderr.columns||80,w=(e)=>{if(gt)return;V(`${P(">")} ${Mn(e)}`)},te=(e,t)=>{if(gt)return;let r=t===void 0?"":`[${T(t)}]`,n=r?` ${P(r)}`:"";V(`${Ot("> Success!")} ${e}${n}`)},J=(e)=>{if(gt)return;V(`${x(Ve("> NOTE:"))} ${Mn(e)}`)},Hn=(e)=>{if(V(`${x(xe("Error:"))} ${e.message}`),e.hint)V(`${P(">")} ${Mn(e.hint)}`)},ii=["⠋","⠙","⠹","⠸","⠼","⠴","⠦","⠧","⠇","⠏"],ww=300,vw="\r\x1B[2K",cu=!1,lu=(e)=>{cu=e},j=async(e,t)=>{if(!cu||gt)return t();let r=0,n=!1,o,s=()=>{n=!0;let a=ii[r%ii.length]??"";r+=1,process.stderr.write(`\r${P(a)} ${Wn(e,{newline:!1,sgr:!0})}`)},i=setTimeout(()=>{s(),o=setInterval(s,80)},ww);try{return await t()}finally{if(clearTimeout(i),clearInterval(o),n)process.stderr.write(vw)}},Bn=async(e)=>{try{return await e()}catch(t){if(t instanceof Error&&t.name==="ExitPromptError")throw new C("Canceled",{exitCode:130});throw t}},rr=(e)=>Wn(e,{newline:!1,sgr:!0}),Gn={prefix:{done:Lt("✔"),idle:Rr.stderr.blue("?")},spinner:{frames:ii.map((e)=>Ve(e)),interval:80},style:{answer:Ot,defaultAnswer:(e)=>P(`(${e})`),description:Ot,error:(e)=>xe(`> ${e}`),help:P,highlight:Ot,keysHelpTip:(e)=>e.map(([t,r])=>`${x(t)} ${P(r)}`).join(P(" • ")),message:x}},uu=(e)=>{let t={input:e.stdin,output:e.stderr},n=!(e.nonInteractive||e.json||!!e.env.CI)&&e.stdin.isTTY===!0&&e.stderr.isTTY===!0;return{choice:(o)=>Bn(()=>Yl({...o,choices:o.choices.map((s)=>({...s,description:s.description===void 0?void 0:rr(s.description),name:rr(s.name)})),message:rr(o.message),theme:Gn},t)),confirm:(o)=>Bn(()=>Jl({...o,message:rr(o.message),theme:Gn},t)),interactive:n,secret:(o)=>Bn(()=>ql({mask:"*",message:rr(o),theme:Gn},t)),text:(o)=>Bn(()=>Hl({...o,message:rr(o.message),required:o.required??!0,theme:Gn},t))}},pu=(e)=>({isTTY:e.isTTY===!0,json:(t)=>{e.write(`${JSON.stringify(t,null,2)}
31
34
  `)},line:(t)=>{e.write(`${t}
32
- `)},write:(t)=>{e.write(t)}}),{bold:x,cyan:Is,dim:T,gray:K,green:Jt,red:Pe,yellow:ft}=Le.default,De=(e,t)=>({paint:()=>`${e}${T(t)}`,text:`${e}${t}`}),zn=(e)=>{let t=[];if(e.vcpus!==null)t.push(ke(e.vcpus,"vCPU"));if(e.ramMb!==null)t.push(`${Er(e.ramMb)} RAM`);return t.length===0?{text:e.flavor}:De(e.flavor,` (${t.join(", ")})`)},zs=" ".repeat(5),pl=(e)=>x(Is(e)),M=(e)=>{let{headings:t,marks:r,rows:n}=e,o=t.map((i,a)=>Math.max(i.length,...n.map((c)=>c[a]?.text.length??0))),s=(i)=>i.map((a,c)=>{let u=c===i.length-1?a.text:a.text.padEnd(o[c]??0);return a.paint?a.paint(u):u}).join(zs);oe(""),oe(` ${s(t.map((i)=>({paint:pl,text:i})))}`);for(let[i,a]of n.entries())oe(`${r?.[i]??" "} ${s(a)}`);oe("")},il=(e)=>e.paint?.(e.text)??e.text,ht=(e)=>{let t=Math.max(...e.map((n)=>n.label.length)),r=" ".repeat(2+t)+zs;oe("");for(let{label:n,lines:o}of e){let[s={text:"-"},...i]=o,a=` ${pl(n.padEnd(t))}${zs}`;oe(`${a}${il(s)}`);for(let c of i)oe(`${r}${il(c)}`)}oe("")};var fl=(e)=>new Map(e.flatMap((t)=>Se(t).map((r)=>[r,t]))),Rs=(e)=>`Use one of: ${e.join(", ")}.`,hl=(e,t)=>{if(e.value.kind==="choice"&&!e.value.choices.includes(t))throw Z(`unknown ${e.long} "${t}"`,Rs(e.value.choices));return t},dl=(e)=>{let{flag:t,hints:r,name:n,next:o}=e;if(o===void 0||o.startsWith("-"))throw Z(`${n} needs${gr(t.value)}`,`Usage: ${r.usage}`);return hl(t,o)},gl=(e)=>{let{hints:t,index:r,next:n,word:o}=e;if(o.startsWith("--")){let u=o.indexOf("="),p=u===-1?o:o.slice(0,u),d=r.get(p);if(!d)return;if(d.value.kind==="none"){if(u!==-1)throw Z(`${p} doesn't take a value`,`Usage: ${t.usage}`);return{options:[{flag:d,value:!0}],used:1}}if(u!==-1)return{options:[{flag:d,value:hl(d,o.slice(u+1))}],used:1};return{options:[{flag:d,value:dl({flag:d,hints:t,name:p,next:n})}],used:2}}let s=[...o].slice(1),a=s.map((u)=>r.get(`-${u}`)).filter((u)=>u!==void 0);if(a.length!==s.length)return;let c=[],l=1;for(let[u,p]of a.entries())if(p.value.kind==="none")c.push({flag:p,value:!0});else if(u===a.length-1)c.push({flag:p,value:dl({flag:p,hints:t,name:`-${s[u]}`,next:n})}),l=2;else throw Z(`-${s[u]} needs${gr(p.value)}`,`Usage: ${t.usage}`);return{options:c,used:l}},As=(e,t)=>{let r=e.flatMap((n)=>{let o=t.get(n.long);return o===void 0?[]:[[n.long,o]]});return Object.fromEntries(r)},jb={command:"nipa",usage:"nipa [options] <command>"},Ob=fl($e),ml=(e)=>{let{at:t,words:r}=e,n=r[t];if(n===void 0||n==="--"||n==="-"||!n.startsWith("-"))return;let o=gl({hints:jb,index:Ob,next:r[t+1],word:n});if(!o&&e.unknown==="reject")throw Z(`unknown option "${n}"`,"Run `nipa --help` to see the options.");return o},js=(e)=>{let{unknown:t,words:r}=e,n=new Map,o=0;for(let s=ml({at:o,unknown:t,words:r});s!==void 0;s=ml({at:o,unknown:t,words:r})){for(let{flag:i,value:a}of s.options)n.set(i.long,a);o+=s.used}return{globals:As($e,n),rest:r.slice(o)}},Lb=/^-[a-zA-Z]+$/u,yl=(e)=>{let t=e.indexOf("--"),r=t===-1?e:e.slice(0,t),n=new Set(Se(ts));return r.some((o)=>n.has(o)||Lb.test(o)&&o.includes("h"))},Db=(e)=>{let{flags:t,hints:r,words:n}=e,o=fl([...t,...$e]),s=new Set(t.map((u)=>u.long)),i=new Map,a=new Map,c=[],l=0;while(l<n.length){let u=n[l]??"";if(u==="--"){c.push(...n.slice(l+1));break}if(u.startsWith("-")&&u!=="-"){let p=gl({hints:r,index:o,next:n[l+1],word:u});if(!p)throw Z(`unknown option "${u}"`,`Run \`${r.command} --help\` to see the options.`);for(let{flag:d,value:m}of p.options)(s.has(d.long)?i:a).set(d.long,m);l+=p.used}else c.push(u),l+=1}return{globals:a,own:i,positionals:c}},Ts=(e,t)=>{if(e.value.kind==="choice"&&!e.value.choices.includes(t))throw Z(`unknown ${e.name} "${t}"`,Rs(e.value.choices));return t},Nb=(e)=>{let t=[...e.positionals],r=e.args.map((o)=>{switch(o.arity){case"one":{let s=t.shift();if(s===void 0)throw Z(`missing <${o.name}>`,o.value.kind==="choice"?Rs(o.value.choices):`Usage: ${e.hints.usage}`);return[o.name,Ts(o,s)]}case"optional":{let s=t.shift();return[o.name,s===void 0?void 0:Ts(o,s)]}case"rest":return[o.name,t.splice(0).map((s)=>Ts(o,s))];default:return o.arity}}),[n]=t;if(n!==void 0)throw Z(`unexpected argument "${n}"`,`Usage: ${e.hints.usage}`);return Object.fromEntries(r)},bl=(e)=>{let{path:t,spec:r,words:n}=e,o={command:yn(t),usage:xr(t)},s=Db({flags:r.flags,hints:o,words:n});return{globals:As($e,s.globals),input:{args:Nb({args:r.args,hints:o,positionals:s.positionals}),flags:As(r.flags,s.own)}}};var z=(e)=>({...e,kind:"leaf"}),ee=(e)=>({...e,kind:"group"}),Ht=(e)=>({...e,kind:"passthrough"}),k=(e,t)=>({kind:"leaf",prepare:({path:r,words:n})=>{let o=bl({path:r,spec:e,words:n});return{globals:o.globals,run:(s)=>t({...o.input,client:s})}},spec:e}),te=(e,t)=>{let r=Object.values(t),n=new Map(r.flatMap((o)=>xe(o.spec).map((s)=>[s,o])));return{fallback:t[e.default],kind:"group",spec:e,subcommands:n}},Zb=(e,t)=>{let{target:r}=e;switch(r.kind){case"program":return{args:t,command:r.program};case"openstack":return{args:t,command:"openstack"};case"command":{let[n,...o]=t;if(n===void 0)throw Z("missing <command>",`Usage: ${xr([e])}`);return{args:o,command:n}}default:return r}},qt=(e,t)=>({kind:"passthrough",run:({client:r,words:n})=>t({...Zb(e,n),client:r}),spec:e}),xl=(e)=>e.spec,In=(e)=>({examples:e.examples,hidden:e.hidden.map(xl),sections:e.sections.map((t)=>({commands:t.commands.map(xl),title:t.title})),summary:e.summary});function Tr(e){let t=Object.values(e).filter((n)=>typeof n==="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function Ls(e,t="|"){return e.map((r)=>Zs(r)).join(t)}function Ar(e,t){if(typeof t==="bigint")return t.toString();return t}class wl{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;if(e!==void 0)this._value=e(),this._getter=void 0;return this._value}}function Tn(e){return new wl(e)}function _l(e){return e===null||e===void 0}function An(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function vl(e,t){let r=e/t,n=Math.round(r),o=4*Number.EPSILON*Math.max(Math.abs(r),1);if(Math.abs(r-n)<o)return 0;return r-n}function Ne(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function Rn(e){let t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function ot(e){return Rn(e._zod.def)??e._zod.def.shape}function $l(e,t,r){Object.defineProperty(e,t,{get(){let n=r();return Ne(this,t,n),n},enumerable:!0,configurable:!0})}function Sl(e,t,r){if(t in e)Ne(e,t,r);else e[t]=r}function At(e,t,r,n){let o=ot(t);for(let s of r){let i=Object.getOwnPropertyDescriptor(o,s);if(!i.enumerable)continue;if(i.get)$l(e,s,()=>{let a=t._zod.def.shape[s];return n?n(a,s):a});else Sl(e,s,n?n(i.value,s):i.value)}}function Ub(e,t){for(let r of Reflect.ownKeys(t)){let n=Object.getOwnPropertyDescriptor(t,r);if(!n.enumerable)continue;if(n.get)$l(e,r,()=>t[r]);else Sl(e,r,n.value)}}function Ce(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function kl(e){return JSON.stringify(e)}function Pl(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var Ds="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Ir(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var Cl=Tn(()=>{if(we.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function Rt(e){if(Ir(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let r=t.prototype;if(Ir(r)===!1)return!1;if(Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)return!1;return!0}function Ns(e){if(Rt(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}var El=new Set(["string","number","symbol"]);function Yt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ze(e,t,r){let n=new e._zod.constr(t??e._zod.def);if(!t||r?.parent)n._zod.parent=e;return n}function C(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function Zs(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function zl(e){return Object.keys(e).filter((t)=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}var jn=(()=>({safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]}))(),Us={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Fb(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let s={};return At(s,e,On(e,t)),Ze(e,Ce(r,{shape:s,checks:[]}))}function On(e,t){let r=ot(e),n=[];for(let o of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(r,o)?.enumerable)throw Error(`Unrecognized key: "${String(o)}"`);if(t[o])n.push(o)}return n}function Mb(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let s=new Set(On(e,t)),i={};return At(i,e,Reflect.ownKeys(ot(e)).filter((a)=>!s.has(a))),Ze(e,Ce(r,{shape:i,checks:[]}))}function Bb(e,t){if(!Rt(t))throw Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let o=ot(e);for(let s of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(o,s)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Ze(e,Ce(e._zod.def,{shape:Il(e,t)}))}function Il(e,t){let r={};return At(r,e,Reflect.ownKeys(ot(e))),Ub(r,t),r}function Gb(e,t){if(!Rt(t))throw Error("Invalid input to safeExtend: expected a plain object");return Ze(e,Ce(e._zod.def,{shape:Il(e,t)}))}function Kb(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r={};At(r,e,Reflect.ownKeys(ot(e))),At(r,t,Reflect.ownKeys(ot(t)));let n=Ce(e._zod.def,{shape:r,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Ze(e,n)}function Tl(e,t,r,n="partial"){let s=t._zod.def.checks;if(s&&s.length>0)throw Error(`.${n}() cannot be used on object schemas containing refinements`);let a=r?new Set(On(t,r)):void 0,c={};return At(c,t,Reflect.ownKeys(ot(t)),e&&((l,u)=>a&&!a.has(u)?l:new e({type:"optional",innerType:l}))),Ze(t,Ce(t._zod.def,{shape:c,checks:[]}))}function Vb(e,t,r){let n=r?new Set(On(t,r)):void 0,o={};return At(o,t,Reflect.ownKeys(ot(t)),(s,i)=>n&&!n.has(i)?s:new e({type:"nonoptional",innerType:s})),Ze(t,Ce(t._zod.def,{shape:o}))}function Be(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Al(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function yt(e,t){return t.map((r)=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function zr(e){return typeof e==="string"?e:e?.message}function Fs(e,t,r){var n;for(let o=t;o<e.length;o++)(n=e[o]).schema??(n.schema=r)}function Ge(e,t,r){var n;let o=e.inst?._zod?.traits;if(o?.has("$ZodType"))if(o.has("$ZodCheck"))(n=e).schema??(n.schema=e.inst);else e.schema=e.inst;let s=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,i=e.message?e.message:zr(e.inst?._zod.def?.error?.(e))??zr(s?.(e))??zr(t?.error?.(e))??zr(r.customError?.(e))??zr(r.localeError?.(e))??"Invalid input",a={};for(let c of Object.keys(e)){if(c==="inst"||c==="schema"||c==="continue"||c==="input"||c==="__proto__")continue;a[c]=e[c]}if(a.path??(a.path=[]),a.message=i,t?.reportInput)a.input=e.input;return a}var Wb=/[\uD800-\uDBFF]/;function Ln(e){let t=e.length;if(!Wb.test(e))return t;let r=t;for(let n=0;n<t-1;n++)if((e.charCodeAt(n)&64512)===55296&&(e.charCodeAt(n+1)&64512)===56320)r--,n++;return r}function Dn(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function Rl(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function jt(...e){let[t,r,n]=e;if(typeof t==="string")return{message:t,code:"custom",input:r,inst:n};return{...t}}function jl(e,t){for(let r in t){let n=Object.getOwnPropertyDescriptor(t,r);if(n.get)Object.defineProperty(e,r,{...n,enumerable:!1});else Jb(e,r,n.value)}}function st(e,t,r,n=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:n,value:r}),r}function Nn(e,t,r){return st(e,t,r,!1)}function Ol(e,t){for(let r in e){let n=e[r];Object.defineProperty(t,r,{configurable:!0,enumerable:!0,get(){return st(this,r,n(this))},set(o){st(this,r,o)}})}return t}function Jb(e,t,r){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?r:st(this,t,r.bind(this))},set(n){st(this,t,n)}})}function Hb(e,t){let r=Object.getPrototypeOf(e);return t in r?void 0:r}var Os,gt=!1,qb={configurable:!0,get(){gt=!0;return}};function B(e,t,r){let n=Object.getPrototypeOf(e._zod);if(t in n&&Os!==e._zod){Os=void 0;return}Os=e._zod,Object.defineProperty(n,t,{configurable:!0,get(){Object.defineProperty(this,t,qb);let o=gt;gt=!1;try{let s=r(this);if(gt)delete this[t];else Object.defineProperty(this,t,{configurable:!0,writable:!0,value:s});return gt=gt||o,s}catch(s){throw delete this[t],gt=gt||o,s}},set(o){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:o})}})}function Yb(e,t,r,n){let o=Hb(e,t);if(!o)return;Object.defineProperty(o,t,{configurable:!0,get(){let s={configurable:!0,writable:!0,enumerable:n,value:void 0};return Object.defineProperty(this,t,s),s.value=r(this),Object.defineProperty(this,t,s),s.value},set(s){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:n,value:s})}})}var Xb="~constantCatch";function Ll(e){let t=()=>e;return t[Xb]=!0,t}var Dl;var Ms={value:void 0,enumerable:!1},Nl="captureStackTrace"in Error?Error:null;function Qb(e){let t=Nl;if(t){let r=t.stackTraceLimit;if(typeof r==="number"){try{t.stackTraceLimit=0}catch{return Nl=null,new e}try{return new e}finally{t.stackTraceLimit=r}}}return new e}function g(e,t,r,n){let o={};function s(d){this.def=d,this.constr=p,this.traits=new Set}s.prototype=o;let i=r,a=i&&new WeakSet;function c(d,m){if(!d._zod){Ms.value=new s(m);try{Object.defineProperty(d,"_zod",Ms)}finally{Ms.value=void 0}}else if(d._zod.traits.has(e))return;if(d._zod.traits.add(e),t(d,m),a){let y=Object.getPrototypeOf(d),b=d._zod.constr.prototype,_=y;while(_&&_!==b)_=Object.getPrototypeOf(_);let P=_??y;if(!a.has(P))a.add(P),jl(P,i)}let h=p.prototype;for(let y in h){if(!Object.prototype.hasOwnProperty.call(h,y))continue;if(!(y in d))d[y]=h[y].bind(d)}}let l=n?.Parent??Object;class u extends l{}Object.defineProperty(u,"name",{value:e});function p(d){let m=n?.Parent?Qb(u):this;c(m,d);let h=m._zod.deferred;if(h){for(let b of h)b();m._zod.deferred=void 0}let y=globalThis.__zod_globalConfig?.postProcessor;if(y)y(m);return m}return Object.defineProperty(p,"init",{value:c}),Object.defineProperty(p,Symbol.hasInstance,{value:(d)=>{if(n?.Parent&&d instanceof n.Parent)return!0;return d?._zod?.traits?.has(e)}}),Object.defineProperty(p,"name",{value:e}),p}class Ke extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Rr extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(Dl=globalThis).__zod_globalConfig??(Dl.__zod_globalConfig={});var we=globalThis.__zod_globalConfig;function _e(e){if(e)Object.assign(we,e);return we}function ex(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,Ar,2)),e.message}function tx(e){this._zod.message=e}var rx={get:ex,set:tx,enumerable:!0,configurable:!0},Gs={value:void 0,enumerable:!1},Zl=new WeakSet([Object.prototype,Error.prototype]),Ul=(e,t)=>{e.name="$ZodError",Gs.value=t,Object.defineProperty(e,"issues",Gs),Gs.value=void 0,Object.defineProperty(e,"message",rx);let r=Object.getPrototypeOf(e);if(!Zl.has(r))Zl.add(r),Object.defineProperty(r,"toString",{configurable:!0,enumerable:!1,get(){let n=()=>this.message;return Object.defineProperty(this,"toString",{value:n,configurable:!0,writable:!0}),n},set(n){Object.defineProperty(this,"toString",{value:n,configurable:!0,writable:!0})}})},Fl=g("$ZodError",Ul),m0=g("$ZodError",Ul,void 0,{Parent:Error});function nx(e,t,r){if(!Object.prototype.hasOwnProperty.call(e,t))if(t==="__proto__")Object.defineProperty(e,t,{value:r(),writable:!0,enumerable:!0,configurable:!0});else e[t]=r();return e[t]}function Ks(e,t=(r)=>r.message){let r={},n=[];for(let o of e.issues)if(o.path.length>0)nx(r,o.path[0],()=>[]).push(t(o));else n.push(t(o));return{formErrors:n,fieldErrors:r}}function Vs(e,t=(r)=>r.message){let r={_errors:[]},n=(o,s=[])=>{for(let i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map((a)=>n({issues:a},[...s,...i.path]));else if(i.code==="invalid_key")n({issues:i.issues},[...s,...i.path]);else if(i.code==="invalid_element")n({issues:i.issues},[...s,...i.path]);else{let a=[...s,...i.path];if(a.length===0)r._errors.push(t(i));else{let c=r,l=0;while(l<a.length){let u=a[l],p=l===a.length-1;if(u==="_errors"){if(p)c._errors.push(t(i));l++;continue}if(!Object.prototype.hasOwnProperty.call(c,u))Object.defineProperty(c,u,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let d=c[u];if(p)d._errors.push(t(i));c=d,l++}}}};return n(e),r}function ox(e){let t=[],r=e.map((n)=>typeof n==="object"?n.key:n);for(let n of r)if(typeof n==="number")t.push(`[${n}]`);else if(typeof n==="symbol")t.push(`[${JSON.stringify(String(n))}]`);else if(/[^\w$]/.test(n))t.push(`[${JSON.stringify(n)}]`);else{if(t.length)t.push(".");t.push(n)}return t.join("")}function Xt(e){let t=[],r=[...e.issues].sort((n,o)=>(n.path??[]).length-(o.path??[]).length);for(let n of r)if(t.push(`✖ ${n.message}`),n.path?.length)t.push(` → at ${ox(n.path)}`);return t.join(`
33
- `)}function Zn(e,t){return{callee:t?.callee??e,Err:t?.Err}}var Un=(e)=>{let t=(r,n,o,s)=>{let i=o?{...o,async:!1}:{async:!1},a=r._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Ke;if(a.issues.length){let c=new(s?.Err??e)(a.issues.map((l)=>Ge(l,i,_e())));throw Ds(c,s?.callee??t),c}return a.value};return t};var Fn=(e)=>{let t=async(r,n,o,s)=>{let i=o?{...o,async:!0}:{async:!0},a=r._zod.run({value:n,issues:[]},i);if(a instanceof Promise)a=await a;if(a.issues.length){let c=new(s?.Err??e)(a.issues.map((l)=>Ge(l,i,_e())));throw Ds(c,s?.callee??t),c}return a.value};return t};var Mn=(e)=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Ke;return s.issues.length?Ml(e,s.issues,o):{success:!0,data:s.value}};function Ml(e,t,r){let n;return{success:!1,get error(){if(!n)n=new e(t.map((o)=>Ge(o,r,_e()))),t=void 0,r=void 0;return n},set error(o){n=o,t=void 0,r=void 0}}}var Bn=(e)=>async(t,r,n)=>{let o=n?{...n,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)s=await s;return s.issues.length?Ml(e,s.issues,o):{success:!0,data:s.value}};var sx=Symbol.for("zod.compile.invalid"),ix=Symbol.for("zod.compile.fallback"),Ws=(e,t,r)=>{let n=e._zod.bag.validator;if(n!==void 0){if(n(t)!==sx)return!0;if(n.definite===!0&&r===void 0)return!1}return ax(e,t,r)};function ax(e,t,r){let n=r?{...r,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},o=e._zod.bag.fallbackRun,s;if(o)n[ix]=!0,s=o({value:t,issues:[]},n);else s=e._zod.run({value:t,issues:[]},n);if(s instanceof Promise)throw new Ke;return s.issues.length===0}var Js=async(e,t,r)=>{let n=r?{...r,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},o=e._zod.run({value:t,issues:[]},n);if(o instanceof Promise)o=await o;return o.issues.length===0},Bl=(e)=>{let t=Un(e),r=(n,o,s,i)=>{let a=s?{...s,direction:"backward"}:{direction:"backward"};return t(n,o,a,Zn(r,i))};return r};var Gl=(e)=>{let t=Un(e),r=(n,o,s,i)=>t(n,o,s,Zn(r,i));return r};var Kl=(e)=>{let t=Fn(e),r=async(n,o,s,i)=>{let a=s?{...s,direction:"backward"}:{direction:"backward"};return await t(n,o,a,Zn(r,i))};return r};var Vl=(e)=>{let t=Fn(e),r=async(n,o,s,i)=>await t(n,o,s,Zn(r,i));return r};var Wl=(e)=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Mn(e)(t,r,o)};var Jl=(e)=>(t,r,n)=>Mn(e)(t,r,n);var Hl=(e)=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return Bn(e)(t,r,o)};var ql=(e)=>async(t,r,n)=>Bn(e)(t,r,n);var Yl=/^[cC][0-9a-z]{6,}$/,Xl=/^[0-9a-z]+$/,Ql=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,eu=/^[0-9a-vA-V]{20}$/,tu=/^[A-Za-z0-9]{27}$/,ru=/^[a-zA-Z0-9_-]{21}$/;function nu(e){return new RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}var ou=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var su=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,qs=(e)=>{if(!e)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var iu=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var cx="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";function au(){return new RegExp(cx,"u")}var cu=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,lu=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;var uu=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,pu=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,du=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,mu=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;var fu=/^https?$/,hu=/^\+[1-9]\d{6,14}$/;var gu="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))";function lx(e){return new RegExp(`^${e}$`)}var yu=lx(gu);function Hs(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?":"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function bu(e){return new RegExp(`^${Hs(e)}$`)}function xu(e){let t=["Z"];if(e.offset)t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let r=`${Hs({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,n=e.local?`${r}|${Hs({precision:e.precision})}`:r;return new RegExp(`^${gu}T(?:${n})$`)}var wu=/^[\s\S]{0,}$/;var Ys=/^-?\d+$/,jr=/^-?\d+(?:\.\d+)?$/,_u=/^(?:true|false)$/i;var vu=/^[^A-Z]*$/,$u=/^[^a-z]*$/;var ue=g("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])});var Xs=(e)=>{let t=e.value;return!_l(t)&&t.length!==void 0},Gn={number:"number",bigint:"bigint",object:"date"},Qs=g("$ZodCheckLessThan",(e,t)=>{ue.init(e,t);let r=Gn[typeof t.value];e._zod.check=(n)=>{if(t.inclusive?n.value<=t.value:n.value<t.value)return;n.issues.push({origin:Gn[typeof n.value]??r,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),ei=g("$ZodCheckGreaterThan",(e,t)=>{ue.init(e,t);let r=Gn[typeof t.value];e._zod.check=(n)=>{if(t.inclusive?n.value>=t.value:n.value>t.value)return;n.issues.push({origin:Gn[typeof n.value]??r,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Su=g("$ZodCheckMultipleOf",(e,t)=>{ue.init(e,t),e._zod.check=(r)=>{if(typeof r.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof r.value==="bigint"?t.value!==BigInt(0)&&r.value%t.value===BigInt(0):vl(r.value,t.value)===0)return;r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),ku=g("$ZodCheckNumberFormat",(e,t)=>{ue.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,s]=jn[t.format];e._zod.check=(i)=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){if(a>0)i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});else i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}if(a<o)i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort});if(a>s)i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}});var Pu=g("$ZodCheckMaxLength",(e,t)=>{var r;ue.init(e,t),(r=e._zod.def).when??(r.when=Xs),e._zod.check=(n)=>{let o=n.value,s=o.length;if((typeof o==="string"&&s>t.maximum?Ln(o):s)<=t.maximum)return;let a=Dn(o);n.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Cu=g("$ZodCheckMinLength",(e,t)=>{var r;ue.init(e,t),(r=e._zod.def).when??(r.when=Xs),e._zod.check=(n)=>{let o=n.value,s=o.length;if((typeof o==="string"&&s>=t.minimum&&s<t.minimum*2?Ln(o):s)>=t.minimum)return;let a=Dn(o);n.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Eu=g("$ZodCheckLengthEquals",(e,t)=>{var r;ue.init(e,t),(r=e._zod.def).when??(r.when=Xs),e._zod.check=(n)=>{let o=n.value,s=o.length,i=typeof o==="string"&&s>=t.length&&s<=t.length*2?Ln(o):s;if(i===t.length)return;let a=Dn(o),c=i>t.length;n.issues.push({origin:a,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Or=g("$ZodCheckStringFormat",(e,t)=>{var r,n;if(ue.init(e,t),t.pattern)(r=e._zod).check??(r.check=(o)=>{if(t.pattern.lastIndex=0,t.pattern.test(o.value))return;o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(n=e._zod).check??(n.check=()=>{})}),zu=g("$ZodCheckRegex",(e,t)=>{Or.init(e,t),e._zod.check=(r)=>{if(t.pattern.lastIndex=0,t.pattern.test(r.value))return;r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),Iu=g("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=vu),Or.init(e,t)}),Tu=g("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=$u),Or.init(e,t)}),Au=g("$ZodCheckIncludes",(e,t)=>{ue.init(e,t);let r=Yt(t.includes),n=new RegExp(typeof t.position==="number"?`^.{${t.position},}${r}`:r);t.pattern=n,e._zod.check=(o)=>{if(o.value.includes(t.includes,t.position))return;o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),Ru=g("$ZodCheckStartsWith",(e,t)=>{ue.init(e,t);let r=new RegExp(`^${Yt(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.check=(n)=>{if(n.value.startsWith(t.prefix))return;n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),ju=g("$ZodCheckEndsWith",(e,t)=>{ue.init(e,t);let r=new RegExp(`.*${Yt(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.check=(n)=>{if(n.value.endsWith(t.suffix))return;n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});var Ou=g("$ZodCheckOverwrite",(e,t)=>{ue.init(e,t),e._zod.check=(r)=>{r.value=t.tx(r.value)}});class ti{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{this.indent-=1}}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.split(`
35
+ `)},write:(t)=>{e.write(t)}}),Ae=(e,t)=>{let r=z(e),n=z(t);return{paint:(o)=>`${r}${P(o.slice(r.length))}`,text:`${r}${n}`}},qn=(e)=>{let t=[];if(e.vcpus!==null)t.push(le(e.vcpus,"vCPU"));if(e.ramMb!==null)t.push(`${Br(e.ramMb)} RAM`);return t.length===0?{text:e.flavor}:Ae(e.flavor,` (${t.join(", ")})`)},Kn=" ".repeat(5),ci=(e)=>({...e,short:e.short&&ci(e.short),text:z(e.text)}),du=(e)=>x(Ot(e)),_w=2,mu=({headings:e,rows:t})=>e.map((r,n)=>Math.max(r.length,...t.map((o)=>o[n]?.text.length??0))),Sw=(e)=>{let t=mu(e);return _w+t.reduce((r,n)=>r+n,0)+Kn.length*Math.max(0,t.length-1)},nu=(e,t)=>({headings:t.map((r)=>e.headings[r]??""),rows:e.rows.map((r)=>t.map((n)=>r[n]??{text:""}))}),fu=(e)=>({headings:e.headings,rows:e.rows.map((t)=>t.map((r)=>r.short??r))}),$w=(e,t)=>{let r=e.headings.map((o,s)=>s),n=[nu(e,r)];for(let o of t.droppable)r=r.filter((s)=>s!==o),n.push(nu(e,r));return n.push(fu(n.at(-1)??e)),n.find((o)=>Sw(o)<=t.width)},Vn=(e)=>e.paint?.(e.text)??e.text,kw=(e,t)=>{let r=e.headings.map((n,o)=>o).filter((n)=>n>0&&!t.includes(n));V("");for(let n of e.rows){let[o={text:""}]=n;V(` ${Vn(o)}`);let s=r.map((i)=>Vn(n[i]??{text:""}));V(` ${s.join(" ")}`)}V("")},G=(e)=>{if(gt)return;let{marks:t}=e,r={headings:e.headings,rows:e.rows.map((l)=>l.map(ci))},{fit:n}=e,o=r;if(n){let l=$w(r,n);if(!l){kw(fu(r),n.droppable);return}o=l}let{headings:s,rows:i}=o,a=mu(o),c=(l)=>l.map((u,p)=>{let m=p===l.length-1?u.text:u.text.padEnd(a[p]??0);return u.paint?u.paint(m):m}).join(Kn);V(""),V(` ${c(s.map((l)=>({paint:du,text:l})))}`);for(let[l,u]of i.entries())V(`${t?.[l]??" "} ${c(u)}`);V("")},Yn=(e,t)=>[e,...t].map((r)=>r.map(z).join("\t")).join(`
36
+ `),yt=(e)=>{if(gt)return;let t=e.map((o)=>({...o,lines:o.lines.map(ci)})),r=Math.max(...t.map((o)=>o.label.length)),n=" ".repeat(2+r)+Kn;V("");for(let{label:o,lines:s}of t){let[i={text:"-"},...a]=s,c=` ${du(o.padEnd(r))}${Kn}`;V(`${c}${Vn(i)}`);for(let l of a)V(`${n}${Vn(l)}`)}V("")};var yu=(e)=>new Map(e.flatMap((t)=>fe(t).map((r)=>[r,t]))),pi=(e)=>`Use one of: ${e.join(", ")}.`,bu=(e,t)=>{if(e.value.kind==="choice"&&!e.value.choices.includes(t))throw Z(`unknown ${e.long} "${t}"`,pi(e.value.choices));return t},hu=(e)=>{let{flag:t,hints:r,name:n,next:o}=e;if(o===void 0||o.startsWith("-"))throw Z(`${n} needs${Er(t.value)}`,`Usage: ${r.usage}`);return bu(t,o)},xu=(e)=>{let{hints:t,index:r,next:n,word:o}=e;if(o.startsWith("--")){let u=o.indexOf("="),p=u===-1?o:o.slice(0,u),d=r.get(p);if(!d)return;if(d.value.kind==="none"){if(u!==-1)throw Z(`${p} doesn't take a value`,`Usage: ${t.usage}`);return{options:[{flag:d,value:!0}],used:1}}if(u!==-1)return{options:[{flag:d,value:bu(d,o.slice(u+1))}],used:1};return{options:[{flag:d,value:hu({flag:d,hints:t,name:p,next:n})}],used:2}}let s=[...o].slice(1),a=s.map((u)=>r.get(`-${u}`)).filter((u)=>u!==void 0);if(a.length!==s.length)return;let c=[],l=1;for(let[u,p]of a.entries())if(p.value.kind==="none")c.push({flag:p,value:!0});else if(u===a.length-1)c.push({flag:p,value:hu({flag:p,hints:t,name:`-${s[u]}`,next:n})}),l=2;else throw Z(`-${s[u]} needs${Er(p.value)}`,`Usage: ${t.usage}`);return{options:c,used:l}},ui=(e,t)=>{let r=e.flatMap((n)=>{let o=t.get(n.long);return o===void 0?[]:[[n.long,o]]});return Object.fromEntries(r)},Pw={command:"nipa",usage:"nipa [options] <command>"},Cw=yu(ke),gu=(e)=>{let{at:t,words:r}=e,n=r[t];if(n===void 0||n==="--"||n==="-"||!n.startsWith("-"))return;let o=xu({hints:Pw,index:Cw,next:r[t+1],word:n});if(!o&&e.unknown==="reject")throw Z(`unknown option "${n}"`,"Run `nipa --help` to see the options.","unknown_option");return o},di=(e)=>{let{unknown:t,words:r}=e,n=new Map,o=0;for(let s=gu({at:o,unknown:t,words:r});s!==void 0;s=gu({at:o,unknown:t,words:r})){for(let{flag:i,value:a}of s.options)n.set(i.long,a);o+=s.used}return{globals:ui(ke,n),rest:r.slice(o)}},Ew=/^-[a-zA-Z]+$/u,wu=(e)=>{let t=e.indexOf("--");return t===-1?e:e.slice(0,t)},vu=(e)=>{let t=new Set(fe(Ss));return wu(e).some((r)=>t.has(r)||Ew.test(r)&&r.includes("h"))},mi=(e)=>{let t=new Set(fe(D));return wu(e).some((r)=>t.has(r))},jw=(e)=>{let{flags:t,hints:r,words:n}=e,o=yu([...t,...ke]),s=new Set(t.map((u)=>u.long)),i=new Map,a=new Map,c=[],l=0;while(l<n.length){let u=n[l]??"";if(u==="--"){c.push(...n.slice(l+1));break}if(u.startsWith("-")&&u!=="-"){let p=xu({hints:r,index:o,next:n[l+1],word:u});if(!p)throw Z(`unknown option "${u}"`,`Run \`${r.command} --help\` to see the options.`,"unknown_option");for(let{flag:d,value:m}of p.options)(s.has(d.long)?i:a).set(d.long,m);l+=p.used}else c.push(u),l+=1}return{globals:a,own:i,positionals:c}},li=(e,t)=>{if(e.value.kind==="choice"&&!e.value.choices.includes(t))throw Z(`unknown ${e.name} "${t}"`,pi(e.value.choices));return t},Aw=(e)=>{let t=[...e.positionals],r=e.args.map((o)=>{switch(o.arity){case"one":{let s=t.shift();if(s===void 0)throw Z(`missing <${o.name}>`,o.value.kind==="choice"?pi(o.value.choices):`Usage: ${e.hints.usage}`);return[o.name,li(o,s)]}case"optional":{let s=t.shift();return[o.name,s===void 0?void 0:li(o,s)]}case"rest":return[o.name,t.splice(0).map((s)=>li(o,s))];default:return o.arity}}),[n]=t;if(n!==void 0)throw Z(`unexpected argument "${n}"`,`Usage: ${e.hints.usage}`);return Object.fromEntries(r)},_u=(e)=>{let{path:t,spec:r,words:n}=e,o={command:Xt(t),usage:Rt(t)},s=jw({flags:r.flags,hints:o,words:n});return{globals:ui(ke,s.globals),input:{args:Aw({args:r.args,hints:o,positionals:s.positionals}),flags:ui(r.flags,s.own)}}};var R=(e)=>({...e,kind:"leaf"}),re=(e)=>({...e,kind:"group"}),or=(e)=>({...e,kind:"passthrough"}),S=(e,t)=>({kind:"leaf",prepare:({path:r,words:n})=>{let o=_u({path:r,spec:e,words:n});return{globals:o.globals,run:(s)=>t({...o.input,client:s})}},spec:e}),ne=(e,t)=>{let r=Object.values(t),n=new Map(r.flatMap((o)=>me(o.spec).map((s)=>[s,o])));return{fallback:t[e.default],kind:"group",spec:e,subcommands:n}},Rw=(e,t)=>{let{target:r}=e;switch(r.kind){case"program":return{args:t,command:r.program};case"openstack":return{args:t,command:"openstack"};case"command":{let[n,...o]=t;if(n===void 0)throw Z("missing <command>",`Usage: ${Rt([e])}`);return{args:o,command:n}}default:return r}},sr=(e,t)=>({kind:"passthrough",run:({client:r,words:n})=>t({...Rw(e,n),client:r}),spec:e}),Su=(e)=>e.spec,Xn=(e)=>({examples:e.examples,hidden:e.hidden.map(Su),sections:e.sections.map((t)=>({commands:t.commands.map(Su),title:t.title})),summary:e.summary});function Vr(e){let t=Object.values(e).filter((n)=>typeof n==="number");return Object.entries(e).filter(([n,o])=>t.indexOf(+n)===-1).map(([n,o])=>o)}function hi(e,t="|"){return e.map((r)=>bi(r)).join(t)}function Wr(e,t){if(typeof t==="bigint")return t.toString();return t}class $u{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;if(e!==void 0)this._value=e(),this._getter=void 0;return this._value}}function Qn(e){return new $u(e)}function ku(e){return e===null||e===void 0}function eo(e){let t=e.startsWith("^")?1:0,r=e.endsWith("$")?e.length-1:e.length;return e.slice(t,r)}function Pu(e,t){let r=e/t,n=Math.round(r),o=4*Number.EPSILON*Math.max(Math.abs(r),1);if(Math.abs(r-n)<o)return 0;return r-n}function Fe(e,t,r){Object.defineProperty(e,t,{value:r,writable:!0,enumerable:!0,configurable:!0})}function to(e){let t=Object.getOwnPropertyDescriptor(e,"shape");return t?.get?t.get.raw:t?.value}function st(e){return to(e._zod.def)??e._zod.def.shape}function Cu(e,t,r){Object.defineProperty(e,t,{get(){let n=r();return Fe(this,t,n),n},enumerable:!0,configurable:!0})}function Eu(e,t,r){if(t in e)Fe(e,t,r);else e[t]=r}function Nt(e,t,r,n){let o=st(t);for(let s of r){let i=Object.getOwnPropertyDescriptor(o,s);if(!i.enumerable)continue;if(i.get)Cu(e,s,()=>{let a=t._zod.def.shape[s];return n?n(a,s):a});else Eu(e,s,n?n(i.value,s):i.value)}}function Iw(e,t){for(let r of Reflect.ownKeys(t)){let n=Object.getOwnPropertyDescriptor(t,r);if(!n.enumerable)continue;if(n.get)Cu(e,r,()=>t[r]);else Eu(e,r,n.value)}}function Re(...e){let t={};for(let r of e){let n=Object.getOwnPropertyDescriptors(r);Object.assign(t,n)}return Object.defineProperties({},t)}function ju(e){return JSON.stringify(e)}function Au(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}var gi="captureStackTrace"in Error?Error.captureStackTrace:(...e)=>{};function Kr(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var Ru=Qn(()=>{if(Pe.jitless)return!1;if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(e){return!1}});function Zt(e){if(Kr(e)===!1)return!1;let t=e.constructor;if(t===void 0)return!0;if(typeof t!=="function")return!0;let r=t.prototype;if(Kr(r)===!1)return!1;if(Object.prototype.hasOwnProperty.call(r,"isPrototypeOf")===!1)return!1;return!0}function yi(e){if(Zt(e))return{...e};if(Array.isArray(e))return[...e];if(e instanceof Map)return new Map(e);if(e instanceof Set)return new Set(e);return e}var Iu=new Set(["string","number","symbol"]);function ir(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Me(e,t,r){let n=new e._zod.constr(t??e._zod.def);if(!t||r?.parent)n._zod.parent=e;return n}function A(e){let t=e;if(!t)return{};if(typeof t==="string")return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}if(delete t.message,typeof t.error==="string")return{...t,error:()=>t.error};return t}function bi(e){if(typeof e==="bigint")return e.toString()+"n";if(typeof e==="string")return`"${e}"`;return`${e}`}function Tu(e){return Object.keys(e).filter((t)=>e[t]._zod.optin!==void 0&&e[t]._zod.optout==="optional")}var ro=(()=>({safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]}))(),xi={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]};function Tw(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw Error(".pick() cannot be used on object schemas containing refinements");let s={};return Nt(s,e,no(e,t)),Me(e,Re(r,{shape:s,checks:[]}))}function no(e,t){let r=st(e),n=[];for(let o of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(r,o)?.enumerable)throw Error(`Unrecognized key: "${String(o)}"`);if(t[o])n.push(o)}return n}function zw(e,t){let r=e._zod.def,n=r.checks;if(n&&n.length>0)throw Error(".omit() cannot be used on object schemas containing refinements");let s=new Set(no(e,t)),i={};return Nt(i,e,Reflect.ownKeys(st(e)).filter((a)=>!s.has(a))),Me(e,Re(r,{shape:i,checks:[]}))}function Ow(e,t){if(!Zt(t))throw Error("Invalid input to extend: expected a plain object");let r=e._zod.def.checks;if(r&&r.length>0){let o=st(e);for(let s of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(o,s)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Me(e,Re(e._zod.def,{shape:zu(e,t)}))}function zu(e,t){let r={};return Nt(r,e,Reflect.ownKeys(st(e))),Iw(r,t),r}function Lw(e,t){if(!Zt(t))throw Error("Invalid input to safeExtend: expected a plain object");return Me(e,Re(e._zod.def,{shape:zu(e,t)}))}function Dw(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");let r={};Nt(r,e,Reflect.ownKeys(st(e))),Nt(r,t,Reflect.ownKeys(st(t)));let n=Re(e._zod.def,{shape:r,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return Me(e,n)}function Ou(e,t,r,n="partial"){let s=t._zod.def.checks;if(s&&s.length>0)throw Error(`.${n}() cannot be used on object schemas containing refinements`);let a=r?new Set(no(t,r)):void 0,c={};return Nt(c,t,Reflect.ownKeys(st(t)),e&&((l,u)=>a&&!a.has(u)?l:new e({type:"optional",innerType:l}))),Me(t,Re(t._zod.def,{shape:c,checks:[]}))}function Nw(e,t,r){let n=r?new Set(no(t,r)):void 0,o={};return Nt(o,t,Reflect.ownKeys(st(t)),(s,i)=>n&&!n.has(i)?s:new e({type:"nonoptional",innerType:s})),Me(t,Re(t._zod.def,{shape:o}))}function We(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue!==!0)return!0;return!1}function Lu(e,t=0){if(e.aborted===!0)return!0;for(let r=t;r<e.issues.length;r++)if(e.issues[r]?.continue===!1)return!0;return!1}function xt(e,t){return t.map((r)=>{var n;return(n=r).path??(n.path=[]),r.path.unshift(e),r})}function Gr(e){return typeof e==="string"?e:e?.message}function wi(e,t,r){var n;for(let o=t;o<e.length;o++)(n=e[o]).schema??(n.schema=r)}function Je(e,t,r){var n;let o=e.inst?._zod?.traits;if(o?.has("$ZodType"))if(o.has("$ZodCheck"))(n=e).schema??(n.schema=e.inst);else e.schema=e.inst;let s=e.schema!==e.inst?e.schema?._zod.def?.error:void 0,i=e.message?e.message:Gr(e.inst?._zod.def?.error?.(e))??Gr(s?.(e))??Gr(t?.error?.(e))??Gr(r.customError?.(e))??Gr(r.localeError?.(e))??"Invalid input",a={};for(let c of Object.keys(e)){if(c==="inst"||c==="schema"||c==="continue"||c==="input"||c==="__proto__")continue;a[c]=e[c]}if(a.path??(a.path=[]),a.message=i,t?.reportInput)a.input=e.input;return a}var Zw=/[\uD800-\uDBFF]/;function oo(e){let t=e.length;if(!Zw.test(e))return t;let r=t;for(let n=0;n<t-1;n++)if((e.charCodeAt(n)&64512)===55296&&(e.charCodeAt(n+1)&64512)===56320)r--,n++;return r}function so(e){if(Array.isArray(e))return"array";if(typeof e==="string")return"string";return"unknown"}function Du(e){let t=typeof e;switch(t){case"number":return Number.isNaN(e)?"nan":"number";case"object":{if(e===null)return"null";if(Array.isArray(e))return"array";let r=e;if(r&&Object.getPrototypeOf(r)!==Object.prototype&&"constructor"in r&&r.constructor)return r.constructor.name}}return t}function Ut(...e){let[t,r,n]=e;if(typeof t==="string")return{message:t,code:"custom",input:r,inst:n};return{...t}}function Nu(e,t){for(let r in t){let n=Object.getOwnPropertyDescriptor(t,r);if(n.get)Object.defineProperty(e,r,{...n,enumerable:!1});else Uw(e,r,n.value)}}function it(e,t,r,n=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:n,value:r}),r}function io(e,t,r){return it(e,t,r,!1)}function Zu(e,t){for(let r in e){let n=e[r];Object.defineProperty(t,r,{configurable:!0,enumerable:!0,get(){return it(this,r,n(this))},set(o){it(this,r,o)}})}return t}function Uw(e,t,r){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?r:it(this,t,r.bind(this))},set(n){it(this,t,n)}})}function Fw(e,t){let r=Object.getPrototypeOf(e);return t in r?void 0:r}var fi,bt=!1,Mw={configurable:!0,get(){bt=!0;return}};function K(e,t,r){let n=Object.getPrototypeOf(e._zod);if(t in n&&fi!==e._zod){fi=void 0;return}fi=e._zod,Object.defineProperty(n,t,{configurable:!0,get(){Object.defineProperty(this,t,Mw);let o=bt;bt=!1;try{let s=r(this);if(bt)delete this[t];else Object.defineProperty(this,t,{configurable:!0,writable:!0,value:s});return bt=bt||o,s}catch(s){throw delete this[t],bt=bt||o,s}},set(o){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:o})}})}function Bw(e,t,r,n){let o=Fw(e,t);if(!o)return;Object.defineProperty(o,t,{configurable:!0,get(){let s={configurable:!0,writable:!0,enumerable:n,value:void 0};return Object.defineProperty(this,t,s),s.value=r(this),Object.defineProperty(this,t,s),s.value},set(s){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:n,value:s})}})}var Gw="~constantCatch";function Uu(e){let t=()=>e;return t[Gw]=!0,t}var Fu;var vi={value:void 0,enumerable:!1},Mu="captureStackTrace"in Error?Error:null;function Kw(e){let t=Mu;if(t){let r=t.stackTraceLimit;if(typeof r==="number"){try{t.stackTraceLimit=0}catch{return Mu=null,new e}try{return new e}finally{t.stackTraceLimit=r}}}return new e}function g(e,t,r,n){let o={};function s(d){this.def=d,this.constr=p,this.traits=new Set}s.prototype=o;let i=r,a=i&&new WeakSet;function c(d,m){if(!d._zod){vi.value=new s(m);try{Object.defineProperty(d,"_zod",vi)}finally{vi.value=void 0}}else if(d._zod.traits.has(e))return;if(d._zod.traits.add(e),t(d,m),a){let y=Object.getPrototypeOf(d),b=d._zod.constr.prototype,v=y;while(v&&v!==b)v=Object.getPrototypeOf(v);let E=v??y;if(!a.has(E))a.add(E),Nu(E,i)}let h=p.prototype;for(let y in h){if(!Object.prototype.hasOwnProperty.call(h,y))continue;if(!(y in d))d[y]=h[y].bind(d)}}let l=n?.Parent??Object;class u extends l{}Object.defineProperty(u,"name",{value:e});function p(d){let m=n?.Parent?Kw(u):this;c(m,d);let h=m._zod.deferred;if(h){for(let b of h)b();m._zod.deferred=void 0}let y=globalThis.__zod_globalConfig?.postProcessor;if(y)y(m);return m}return Object.defineProperty(p,"init",{value:c}),Object.defineProperty(p,Symbol.hasInstance,{value:(d)=>{if(n?.Parent&&d instanceof n.Parent)return!0;return d?._zod?.traits?.has(e)}}),Object.defineProperty(p,"name",{value:e}),p}class He extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class Jr extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`);this.name="ZodEncodeError"}}(Fu=globalThis).__zod_globalConfig??(Fu.__zod_globalConfig={});var Pe=globalThis.__zod_globalConfig;function Ce(e){if(e)Object.assign(Pe,e);return Pe}function Vw(){let e=this._zod;return e.message??(e.message=JSON.stringify(e.def,Wr,2)),e.message}function Ww(e){this._zod.message=e}var Jw={get:Vw,set:Ww,enumerable:!0,configurable:!0},Si={value:void 0,enumerable:!1},Bu=new WeakSet([Object.prototype,Error.prototype]),Gu=(e,t)=>{e.name="$ZodError",Si.value=t,Object.defineProperty(e,"issues",Si),Si.value=void 0,Object.defineProperty(e,"message",Jw);let r=Object.getPrototypeOf(e);if(!Bu.has(r))Bu.add(r),Object.defineProperty(r,"toString",{configurable:!0,enumerable:!1,get(){let n=()=>this.message;return Object.defineProperty(this,"toString",{value:n,configurable:!0,writable:!0}),n},set(n){Object.defineProperty(this,"toString",{value:n,configurable:!0,writable:!0})}})},Ku=g("$ZodError",Gu),Gj=g("$ZodError",Gu,void 0,{Parent:Error});function Hw(e,t,r){if(!Object.prototype.hasOwnProperty.call(e,t))if(t==="__proto__")Object.defineProperty(e,t,{value:r(),writable:!0,enumerable:!0,configurable:!0});else e[t]=r();return e[t]}function $i(e,t=(r)=>r.message){let r={},n=[];for(let o of e.issues)if(o.path.length>0)Hw(r,o.path[0],()=>[]).push(t(o));else n.push(t(o));return{formErrors:n,fieldErrors:r}}function ki(e,t=(r)=>r.message){let r={_errors:[]},n=(o,s=[])=>{for(let i of o.issues)if(i.code==="invalid_union"&&i.errors.length)i.errors.map((a)=>n({issues:a},[...s,...i.path]));else if(i.code==="invalid_key")n({issues:i.issues},[...s,...i.path]);else if(i.code==="invalid_element")n({issues:i.issues},[...s,...i.path]);else{let a=[...s,...i.path];if(a.length===0)r._errors.push(t(i));else{let c=r,l=0;while(l<a.length){let u=a[l],p=l===a.length-1;if(u==="_errors"){if(p)c._errors.push(t(i));l++;continue}if(!Object.prototype.hasOwnProperty.call(c,u))Object.defineProperty(c,u,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let d=c[u];if(p)d._errors.push(t(i));c=d,l++}}}};return n(e),r}function qw(e){let t=[],r=e.map((n)=>typeof n==="object"?n.key:n);for(let n of r)if(typeof n==="number")t.push(`[${n}]`);else if(typeof n==="symbol")t.push(`[${JSON.stringify(String(n))}]`);else if(/[^\w$]/.test(n))t.push(`[${JSON.stringify(n)}]`);else{if(t.length)t.push(".");t.push(n)}return t.join("")}function Hr(e){let t=[],r=[...e.issues].sort((n,o)=>(n.path??[]).length-(o.path??[]).length);for(let n of r)if(t.push(`✖ ${n.message}`),n.path?.length)t.push(` → at ${qw(n.path)}`);return t.join(`
37
+ `)}function ao(e,t){return{callee:t?.callee??e,Err:t?.Err}}var co=(e)=>{let t=(r,n,o,s)=>{let i=o?{...o,async:!1}:{async:!1},a=r._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new He;if(a.issues.length){let c=new(s?.Err??e)(a.issues.map((l)=>Je(l,i,Ce())));throw gi(c,s?.callee??t),c}return a.value};return t};var lo=(e)=>{let t=async(r,n,o,s)=>{let i=o?{...o,async:!0}:{async:!0},a=r._zod.run({value:n,issues:[]},i);if(a instanceof Promise)a=await a;if(a.issues.length){let c=new(s?.Err??e)(a.issues.map((l)=>Je(l,i,Ce())));throw gi(c,s?.callee??t),c}return a.value};return t};var uo=(e)=>(t,r,n)=>{let o=n?{...n,async:!1}:{async:!1},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new He;return s.issues.length?Vu(e,s.issues,o):{success:!0,data:s.value}};function Vu(e,t,r){let n;return{success:!1,get error(){if(!n)n=new e(t.map((o)=>Je(o,r,Ce()))),t=void 0,r=void 0;return n},set error(o){n=o,t=void 0,r=void 0}}}var po=(e)=>async(t,r,n)=>{let o=n?{...n,async:!0}:{async:!0},s=t._zod.run({value:r,issues:[]},o);if(s instanceof Promise)s=await s;return s.issues.length?Vu(e,s.issues,o):{success:!0,data:s.value}};var Yw=Symbol.for("zod.compile.invalid"),Xw=Symbol.for("zod.compile.fallback"),Pi=(e,t,r)=>{let n=e._zod.bag.validator;if(n!==void 0){if(n(t)!==Yw)return!0;if(n.definite===!0&&r===void 0)return!1}return Qw(e,t,r)};function Qw(e,t,r){let n=r?{...r,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},o=e._zod.bag.fallbackRun,s;if(o)n[Xw]=!0,s=o({value:t,issues:[]},n);else s=e._zod.run({value:t,issues:[]},n);if(s instanceof Promise)throw new He;return s.issues.length===0}var Ci=async(e,t,r)=>{let n=r?{...r,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},o=e._zod.run({value:t,issues:[]},n);if(o instanceof Promise)o=await o;return o.issues.length===0},Wu=(e)=>{let t=co(e),r=(n,o,s,i)=>{let a=s?{...s,direction:"backward"}:{direction:"backward"};return t(n,o,a,ao(r,i))};return r};var Ju=(e)=>{let t=co(e),r=(n,o,s,i)=>t(n,o,s,ao(r,i));return r};var Hu=(e)=>{let t=lo(e),r=async(n,o,s,i)=>{let a=s?{...s,direction:"backward"}:{direction:"backward"};return await t(n,o,a,ao(r,i))};return r};var qu=(e)=>{let t=lo(e),r=async(n,o,s,i)=>await t(n,o,s,ao(r,i));return r};var Yu=(e)=>(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return uo(e)(t,r,o)};var Xu=(e)=>(t,r,n)=>uo(e)(t,r,n);var Qu=(e)=>async(t,r,n)=>{let o=n?{...n,direction:"backward"}:{direction:"backward"};return po(e)(t,r,o)};var ep=(e)=>async(t,r,n)=>po(e)(t,r,n);var tp=/^[cC][0-9a-z]{6,}$/,rp=/^[0-9a-z]+$/,np=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,op=/^[0-9a-vA-V]{20}$/,sp=/^[A-Za-z0-9]{27}$/,ip=/^[a-zA-Z0-9_-]{21}$/;function ap(e){return new RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}var cp=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/;var lp=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,ji=(e)=>{if(!e)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)};var up=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;var ev="^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$";function pp(){return new RegExp(ev,"u")}var dp=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,mp=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/;var fp=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,hp=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,gp=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,yp=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/;var bp=/^https?$/,xp=/^\+[1-9]\d{6,14}$/;var wp="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))";function tv(e){return new RegExp(`^${e}$`)}var vp=tv(wp);function Ei(e){return typeof e.precision==="number"?e.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":e.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?":"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function _p(e){return new RegExp(`^${Ei(e)}$`)}function Sp(e){let t=["Z"];if(e.offset)t.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let r=`${Ei({precision:e.precision,seconds:!0})}(?:${t.join("|")})`,n=e.local?`${r}|${Ei({precision:e.precision})}`:r;return new RegExp(`^${wp}T(?:${n})$`)}var $p=/^[\s\S]{0,}$/;var Ai=/^-?\d+$/,qr=/^-?\d+(?:\.\d+)?$/,kp=/^(?:true|false)$/i;var Pp=/^[^A-Z]*$/,Cp=/^[^a-z]*$/;var he=g("$ZodCheck",(e,t)=>{var r;e._zod??(e._zod={}),e._zod.def=t,(r=e._zod).onattach??(r.onattach=[])});var Ri=(e)=>{let t=e.value;return!ku(t)&&t.length!==void 0},mo={number:"number",bigint:"bigint",object:"date"},Ii=g("$ZodCheckLessThan",(e,t)=>{he.init(e,t);let r=mo[typeof t.value];e._zod.check=(n)=>{if(t.inclusive?n.value<=t.value:n.value<t.value)return;n.issues.push({origin:mo[typeof n.value]??r,code:"too_big",maximum:typeof t.value==="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ti=g("$ZodCheckGreaterThan",(e,t)=>{he.init(e,t);let r=mo[typeof t.value];e._zod.check=(n)=>{if(t.inclusive?n.value>=t.value:n.value>t.value)return;n.issues.push({origin:mo[typeof n.value]??r,code:"too_small",minimum:typeof t.value==="object"?t.value.getTime():t.value,input:n.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Ep=g("$ZodCheckMultipleOf",(e,t)=>{he.init(e,t),e._zod.check=(r)=>{if(typeof r.value!==typeof t.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof r.value==="bigint"?t.value!==BigInt(0)&&r.value%t.value===BigInt(0):Pu(r.value,t.value)===0)return;r.issues.push({origin:typeof r.value,code:"not_multiple_of",divisor:t.value,input:r.value,inst:e,continue:!t.abort})}}),jp=g("$ZodCheckNumberFormat",(e,t)=>{he.init(e,t),t.format=t.format||"float64";let r=t.format?.includes("int"),n=r?"int":"number",[o,s]=ro[t.format];e._zod.check=(i)=>{let a=i.value;if(r){if(!Number.isInteger(a)){i.issues.push({expected:n,format:t.format,code:"invalid_type",continue:!1,input:a,inst:e});return}if(!Number.isSafeInteger(a)){if(a>0)i.issues.push({input:a,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});else i.issues.push({input:a,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:e,origin:n,inclusive:!0,continue:!t.abort});return}}if(a<o)i.issues.push({origin:"number",input:a,code:"too_small",minimum:o,inclusive:!0,inst:e,continue:!t.abort});if(a>s)i.issues.push({origin:"number",input:a,code:"too_big",maximum:s,inclusive:!0,inst:e,continue:!t.abort})}});var Ap=g("$ZodCheckMaxLength",(e,t)=>{var r;he.init(e,t),(r=e._zod.def).when??(r.when=Ri),e._zod.check=(n)=>{let o=n.value,s=o.length;if((typeof o==="string"&&s>t.maximum?oo(o):s)<=t.maximum)return;let a=so(o);n.issues.push({origin:a,code:"too_big",maximum:t.maximum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Rp=g("$ZodCheckMinLength",(e,t)=>{var r;he.init(e,t),(r=e._zod.def).when??(r.when=Ri),e._zod.check=(n)=>{let o=n.value,s=o.length;if((typeof o==="string"&&s>=t.minimum&&s<t.minimum*2?oo(o):s)>=t.minimum)return;let a=so(o);n.issues.push({origin:a,code:"too_small",minimum:t.minimum,inclusive:!0,input:o,inst:e,continue:!t.abort})}}),Ip=g("$ZodCheckLengthEquals",(e,t)=>{var r;he.init(e,t),(r=e._zod.def).when??(r.when=Ri),e._zod.check=(n)=>{let o=n.value,s=o.length,i=typeof o==="string"&&s>=t.length&&s<=t.length*2?oo(o):s;if(i===t.length)return;let a=so(o),c=i>t.length;n.issues.push({origin:a,...c?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),Yr=g("$ZodCheckStringFormat",(e,t)=>{var r,n;if(he.init(e,t),t.pattern)(r=e._zod).check??(r.check=(o)=>{if(t.pattern.lastIndex=0,t.pattern.test(o.value))return;o.issues.push({origin:"string",code:"invalid_format",format:t.format,input:o.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})});else(n=e._zod).check??(n.check=()=>{})}),Tp=g("$ZodCheckRegex",(e,t)=>{Yr.init(e,t),e._zod.check=(r)=>{if(t.pattern.lastIndex=0,t.pattern.test(r.value))return;r.issues.push({origin:"string",code:"invalid_format",format:"regex",input:r.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),zp=g("$ZodCheckLowerCase",(e,t)=>{t.pattern??(t.pattern=Pp),Yr.init(e,t)}),Op=g("$ZodCheckUpperCase",(e,t)=>{t.pattern??(t.pattern=Cp),Yr.init(e,t)}),Lp=g("$ZodCheckIncludes",(e,t)=>{he.init(e,t);let r=ir(t.includes),n=new RegExp(typeof t.position==="number"?`^.{${t.position},}${r}`:r);t.pattern=n,e._zod.check=(o)=>{if(o.value.includes(t.includes,t.position))return;o.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:o.value,inst:e,continue:!t.abort})}}),Dp=g("$ZodCheckStartsWith",(e,t)=>{he.init(e,t);let r=new RegExp(`^${ir(t.prefix)}.*`);t.pattern??(t.pattern=r),e._zod.check=(n)=>{if(n.value.startsWith(t.prefix))return;n.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),Np=g("$ZodCheckEndsWith",(e,t)=>{he.init(e,t);let r=new RegExp(`.*${ir(t.suffix)}$`);t.pattern??(t.pattern=r),e._zod.check=(n)=>{if(n.value.endsWith(t.suffix))return;n.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}});var Zp=g("$ZodCheckOverwrite",(e,t)=>{he.init(e,t),e._zod.check=(r)=>{r.value=t.tx(r.value)}});class zi{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{this.indent-=1}}write(e){if(typeof e==="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}let r=e.split(`
34
38
  `).filter((s)=>s),n=Math.min(...r.map((s)=>s.length-s.trimStart().length)),o=r.map((s)=>s.slice(n)).map((s)=>" ".repeat(this.indent*2)+s);for(let s of o)this.content.push(s)}compile(){let e=Function,t=this?.content??[""];return new e(...Object.keys(this.closed),`return function (${this.args.join(", ")}) {
35
39
  ${t.join(`
36
40
  `)}
37
- };`)(...Object.values(this.closed))}}var Du={major:4,minor:6,patch:5};var q=g("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Du;let n=e._zod.def.checks,o=e._zod.traits.has("$ZodCheck")?[e,...n??[]]:n?.length?[...n]:[];for(let s of o)for(let i of s._zod.onattach)i(e);if(o.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let s=(a,c,l)=>{if(a.memo)return a;let u=Be(a),p;for(let d of c){if(d._zod.def.when){if(Al(a))continue;if(!d._zod.def.when(a))continue}else if(u)continue;let m=a.issues.length,h=d._zod.check(a);if(h instanceof Promise&&l?.async===!1)throw new Ke;if(p||h instanceof Promise)p=(p??Promise.resolve()).then(async()=>{if(await h,a.issues.length===m)return;if(Fs(a.issues,m,e),!u)u=Be(a,m)});else{if(a.issues.length===m)continue;if(Fs(a.issues,m,e),!u)u=Be(a,m)}}if(p)return p.then(()=>a);return a},i=(a,c,l)=>{if(Be(a))return a.aborted=!0,a;let u=s(c,o,l);if(u instanceof Promise){if(l.async===!1)throw new Ke;return u.then((p)=>e._zod.parse(p,l))}return e._zod.parse(u,l)};e._zod.run=(a,c)=>{if(c.skipChecks)return e._zod.parse(a,c);if(c.direction==="backward"){let u=e._zod.parse({value:a.value,issues:[]},{...c,skipChecks:!0});if(u instanceof Promise)return u.then((p)=>i(p,a,c));return i(u,a,c)}let l=e._zod.parse(a,c);if(l instanceof Promise){if(c.async===!1)throw new Ke;return l.then((u)=>s(u,o,c))}return s(l,o,c)}}},{get "~standard"(){return Nn(this,"~standard",ni(this))},set "~standard"(e){st(this,"~standard",e)}}),Ju=(e,t)=>e.issues.length?{issues:e.issues.map((r)=>Ge(r,t,_e()))}:{value:e.value};async function ux(e,t){let r={async:!0};return Ju(await e._zod.run({value:t,issues:[]},r),r)}function ni(e){return{validate:(t)=>{let r={async:!1};try{let n=e._zod.run({value:t,issues:[]},r);if(!(n instanceof Promise))return Ju(n,r)}catch(n){}return ux(e,t)},vendor:"zod",version:1}}var Jn=g("$ZodString",(e,t)=>{q.init(e,t),e._zod.pattern=t.pattern??wu,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch(o){}if(typeof r.value==="string")return r;return r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),W=g("$ZodStringFormat",(e,t)=>{Or.init(e,t),Jn.init(e,t)}),Hu=g("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=su),W.init(e,t)}),qu=g("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=qs(n))}else t.pattern??(t.pattern=qs());W.init(e,t)}),Yu=g("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=iu),W.init(e,t)}),Xu=1,Vn=2;function Qu(e){try{if(typeof URL<"u"&&typeof URL.canParse==="function")return URL.canParse(e);return new URL(e),!0}catch{return!1}}function px(e,t){if(!("normalize"in t)&&!("hostname"in t)&&!("protocol"in t))return Qu(e)||Vn;return dx(e,t)}function dx(e,t){if(!t.normalize&&t.protocol?.source===fu.source&&!/^https?:\/\//i.test(e))return Xu;try{if(typeof URL<"u"){let r=URL;if(typeof r.parse==="function")return r.parse(e)??Vn}return new URL(e)}catch{return Vn}}var mx=/[\t\n\r]/g;function Nu(e){return e.replace(mx,"")}function fx(e,t){return t.lastIndex=0,t.test(e.hostname)}function hx(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)}var ep=g("$ZodURL",(e,t)=>{W.init(e,t),e._zod.check=(r)=>{try{let n=r.value.trim(),o=px(n,t);if(o===Xu){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});return}if(o===Vn){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort});return}if(o===!0){r.value=Nu(n);return}if(t.hostname&&!fx(o,t.hostname))r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort});if(t.protocol&&!hx(o,t.protocol))r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort});r.value=t.normalize?o.href:Nu(n);return}catch(n){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),tp=g("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=au()),W.init(e,t)}),rp=g("$ZodNanoID",(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??(t.pattern=t.length===void 0?ru:nu(t.length)),W.init(e,t)}),np=g("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=Yl),W.init(e,t)}),op=g("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=Xl),W.init(e,t)}),sp=g("$ZodULID",(e,t)=>{t.pattern??(t.pattern=Ql),W.init(e,t)}),ip=g("$ZodXID",(e,t)=>{t.pattern??(t.pattern=eu),W.init(e,t)}),ap=g("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=tu),W.init(e,t)}),cp=g("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=xu(t)),W.init(e,t)}),lp=g("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=yu),W.init(e,t)}),up=g("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=bu(t)),W.init(e,t)}),pp=g("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=ou),W.init(e,t)}),dp=g("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=cu),W.init(e,t)}),gx=/^[0-9a-fA-F:.]+$/;function mp(e){if(!gx.test(e))return!1;return Qu(`http://[${e}]`)}var fp=g("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=lu),W.init(e,t),e._zod.check=(r)=>{if(!mp(r.value))r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}});var hp=g("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=uu),W.init(e,t)});function yx(e){let t=e.split("/");if(t.length!==2)return!1;let[r,n]=t;if(!n)return!1;let o=Number(n);if(`${o}`!==n)return!1;if(o<0||o>128)return!1;return mp(r)}var gp=g("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=pu),W.init(e,t),e._zod.check=(r)=>{if(!yx(r.value))r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}});function yp(e){if(e==="")return!0;if(/\s/.test(e))return!1;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var oi=/^[0-9a-zA-Z+/]*={0,2}$/,bp=g("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=oi),W.init(e,t),e._zod.check=(r)=>{if(yp(r.value))return;r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}}),Hn=/^[A-Za-z0-9_-]*$/;function bx(e){if(!Hn.test(e))return!1;let t=e.replace(/[-_]/g,(n)=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return yp(r)}var xp=g("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=Hn),W.init(e,t),e._zod.check=(r)=>{if(bx(r.value))return;r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),wp=g("$ZodE164",(e,t)=>{t.pattern??(t.pattern=hu),W.init(e,t)});function xx(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));if("typ"in o&&o?.typ!=="JWT")return!1;if(!o.alg)return!1;if(t&&(!("alg"in o)||o.alg!==t))return!1;return!0}catch{return!1}}var _p=g("$ZodJWT",(e,t)=>{W.init(e,t),e._zod.check=(r)=>{if(xx(r.value,t.alg))return;r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var si=g("$ZodNumber",(e,t)=>{q.init(e,t),e._zod.pattern=jr,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch(i){}let o=r.value;if(typeof o==="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o==="number"?Number.isNaN(o)?"NaN":!Number.isFinite(o)?String(o):void 0:void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),r}}),vp=g("$ZodNumberFormat",(e,t)=>{ku.init(e,t),si.init(e,t)}),$p=g("$ZodBoolean",(e,t)=>{q.init(e,t),e._zod.pattern=_u,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Boolean(r.value)}catch(s){}let o=r.value;if(typeof o==="boolean")return r;return r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}});var Sp=g("$ZodUnknown",(e,t)=>{q.init(e,t),e._zod.parse=(r)=>r}),kp=g("$ZodNever",(e,t)=>{q.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function Zu(e,t,r){if(e.issues.length)t.issues.push(...yt(r,e.issues));t.value[r]=e.value}var Pp=g("$ZodArray",(e,t)=>{q.init(e,t);let r=we.memoizer;r?.attach(e),e._zod.parse=(n,o)=>{let s=n.value;if(!Array.isArray(s))return n.issues.push({expected:"array",code:"invalid_type",input:s,inst:e}),n;n.value=r?r.alloc(e,n,Array(s.length),o):Array(s.length);let i=[],a=o?.abortEarly;for(let c=0;c<s.length;c++){let l=s[c],u=t.element._zod.run({value:l,issues:[]},o);if(u instanceof Promise)i.push(u.then((p)=>Zu(p,n,c)));else if(Zu(u,n,c),a&&u.issues.length!==0&&Be(u))break}if(i.length)return Promise.all(i).then(()=>n);return n}});function Wn(e,t,r,n,o,s){let i=r in n,a=s==="optional";if(!i&&a&&o==="optional")return;if(e.issues.length){if(o!==void 0&&a&&!i)return;t.issues.push(...yt(r,e.issues))}if(!i&&o===void 0){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}if(e.value===void 0){if(i||o==="defaulted"&&!a)t.value[r]=void 0}else t.value[r]=e.value}var wx=[];function Cp(e){let t=Object.keys(e.shape),r=Object.getOwnPropertySymbols(e.shape),n=r.length?r:wx,o=n.length?[...t,...n]:t;for(let i of o)if(!e.shape?.[i]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${String(i)}": expected a Zod schema`);let s=zl(e.shape);return{...e,allKeys:o,symbolKeys:n,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(s)}}function Ep(e,t,r,n,o,s,i){let a=[],c=o.keySet,l=o.catchall._zod,u=l.def.type,{optin:p,optout:d}=l,m=0;for(let h in t){if(i&&r.issues.length!==m){if(Be(r,m))break;m=r.issues.length}if(c.has(h))continue;if(h==="__proto__"){if(u==="never")a.push(h);continue}if(u==="never"){a.push(h);continue}let y=l.run({value:t[h],issues:[]},n);if(y instanceof Promise)e.push(y.then((b)=>Wn(b,r,h,t,p,d)));else Wn(y,r,h,t,p,d)}if(a.length)r.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:s,continue:!0});if(!e.length)return r;return Promise.all(e).then(()=>r)}var _x=g("$ZodObject",(e,t)=>{q.init(e,t);let r=Object.getOwnPropertyDescriptor(t,"shape"),n=r?.get?r.get.raw:t.shape??{};if(n){let l=()=>{let u={...n};return Object.defineProperty(t,"shape",{value:u}),l.raw=u,u};l.raw=n,Object.defineProperty(t,"shape",{get:l})}let o=Tn(()=>Cp(t));B(e,"propValues",(l)=>{let u=l.def.shape,p={};for(let d in u){let m=u[d]._zod;if(m.values){if(!Object.prototype.hasOwnProperty.call(p,d))Ne(p,d,new Set);for(let h of m.values)p[d].add(h);if(m.optin!==void 0)p[d].add(void 0)}}return p});let s=Ir,i=t.catchall,a,c=we.memoizer;c?.attach(e),e._zod.parse=(l,u)=>{a??(a=o.value);let p=l.value;if(!s(p))return l.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),l;l.value=c?c.alloc(e,l,{},u):{};let d=[],m=a.shape,h=u?.abortEarly,y=l.issues.length;for(let b of a.allKeys){if(h&&l.issues.length!==y){if(Be(l,y))break;y=l.issues.length}if(b==="__proto__")continue;let _=m[b],P=_._zod.optin,O=_._zod.optout,D=_._zod.run({value:p[b],issues:[]},u);if(D instanceof Promise)d.push(D.then((S)=>Wn(S,l,b,p,P,O)));else Wn(D,l,b,p,P,O)}if(!i)return d.length?Promise.all(d).then(()=>l):l;return Ep(d,p,l,u,o.value,e,h===!0)}}),zp=g("$ZodObjectJIT",(e,t)=>{_x.init(e,t);let r=e._zod.parse,n=Tn(()=>Cp(t)),o=we.memoizer,s=(m)=>{let h=n.value,y=h.symbolKeys,b=new ti(["payload","ctx"],{shape:m,inst:e,memo:o,syms:y}),_=(S)=>`shape[${S}]._zod.run({ value: input[${S}], issues: [] }, ctx)`,P=(S,A)=>`
38
- let ${S}_ab = false;
39
- for (let i = 0; i < ${S}.issues.length; i++) {
40
- const iss = ${S}.issues[i];
41
- iss.path = iss.path ? [${A}, ...iss.path] : [${A}];
41
+ };`)(...Object.values(this.closed))}}var Fp={major:4,minor:6,patch:5};var X=g("$ZodType",(e,t)=>{var r;e??(e={}),e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=Fp;let n=e._zod.def.checks,o=e._zod.traits.has("$ZodCheck")?[e,...n??[]]:n?.length?[...n]:[];for(let s of o)for(let i of s._zod.onattach)i(e);if(o.length===0)(r=e._zod).deferred??(r.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let s=(a,c,l)=>{if(a.memo)return a;let u=We(a),p;for(let d of c){if(d._zod.def.when){if(Lu(a))continue;if(!d._zod.def.when(a))continue}else if(u)continue;let m=a.issues.length,h=d._zod.check(a);if(h instanceof Promise&&l?.async===!1)throw new He;if(p||h instanceof Promise)p=(p??Promise.resolve()).then(async()=>{if(await h,a.issues.length===m)return;if(wi(a.issues,m,e),!u)u=We(a,m)});else{if(a.issues.length===m)continue;if(wi(a.issues,m,e),!u)u=We(a,m)}}if(p)return p.then(()=>a);return a},i=(a,c,l)=>{if(We(a))return a.aborted=!0,a;let u=s(c,o,l);if(u instanceof Promise){if(l.async===!1)throw new He;return u.then((p)=>e._zod.parse(p,l))}return e._zod.parse(u,l)};e._zod.run=(a,c)=>{if(c.skipChecks)return e._zod.parse(a,c);if(c.direction==="backward"){let u=e._zod.parse({value:a.value,issues:[]},{...c,skipChecks:!0});if(u instanceof Promise)return u.then((p)=>i(p,a,c));return i(u,a,c)}let l=e._zod.parse(a,c);if(l instanceof Promise){if(c.async===!1)throw new He;return l.then((u)=>s(u,o,c))}return s(l,o,c)}}},{get "~standard"(){return io(this,"~standard",Li(this))},set "~standard"(e){it(this,"~standard",e)}}),Xp=(e,t)=>e.issues.length?{issues:e.issues.map((r)=>Je(r,t,Ce()))}:{value:e.value};async function rv(e,t){let r={async:!0};return Xp(await e._zod.run({value:t,issues:[]},r),r)}function Li(e){return{validate:(t)=>{let r={async:!1};try{let n=e._zod.run({value:t,issues:[]},r);if(!(n instanceof Promise))return Xp(n,r)}catch(n){}return rv(e,t)},vendor:"zod",version:1}}var yo=g("$ZodString",(e,t)=>{X.init(e,t),e._zod.pattern=t.pattern??$p,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=String(r.value)}catch(o){}if(typeof r.value==="string")return r;return r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:e}),r}}),q=g("$ZodStringFormat",(e,t)=>{Yr.init(e,t),yo.init(e,t)}),Qp=g("$ZodGUID",(e,t)=>{t.pattern??(t.pattern=lp),q.init(e,t)}),ed=g("$ZodUUID",(e,t)=>{if(t.version){let n={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(n===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=ji(n))}else t.pattern??(t.pattern=ji());q.init(e,t)}),td=g("$ZodEmail",(e,t)=>{t.pattern??(t.pattern=up),q.init(e,t)}),rd=1,ho=2;function nd(e){try{if(typeof URL<"u"&&typeof URL.canParse==="function")return URL.canParse(e);return new URL(e),!0}catch{return!1}}function nv(e,t){if(!("normalize"in t)&&!("hostname"in t)&&!("protocol"in t))return nd(e)||ho;return ov(e,t)}function ov(e,t){if(!t.normalize&&t.protocol?.source===bp.source&&!/^https?:\/\//i.test(e))return rd;try{if(typeof URL<"u"){let r=URL;if(typeof r.parse==="function")return r.parse(e)??ho}return new URL(e)}catch{return ho}}var sv=/[\t\n\r]/g;function Mp(e){return e.replace(sv,"")}function iv(e,t){return t.lastIndex=0,t.test(e.hostname)}function av(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(":")?e.protocol.slice(0,-1):e.protocol)}var od=g("$ZodURL",(e,t)=>{q.init(e,t),e._zod.check=(r)=>{try{let n=r.value.trim(),o=nv(n,t);if(o===rd){r.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:r.value,inst:e,continue:!t.abort});return}if(o===ho){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort});return}if(o===!0){r.value=Mp(n);return}if(t.hostname&&!iv(o,t.hostname))r.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:r.value,inst:e,continue:!t.abort});if(t.protocol&&!av(o,t.protocol))r.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:r.value,inst:e,continue:!t.abort});r.value=t.normalize?o.href:Mp(n);return}catch(n){r.issues.push({code:"invalid_format",format:"url",input:r.value,inst:e,continue:!t.abort})}}}),sd=g("$ZodEmoji",(e,t)=>{t.pattern??(t.pattern=pp()),q.init(e,t)}),id=g("$ZodNanoID",(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??(t.pattern=t.length===void 0?ip:ap(t.length)),q.init(e,t)}),ad=g("$ZodCUID",(e,t)=>{t.pattern??(t.pattern=tp),q.init(e,t)}),cd=g("$ZodCUID2",(e,t)=>{t.pattern??(t.pattern=rp),q.init(e,t)}),ld=g("$ZodULID",(e,t)=>{t.pattern??(t.pattern=np),q.init(e,t)}),ud=g("$ZodXID",(e,t)=>{t.pattern??(t.pattern=op),q.init(e,t)}),pd=g("$ZodKSUID",(e,t)=>{t.pattern??(t.pattern=sp),q.init(e,t)}),dd=g("$ZodISODateTime",(e,t)=>{t.pattern??(t.pattern=Sp(t)),q.init(e,t)}),md=g("$ZodISODate",(e,t)=>{t.pattern??(t.pattern=vp),q.init(e,t)}),fd=g("$ZodISOTime",(e,t)=>{t.pattern??(t.pattern=_p(t)),q.init(e,t)}),hd=g("$ZodISODuration",(e,t)=>{t.pattern??(t.pattern=cp),q.init(e,t)}),gd=g("$ZodIPv4",(e,t)=>{t.pattern??(t.pattern=dp),q.init(e,t)}),cv=/^[0-9a-fA-F:.]+$/;function yd(e){if(!cv.test(e))return!1;return nd(`http://[${e}]`)}var bd=g("$ZodIPv6",(e,t)=>{t.pattern??(t.pattern=mp),q.init(e,t),e._zod.check=(r)=>{if(!yd(r.value))r.issues.push({code:"invalid_format",format:"ipv6",input:r.value,inst:e,continue:!t.abort})}});var xd=g("$ZodCIDRv4",(e,t)=>{t.pattern??(t.pattern=fp),q.init(e,t)});function lv(e){let t=e.split("/");if(t.length!==2)return!1;let[r,n]=t;if(!n)return!1;let o=Number(n);if(`${o}`!==n)return!1;if(o<0||o>128)return!1;return yd(r)}var wd=g("$ZodCIDRv6",(e,t)=>{t.pattern??(t.pattern=hp),q.init(e,t),e._zod.check=(r)=>{if(!lv(r.value))r.issues.push({code:"invalid_format",format:"cidrv6",input:r.value,inst:e,continue:!t.abort})}});function vd(e){if(e==="")return!0;if(/\s/.test(e))return!1;if(e.length%4!==0)return!1;try{return atob(e),!0}catch{return!1}}var Di=/^[0-9a-zA-Z+/]*={0,2}$/,_d=g("$ZodBase64",(e,t)=>{t.pattern??(t.pattern=Di),q.init(e,t),e._zod.check=(r)=>{if(vd(r.value))return;r.issues.push({code:"invalid_format",format:"base64",input:r.value,inst:e,continue:!t.abort})}}),bo=/^[A-Za-z0-9_-]*$/;function uv(e){if(!bo.test(e))return!1;let t=e.replace(/[-_]/g,(n)=>n==="-"?"+":"/"),r=t.padEnd(Math.ceil(t.length/4)*4,"=");return vd(r)}var Sd=g("$ZodBase64URL",(e,t)=>{t.pattern??(t.pattern=bo),q.init(e,t),e._zod.check=(r)=>{if(uv(r.value))return;r.issues.push({code:"invalid_format",format:"base64url",input:r.value,inst:e,continue:!t.abort})}}),$d=g("$ZodE164",(e,t)=>{t.pattern??(t.pattern=xp),q.init(e,t)});function pv(e,t=null){try{let r=e.split(".");if(r.length!==3)return!1;let[n]=r;if(!n)return!1;let o=JSON.parse(atob(n));if("typ"in o&&o?.typ!=="JWT")return!1;if(!o.alg)return!1;if(t&&(!("alg"in o)||o.alg!==t))return!1;return!0}catch{return!1}}var kd=g("$ZodJWT",(e,t)=>{q.init(e,t),e._zod.check=(r)=>{if(pv(r.value,t.alg))return;r.issues.push({code:"invalid_format",format:"jwt",input:r.value,inst:e,continue:!t.abort})}});var Ni=g("$ZodNumber",(e,t)=>{X.init(e,t),e._zod.pattern=qr,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Number(r.value)}catch(i){}let o=r.value;if(typeof o==="number"&&!Number.isNaN(o)&&Number.isFinite(o))return r;let s=typeof o==="number"?Number.isNaN(o)?"NaN":!Number.isFinite(o)?String(o):void 0:void 0;return r.issues.push({expected:"number",code:"invalid_type",input:o,inst:e,...s?{received:s}:{}}),r}}),Pd=g("$ZodNumberFormat",(e,t)=>{jp.init(e,t),Ni.init(e,t)}),Cd=g("$ZodBoolean",(e,t)=>{X.init(e,t),e._zod.pattern=kp,e._zod.parse=(r,n)=>{if(t.coerce)try{r.value=Boolean(r.value)}catch(s){}let o=r.value;if(typeof o==="boolean")return r;return r.issues.push({expected:"boolean",code:"invalid_type",input:o,inst:e}),r}});var Ed=g("$ZodUnknown",(e,t)=>{X.init(e,t),e._zod.parse=(r)=>r}),jd=g("$ZodNever",(e,t)=>{X.init(e,t),e._zod.parse=(r,n)=>(r.issues.push({expected:"never",code:"invalid_type",input:r.value,inst:e}),r)});function Bp(e,t,r){if(e.issues.length)t.issues.push(...xt(r,e.issues));t.value[r]=e.value}var Ad=g("$ZodArray",(e,t)=>{X.init(e,t);let r=Pe.memoizer;r?.attach(e),e._zod.parse=(n,o)=>{let s=n.value;if(!Array.isArray(s))return n.issues.push({expected:"array",code:"invalid_type",input:s,inst:e}),n;n.value=r?r.alloc(e,n,Array(s.length),o):Array(s.length);let i=[],a=o?.abortEarly;for(let c=0;c<s.length;c++){let l=s[c],u=t.element._zod.run({value:l,issues:[]},o);if(u instanceof Promise)i.push(u.then((p)=>Bp(p,n,c)));else if(Bp(u,n,c),a&&u.issues.length!==0&&We(u))break}if(i.length)return Promise.all(i).then(()=>n);return n}});function go(e,t,r,n,o,s){let i=r in n,a=s==="optional";if(!i&&a&&o==="optional")return;if(e.issues.length){if(o!==void 0&&a&&!i)return;t.issues.push(...xt(r,e.issues))}if(!i&&o===void 0){if(!e.issues.length)t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[r]});return}if(e.value===void 0){if(i||o==="defaulted"&&!a)t.value[r]=void 0}else t.value[r]=e.value}var dv=[];function Rd(e){let t=Object.keys(e.shape),r=Object.getOwnPropertySymbols(e.shape),n=r.length?r:dv,o=n.length?[...t,...n]:t;for(let i of o)if(!e.shape?.[i]?._zod?.traits?.has("$ZodType"))throw Error(`Invalid element at key "${String(i)}": expected a Zod schema`);let s=Tu(e.shape);return{...e,allKeys:o,symbolKeys:n,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(s)}}function Id(e,t,r,n,o,s,i){let a=[],c=o.keySet,l=o.catchall._zod,u=l.def.type,{optin:p,optout:d}=l,m=0;for(let h in t){if(i&&r.issues.length!==m){if(We(r,m))break;m=r.issues.length}if(c.has(h))continue;if(h==="__proto__"){if(u==="never")a.push(h);continue}if(u==="never"){a.push(h);continue}let y=l.run({value:t[h],issues:[]},n);if(y instanceof Promise)e.push(y.then((b)=>go(b,r,h,t,p,d)));else go(y,r,h,t,p,d)}if(a.length)r.issues.push({code:"unrecognized_keys",keys:a,input:t,inst:s,continue:!0});if(!e.length)return r;return Promise.all(e).then(()=>r)}var mv=g("$ZodObject",(e,t)=>{X.init(e,t);let r=Object.getOwnPropertyDescriptor(t,"shape"),n=r?.get?r.get.raw:t.shape??{};if(n){let l=()=>{let u={...n};return Object.defineProperty(t,"shape",{value:u}),l.raw=u,u};l.raw=n,Object.defineProperty(t,"shape",{get:l})}let o=Qn(()=>Rd(t));K(e,"propValues",(l)=>{let u=l.def.shape,p={};for(let d in u){let m=u[d]._zod;if(m.values){if(!Object.prototype.hasOwnProperty.call(p,d))Fe(p,d,new Set);for(let h of m.values)p[d].add(h);if(m.optin!==void 0)p[d].add(void 0)}}return p});let s=Kr,i=t.catchall,a,c=Pe.memoizer;c?.attach(e),e._zod.parse=(l,u)=>{a??(a=o.value);let p=l.value;if(!s(p))return l.issues.push({expected:"object",code:"invalid_type",input:p,inst:e}),l;l.value=c?c.alloc(e,l,{},u):{};let d=[],m=a.shape,h=u?.abortEarly,y=l.issues.length;for(let b of a.allKeys){if(h&&l.issues.length!==y){if(We(l,y))break;y=l.issues.length}if(b==="__proto__")continue;let v=m[b],E=v._zod.optin,L=v._zod.optout,U=v._zod.run({value:p[b],issues:[]},u);if(U instanceof Promise)d.push(U.then((k)=>go(k,l,b,p,E,L)));else go(U,l,b,p,E,L)}if(!i)return d.length?Promise.all(d).then(()=>l):l;return Id(d,p,l,u,o.value,e,h===!0)}}),Td=g("$ZodObjectJIT",(e,t)=>{mv.init(e,t);let r=e._zod.parse,n=Qn(()=>Rd(t)),o=Pe.memoizer,s=(m)=>{let h=n.value,y=h.symbolKeys,b=new zi(["payload","ctx"],{shape:m,inst:e,memo:o,syms:y}),v=(k)=>`shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`,E=(k,I)=>`
42
+ let ${k}_ab = false;
43
+ for (let i = 0; i < ${k}.issues.length; i++) {
44
+ const iss = ${k}.issues[i];
45
+ iss.path = iss.path ? [${I}, ...iss.path] : [${I}];
42
46
  payload.issues.push(iss);
43
- if (iss.continue !== true) ${S}_ab = true;
47
+ if (iss.continue !== true) ${k}_ab = true;
44
48
  }
45
- if (${S}_ab && ctx && ctx.abortEarly) {
49
+ if (${k}_ab && ctx && ctx.abortEarly) {
46
50
  payload.value = newResult;
47
51
  return payload;
48
- }`;b.write("const input = payload.value;");let O=Object.create(null),D=0;for(let S of h.allKeys)O[S]=`key_${D++}`;b.write(o?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(let S of h.allKeys){if(S==="__proto__")continue;let A=O[S],U=typeof S==="symbol"?`syms[${y.indexOf(S)}]`:kl(S),ce=`${U} in input`,L=m[S],F=L?._zod?.optin,ne=F!==void 0,le=L?._zod?.optout==="optional";if(b.write(`const ${A} = ${_(U)};`),ne&&le){let Ae=F==="optional"?`${A}_present`:`${A}.value !== undefined || ${A}_present`;b.write(`
49
- const ${A}_present = ${ce};
50
- if (!${A}.issues.length || ${A}_present) {
51
- if (${A}.issues.length) {${P(A,U)}
52
+ }`;b.write("const input = payload.value;");let L=Object.create(null),U=0;for(let k of h.allKeys)L[k]=`key_${U++}`;b.write(o?"const newResult = memo.alloc(inst, payload, {}, ctx);":"const newResult = {};");for(let k of h.allKeys){if(k==="__proto__")continue;let I=L[k],M=typeof k==="symbol"?`syms[${y.indexOf(k)}]`:ju(k),pe=`${M} in input`,N=m[k],B=N?._zod?.optin,se=B!==void 0,de=N?._zod?.optout==="optional";if(b.write(`const ${I} = ${v(M)};`),se&&de){let De=B==="optional"?`${I}_present`:`${I}.value !== undefined || ${I}_present`;b.write(`
53
+ const ${I}_present = ${pe};
54
+ if (!${I}.issues.length || ${I}_present) {
55
+ if (${I}.issues.length) {${E(I,M)}
52
56
  }
53
57
 
54
- if (${Ae}) {
55
- newResult[${U}] = ${A}.value;
58
+ if (${De}) {
59
+ newResult[${M}] = ${I}.value;
56
60
  }
57
61
  }
58
62
 
59
- `)}else if(!ne)b.write(`
60
- const ${A}_present = ${ce};
61
- if (${A}.issues.length) {${P(A,U)}
63
+ `)}else if(!se)b.write(`
64
+ const ${I}_present = ${pe};
65
+ if (${I}.issues.length) {${E(I,M)}
62
66
  }
63
- if (!${A}_present && !${A}.issues.length) {
67
+ if (!${I}_present && !${I}.issues.length) {
64
68
  payload.issues.push({
65
69
  code: "invalid_type",
66
70
  expected: "nonoptional",
67
71
  input: undefined,
68
- path: [${U}]
72
+ path: [${M}]
69
73
  });
70
74
  if (ctx && ctx.abortEarly) {
71
75
  payload.value = newResult;
@@ -73,30 +77,32 @@ ${t.join(`
73
77
  }
74
78
  }
75
79
 
76
- if (${A}_present) {
77
- newResult[${U}] = ${A}.value;
80
+ if (${I}_present) {
81
+ newResult[${M}] = ${I}.value;
78
82
  }
79
83
 
80
84
  `);else if(b.write(`
81
- if (${A}.issues.length) {${P(A,U)}
85
+ if (${I}.issues.length) {${E(I,M)}
82
86
  }
83
- `),F==="defaulted")b.write(`newResult[${U}] = ${A}.value;`);else b.write(`
84
- if (${A}.value !== undefined || ${ce}) {
85
- newResult[${U}] = ${A}.value;
87
+ `),B==="defaulted")b.write(`newResult[${M}] = ${I}.value;`);else b.write(`
88
+ if (${I}.value !== undefined || ${pe}) {
89
+ newResult[${M}] = ${I}.value;
86
90
  }
87
- `)}return b.write("payload.value = newResult;"),b.write("return payload;"),b.compile()},i,a=Ir,c=!we.jitless,u=c&&Cl.value,p=t.catchall,d;e._zod.parse=(m,h)=>{d??(d=n.value);let y=m.value;if(!a(y))return m.issues.push({expected:"object",code:"invalid_type",input:y,inst:e}),m;if(c&&u&&h?.async===!1&&h.jitless!==!0){if(!i)i=s(t.shape);if(m=i(m,h),!p)return m;return Ep([],y,m,h,d,e,h?.abortEarly===!0)}return r(m,h)}});function Uu(e,t,r,n){for(let s of e)if(s.issues.length===0)return t.value=s.value,t;let o=e.filter((s)=>!Be(s));if(o.length===1)return t.value=o[0].value,o[0];return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map((s)=>s.issues.map((i)=>Ge(i,n,_e())))}),t}var Ip=g("$ZodUnion",(e,t)=>{q.init(e,t),B(e,"optin",(n)=>n.def.options.some((o)=>o._zod.optin==="defaulted")?"defaulted":n.def.options.some((o)=>o._zod.optin!==void 0)?"optional":void 0),B(e,"optout",(n)=>n.def.options.some((o)=>o._zod.optout==="optional")?"optional":void 0),B(e,"values",(n)=>{if(n.def.options.every((o)=>o._zod.values))return new Set(n.def.options.flatMap((o)=>Array.from(o._zod.values)));return}),B(e,"pattern",(n)=>{if(n.def.options.every((o)=>o._zod.pattern)){let o=n.def.options.map((s)=>s._zod.pattern);return new RegExp(`^(${o.map((s)=>An(s.source)).join("|")})$`)}return});let r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(n,o)=>{if(r)return r(n,o);let s=!1,i=[];for(let a of t.options){let c=a._zod.run({value:n.value,issues:[]},o);if(c instanceof Promise)i.push(c),s=!0;else{if(c.issues.length===0)return c;i.push(c)}}if(!s)return Uu(i,n,e,o);return Promise.all(i).then((a)=>Uu(a,n,e,o))}});var Tp=g("$ZodIntersection",(e,t)=>{q.init(e,t),e._zod.parse=(r,n)=>{let o=r.value,s=t.left._zod.run({value:o,issues:[]},n),i=t.right._zod.run({value:o,issues:[]},n);if(s instanceof Promise||i instanceof Promise)return Promise.all([s,i]).then(([c,l])=>Fu(r,c,l));return Fu(r,s,i)}});function ri(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(Rt(e)&&Rt(t)){let r=Object.keys(t),n=Object.keys(e).filter((s)=>r.indexOf(s)!==-1),o={...e,...t};if(Object.prototype.hasOwnProperty.call(o,"__proto__"))delete o.__proto__;for(let s of n){if(s==="__proto__")continue;let i=ri(e[s],t[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<e.length;n++){let o=e[n],s=t[n],i=ri(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Fu(e,t,r){let n=new Map,o,s=new Map,i=(l,u)=>{let p;if(l.code==="unrecognized_keys"&&!l.path?.length)o??(o=l),p=l.keys;else if(l.code==="invalid_key"&&l.origin==="record"&&l.path?.length===1){let d=String(l.path[0]);if(!s.has(d))s.set(d,l);p=[d]}else return!1;for(let d of p){if(!n.has(d))n.set(d,{});n.get(d)[u]=!0}return!0};for(let l of t.issues)if(!i(l,"l"))e.issues.push(l);for(let l of r.issues)if(!i(l,"r"))e.issues.push(l);let a=[...n].filter(([,l])=>l.l&&l.r).map(([l])=>l);if(a.length){let l=o?a.filter((u)=>o.keys.includes(u)):[];if(l.length)e.issues.push({...o,keys:l});for(let u of a)if(!l.includes(u)&&s.has(u))e.issues.push(s.get(u))}let c=ri(t.value,r.value);if(!c.valid){if(Be(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}var Ap=g("$ZodRecord",(e,t)=>{q.init(e,t);let r=we.memoizer;r?.attach(e),e._zod.parse=(n,o)=>{let s=n.value;if(!Rt(s))return n.issues.push({expected:"record",code:"invalid_type",input:s,inst:e}),n;let i=[],a=t.keyType._zod.values;if(a&&!t.partial){n.value=r?r.alloc(e,n,{},o):{};let c=new Set;for(let u of a)if(typeof u==="string"||typeof u==="number"||typeof u==="symbol"){if(c.add(typeof u==="number"?u.toString():u),u==="__proto__")continue;let p=t.keyType._zod.run({value:u,issues:[]},o);if(p instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(p.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:p.issues.map((h)=>Ge(h,o,_e())),input:u,path:[u],inst:e});continue}let d=p.value;if(d==="__proto__")continue;let m=t.valueType._zod.run({value:s[u],issues:[]},o);if(m instanceof Promise)i.push(m.then((h)=>{if(h.issues.length)n.issues.push(...yt(u,h.issues));n.value[d]=h.value}));else{if(m.issues.length)n.issues.push(...yt(u,m.issues));n.value[d]=m.value}}let l;for(let u in s)if(!c.has(u))if(t.mode==="loose"){if(u==="__proto__")continue;n.value[u]=s[u]}else l=l??[],l.push(u);if(l&&l.length>0)n.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:l,continue:!0})}else{n.value=r?r.alloc(e,n,{},o):{};let c;for(let l of Reflect.ownKeys(s)){if(l==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(s,l))continue;let u=t.keyType._zod.run({value:l,issues:[]},o);if(u instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof l==="string"&&jr.test(l)&&u.issues.length){let h=t.keyType._zod.run({value:Number(l),issues:[]},o);if(h instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(h.issues.length===0)u=h}if(u.issues.length){if(t.mode==="loose")n.value[l]=s[l];else if(a)c=c??[],c.push(l);else n.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map((h)=>Ge(h,o,_e())),input:l,path:[l],inst:e});continue}let d=u.value;if(d==="__proto__")continue;let m=t.valueType._zod.run({value:s[l],issues:[]},o);if(m instanceof Promise)i.push(m.then((h)=>{if(h.issues.length)n.issues.push(...yt(l,h.issues));n.value[d]=h.value}));else{if(m.issues.length)n.issues.push(...yt(l,m.issues));n.value[d]=m.value}}if(c&&c.length>0)n.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:c,continue:!0})}if(i.length)return Promise.all(i).then(()=>n);return n}});var Rp=g("$ZodEnum",(e,t)=>{q.init(e,t);let r=Tr(t.entries),n=new Set(r);e._zod.values=n,B(e,"pattern",(o)=>{let s=Tr(o.def.entries).filter((i)=>El.has(typeof i));return new RegExp(s.length?`^(${s.map((i)=>Yt(i.toString())).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(o,s)=>{let i=o.value;if(n.has(i))return o;return o.issues.push({code:"invalid_value",values:r,input:i,inst:e}),o}});var jp=g("$ZodTransform",(e,t)=>{q.init(e,t),e._zod.optin="optional",we.memoizer?.guard(e),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Rr(e.constructor.name);let o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then((i)=>(r.value=i,r));if(o instanceof Promise)throw new Ke;return r.value=o,r}});function Mu(e,t){return e.value=t.issues.length?void 0:t.value,e}var ii=g("$ZodOptional",(e,t)=>{q.init(e,t),B(e,"optin",(r)=>r.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),e._zod.optout="optional",B(e,"values",(r)=>{let n=r.def.innerType._zod.values;return n?new Set([...n,void 0]):void 0}),B(e,"pattern",(r)=>{let n=r.def.innerType._zod.pattern;return n?new RegExp(`^(${An(n.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(r.value===void 0){if(t.innerType._zod.optin!=="defaulted")return r;let o=t.innerType._zod.run({value:r.value,issues:[]},n);if(o instanceof Promise)return o.then((s)=>Mu(r,s));return Mu(r,o)}return t.innerType._zod.run(r,n)}}),Op=g("$ZodExactOptional",(e,t)=>{ii.init(e,t),B(e,"values",(r)=>r.def.innerType._zod.values),B(e,"pattern",(r)=>r.def.innerType._zod.pattern),e._zod.parse=(r,n)=>t.innerType._zod.run(r,n)}),Lp=g("$ZodNullable",(e,t)=>{q.init(e,t),B(e,"optin",(r)=>r.def.innerType._zod.optin),B(e,"optout",(r)=>r.def.innerType._zod.optout),B(e,"pattern",(r)=>{let n=r.def.innerType._zod.pattern;return n?new RegExp(`^(${An(n.source)}|null)$`):void 0}),B(e,"values",(r)=>r.def.innerType._zod.values?new Set([...r.def.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>{if(r.value===null)return r;return t.innerType._zod.run(r,n)}}),Dp=g("$ZodDefault",(e,t)=>{q.init(e,t),e._zod.optin="defaulted",B(e,"values",(r)=>r.def.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)return r.value=t.defaultValue,r;let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then((s)=>Bu(s,t));return Bu(o,t)}});function Bu(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var Np=g("$ZodPrefault",(e,t)=>{q.init(e,t),e._zod.optin="defaulted",B(e,"values",(r)=>r.def.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)r.value=t.defaultValue;return t.innerType._zod.run(r,n)}}),Zp=g("$ZodNonOptional",(e,t)=>{q.init(e,t),B(e,"values",(r)=>{let n=r.def.innerType._zod.values;return n?new Set([...n].filter((o)=>o!==void 0)):void 0}),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then((s)=>Gu(s,e));return Gu(o,e)}});function Gu(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t});return e}function Ku(e,t,r,n){if(!t.issues.length){if(e.value=t.value,t.memo)e.memo=!0;return e}return e.value=r.catchValue({...t,value:e.value,error:{issues:t.issues.map((o)=>Ge(o,n,_e()))},input:e.value}),e}var Up=g("$ZodCatch",(e,t)=>{q.init(e,t),B(e,"optin",(r)=>r.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),B(e,"optout",(r)=>r.def.innerType._zod.optout),B(e,"values",(r)=>r.def.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run({value:r.value,issues:[]},n);if(o instanceof Promise)return o.then((s)=>Ku(r,s,t,n));return Ku(r,o,t,n)}});var Fp=g("$ZodPipe",(e,t)=>{q.init(e,t),B(e,"values",(r)=>r.def.in._zod.values),B(e,"optin",(r)=>r.def.in._zod.optin),B(e,"optout",(r)=>r.def.out._zod.optout),B(e,"propValues",(r)=>r.def.in._zod.propValues),e._zod.parse=(r,n)=>{if(n.direction==="backward"){let s=t.out._zod.run(r,n);if(s instanceof Promise)return s.then((i)=>Kn(i,t.in,n));return Kn(s,t.in,n)}let o=t.in._zod.run(r,n);if(o instanceof Promise)return o.then((s)=>Kn(s,t.out,n));return Kn(o,t.out,n)}});function Kn(e,t,r){if(e.issues.some((n)=>n.code!=="unrecognized_keys"))return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues},r)}var Mp=g("$ZodReadonly",(e,t)=>{q.init(e,t),B(e,"propValues",(r)=>r.def.innerType._zod.propValues),B(e,"values",(r)=>r.def.innerType._zod.values),B(e,"optin",(r)=>r.def.innerType?._zod?.optin),B(e,"optout",(r)=>r.def.innerType?._zod?.optout),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then(Vu);return Vu(o)}});function Vu(e){if(!e.memo)e.value=Object.freeze(e.value);return e}var Bp=g("$ZodCustom",(e,t)=>{ue.init(e,t),q.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=(r)=>{let n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then((s)=>Wu(s,r,n,e));Wu(o,r,n,e);return}});function Wu(e,t,r,n){if(!e){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};if(n._zod.def.params)o.params=n._zod.def.params;t.issues.push(jt(o))}}class Kp extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform");this.name="ZodCyclicError"}}var ci="~memo",Gp=[];function Vp(e){return e!==null&&typeof e==="object"}function ai(e){return e.map((t)=>t.path?{...t,path:t.path.slice()}:{...t})}var Wp=new WeakMap,Lr=0,Xn=1,Dr=2;function Qn(e,t,r){let n=Wp.get(e);if(n!==void 0)return n?Dr:Lr;if(t.has(e))return Dr;t.add(e);let o=Lr,s=(u)=>{if(o!==Dr&&u?._zod){let p=Qn(u,t,r);if(p>o)o=p}},i=(u,p)=>{let d=Lr;for(let m of Reflect.ownKeys(u)){let h=Object.getOwnPropertyDescriptor(u,m);if(p&&!h.enumerable)continue;let y=h.get?Xn:h.value?._zod?Qn(h.value,t,r):Lr;if(y>d)d=y}return d},a=(u)=>{if(u>o)o=u},c=e._zod.def,l=c.type;switch(l){case"object":{let u=Rn(c);a(u?i(u,!0):Xn),s(c.catchall);break}case"array":s(c.element);break;case"tuple":for(let u of c.items)s(u);s(c.rest);break;case"record":case"map":s(c.keyType),s(c.valueType);break;case"set":s(c.valueType);break;case"union":for(let u of c.options)s(u);break;case"intersection":s(c.left),s(c.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":s(c.innerType);break;case"pipe":s(c.in),s(c.out);break;case"function":s(c.input),s(c.output);break;case"lazy":{let u=c._cachedInner??(r?e._zod.innerType:void 0);a(u?Qn(u,t,!1):Xn);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(let u in c){let p=Object.getOwnPropertyDescriptor(c,u);if(!p||p.get)continue;let d=p.value;if(!d||typeof d!=="object")continue;if(d._zod)s(d);else if(Array.isArray(d))for(let m of d)s(m)}}return t.delete(e),vx(e,o)}function vx(e,t){if(t!==Xn)Wp.set(e,t===Dr);return t}function $x(e,t){let r=e.buckets.get(t);if(!r)r=new WeakMap,e.buckets.set(t,r);return r}var qn,Yn=[],Sx={alloc(e,t,r){let n=qn;if(!n)return r;qn=void 0;let o={value:r,issues:null};return n.set(t.value,o),Yn.push(o),r},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let r=e._zod.parse,n=(o,s)=>{if(s.direction!=="backward"&&kx(s,o.value))throw new Kp;return r(o,s)};if(e._zod.parse=n,e._zod.run===r)e._zod.run=n})},attach(e){var t;let r,n=!1,o,s;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let i=e._zod.parse,a=(c,l)=>{if(r===void 0){let _=Qn(e,new Set,!1);if(_===Lr){if(e._zod.parse=i,e._zod.run===a)e._zod.run=i;return i(c,l)}if(_===Dr||n)r=!0;else n=!0}let u=c.value;if(!Vp(u))return i(c,l);let p=l[ci];if(!p)p={buckets:new WeakMap,backEdges:void 0},l[ci]=p;let d;if(o===l)d=s;else d=$x(p,e),o=l,s=d;let m=d.get(u);if(m){if(c.value=m.value,m.issues){if(m.issues.length)c.issues.push(...ai(m.issues))}else c.memo=!0,p.backEdges??(p.backEdges=new WeakSet),p.backEdges.add(m.value);return c}qn=d;let h=Yn.length,y=i(c,l);qn=void 0;let b=Yn.length>h?Yn.pop():void 0;if(y instanceof Promise)return y.then((_)=>{if(b)b.issues=_.issues.length?ai(_.issues):Gp;return _});if(b)b.issues=y.issues.length?ai(y.issues):Gp;return y};if(e._zod.parse=a,e._zod.run===i)e._zod.run=a})}};function li(){return Sx}function kx(e,t){let r=e[ci]?.backEdges;return r!==void 0&&Vp(t)&&r.has(t)}var Px=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(s){return e[s]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},n={nan:"NaN"};function o(s,i){if(s==="number"&&typeof i==="number"&&!Number.isFinite(i))return String(i);return n[s]??s}return(s)=>{switch(s.code){case"invalid_type":{let i=o(s.expected),a=Rl(s.input),c=o(a,s.input);return`Invalid input: expected ${i}, received ${c}`}case"invalid_value":if(s.values.length===1)return`Invalid input: expected ${Zs(s.values[0])}`;return`Invalid option: expected one of ${Ls(s.values,"|")}`;case"too_big":{let i=s.exact?"exactly ":s.inclusive?"<=":"<",a=t(s.origin);if(a)return`Too big: expected ${s.origin??"value"} to have ${i}${s.maximum.toString()} ${a.unit??"elements"}`;return`Too big: expected ${s.origin??"value"} to be ${i}${s.maximum.toString()}`}case"too_small":{let i=s.exact?"exactly ":s.inclusive?">=":">",a=t(s.origin);if(a)return`Too small: expected ${s.origin} to have ${i}${s.minimum.toString()} ${a.unit}`;return`Too small: expected ${s.origin} to be ${i}${s.minimum.toString()}`}case"invalid_format":{let i=s;if(i.format==="starts_with")return`Invalid string: must start with "${i.prefix}"`;if(i.format==="ends_with")return`Invalid string: must end with "${i.suffix}"`;if(i.format==="includes")return`Invalid string: must include "${i.includes}"`;if(i.format==="regex")return`Invalid string: must match pattern ${i.pattern}`;return`Invalid ${r[i.format]??s.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${s.divisor}`;case"unrecognized_keys":return`Unrecognized key${s.keys.length>1?"s":""}: ${Ls(s.keys,", ")}`;case"invalid_key":return`Invalid key in ${s.origin}`;case"invalid_union":if(s.options&&Array.isArray(s.options)&&s.options.length>0)return`Invalid discriminator value. Expected ${s.options.map((a)=>`'${a}'`).join(" | ")}`;if(s.inclusive===!1)return"Invalid input: more than one option matched";return"Invalid input";case"invalid_element":return`Invalid value in ${s.origin}`;default:return"Invalid input"}}};function ui(){return{localeError:Px()}}var Jp;class Hp{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let r=t[0];if(this._map.set(e,r),r&&typeof r==="object"&&"id"in r)this._idmap.set(r.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t)this._idmap.delete(t.id);return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let r={...this.get(t)??{}};delete r.id;let n={...r,...this._map.get(e)};return Object.keys(n).length?n:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function qp(){return new Hp}(Jp=globalThis).__zod_globalRegistry??(Jp.__zod_globalRegistry=qp());var bt=globalThis.__zod_globalRegistry;function Yp(e){if(e.checks)e.checks=[...e.checks];return e}function Xp(e,t){return new e(Yp({type:"string",...C(t)}))}function Qp(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...C(t)})}function ed(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...C(t)})}function td(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...C(t)})}function rd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...C(t)})}function nd(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...C(t)})}function od(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...C(t)})}function pi(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...C(t)})}function sd(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...C(t)})}function id(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...C(t)})}function ad(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...C(t)})}function cd(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...C(t)})}function ld(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...C(t)})}function ud(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...C(t)})}function pd(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...C(t)})}function dd(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...C(t)})}function md(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...C(t)})}function fd(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...C(t)})}function hd(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...C(t)})}function gd(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...C(t)})}function yd(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...C(t)})}function bd(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...C(t)})}function xd(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...C(t)})}function eo(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...C(t)})}function to(e,t){return new e({type:"string",format:"date",check:"string_format",...C(t)})}function ro(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...C(t)})}function no(e,t){return new e({type:"string",format:"duration",check:"string_format",...C(t)})}function wd(e,t){return new e(Yp({type:"number",checks:[],...C(t)}))}function _d(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...C(t)})}function vd(e,t){return new e({type:"boolean",...C(t)})}function $d(e){return new e({type:"unknown"})}function Sd(e,t){return new e({type:"never",...C(t)})}function oo(e,t){return new Qs({check:"less_than",...C(t),value:e,inclusive:!1})}function Nr(e,t){return new Qs({check:"less_than",...C(t),value:e,inclusive:!0})}function so(e,t){return new ei({check:"greater_than",...C(t),value:e,inclusive:!1})}function Zr(e,t){return new ei({check:"greater_than",...C(t),value:e,inclusive:!0})}function io(e,t){return new Su({check:"multiple_of",...C(t),value:e})}function ao(e,t){return new Pu({check:"max_length",...C(t),maximum:e})}function er(e,t){return new Cu({check:"min_length",...C(t),minimum:e})}function co(e,t){return new Eu({check:"length_equals",...C(t),length:e})}function di(e,t){return new zu({check:"string_format",format:"regex",...C(t),pattern:e})}function mi(e){return new Iu({check:"string_format",format:"lowercase",...C(e)})}function fi(e){return new Tu({check:"string_format",format:"uppercase",...C(e)})}function hi(e,t){return new Au({check:"string_format",format:"includes",...C(t),includes:e})}function gi(e,t){return new Ru({check:"string_format",format:"starts_with",...C(t),prefix:e})}function yi(e,t){return new ju({check:"string_format",format:"ends_with",...C(t),suffix:e})}function xt(e){return new Ou({check:"overwrite",tx:e})}function bi(e){return xt((t)=>t.normalize(e))}function xi(){return xt((e)=>e.trim())}function wi(){return xt((e)=>e.toLowerCase())}function _i(){return xt((e)=>e.toUpperCase())}function vi(){return xt((e)=>Pl(e))}function kd(e,t,r){return new e({type:"array",element:t,...C(r)})}function Pd(e,t,r){return new e({type:"custom",check:"custom",fn:t,...C(r)})}function Cd(e,t){let r=Cx((n)=>(n.addIssue=(o)=>{if(typeof o==="string")n.issues.push(jt(o,n.value,r._zod.def));else{let s=o;if(s.fatal)s.continue=!1;if(s.code??(s.code="custom"),!("input"in s))s.input=n.value;s.inst??(s.inst=r),s.continue??(s.continue=!r._zod.def.abort),n.issues.push(jt(s))}},e(n.value,n)),t);return r}function Cx(e,t){let r=new ue({check:"custom",...C(t)});return r._zod.check=e,r}function Ur(e,...t){for(let r of t)for(let n of Reflect.ownKeys(r))if(Object.prototype.propertyIsEnumerable.call(r,n))Ne(e,n,r[n]);return e}function Si(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";return{processors:e.processors??{},metadataRegistry:e?.metadata??bt,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function Ot(e,t,r,n,o){let s=typeof t.unrepresentable==="function"?t.unrepresentable({zodSchema:e,path:n.path,message:o}):t.unrepresentable;if(s==="any")return!1;if(s===void 0||s==="throw")throw Error(o);return Object.assign(r,s),!0}function se(e,t,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s=t.seen.get(e);if(s){if(s.count++,r.schemaPath.includes(e))s.cycle=r.path;return s.schema}let i={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,i),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let a=e._zod.toJSONSchema?.();if(a)i.schema=a;else{let u={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,u);else{let d=i.schema,m=t.processors[o.type];if(!m)throw Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);m(e,t,d,u)}let p=e._zod.parent;if(p){if(!i.ref)i.ref=p;se(p,t,u),t.seen.get(p).isParent=!0}}let c=t.metadataRegistry.get(e);if(c)Ur(i.schema,c);if(t.io==="input"&&fe(e))delete i.schema.examples,delete i.schema.default;if(t.io==="input"&&"_prefault"in i.schema)(n=i.schema).default??(n.default=i.schema._prefault);return delete i.schema._prefault,t.seen.get(e).schema}function Ed(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function ki(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;let n=new Map;for(let i of e.seen.entries()){let a=e.metadataRegistry.get(i[0])?.id;if(a){let c=n.get(a);if(c&&c!==i[0])throw Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(a,i[0])}}let o=(i)=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let p=e.external.registry.get(i[0])?.id,d=e.external.uri??((h)=>h);if(p)return{ref:d(p)};let m=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=m,{defId:m,ref:`${d("__shared")}#/${a}/${Ed(m)}`}}let c="#",l=`${c}/${a}/`;if(i[1]===r&&!i[1].schema.id)return{ref:c};let u=i[1].schema.id??`__schema${e.counter++}`;return{defId:u,ref:l+Ed(u)}},s=(i)=>{if(i[1].schema.$ref)return;let a=i[1],{ref:c,defId:l}=o(i);if(a.def={...a.schema},l)a.defId=l;let u=a.schema;for(let p in u)delete u[p];u.$ref=c};if(e.cycles==="throw")for(let i of e.seen.entries()){let a=i[1];if(a.cycle)throw Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
91
+ `)}return b.write("payload.value = newResult;"),b.write("return payload;"),b.compile()},i,a=Kr,c=!Pe.jitless,u=c&&Ru.value,p=t.catchall,d;e._zod.parse=(m,h)=>{d??(d=n.value);let y=m.value;if(!a(y))return m.issues.push({expected:"object",code:"invalid_type",input:y,inst:e}),m;if(c&&u&&h?.async===!1&&h.jitless!==!0){if(!i)i=s(t.shape);if(m=i(m,h),!p)return m;return Id([],y,m,h,d,e,h?.abortEarly===!0)}return r(m,h)}});function Gp(e,t,r,n){for(let s of e)if(s.issues.length===0)return t.value=s.value,t;let o=e.filter((s)=>!We(s));if(o.length===1)return t.value=o[0].value,o[0];return t.issues.push({code:"invalid_union",input:t.value,inst:r,errors:e.map((s)=>s.issues.map((i)=>Je(i,n,Ce())))}),t}var zd=g("$ZodUnion",(e,t)=>{X.init(e,t),K(e,"optin",(n)=>n.def.options.some((o)=>o._zod.optin==="defaulted")?"defaulted":n.def.options.some((o)=>o._zod.optin!==void 0)?"optional":void 0),K(e,"optout",(n)=>n.def.options.some((o)=>o._zod.optout==="optional")?"optional":void 0),K(e,"values",(n)=>{if(n.def.options.every((o)=>o._zod.values))return new Set(n.def.options.flatMap((o)=>Array.from(o._zod.values)));return}),K(e,"pattern",(n)=>{if(n.def.options.every((o)=>o._zod.pattern)){let o=n.def.options.map((s)=>s._zod.pattern);return new RegExp(`^(${o.map((s)=>eo(s.source)).join("|")})$`)}return});let r=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(n,o)=>{if(r)return r(n,o);let s=!1,i=[];for(let a of t.options){let c=a._zod.run({value:n.value,issues:[]},o);if(c instanceof Promise)i.push(c),s=!0;else{if(c.issues.length===0)return c;i.push(c)}}if(!s)return Gp(i,n,e,o);return Promise.all(i).then((a)=>Gp(a,n,e,o))}});var Od=g("$ZodIntersection",(e,t)=>{X.init(e,t),e._zod.parse=(r,n)=>{let o=r.value,s=t.left._zod.run({value:o,issues:[]},n),i=t.right._zod.run({value:o,issues:[]},n);if(s instanceof Promise||i instanceof Promise)return Promise.all([s,i]).then(([c,l])=>Kp(r,c,l));return Kp(r,s,i)}});function Oi(e,t){if(e===t)return{valid:!0,data:e};if(e instanceof Date&&t instanceof Date&&+e===+t)return{valid:!0,data:e};if(Zt(e)&&Zt(t)){let r=Object.keys(t),n=Object.keys(e).filter((s)=>r.indexOf(s)!==-1),o={...e,...t};if(Object.prototype.hasOwnProperty.call(o,"__proto__"))delete o.__proto__;for(let s of n){if(s==="__proto__")continue;let i=Oi(e[s],t[s]);if(!i.valid)return{valid:!1,mergeErrorPath:[s,...i.mergeErrorPath]};o[s]=i.data}return{valid:!0,data:o}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let r=[];for(let n=0;n<e.length;n++){let o=e[n],s=t[n],i=Oi(o,s);if(!i.valid)return{valid:!1,mergeErrorPath:[n,...i.mergeErrorPath]};r.push(i.data)}return{valid:!0,data:r}}return{valid:!1,mergeErrorPath:[]}}function Kp(e,t,r){let n=new Map,o,s=new Map,i=(l,u)=>{let p;if(l.code==="unrecognized_keys"&&!l.path?.length)o??(o=l),p=l.keys;else if(l.code==="invalid_key"&&l.origin==="record"&&l.path?.length===1){let d=String(l.path[0]);if(!s.has(d))s.set(d,l);p=[d]}else return!1;for(let d of p){if(!n.has(d))n.set(d,{});n.get(d)[u]=!0}return!0};for(let l of t.issues)if(!i(l,"l"))e.issues.push(l);for(let l of r.issues)if(!i(l,"r"))e.issues.push(l);let a=[...n].filter(([,l])=>l.l&&l.r).map(([l])=>l);if(a.length){let l=o?a.filter((u)=>o.keys.includes(u)):[];if(l.length)e.issues.push({...o,keys:l});for(let u of a)if(!l.includes(u)&&s.has(u))e.issues.push(s.get(u))}let c=Oi(t.value,r.value);if(!c.valid){if(We(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}var Ld=g("$ZodRecord",(e,t)=>{X.init(e,t);let r=Pe.memoizer;r?.attach(e),e._zod.parse=(n,o)=>{let s=n.value;if(!Zt(s))return n.issues.push({expected:"record",code:"invalid_type",input:s,inst:e}),n;let i=[],a=t.keyType._zod.values;if(a&&!t.partial){n.value=r?r.alloc(e,n,{},o):{};let c=new Set;for(let u of a)if(typeof u==="string"||typeof u==="number"||typeof u==="symbol"){if(c.add(typeof u==="number"?u.toString():u),u==="__proto__")continue;let p=t.keyType._zod.run({value:u,issues:[]},o);if(p instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(p.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:p.issues.map((h)=>Je(h,o,Ce())),input:u,path:[u],inst:e});continue}let d=p.value;if(d==="__proto__")continue;let m=t.valueType._zod.run({value:s[u],issues:[]},o);if(m instanceof Promise)i.push(m.then((h)=>{if(h.issues.length)n.issues.push(...xt(u,h.issues));n.value[d]=h.value}));else{if(m.issues.length)n.issues.push(...xt(u,m.issues));n.value[d]=m.value}}let l;for(let u in s)if(!c.has(u))if(t.mode==="loose"){if(u==="__proto__")continue;n.value[u]=s[u]}else l=l??[],l.push(u);if(l&&l.length>0)n.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:l,continue:!0})}else{n.value=r?r.alloc(e,n,{},o):{};let c;for(let l of Reflect.ownKeys(s)){if(l==="__proto__")continue;if(!Object.prototype.propertyIsEnumerable.call(s,l))continue;let u=t.keyType._zod.run({value:l,issues:[]},o);if(u instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(typeof l==="string"&&qr.test(l)&&u.issues.length){let h=t.keyType._zod.run({value:Number(l),issues:[]},o);if(h instanceof Promise)throw Error("Async schemas not supported in object keys currently");if(h.issues.length===0)u=h}if(u.issues.length){if(t.mode==="loose")n.value[l]=s[l];else if(a)c=c??[],c.push(l);else n.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map((h)=>Je(h,o,Ce())),input:l,path:[l],inst:e});continue}let d=u.value;if(d==="__proto__")continue;let m=t.valueType._zod.run({value:s[l],issues:[]},o);if(m instanceof Promise)i.push(m.then((h)=>{if(h.issues.length)n.issues.push(...xt(l,h.issues));n.value[d]=h.value}));else{if(m.issues.length)n.issues.push(...xt(l,m.issues));n.value[d]=m.value}}if(c&&c.length>0)n.issues.push({code:"unrecognized_keys",input:s,inst:e,keys:c,continue:!0})}if(i.length)return Promise.all(i).then(()=>n);return n}});var Dd=g("$ZodEnum",(e,t)=>{X.init(e,t);let r=Vr(t.entries),n=new Set(r);e._zod.values=n,K(e,"pattern",(o)=>{let s=Vr(o.def.entries).filter((i)=>Iu.has(typeof i));return new RegExp(s.length?`^(${s.map((i)=>ir(i.toString())).join("|")})$`:"^[^\\s\\S]$")}),e._zod.parse=(o,s)=>{let i=o.value;if(n.has(i))return o;return o.issues.push({code:"invalid_value",values:r,input:i,inst:e}),o}});var Nd=g("$ZodTransform",(e,t)=>{X.init(e,t),e._zod.optin="optional",Pe.memoizer?.guard(e),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Jr(e.constructor.name);let o=t.transform(r.value,r);if(n.async)return(o instanceof Promise?o:Promise.resolve(o)).then((i)=>(r.value=i,r));if(o instanceof Promise)throw new He;return r.value=o,r}});function Vp(e,t){return e.value=t.issues.length?void 0:t.value,e}var Zi=g("$ZodOptional",(e,t)=>{X.init(e,t),K(e,"optin",(r)=>r.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),e._zod.optout="optional",K(e,"values",(r)=>{let n=r.def.innerType._zod.values;return n?new Set([...n,void 0]):void 0}),K(e,"pattern",(r)=>{let n=r.def.innerType._zod.pattern;return n?new RegExp(`^(${eo(n.source)})?$`):void 0}),e._zod.parse=(r,n)=>{if(r.value===void 0){if(t.innerType._zod.optin!=="defaulted")return r;let o=t.innerType._zod.run({value:r.value,issues:[]},n);if(o instanceof Promise)return o.then((s)=>Vp(r,s));return Vp(r,o)}return t.innerType._zod.run(r,n)}}),Zd=g("$ZodExactOptional",(e,t)=>{Zi.init(e,t),K(e,"values",(r)=>r.def.innerType._zod.values),K(e,"pattern",(r)=>r.def.innerType._zod.pattern),e._zod.parse=(r,n)=>t.innerType._zod.run(r,n)}),Ud=g("$ZodNullable",(e,t)=>{X.init(e,t),K(e,"optin",(r)=>r.def.innerType._zod.optin),K(e,"optout",(r)=>r.def.innerType._zod.optout),K(e,"pattern",(r)=>{let n=r.def.innerType._zod.pattern;return n?new RegExp(`^(${eo(n.source)}|null)$`):void 0}),K(e,"values",(r)=>r.def.innerType._zod.values?new Set([...r.def.innerType._zod.values,null]):void 0),e._zod.parse=(r,n)=>{if(r.value===null)return r;return t.innerType._zod.run(r,n)}}),Fd=g("$ZodDefault",(e,t)=>{X.init(e,t),e._zod.optin="defaulted",K(e,"values",(r)=>r.def.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)return r.value=t.defaultValue,r;let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then((s)=>Wp(s,t));return Wp(o,t)}});function Wp(e,t){if(e.value===void 0)e.value=t.defaultValue;return e}var Md=g("$ZodPrefault",(e,t)=>{X.init(e,t),e._zod.optin="defaulted",K(e,"values",(r)=>r.def.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);if(r.value===void 0)r.value=t.defaultValue;return t.innerType._zod.run(r,n)}}),Bd=g("$ZodNonOptional",(e,t)=>{X.init(e,t),K(e,"values",(r)=>{let n=r.def.innerType._zod.values;return n?new Set([...n].filter((o)=>o!==void 0)):void 0}),e._zod.parse=(r,n)=>{let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then((s)=>Jp(s,e));return Jp(o,e)}});function Jp(e,t){if(!e.issues.length&&e.value===void 0)e.issues.push({code:"invalid_type",expected:"nonoptional",input:e.value,inst:t});return e}function Hp(e,t,r,n){if(!t.issues.length){if(e.value=t.value,t.memo)e.memo=!0;return e}return e.value=r.catchValue({...t,value:e.value,error:{issues:t.issues.map((o)=>Je(o,n,Ce()))},input:e.value}),e}var Gd=g("$ZodCatch",(e,t)=>{X.init(e,t),K(e,"optin",(r)=>r.def.innerType._zod.optin==="defaulted"?"defaulted":"optional"),K(e,"optout",(r)=>r.def.innerType._zod.optout),K(e,"values",(r)=>r.def.innerType._zod.values),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run({value:r.value,issues:[]},n);if(o instanceof Promise)return o.then((s)=>Hp(r,s,t,n));return Hp(r,o,t,n)}});var Kd=g("$ZodPipe",(e,t)=>{X.init(e,t),K(e,"values",(r)=>r.def.in._zod.values),K(e,"optin",(r)=>r.def.in._zod.optin),K(e,"optout",(r)=>r.def.out._zod.optout),K(e,"propValues",(r)=>r.def.in._zod.propValues),e._zod.parse=(r,n)=>{if(n.direction==="backward"){let s=t.out._zod.run(r,n);if(s instanceof Promise)return s.then((i)=>fo(i,t.in,n));return fo(s,t.in,n)}let o=t.in._zod.run(r,n);if(o instanceof Promise)return o.then((s)=>fo(s,t.out,n));return fo(o,t.out,n)}});function fo(e,t,r){if(e.issues.some((n)=>n.code!=="unrecognized_keys"))return e.aborted=!0,e;return t._zod.run({value:e.value,issues:e.issues},r)}var Vd=g("$ZodReadonly",(e,t)=>{X.init(e,t),K(e,"propValues",(r)=>r.def.innerType._zod.propValues),K(e,"values",(r)=>r.def.innerType._zod.values),K(e,"optin",(r)=>r.def.innerType?._zod?.optin),K(e,"optout",(r)=>r.def.innerType?._zod?.optout),e._zod.parse=(r,n)=>{if(n.direction==="backward")return t.innerType._zod.run(r,n);let o=t.innerType._zod.run(r,n);if(o instanceof Promise)return o.then(qp);return qp(o)}});function qp(e){if(!e.memo)e.value=Object.freeze(e.value);return e}var Wd=g("$ZodCustom",(e,t)=>{he.init(e,t),X.init(e,t),e._zod.parse=(r,n)=>r,e._zod.check=(r)=>{let n=r.value,o=t.fn(n);if(o instanceof Promise)return o.then((s)=>Yp(s,r,n,e));Yp(o,r,n,e);return}});function Yp(e,t,r,n){if(!e){let o={code:"custom",input:r,inst:n,path:[...n._zod.def.path??[]],continue:!n._zod.def.abort};if(n._zod.def.params)o.params=n._zod.def.params;t.issues.push(Ut(o))}}class Hd extends Error{constructor(){super("Cannot parse a reference cycle that closes through a transform");this.name="ZodCyclicError"}}var Fi="~memo",Jd=[];function qd(e){return e!==null&&typeof e==="object"}function Ui(e){return e.map((t)=>t.path?{...t,path:t.path.slice()}:{...t})}var Yd=new WeakMap,Xr=0,vo=1,Qr=2;function _o(e,t,r){let n=Yd.get(e);if(n!==void 0)return n?Qr:Xr;if(t.has(e))return Qr;t.add(e);let o=Xr,s=(u)=>{if(o!==Qr&&u?._zod){let p=_o(u,t,r);if(p>o)o=p}},i=(u,p)=>{let d=Xr;for(let m of Reflect.ownKeys(u)){let h=Object.getOwnPropertyDescriptor(u,m);if(p&&!h.enumerable)continue;let y=h.get?vo:h.value?._zod?_o(h.value,t,r):Xr;if(y>d)d=y}return d},a=(u)=>{if(u>o)o=u},c=e._zod.def,l=c.type;switch(l){case"object":{let u=to(c);a(u?i(u,!0):vo),s(c.catchall);break}case"array":s(c.element);break;case"tuple":for(let u of c.items)s(u);s(c.rest);break;case"record":case"map":s(c.keyType),s(c.valueType);break;case"set":s(c.valueType);break;case"union":for(let u of c.options)s(u);break;case"intersection":s(c.left),s(c.right);break;case"optional":case"nullable":case"default":case"prefault":case"catch":case"readonly":case"nonoptional":case"promise":case"success":s(c.innerType);break;case"pipe":s(c.in),s(c.out);break;case"function":s(c.input),s(c.output);break;case"lazy":{let u=c._cachedInner??(r?e._zod.innerType:void 0);a(u?_o(u,t,!1):vo);break}case"template_literal":case"string":case"number":case"int":case"boolean":case"bigint":case"symbol":case"undefined":case"null":case"void":case"never":case"any":case"unknown":case"date":case"nan":case"enum":case"literal":case"file":case"transform":case"custom":break;default:for(let u in c){let p=Object.getOwnPropertyDescriptor(c,u);if(!p||p.get)continue;let d=p.value;if(!d||typeof d!=="object")continue;if(d._zod)s(d);else if(Array.isArray(d))for(let m of d)s(m)}}return t.delete(e),fv(e,o)}function fv(e,t){if(t!==vo)Yd.set(e,t===Qr);return t}function hv(e,t){let r=e.buckets.get(t);if(!r)r=new WeakMap,e.buckets.set(t,r);return r}var xo,wo=[],gv={alloc(e,t,r){let n=xo;if(!n)return r;xo=void 0;let o={value:r,issues:null};return n.set(t.value,o),wo.push(o),r},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let r=e._zod.parse,n=(o,s)=>{if(s.direction!=="backward"&&yv(s,o.value))throw new Hd;return r(o,s)};if(e._zod.parse=n,e._zod.run===r)e._zod.run=n})},attach(e){var t;let r,n=!1,o,s;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let i=e._zod.parse,a=(c,l)=>{if(r===void 0){let v=_o(e,new Set,!1);if(v===Xr){if(e._zod.parse=i,e._zod.run===a)e._zod.run=i;return i(c,l)}if(v===Qr||n)r=!0;else n=!0}let u=c.value;if(!qd(u))return i(c,l);let p=l[Fi];if(!p)p={buckets:new WeakMap,backEdges:void 0},l[Fi]=p;let d;if(o===l)d=s;else d=hv(p,e),o=l,s=d;let m=d.get(u);if(m){if(c.value=m.value,m.issues){if(m.issues.length)c.issues.push(...Ui(m.issues))}else c.memo=!0,p.backEdges??(p.backEdges=new WeakSet),p.backEdges.add(m.value);return c}xo=d;let h=wo.length,y=i(c,l);xo=void 0;let b=wo.length>h?wo.pop():void 0;if(y instanceof Promise)return y.then((v)=>{if(b)b.issues=v.issues.length?Ui(v.issues):Jd;return v});if(b)b.issues=y.issues.length?Ui(y.issues):Jd;return y};if(e._zod.parse=a,e._zod.run===i)e._zod.run=a})}};function Mi(){return gv}function yv(e,t){let r=e[Fi]?.backEdges;return r!==void 0&&qd(t)&&r.has(t)}var bv=()=>{let e={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function t(s){return e[s]??null}let r={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",currency_code:"currency code",credit_card:"credit card number",iban:"IBAN",jwt:"JWT",template_literal:"input"},n={nan:"NaN"};function o(s,i){if(s==="number"&&typeof i==="number"&&!Number.isFinite(i))return String(i);return n[s]??s}return(s)=>{switch(s.code){case"invalid_type":{let i=o(s.expected),a=Du(s.input),c=o(a,s.input);return`Invalid input: expected ${i}, received ${c}`}case"invalid_value":if(s.values.length===1)return`Invalid input: expected ${bi(s.values[0])}`;return`Invalid option: expected one of ${hi(s.values,"|")}`;case"too_big":{let i=s.exact?"exactly ":s.inclusive?"<=":"<",a=t(s.origin);if(a)return`Too big: expected ${s.origin??"value"} to have ${i}${s.maximum.toString()} ${a.unit??"elements"}`;return`Too big: expected ${s.origin??"value"} to be ${i}${s.maximum.toString()}`}case"too_small":{let i=s.exact?"exactly ":s.inclusive?">=":">",a=t(s.origin);if(a)return`Too small: expected ${s.origin} to have ${i}${s.minimum.toString()} ${a.unit}`;return`Too small: expected ${s.origin} to be ${i}${s.minimum.toString()}`}case"invalid_format":{let i=s;if(i.format==="starts_with")return`Invalid string: must start with "${i.prefix}"`;if(i.format==="ends_with")return`Invalid string: must end with "${i.suffix}"`;if(i.format==="includes")return`Invalid string: must include "${i.includes}"`;if(i.format==="regex")return`Invalid string: must match pattern ${i.pattern}`;return`Invalid ${r[i.format]??s.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${s.divisor}`;case"unrecognized_keys":return`Unrecognized key${s.keys.length>1?"s":""}: ${hi(s.keys,", ")}`;case"invalid_key":return`Invalid key in ${s.origin}`;case"invalid_union":if(s.options&&Array.isArray(s.options)&&s.options.length>0)return`Invalid discriminator value. Expected ${s.options.map((a)=>`'${a}'`).join(" | ")}`;if(s.inclusive===!1)return"Invalid input: more than one option matched";return"Invalid input";case"invalid_element":return`Invalid value in ${s.origin}`;default:return"Invalid input"}}};function Bi(){return{localeError:bv()}}var Xd;class Qd{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let r=t[0];if(this._map.set(e,r),r&&typeof r==="object"&&"id"in r)this._idmap.set(r.id,e);return this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);if(t&&typeof t==="object"&&"id"in t)this._idmap.delete(t.id);return this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let r={...this.get(t)??{}};delete r.id;let n={...r,...this._map.get(e)};return Object.keys(n).length?n:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function em(){return new Qd}(Xd=globalThis).__zod_globalRegistry??(Xd.__zod_globalRegistry=em());var wt=globalThis.__zod_globalRegistry;function tm(e){if(e.checks)e.checks=[...e.checks];return e}function rm(e,t){return new e(tm({type:"string",...A(t)}))}function nm(e,t){return new e({type:"string",format:"email",check:"string_format",abort:!1,...A(t)})}function om(e,t){return new e({type:"string",format:"guid",check:"string_format",abort:!1,...A(t)})}function sm(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,...A(t)})}function im(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...A(t)})}function am(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...A(t)})}function cm(e,t){return new e({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...A(t)})}function Gi(e,t){return new e({type:"string",format:"url",check:"string_format",abort:!1,...A(t)})}function lm(e,t){return new e({type:"string",format:"emoji",check:"string_format",abort:!1,...A(t)})}function um(e,t){return new e({type:"string",format:"nanoid",check:"string_format",abort:!1,...A(t)})}function pm(e,t){return new e({type:"string",format:"cuid",check:"string_format",abort:!1,...A(t)})}function dm(e,t){return new e({type:"string",format:"cuid2",check:"string_format",abort:!1,...A(t)})}function mm(e,t){return new e({type:"string",format:"ulid",check:"string_format",abort:!1,...A(t)})}function fm(e,t){return new e({type:"string",format:"xid",check:"string_format",abort:!1,...A(t)})}function hm(e,t){return new e({type:"string",format:"ksuid",check:"string_format",abort:!1,...A(t)})}function gm(e,t){return new e({type:"string",format:"ipv4",check:"string_format",abort:!1,...A(t)})}function ym(e,t){return new e({type:"string",format:"ipv6",check:"string_format",abort:!1,...A(t)})}function bm(e,t){return new e({type:"string",format:"cidrv4",check:"string_format",abort:!1,...A(t)})}function xm(e,t){return new e({type:"string",format:"cidrv6",check:"string_format",abort:!1,...A(t)})}function wm(e,t){return new e({type:"string",format:"base64",check:"string_format",abort:!1,...A(t)})}function vm(e,t){return new e({type:"string",format:"base64url",check:"string_format",abort:!1,...A(t)})}function _m(e,t){return new e({type:"string",format:"e164",check:"string_format",abort:!1,...A(t)})}function Sm(e,t){return new e({type:"string",format:"jwt",check:"string_format",abort:!1,...A(t)})}function So(e,t){return new e({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...A(t)})}function $o(e,t){return new e({type:"string",format:"date",check:"string_format",...A(t)})}function ko(e,t){return new e({type:"string",format:"time",check:"string_format",precision:null,...A(t)})}function Po(e,t){return new e({type:"string",format:"duration",check:"string_format",...A(t)})}function $m(e,t){return new e(tm({type:"number",checks:[],...A(t)}))}function km(e,t){return new e({type:"number",check:"number_format",abort:!1,format:"safeint",...A(t)})}function Pm(e,t){return new e({type:"boolean",...A(t)})}function Cm(e){return new e({type:"unknown"})}function Em(e,t){return new e({type:"never",...A(t)})}function Co(e,t){return new Ii({check:"less_than",...A(t),value:e,inclusive:!1})}function en(e,t){return new Ii({check:"less_than",...A(t),value:e,inclusive:!0})}function Eo(e,t){return new Ti({check:"greater_than",...A(t),value:e,inclusive:!1})}function tn(e,t){return new Ti({check:"greater_than",...A(t),value:e,inclusive:!0})}function jo(e,t){return new Ep({check:"multiple_of",...A(t),value:e})}function Ao(e,t){return new Ap({check:"max_length",...A(t),maximum:e})}function cr(e,t){return new Rp({check:"min_length",...A(t),minimum:e})}function Ro(e,t){return new Ip({check:"length_equals",...A(t),length:e})}function Ki(e,t){return new Tp({check:"string_format",format:"regex",...A(t),pattern:e})}function Vi(e){return new zp({check:"string_format",format:"lowercase",...A(e)})}function Wi(e){return new Op({check:"string_format",format:"uppercase",...A(e)})}function Ji(e,t){return new Lp({check:"string_format",format:"includes",...A(t),includes:e})}function Hi(e,t){return new Dp({check:"string_format",format:"starts_with",...A(t),prefix:e})}function qi(e,t){return new Np({check:"string_format",format:"ends_with",...A(t),suffix:e})}function vt(e){return new Zp({check:"overwrite",tx:e})}function Yi(e){return vt((t)=>t.normalize(e))}function Xi(){return vt((e)=>e.trim())}function Qi(){return vt((e)=>e.toLowerCase())}function ea(){return vt((e)=>e.toUpperCase())}function ta(){return vt((e)=>Au(e))}function jm(e,t,r){return new e({type:"array",element:t,...A(r)})}function Am(e,t,r){return new e({type:"custom",check:"custom",fn:t,...A(r)})}function Rm(e,t){let r=xv((n)=>(n.addIssue=(o)=>{if(typeof o==="string")n.issues.push(Ut(o,n.value,r._zod.def));else{let s=o;if(s.fatal)s.continue=!1;if(s.code??(s.code="custom"),!("input"in s))s.input=n.value;s.inst??(s.inst=r),s.continue??(s.continue=!r._zod.def.abort),n.issues.push(Ut(s))}},e(n.value,n)),t);return r}function xv(e,t){let r=new he({check:"custom",...A(t)});return r._zod.check=e,r}function rn(e,...t){for(let r of t)for(let n of Reflect.ownKeys(r))if(Object.prototype.propertyIsEnumerable.call(r,n))Fe(e,n,r[n]);return e}function na(e){let t=e?.target??"draft-2020-12";if(t==="draft-4")t="draft-04";if(t==="draft-7")t="draft-07";return{processors:e.processors??{},metadataRegistry:e?.metadata??wt,target:t,unrepresentable:e?.unrepresentable??"throw",override:e?.override??(()=>{}),io:e?.io??"output",counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??"ref",reused:e?.reused??"inline",intersections:[],deferred:[],external:e?.external??void 0}}function Ft(e,t,r,n,o){let s=typeof t.unrepresentable==="function"?t.unrepresentable({zodSchema:e,path:n.path,message:o}):t.unrepresentable;if(s==="any")return!1;if(s===void 0||s==="throw")throw Error(o);return Object.assign(r,s),!0}function ie(e,t,r={path:[],schemaPath:[]}){var n;let o=e._zod.def,s=t.seen.get(e);if(s){if(s.count++,r.schemaPath.includes(e))s.cycle=r.path;return s.schema}let i={schema:{},count:1,cycle:void 0,path:r.path};t.seen.set(e,i),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let a=e._zod.toJSONSchema?.();if(a)i.schema=a;else{let u={...r,schemaPath:[...r.schemaPath,e],path:r.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,i.schema,u);else{let d=i.schema,m=t.processors[o.type];if(!m)throw Error(`[toJSONSchema]: Non-representable type encountered: ${o.type}`);m(e,t,d,u)}let p=e._zod.parent;if(p){if(!i.ref)i.ref=p;ie(p,t,u),t.seen.get(p).isParent=!0}}let c=t.metadataRegistry.get(e);if(c)rn(i.schema,c);if(t.io==="input"&&we(e))delete i.schema.examples,delete i.schema.default;if(t.io==="input"&&"_prefault"in i.schema)(n=i.schema).default??(n.default=i.schema._prefault);return delete i.schema._prefault,t.seen.get(e).schema}function Im(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}function oa(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");if(e.external&&e.sharedDefsExtractedFor===e.external)return;let n=new Map;for(let i of e.seen.entries()){let a=e.metadataRegistry.get(i[0])?.id;if(a){let c=n.get(a);if(c&&c!==i[0])throw Error(`Duplicate schema id "${a}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);n.set(a,i[0])}}let o=(i)=>{let a=e.target==="draft-2020-12"?"$defs":"definitions";if(e.external){let p=e.external.registry.get(i[0])?.id,d=e.external.uri??((h)=>h);if(p)return{ref:d(p)};let m=i[1].defId??i[1].schema.id??`schema${e.counter++}`;return i[1].defId=m,{defId:m,ref:`${d("__shared")}#/${a}/${Im(m)}`}}let c="#",l=`${c}/${a}/`;if(i[1]===r&&!i[1].schema.id)return{ref:c};let u=i[1].schema.id??`__schema${e.counter++}`;return{defId:u,ref:l+Im(u)}},s=(i)=>{if(i[1].schema.$ref)return;let a=i[1],{ref:c,defId:l}=o(i);if(a.def={...a.schema},l)a.defId=l;let u=a.schema;for(let p in u)delete u[p];u.$ref=c};if(e.cycles==="throw")for(let i of e.seen.entries()){let a=i[1];if(a.cycle)throw Error(`Cycle detected: #/${a.cycle?.join("/")}/<root>
88
92
 
89
- Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of e.seen.entries()){let a=i[1];if(t===i[0]){s(i);continue}if(e.external){let l=e.external.registry.get(i[0])?.id;if(t!==i[0]&&l){s(i);continue}}if(e.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1){if(e.reused==="ref")s(i)}}if(e.external)e.sharedDefsExtractedFor=e.external}function Td(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let r=[];for(let n of t){if(!n||typeof n!=="object")return;Td(n);let o=Object.keys(n);if(o.length!==1||o[0]!=="type")return;let s=n.type;for(let i of Array.isArray(s)?s:[s]){if(typeof i!=="string")return;if(!r.includes(i))r.push(i)}}delete e.anyOf,e.type=r.length===1?r[0]:r}var Ad=new Set(["type","properties","required","additionalProperties"]),zd=["oneOf","anyOf"];function Id(e){let t=e.additionalProperties;if(t===void 0||t===!1||typeof t!=="object"||t===null)return null;return Object.keys(t).length?t:null}function $i(e){let t=[];for(let s of e){if(typeof s!=="object"||s.type!=="object")return null;for(let i in s)if(!Ad.has(i))return null;t.push(s)}let r={},n=new Set;for(let s of t){for(let i in s.properties){if(Object.prototype.hasOwnProperty.call(r,i))continue;let a=[];for(let l of t){let u=l.properties?.[i]??Id(l);if(u===null||u===void 0)continue;if(!a.some((p)=>JSON.stringify(p)===JSON.stringify(u)))a.push(u)}let c=a.length===1?a[0]:$i(a)??{allOf:a};Ne(r,i,c)}for(let i of s.required??[])n.add(i)}let o={type:"object",properties:r};if(n.size)o.required=[...n];if(t.every((s)=>s.additionalProperties===!1))o.additionalProperties=!1;else{let s=[];for(let i of t){let a=Id(i);if(a&&!s.some((c)=>JSON.stringify(c)===JSON.stringify(a)))s.push(a)}if(s.length===1)o.additionalProperties=s[0];else if(s.length>1)o.additionalProperties={allOf:s}}return o}function Ex(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let o of Ad)if(o in e)return;let r=t.filter((o)=>zd.some((s)=>Array.isArray(o[s]))),n=null;if(!r.length)n=$i(t);else{let o=r[0],s=zd.find((c)=>Array.isArray(o[c]));if(Object.keys(o).length!==1)return;let i=t.filter((c)=>c!==o),a=o[s].map((c)=>$i([...i,c]));if(a.some((c)=>!c))return;n={[s]:a}}if(!n)return;delete e.allOf,Ur(e,n)}function Pi(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let n=(a)=>{let c=e.seen.get(a);if(c.ref===null)return;let l=c.def??c.schema,u={...l},p=c.ref;if(c.ref=null,p){n(p);let m=e.seen.get(p),h=m.schema;if(h.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))l.allOf=l.allOf??[],l.allOf.push(h);else Ur(l,h);if(Ur(l,u),a._zod.parent===p)for(let b in l){if(b==="$ref"||b==="allOf")continue;if(!(b in u))delete l[b]}if(h.$ref&&m.def)for(let b in l){if(b==="$ref"||b==="allOf")continue;if(b in m.def&&JSON.stringify(l[b])===JSON.stringify(m.def[b]))delete l[b]}}let d=a._zod.parent;if(d&&d!==p){n(d);let m=e.seen.get(d);if(m?.schema.$ref){if(l.$ref=m.schema.$ref,m.def)for(let h in l){if(h==="$ref"||h==="allOf")continue;if(h in m.def&&JSON.stringify(l[h])===JSON.stringify(m.def[h]))delete l[h]}}}e.override({zodSchema:a,jsonSchema:l,path:c.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let a of[...e.seen.entries()].reverse())n(a[0]);if(e.target!=="openapi-3.0")for(let a of e.seen.entries())Td(a[1].def??a[1].schema);for(let a of e.deferred)a();if(e.intersections.length){let a=new Map;for(let c of e.seen.values())for(let l of[c.schema,c.def]){let u=l?.allOf;if(!Array.isArray(u))continue;let p=a.get(u);if(p)p.push(l);else a.set(u,[l])}for(let c of e.intersections)for(let l of a.get(c)??[])Ex(l)}}let o={};if(e.target==="draft-2020-12")o.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")o.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")o.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw Error("Schema is missing an `id` property");o.$id=e.external.uri(a)}Ur(o,r.defId?r.schema:r.def??r.schema);let s=e.metadataRegistry.get(t)?.id;if(s!==void 0&&o.id===s)delete o.id;let i=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let a of e.seen.entries()){let c=a[1];if(c.def&&c.defId){if(c.def.id===c.defId)delete c.def.id;Ne(i,c.defId,c.def)}}if(e.external)e.sharedEmitDoneFor=e.external;if(e.external);else if(Object.keys(i).length>0)if(e.target==="draft-2020-12")o.$defs=i;else o.definitions=i;try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:Fr(t,"input",e.processors),output:Fr(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function fe(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return fe(n.element,r);if(n.type==="set")return fe(n.valueType,r);if(n.type==="lazy")return fe(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault"||n.type==="catch")return fe(n.innerType,r);if(n.type==="intersection")return fe(n.left,r)||fe(n.right,r);if(n.type==="record"||n.type==="map")return fe(n.keyType,r)||fe(n.valueType,r);if(n.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return fe(n.in,r)||fe(n.out,r)}if(n.type==="object"){for(let o in n.shape)if(fe(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(fe(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(fe(o,r))return!0;if(n.rest&&fe(n.rest,r))return!0;return!1}return!1}var Rd=(e,t={})=>(r)=>{let n=Si({...r,processors:t});return se(e,n),ki(n,e),Pi(n,e)},Fr=(e,t,r={})=>(n)=>{let{libraryOptions:o,target:s}=n??{},i=Si({...o??{},target:s,io:t,processors:r});return se(e,i),ki(i,e),Pi(i,e)};var tr=(e,t,r)=>{if(e[t]===void 0||r>e[t])e[t]=r},rr=(e,t,r)=>{if(e[t]===void 0||r<e[t])e[t]=r},jd=(e,t)=>{tr(e,"minimum",t),rr(e,"maximum",t)},Nd=(e,t)=>{if(e.multipleOf??(e.multipleOf=[]),!e.multipleOf.includes(t))e.multipleOf.push(t)},Zd=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},Ud=(e,t)=>{e.mime=e.mime?e.mime.filter((r)=>t.includes(r)):[...t]},Fd=(e,t)=>{if(e.format=t,t.includes("int"))e.isInt=!0},Od=(e,t)=>tr(e,"minimum",t.minimum),Ld=(e,t)=>rr(e,"maximum",t.maximum),Dd=(e)=>(t,r)=>{Fd(t,r.format);let[n,o]=e[r.format];tr(t,"minimum",n),rr(t,"maximum",o)},zx={greater_than:(e,t)=>tr(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>rr(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>Nd(e,t.value),number_format:Dd(jn),bigint_format:Dd(Us),min_length:Od,max_length:Ld,length_equals:(e,t)=>jd(e,t.length),min_size:Od,max_size:Ld,size_equals:(e,t)=>jd(e,t.size),string_format:(e,t)=>{if(Fd(e,t.format),t.pattern)Zd(e,t.pattern);if(t.format==="base64"||t.format==="base64url")e.contentEncoding=t.format;if(t.local||t.precision===-1)e.laxFormat=!0},mime_type:(e,t)=>Ud(e,t.mime)};function Ie(e){let t={},r=e._zod.def,n=e._zod.traits.has("$ZodCheck")?[e,...r.checks??[]]:r.checks??[];for(let s of n)zx[s._zod.def.check]?.(t,s._zod.def);let o=e._zod.bag;if(o.minimum!==void 0)tr(t,"minimum",o.minimum);if(o.exclusiveMinimum!==void 0)tr(t,"exclusiveMinimum",o.exclusiveMinimum);if(o.maximum!==void 0)rr(t,"maximum",o.maximum);if(o.exclusiveMaximum!==void 0)rr(t,"exclusiveMaximum",o.exclusiveMaximum);if(o.multipleOf!==void 0)Nd(t,o.multipleOf);if(o.format!==void 0){if(t.format??(t.format=o.format),o.format.includes("int"))t.isInt=!0}if(o.mime)Ud(t,o.mime);for(let s of o.patterns??[])Zd(t,s);return t}var Ix={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Tx=new Map([[oi,du],[Hn,mu]]),Md=(e)=>Tx.get(e)??e,Bd=(e,t,r,n)=>{let o=r;o.type="string";let{minimum:s,maximum:i,format:a,patterns:c,contentEncoding:l,laxFormat:u}=Ie(e);if(typeof s==="number")o.minLength=s;if(typeof i==="number")o.maxLength=i;if(a){if(o.format=Ix[a]??a,o.format==="")delete o.format;if(a==="time"||u)delete o.format}if(l)o.contentEncoding=l;if(c&&c.size>0){let p=[...c].map(Md);if(p.length===1)o.pattern=p[0].source;else if(p.length>1)o.allOf=[...p.map((d)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))]}},Gd=(e,t,r,n)=>{let o=r,{minimum:s,maximum:i,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=Ie(e);o.type=u?"integer":"number";let p=typeof l==="number"&&l>=(s??Number.NEGATIVE_INFINITY),d=typeof c==="number"&&c<=(i??Number.POSITIVE_INFINITY),m=t.target==="draft-04"||t.target==="openapi-3.0";if(p)if(m)o.minimum=l,o.exclusiveMinimum=!0;else o.exclusiveMinimum=l;else if(typeof s==="number")o.minimum=s;if(d)if(m)o.maximum=c,o.exclusiveMaximum=!0;else o.exclusiveMaximum=c;else if(typeof i==="number")o.maximum=i;if(a){let h=new Set;for(let _ of a)if(Number.isFinite(_)&&_!==0)h.add(Math.abs(_));else Ot(e,t,o,n,`A multipleOf divisor of ${_} cannot be represented in JSON Schema`);let[y,...b]=h;if(y!==void 0)o.multipleOf=y;if(b.length)o.allOf=[...o.allOf??[],...b.map((_)=>({multipleOf:_}))]}},Kd=(e,t,r,n)=>{r.type="boolean"};var Vd=(e,t,r,n)=>{r.not={}};var Wd=(e,t,r,n)=>{};var Jd=(e,t,r,n)=>{let o=e._zod.def,s=Tr(o.entries);if(s.length===0){r.not={};return}if(s.every((i)=>typeof i==="number"))r.type="number";if(s.every((i)=>typeof i==="string"))r.type="string";r.enum=s};var Hd=(e,t,r,n)=>{Ot(e,t,r,n,"Custom types cannot be represented in JSON Schema")};var qd=(e,t,r,n)=>{Ot(e,t,r,n,"Transforms cannot be represented in JSON Schema")};var Yd=(e,t,r,n)=>{let o=r,s=e._zod.def,{minimum:i,maximum:a}=Ie(e);if(typeof i==="number")o.minItems=i;if(typeof a==="number")o.maxItems=a;o.type="array",o.items=se(s.element,t,{...n,path:[...n.path,"items"]})};function lo(e){let t=e._zod.def;if(t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform"))return lo(t.out);if(t.type==="catch")return lo(t.innerType);return e._zod.optin}var Xd=(e,t,r,n)=>{let o=r,s=e._zod.def,i=s.shape;if(Object.getOwnPropertySymbols(i).length&&Ot(e,t,o,n,"Symbol keys cannot be represented in JSON Schema"))return;o.type="object",o.properties={};for(let l in i)Ne(o.properties,l,se(i[l],t,{...n,path:[...n.path,"properties",l]}));let c=[];for(let l of Object.keys(i)){let u=s.shape[l];if(t.io==="input"?lo(u)===void 0:u._zod.optout===void 0)c.push(l)}if(c.length>0)o.required=c;if(s.catchall?._zod.def.type==="never")o.additionalProperties=!1;else if(!s.catchall){if(t.io==="output")o.additionalProperties=!1}else if(s.catchall)o.additionalProperties=se(s.catchall,t,{...n,path:[...n.path,"additionalProperties"]})},Qd=(e,t,r,n)=>{let o=e._zod.def,s=o.inclusive===!1,i=o.options.map((a,c)=>se(a,t,{...n,path:[...n.path,s?"oneOf":"anyOf",c]}));if(s)r.oneOf=i;else r.anyOf=i},em=(e,t,r,n)=>{let o=e._zod.def,s=se(o.left,t,{...n,path:[...n.path,"allOf",0]}),i=se(o.right,t,{...n,path:[...n.path,"allOf",1]}),a=(l)=>("allOf"in l)&&Object.keys(l).length===1,c=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];r.allOf=c,t.intersections.push(c)};function Ci(e,t,r){if(t.$ref){if(r.has(t))return t;r.add(t);let h=e.get(t)?.def;if(!h)return t;let y=Ci(e,h,r);return y===h?t:y}for(let h of["anyOf","oneOf"]){let y=t[h];if(!Array.isArray(y))continue;let b=y.map((_)=>Ci(e,_,r));if(b.some((_,P)=>_!==y[P]))t={...t,[h]:b}}let n=Array.isArray(t.type)?t.type:[t.type],o=!n.includes("string")&&n.some((h)=>h==="number"||h==="integer"),s=t.enum??(t.const!==void 0?[t.const]:void 0);if(!o&&!s?.some((h)=>typeof h==="number"))return t;let{minimum:i,maximum:a,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:p,id:d,...m}=t;if(m.enum)m.enum=m.enum.map((h)=>typeof h==="number"?String(h):h);else if(typeof m.const==="number")m.const=String(m.const);if(!o)return m;if(m.type="string",!s)m.pattern=(n.includes("number")?jr:Ys).source;return m}var Ei=new WeakMap;function Ax(e){let t=new Map;for(let n of e.seen.values())if(n.def&&!t.has(n.schema))t.set(n.schema,n);let r=new Map;for(let n of Ei.get(e)??[]){let o=e.seen.get(n),s=(o?.def??o?.schema)?.propertyNames;if(!s||s===!0||r.has(s))continue;let i=Ci(t,s,new Set);if(i!==s)r.set(s,i)}if(!r.size)return;for(let n of e.seen.values())for(let o of[n.schema,n.def]){let s=o&&r.get(o.propertyNames);if(s)o.propertyNames=s}}var tm=(e,t,r,n)=>{let o=r,s=e._zod.def;o.type="object";let i=s.keyType,a=Ie(i).patterns;if(s.mode==="loose"&&a&&a.size>0){let u=se(s.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});o.patternProperties={};for(let p of a)Ne(o.patternProperties,Md(p).source,u)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){o.propertyNames=se(s.keyType,t,{...n,path:[...n.path,"propertyNames"]});let u=Ei.get(t);if(!u)u=[],Ei.set(t,u),t.deferred.push(()=>Ax(t));u.push(e)}o.additionalProperties=se(s.valueType,t,{...n,path:[...n.path,"additionalProperties"]})}let c=i._zod.values,l=t.io==="input"&&lo(s.valueType)!==void 0;if(c&&!s.partial&&!l){let u=[...c].filter((p)=>typeof p==="string"||typeof p==="number");if(u.length>0)o.required=u.map(String)}},rm=(e,t,r,n)=>{let o=e._zod.def,s=se(o.innerType,t,n),i=t.seen.get(e);if(t.target==="openapi-3.0")i.ref=o.innerType,r.nullable=!0;else r.anyOf=[s,{type:"null"}]},nm=(e,t,r,n)=>{let o=e._zod.def;se(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType},zi=Symbol();function om(e,t,r,n,o){let s=!1,i=JSON.stringify(e,(a,c)=>{if(typeof c!=="bigint")return c;return s=!0,null});if(!s)return JSON.parse(i);return Ot(t,r,n,o,"BigInt defaults cannot be represented in JSON Schema"),zi}var sm=(e,t,r,n)=>{let o=e._zod.def;se(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType;let i=om(o.defaultValue,e,t,r,n);if(i!==zi)r.default=i},im=(e,t,r,n)=>{let o=e._zod.def;se(o.innerType,t,n);let s=t.seen.get(e);if(s.ref=o.innerType,t.io!=="input")return;let i=om(o.defaultValue,e,t,r,n);if(i!==zi)r._prefault=i},am=(e,t,r,n)=>{let o=e._zod.def;se(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{Ot(e,t,r,n,"Dynamic catch values are not supported in JSON Schema");return}r.default=i},cm=(e,t,r,n)=>{let o=e._zod.def,s=o.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?s?o.out:o.in:o.out;se(i,t,n);let a=t.seen.get(e);a.ref=i},lm=(e,t,r,n)=>{let o=e._zod.def;se(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType,r.readOnly=!0};var Ii=(e,t,r,n)=>{let o=e._zod.def;se(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType};var um=new WeakSet([Object.prototype,Error.prototype]);function uo(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let n=r(this);return Object.defineProperty(this,t,{value:n,configurable:!0,writable:!0}),n},set(n){Object.defineProperty(this,t,{value:n,configurable:!0,writable:!0})}})}var Fx=(e,t)=>{Fl.init(e,t),e.name="ZodError";let r=Object.getPrototypeOf(e);if(um.has(r))return;um.add(r),uo(r,"format",(n)=>(o)=>Vs(n,o)),uo(r,"flatten",(n)=>(o)=>Ks(n,o)),uo(r,"addIssue",(n)=>(o)=>{n.issues.push(o),n.message=JSON.stringify(n.issues,Ar,2)}),uo(r,"addIssues",(n)=>(o)=>{n.issues.push(...o),n.message=JSON.stringify(n.issues,Ar,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}})};var Ee=g("ZodError",Fx,void 0,{Parent:Error});var pm=Un(Ee),dm=Fn(Ee),mm=Mn(Ee),fm=Bn(Ee),hm=Bl(Ee),gm=Gl(Ee),ym=Kl(Ee),bm=Vl(Ee),xm=Wl(Ee),wm=Jl(Ee),_m=Hl(Ee),vm=ql(Ee);function Bx(){if(!we.localeError)_e(ui())}function fo(){if(!we.memoizer)_e({memoizer:li()})}var re=g("ZodType",(e,t)=>(Bx(),q.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(Ce(t,{checks:[...t.checks??[],...e.map((r)=>typeof r==="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Ze(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Lw(e,t))},superRefine(e,t){return this.check(Dw(e,t))},overwrite(e){return this.check(xt(e))},optional(){return Sm(this)},exactOptional(){return $w(this)},nullable(){return km(this)},nullish(){return Sm(km(this))},nonoptional(e){return zw(this,e)},array(){return j(this)},or(e){return yw([this,e])},and(e){return xw(this,e)},transform(e){return Pm(this,vw(e))},default(e){return Pw(this,e)},prefault(e){return Ew(this,e)},catch(e){return Tw(this,e)},pipe(e){return Pm(this,e)},readonly(){return jw(this)},describe(e){let t=this.clone();return bt.add(t,{description:e}),t},meta(...e){if(e.length===0)return bt.get(this);let t=this.clone();return bt.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get "~standard"(){return Nn(this,"~standard",{...ni(this),jsonSchema:{input:Fr(this,"input"),output:Fr(this,"output")}})},set "~standard"(e){st(this,"~standard",e)},parse:function e(t,r){return pm(this,t,r,{callee:e})},parseAsync:async function e(t,r){return await dm(this,t,r,{callee:e})},safeParse(e,t){return mm(this,e,t)},async safeParseAsync(e,t){return fm(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){st(this,"spa",e)},validate(e,t){return Ws(this,e,t)},validateAsync(e,t){return Js(this,e,t)},encode:function e(t,r){return hm(this,t,r,{callee:e})},decode:function e(t,r){return gm(this,t,r,{callee:e})},encodeAsync:async function e(t,r){return await ym(this,t,r,{callee:e})},decodeAsync:async function e(t,r){return await bm(this,t,r,{callee:e})},safeEncode(e,t){return xm(this,e,t)},safeDecode(e,t){return wm(this,e,t)},async safeEncodeAsync(e,t){return _m(this,e,t)},async safeDecodeAsync(e,t){return vm(this,e,t)},toJSONSchema(e){return Rd(this,{})(e)},get description(){return bt.get(this)?.description},get _def(){return this._zod.def}}),Cm=g("_ZodString",(e,t)=>{Jn.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Bd(e,r,n,o)},Ol({format:(e)=>Ie(e).format??null,minLength:(e)=>Ie(e).minimum??null,maxLength:(e)=>Ie(e).maximum??null},{regex(...e){return this.check(di(...e))},includes(...e){return this.check(hi(...e))},startsWith(...e){return this.check(gi(...e))},endsWith(...e){return this.check(yi(...e))},min(...e){return this.check(er(...e))},max(...e){return this.check(ao(...e))},length(...e){return this.check(co(...e))},nonempty(...e){return this.check(er(1,...e))},lowercase(e){return this.check(mi(e))},uppercase(e){return this.check(fi(e))},trim(){return this.check(xi())},normalize(...e){return this.check(bi(...e))},toLowerCase(){return this.check(wi())},toUpperCase(){return this.check(_i())},slugify(){return this.check(vi())}})),Gx=g("ZodString",(e,t)=>{Jn.init(e,t),Cm.init(e,t)},{email(e){return this.check(Qp(Kx,e))},url(e){return this.check(pi(Em,e))},jwt(e){return this.check(xd(cw,e))},emoji(e){return this.check(sd(Jx,e))},guid(e){return this.check(ed(Vx,e))},uuid(e){return this.check(td(po,e))},uuidv4(e){return this.check(rd(po,e))},uuidv6(e){return this.check(nd(po,e))},uuidv7(e){return this.check(od(po,e))},nanoid(e){return this.check(id(Hx,e))},cuid(e){return this.check(ad(qx,e))},cuid2(e){return this.check(cd(Yx,e))},ulid(e){return this.check(ld(Xx,e))},base64(e){return this.check(gd(sw,e))},base64url(e){return this.check(yd(iw,e))},xid(e){return this.check(ud(Qx,e))},ksuid(e){return this.check(pd(ew,e))},ipv4(e){return this.check(dd(tw,e))},ipv6(e){return this.check(md(rw,e))},cidrv4(e){return this.check(fd(nw,e))},cidrv6(e){return this.check(hd(ow,e))},e164(e){return this.check(bd(aw,e))},datetime(e){return this.check(eo(Br,e))},date(e){return this.check(to(Gr,e))},time(e){return this.check(ro(Kr,e))},duration(e){return this.check(no(Vr,e))}});function f(e){return Xp(Gx,e)}var Y=g("ZodStringFormat",(e,t)=>{W.init(e,t),Cm.init(e,t)}),Br=g("ZodISODateTime",(e,t)=>{cp.init(e,t),Y.init(e,t)}),Gr=g("ZodISODate",(e,t)=>{lp.init(e,t),Y.init(e,t)}),Kr=g("ZodISOTime",(e,t)=>{up.init(e,t),Y.init(e,t)}),Vr=g("ZodISODuration",(e,t)=>{pp.init(e,t),Y.init(e,t)}),Kx=g("ZodEmail",(e,t)=>{Yu.init(e,t),Y.init(e,t)});var Vx=g("ZodGUID",(e,t)=>{Hu.init(e,t),Y.init(e,t)});var po=g("ZodUUID",(e,t)=>{qu.init(e,t),Y.init(e,t)});var Em=g("ZodURL",(e,t)=>{ep.init(e,t),Y.init(e,t)});function Wx(e){return pi(Em,e)}var Jx=g("ZodEmoji",(e,t)=>{tp.init(e,t),Y.init(e,t)});var Hx=g("ZodNanoID",(e,t)=>{rp.init(e,t),Y.init(e,t)});var qx=g("ZodCUID",(e,t)=>{np.init(e,t),Y.init(e,t)});var Yx=g("ZodCUID2",(e,t)=>{op.init(e,t),Y.init(e,t)});var Xx=g("ZodULID",(e,t)=>{sp.init(e,t),Y.init(e,t)});var Qx=g("ZodXID",(e,t)=>{ip.init(e,t),Y.init(e,t)});var ew=g("ZodKSUID",(e,t)=>{ap.init(e,t),Y.init(e,t)});var tw=g("ZodIPv4",(e,t)=>{dp.init(e,t),Y.init(e,t)});var rw=g("ZodIPv6",(e,t)=>{fp.init(e,t),Y.init(e,t)});var nw=g("ZodCIDRv4",(e,t)=>{hp.init(e,t),Y.init(e,t)});var ow=g("ZodCIDRv6",(e,t)=>{gp.init(e,t),Y.init(e,t)});var sw=g("ZodBase64",(e,t)=>{bp.init(e,t),Y.init(e,t)});var iw=g("ZodBase64URL",(e,t)=>{xp.init(e,t),Y.init(e,t)});var aw=g("ZodE164",(e,t)=>{wp.init(e,t),Y.init(e,t)});var cw=g("ZodJWT",(e,t)=>{_p.init(e,t),Y.init(e,t)});var zm=g("ZodNumber",(e,t)=>{si.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Gd(e,r,n,o),e.isFinite=!0},Ol({minValue:(e)=>{let{minimum:t,exclusiveMinimum:r}=Ie(e);return Math.max(t??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:(e)=>{let{maximum:t,exclusiveMaximum:r}=Ie(e);return Math.min(t??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:(e)=>{let{isInt:t,multipleOf:r}=Ie(e);return!!t||!!r?.some(Number.isSafeInteger)},format:(e)=>Ie(e).format??null},{gt(e,t){return this.check(so(e,t))},gte(e,t){return this.check(Zr(e,t))},min(e,t){return this.check(Zr(e,t))},lt(e,t){return this.check(oo(e,t))},lte(e,t){return this.check(Nr(e,t))},max(e,t){return this.check(Nr(e,t))},int(e){return this.check($m(e))},safe(e){return this.check($m(e))},positive(e){return this.check(so(0,e))},nonnegative(e){return this.check(Zr(0,e))},negative(e){return this.check(oo(0,e))},nonpositive(e){return this.check(Nr(0,e))},multipleOf(e,t){return this.check(io(e,t))},step(e,t){return this.check(io(e,t))},finite(){return this}}));function X(e){return wd(zm,e)}var lw=g("ZodNumberFormat",(e,t)=>{vp.init(e,t),zm.init(e,t)});function $m(e){return _d(lw,e)}var uw=g("ZodBoolean",(e,t)=>{$p.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Kd(e,r,n,o)});function nr(e){return vd(uw,e)}var pw=g("ZodUnknown",(e,t)=>{Sp.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Wd(e,r,n,o)});function mo(){return $d(pw)}var dw=g("ZodNever",(e,t)=>{kp.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Vd(e,r,n,o)});function mw(e){return Sd(dw,e)}var fw=g("ZodArray",(e,t)=>{fo(),Pp.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Yd(e,r,n,o),e.element=t.element},{min(e,t){return this.check(er(e,t))},nonempty(e){return this.check(er(1,e))},max(e,t){return this.check(ao(e,t))},length(e,t){return this.check(co(e,t))},unwrap(){return this.element}});function j(e,t){return kd(fw,e,t)}var hw=g("ZodObject",(e,t)=>{fo(),zp.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Xd(e,r,n,o),Yb(e,"shape",(r)=>r._zod.def.shape,!1)},{keyof(){return Im(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(Ce(this._zod.def,{catchall:e}))},passthrough(){return this.clone(Ce(this._zod.def,{catchall:mo()}))},loose(){return this.clone(Ce(this._zod.def,{catchall:mo()}))},strict(){return this.clone(Ce(this._zod.def,{catchall:mw()}))},strip(){return this.clone(Ce(this._zod.def,{catchall:void 0}))},extend(e){return Bb(this,e)},safeExtend(e){return Gb(this,e)},merge(e){return Kb(this,e)},pick(e){return Fb(this,e)},omit(e){return Mb(this,e)},partial(...e){return Tl(Tm,this,e[0])},exactPartial(...e){return Tl(Am,this,e[0],"exactPartial")},required(...e){return Vb(Rm,this,e[0])}});function v(e,t){let r={type:"object",shape:e??{},...C(t)};return new hw(r)}var gw=g("ZodUnion",(e,t)=>{Ip.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Qd(e,r,n,o),e.options=t.options});function yw(e,t){return new gw({type:"union",options:e,...C(t)})}var bw=g("ZodIntersection",(e,t)=>{Tp.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,n,o)=>em(e,r,n,o)});function xw(e,t){return new bw({type:"intersection",left:e,right:t})}var Ti=g("ZodRecord",(e,t)=>{fo(),Ap.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,n,o)=>tm(e,r,n,o),e.keyType=t.keyType,e.valueType=t.valueType});function or(e,t,r){if(!t||!t._zod)return new Ti({type:"record",keyType:f(),valueType:e,...C(t)});return new Ti({type:"record",keyType:e,valueType:t,...C(r)})}function ww(e,t,r){return new Ti({type:"record",keyType:e,valueType:t,...C(r),partial:!0})}var Ai=g("ZodEnum",(e,t)=>{Rp.init(e,t),re.init(e,t),e._zod.processJSONSchema=(n,o,s)=>Jd(e,n,o,s),e.enum=t.entries,e.options=[...e._zod.values];let r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=t.entries[i];else throw Error(`Key ${i} not found in enum`);return new Ai({...t,checks:[],...C(o),entries:s})},e.exclude=(n,o)=>{let s={...t.entries};for(let i of n)if(r.has(i))delete s[i];else throw Error(`Key ${i} not found in enum`);return new Ai({...t,checks:[],...C(o),entries:s})}});function Im(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map((n)=>[n,n])):e;return new Ai({type:"enum",entries:r,...C(t)})}var _w=g("ZodTransform",(e,t)=>{fo(),jp.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,n,o)=>qd(e,r,n,o),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Rr(e.constructor.name);r.addIssue=(s)=>{if(typeof s==="string")r.issues.push(jt(s,r.value,t));else{let i=s;if(i.fatal)i.continue=!1;if(i.code??(i.code="custom"),!("input"in i))i.input=r.value;i.inst??(i.inst=e),r.issues.push(jt(i))}};let o=t.transform(r.value,r);if(o instanceof Promise)return o.then((s)=>(r.value=s,r));return r.value=o,r}});function vw(e){return new _w({type:"transform",transform:e})}var Tm=g("ZodOptional",(e,t)=>{ii.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Ii(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function Sm(e){return new Tm({type:"optional",innerType:e})}var Am=g("ZodExactOptional",(e,t)=>{Op.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Ii(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function $w(e){return new Am({type:"optional",innerType:e})}var Sw=g("ZodNullable",(e,t)=>{Lp.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,n,o)=>rm(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function km(e){return new Sw({type:"nullable",innerType:e})}var kw=g("ZodDefault",(e,t)=>{Dp.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,n,o)=>sm(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Pw(e,t){return new kw({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():Ns(t)}})}var Cw=g("ZodPrefault",(e,t)=>{Np.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,n,o)=>im(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function Ew(e,t){return new Cw({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():Ns(t)}})}var Rm=g("ZodNonOptional",(e,t)=>{Zp.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,n,o)=>nm(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function zw(e,t){return new Rm({type:"nonoptional",innerType:e,...C(t)})}var Iw=g("ZodCatch",(e,t)=>{Up.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,n,o)=>am(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Tw(e,t){return new Iw({type:"catch",innerType:e,catchValue:typeof t==="function"?t:Ll(t)})}var Aw=g("ZodPipe",(e,t)=>{Fp.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,n,o)=>cm(e,r,n,o),e.in=t.in,e.out=t.out});function Pm(e,t){return new Aw({type:"pipe",in:e,out:t})}var Rw=g("ZodReadonly",(e,t)=>{Mp.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,n,o)=>lm(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function jw(e){return new Rw({type:"readonly",innerType:e})}var Ow=g("ZodCustom",(e,t)=>{Bp.init(e,t),re.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Hd(e,r,n,o)});function Lw(e,t={}){return Pd(Ow,e,t)}function Dw(e,t){return Cd(e,t)}function Nw(e){return eo(Br,e)}function Zw(e){return to(Gr,e)}function Uw(e){return ro(Kr,e)}function Fw(e){return no(Vr,e)}var jm=Gt(fr(),1);var Ri=()=>process.env.NIPA_DEBUG==="1",Lt=(e)=>{if(Ri())oe(jm.default.dim(`> [debug] [${new Date().toISOString()}] ${e}`))};class it extends Error{url;constructor(e,t){super(`can't reach ${new URL(e).host}: ${t}`);this.name="NetworkError",this.url=e}}var Om=(e)=>e.cause instanceof Error?`${e.message} (${Om(e.cause)})`:e.message,Ve=async(e,t={})=>{let r=t.method??"GET",n=performance.now();Lt(`${r} ${e}`);let o;try{o=await fetch(e,t)}catch(s){throw new it(e,s instanceof Error?Om(s):String(s))}return Lt(`${o.status} ${r} ${e} [${R(performance.now()-n)}]`),o};var Wr=v({domainId:f().optional(),id:f(),name:f()});class ae extends Error{status;constructor(e,t){super(e);this.name="KeystoneError",this.status=t}}var sr=(e)=>{let t=e;while(t.endsWith("/"))t=t.slice(0,-1);if(t.endsWith("/v3"))t=t.slice(0,-3);return`${t}/v3`},ji=(e,t)=>t?{auth:{identity:e,scope:{project:{id:t}}}}:{auth:{identity:e}},Dm=(e)=>({domain:{name:e.userDomain},name:e.username}),Mw=(e,t)=>ji({methods:["password"],password:{user:{...Dm(e),password:t}}},e.projectId),Bw=(e,t)=>ji({methods:["totp"],totp:{user:{...Dm(e),passcode:t}}},e.projectId),Gw=(e,t)=>ji({methods:["token"],token:{id:e}},t),Kw=v({error:v({message:f().optional()}).optional(),receipt:v({}).loose().optional(),required_auth_methods:j(j(f())).optional()}),Nm=async(e)=>{try{let t=Kw.safeParse(JSON.parse(await e.text()));return t.success?t.data:{}}catch{return{}}},Zm=(e)=>e.length>0?`this account needs ${e.map((t)=>t.join(" + ")).join(" or ")} to log in`:"this account's MFA rules don't allow this login method",Vw=(e)=>{let{body:t,status:r}=e;if(t.receipt)return Zm(t.required_auth_methods??[]);if(r===401)return e.unauthorized;return t.error?.message??`Keystone returned HTTP ${r}`},Jr=async(e,t)=>{let r=await Nm(e);throw new ae(Vw({body:r,status:e.status,unauthorized:t}),e.status)},Ww=v({token:v({expires_at:f(),project:v({domain:v({id:f()}).optional(),id:f(),name:f()}).optional(),user:v({id:f(),name:f()})})}),Jw=(e,t)=>{let{expires_at:r,project:n,user:o}=t.token;return{expiresAt:r,project:n&&{domainId:n.domain?.id,id:n.id,name:n.name},user:o,value:e}},Um="Openstack-Auth-Receipt",Oi=(e,t,r)=>{let n=new Headers({"Content-Type":"application/json"});if(r!==void 0)n.set(Um,r);return Ve(`${sr(e)}/auth/tokens`,{body:JSON.stringify(t),headers:n,method:"POST"})},Li=async(e)=>{let t=e.headers.get("X-Subject-Token");if(!t)throw new ae("Keystone didn't return a token",e.status);let r=Ww.safeParse(await e.json());if(!r.success)throw new ae(`unexpected token response: ${Xt(r.error)}`,e.status);return Jw(t,r.data)},Fm=async(e,t)=>{let r=await Oi(e.authUrl,Mw(e,t));if(r.ok)return{kind:"token",token:await Li(r)};let n=r.headers.get(Um);if(r.status===401&&n){let s=(await Nm(r)).required_auth_methods;if(!s||s.some((i)=>i.includes("totp")))return{kind:"mfa",receipt:n};throw new ae(Zm(s),r.status)}return Jr(r,"wrong email or password")},Mm=async(e)=>{let{account:t,passcode:r,receipt:n}=e,o=await Oi(t.authUrl,Bw(t,r),n);return o.ok?Li(o):Jr(o,"wrong OTP code")},Di="the session expired or was revoked",Hr=async(e)=>{let t=await Oi(e.authUrl,Gw(e.token,e.projectId));return t.ok?Li(t):Jr(t,Di)},Hw=v({projects:j(v({domain_id:f().optional(),enabled:nr().optional(),id:f(),name:f()}))}),qw=(e)=>e.projects.filter((t)=>t.enabled!==!1).map((t)=>({domainId:t.domain_id,id:t.id,name:t.name})).toSorted((t,r)=>t.name.localeCompare(r.name)),Ue=async({authUrl:e,signal:t,token:r})=>{let n=await Ve(`${sr(e)}/auth/projects`,{headers:{"X-Auth-Token":r},signal:t});if(!n.ok)return Jr(n,Di);let o=Hw.safeParse(await n.json());if(!o.success)throw new ae(`unexpected project list: ${Xt(o.error)}`,n.status);return qw(o.data)},go=async({authUrl:e,token:t})=>{let r=await Ve(`${sr(e)}/auth/tokens`,{headers:{"X-Auth-Token":t,"X-Subject-Token":t},method:"DELETE"});if(!(r.ok||r.status===401||r.status===404))await Jr(r,Di)},Lm=v({version:v({id:f(),status:f()})}),yo=async(e)=>{let t=sr(e),r=await Ve(t,{signal:AbortSignal.timeout(1e4)}),n;try{n=Lm.safeParse(await r.json())}catch{n=Lm.safeParse(null)}if(!(r.ok&&n.success))throw new ae(`${t} doesn't answer like Keystone v3 (HTTP ${r.status})`,r.status);return n.data.version.id};import{setTimeout as e_}from"node:timers/promises";class he extends Error{status;constructor(e,t){super(e);this.name="ApiError",this.status=t}}var Yw=v({message:f()}),Gm=async(e)=>{try{let t=Yw.safeParse(JSON.parse(await e.text()));return t.success?t.data.message:void 0}catch{return}},Xw=(e,t)=>{try{return t.safeParse(JSON.parse(e))}catch{return t.safeParse(null)}},Bm=(e,t,r)=>{let n=Xw(e,t);if(!n.success)throw new he(`unexpected Space API response: ${Xt(n.error)}`,r);return n.data},Ni=(e)=>{let t=e;while(t.endsWith("/"))t=t.slice(0,-1);return t},qr=(e)=>{let{origin:t,pathname:r}=new URL(e),n=Ni(r);return n===""?`${t}/api`:`${t}${n}`},Km=(e)=>{let{origin:t,pathname:r}=new URL(e),n=Ni(r);return n.endsWith("/api")?`${t}${n.slice(0,-4)}`:t},bo=async(e)=>{let t=await Ve(`${e}/v3/instances`,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)}),r=await Gm(t);if(t.status!==401||r===void 0)throw new he(`${e} doesn't answer like the Space API (HTTP ${t.status})`,t.status)},Qw=/(?:Z|[+-]\d{2}:?\d{2})$/iu,wt=(e)=>Qw.test(e)?e:`${e}Z`,xo=(e)=>{let t=Ni(e.url),r=async(o,s)=>{let i=await Ve(`${t}${o}`,{headers:{Accept:"application/json","Project-Id":e.projectId,Region:e.region,"X-Auth-Token":e.token},method:s,signal:e.signal});if(!i.ok){let a=await Gm(i)??`the Space API returned HTTP ${i.status}`;throw new he(a,i.status)}return i},n=async(o)=>{let s=await r(o,"GET");if(!s.headers.get("Content-Type")?.includes("json"))throw new E(`${t} doesn't answer like the Space API`,{hint:"Check the profile's `spaceUrl` with `nipa profile ls --json`. It's the portal URL with /api, such as https://space.nipa.cloud/api."});return s};return{get:async(o,s)=>{let i=await n(o);return Bm(await i.text(),s,i.status)},getLines:async(o,s)=>{let i=await n(o);return(await i.text()).split(`
90
- `).filter((l)=>l.trim()).map((l)=>Bm(l,s,i.status))},post:async(o)=>{await r(o,"POST")}}};var Vm=v({address:f()}),t_=v({kube_version:f().optional(),magnum_cluster_id:f().optional(),magnum_role:f().optional()}),r_=v({attached_as:f().nullish(),id:f(),name:f().nullish(),size:X(),volume_type:f().nullish()}),n_=v({"OS-EXT-AZ:availability_zone":f().nullish(),created:f(),external_ips:j(Vm),flavor:v({name:f(),ram:X().optional(),vcpus:X().optional()}),id:f(),internal_ips:j(Vm),metadata:t_.optional(),name:f(),security_groups:j(f()).optional(),status:f(),volumes:j(r_).optional()}),o_=v({instances:j(n_)}),Wm=(e,t)=>({address:e.address,type:t,version:e.address.includes(":")?6:4}),s_=(e={})=>e.magnum_cluster_id===void 0?null:{clusterId:e.magnum_cluster_id,role:e.magnum_role??null,version:e.kube_version??null},i_=(e)=>({attachedAs:e.attached_as??null,id:e.id,name:e.name??null,sizeGb:e.size,type:e.volume_type??null}),a_=(e)=>({addresses:[...e.internal_ips.map((t)=>Wm(t,"fixed")),...e.external_ips.map((t)=>Wm(t,"floating"))],createdAt:e.created,flavor:e.flavor.name,id:e.id,kubernetes:s_(e.metadata),name:e.name,ramMb:e.flavor.ram??null,securityGroups:e.security_groups??[],status:e.status,vcpus:e.flavor.vcpus??null,volumes:(e.volumes??[]).map(i_),zone:e["OS-EXT-AZ:availability_zone"]??null}),We=async(e)=>(await e.get("/v3/instances",o_)).instances.map(a_),c_=v({instance:v({locked:nr().nullish(),status:f(),task_state:f().nullable()})}),Zi=async(e,t)=>{let{instance:r}=await e.get(`/v4/instances/${t}`,c_);return{locked:r.locked??null,status:r.status,taskState:r.task_state}},Ui=(e,t,r)=>e.post(`/v4/instances/${t}/action/${r}`),Jm=(e)=>{let t=e.sleep??e_,r=e.now??Date.now,n=r()+e.timeoutMs,o=async()=>{let s=await Zi(e.space,e.id);if(s.status==="ERROR")return{kind:"error"};if(s.status===e.status&&s.taskState===null)return{kind:"done"};if(r()>=n)return{kind:"timeout",state:s};return await t(e.intervalMs),o()};return o()},l_=v({logs:f()}),Hm=async(e,t)=>{try{return{kind:"log",text:(await e.get(`/v4/instances/${t}/logs`,l_)).logs}}catch(r){if(r instanceof he&&r.status===406)return{kind:"none"};throw r}},u_=v({action:f(),id:f(),remark:f().nullish(),started_at:f(),user_name:f().nullish()}),p_=v({action_histories:j(u_)}),wo=(e)=>e.remark==="Error",_o=async(e,t)=>(await e.get(`/v4/instances/${t}/action_histories`,p_)).action_histories.map((o)=>({action:o.action,remark:o.remark??null,requestId:o.id,startedAt:wt(o.started_at),user:o.user_name??null})).toSorted((o,s)=>Date.parse(s.startedAt)-Date.parse(o.startedAt));var d_=v({allowed_cidrs:j(f()).nullish(),availability_zone:f().nullish(),datastore_type:f(),datastore_version:f(),external_ip_address:f().nullish(),id:f(),instance_status:f(),ip_address:f(),machine_type:v({name:f(),ram:X().nullish(),vcpus:X().nullish()}),operating_status:f(),service_status_updated:f().nullish(),volume_size:X()}),m_=v({created_at:f(),id:f(),name:f(),primary:d_.nullish()}),f_=v({database_clusters:j(m_)}),h_=v({database_instances:j(v({database_cluster_id:f().nullish(),id:f(),instance_status:f(),ip_address:f().nullish(),name:f(),operating_status:f().nullish()}))}),g_=or(f(),v({name:f(),published:X().nullish(),status:f()})),y_=v({database_backups:j(v({created_at:f(),database_instance_id:f(),id:f(),name:f(),size:X().nullish(),status:f()}))}),b_=new Map([["mariadb",3306],["mongodb",27017],["mysql",3306],["percona",3306],["postgresql",5432],["redis",6379]]),x_=(e)=>({address:e.ip_address,allowedCidrs:e.allowed_cidrs??[],engine:e.datastore_type,externalAddress:e.external_ip_address||null,flavor:e.machine_type.name,health:e.operating_status,healthCheckedAt:e.service_status_updated??null,id:e.id,ramMb:e.machine_type.ram??null,status:e.instance_status,storageGb:e.volume_size,vcpus:e.machine_type.vcpus??null,version:e.datastore_version,zone:e.availability_zone||null}),w_=(e)=>({createdAt:e.created_at,id:e.id,name:e.name,primary:e.primary?x_(e.primary):null}),vo=async(e)=>(await e.get("/v4/database/clusters?include_primary=true&include_machine_type=true",f_)).database_clusters.map(w_).toSorted((r,n)=>Date.parse(n.createdAt)-Date.parse(r.createdAt)),__=async(e,t,r)=>(await e.get(`/v4/databases?database_cluster_id=${encodeURIComponent(t.id)}`,h_)).database_instances.filter((o)=>o.database_cluster_id===t.id&&o.id!==r).map((o)=>({address:o.ip_address||null,health:o.operating_status??"UNKNOWN",id:o.id,name:o.name,status:o.instance_status})),v_=new Set(["DISABLED","UNAVAILABLE"]),$_=async(e,t)=>{let r=await e.get(`/v4/database/${encodeURIComponent(t)}/logs`,g_);return Object.values(r).map((n)=>({enabled:!v_.has(n.status.toUpperCase()),name:n.name,publishedBytes:n.published??0,status:n.status}))},S_=async(e,t)=>(await e.get(`/v4/database/backups?database_instance_id=${encodeURIComponent(t)}`,y_)).database_backups.filter((n)=>n.database_instance_id===t).map((n)=>({createdAt:wt(n.created_at),id:n.id,name:n.name,sizeGb:n.size??null,status:n.status})).toSorted((n,o)=>Date.parse(o.createdAt)-Date.parse(n.createdAt)),Fi=(e)=>e.status==="fulfilled"?e.value:null,qm=async(e,t)=>{let{primary:r}=t;if(!r)return{...t,backups:[],defaultPort:null,logs:[],replicas:[]};let[n,o,s]=await Promise.allSettled([__(e,t,r.id),$_(e,r.id),S_(e,r.id)]);return{...t,backups:Fi(s),defaultPort:b_.get(r.engine.toLowerCase())??null,logs:Fi(o),replicas:Fi(n)}};var k_=v({availability_zone:f(),external_ip_address:f(),id:f(),internal_ip_address:f().nullable(),name:f(),status:f()}),P_=v({external_ips:j(k_)}),C_=(e)=>({address:e.external_ip_address,id:e.id,internalAddress:e.internal_ip_address,name:e.name,status:e.status,zone:e.availability_zone}),$o=async(e)=>(await e.get("/v4/external_ips",P_)).external_ips.map(C_);var E_=v({created_at:f(),id:f(),listeners:j(mo()),name:f(),operating_status:f(),provisioning_status:f(),vip_address:f()}),z_=v({loadbalancers:j(E_)}),I_=(e)=>({address:e.vip_address,createdAt:e.created_at,health:e.operating_status,id:e.id,listeners:e.listeners.length,name:e.name,status:e.provisioning_status}),So=async(e)=>(await e.get("/v4/loadbalancers",z_)).loadbalancers.map(I_).toSorted((r,n)=>Date.parse(n.createdAt)-Date.parse(r.createdAt)),Xr=v({id:f(),operating_status:f(),provisioning_status:f()}),T_=v({loadbalancer:Xr.extend({created_at:f(),external_ip_id:f().nullish(),flavor_id:f().nullish(),name:f(),vip_address:f()})}),A_=v({listeners:j(Xr.extend({allowed_cidrs:j(f()).nullish(),backend_group_id:f().nullish(),name:f().nullish(),protocol:f(),protocol_port:X()}))}),R_=Xr.extend({delay:X(),max_retries:X(),timeout:X(),type:f()}),j_=v({backend_groups:j(Xr.extend({healthcheck:R_.nullish(),lb_algorithm:f(),name:f().nullish(),protocol:f()}))}),O_=v({members:j(Xr.extend({address:f(),backup:nr().nullish(),name:f().nullish(),protocol_port:X(),weight:X().nullish()}))}),L_=v({loadbalancer_flavors:j(v({id:f(),name:f()}))}),Yr=(e)=>({health:e.operating_status,id:e.id,status:e.provisioning_status}),D_=async(e,t)=>(await e.get(`${t}/members`,O_)).members.map((n)=>({...Yr(n),address:n.address,backup:n.backup??!1,name:n.name??null,port:n.protocol_port,weight:n.weight??null})),N_=async(e,t)=>{if(!t)return null;return(await $o(e)).find((n)=>n.id===t)?.address??null},Z_=async(e,t)=>{if(!t)return null;let{loadbalancer_flavors:r}=await e.get("/v4/loadbalancerflavors",L_);return r.find((n)=>n.id===t)?.name??t},Ym=(e)=>e.status==="fulfilled"?e.value:null,Qm=async(e,t)=>{let r=`/v4/loadbalancers/${encodeURIComponent(t)}`,[n,o,s]=await Promise.all([e.get(r,T_),e.get(`${r}/listeners`,A_),e.get(`${r}/backend_groups`,j_)]),i=n.loadbalancer,[a,c]=await Promise.all([Promise.all(s.backend_groups.map((p)=>D_(e,`${r}/backend_groups/${p.id}`))),Promise.allSettled([Z_(e,i.flavor_id),N_(e,i.external_ip_id)])]),[l,u]=c;return{...Yr(i),address:i.vip_address,backendGroups:s.backend_groups.map((p,d)=>({...Yr(p),algorithm:p.lb_algorithm,healthCheck:p.healthcheck?{...Yr(p.healthcheck),delaySeconds:p.healthcheck.delay,maxRetries:p.healthcheck.max_retries,timeoutSeconds:p.healthcheck.timeout,type:p.healthcheck.type}:null,members:a[d]??[],name:p.name??null,protocol:p.protocol})),createdAt:i.created_at,externalAddress:Ym(u),flavor:Ym(l),listenerDetails:o.listeners.map((p)=>({...Yr(p),allowedCidrs:p.allowed_cidrs??[],backendGroupId:p.backend_group_id??null,name:p.name??null,port:p.protocol_port,protocol:p.protocol})),name:i.name}},U_=new Set(["ONLINE","NO_MONITOR"]),_t=(e)=>e.status==="ACTIVE"&&U_.has(e.health),F_=new Set(["OFFLINE","DRAINING"]),Gi=(e)=>e.backup&&e.status==="ACTIVE"&&F_.has(e.health),Xm=["listener","listeners"],Mi=["is unhealthy","are unhealthy"],Bi=(e)=>e.filter((t)=>!_t(t)).length,M_=({failing:e,noun:t,predicate:r,total:n})=>{if(n===1)return`the ${t[0]} ${r[0]}`;let[o,s]=r;return`${e} of ${n} ${t[1]} ${e===1?o:s}`},B_=(e)=>{if(_t(e)||e.members.length===0)return!1;if(e.healthCheck&&!_t(e.healthCheck))return!1;return!e.members.some((t)=>!(_t(t)||Gi(t)))},G_=(e)=>`Backup member ${e.name??e.id} is ${e.health.toLowerCase()} until the other members go down`,ef=(e)=>{let{backendGroups:t,listenerDetails:r}=e,n=new Map(t.map((p)=>[p.id,p.members.length])),o=r.filter((p)=>!n.get(p.backendGroupId??"")),s=t.flatMap((p)=>p.healthCheck??[]),i=t.flatMap((p)=>p.members),a=i.filter((p)=>!Gi(p)),l=[{failing:Bi(r),noun:Xm,predicate:Mi,total:r.length},{failing:o.length,noun:Xm,predicate:["has no members to send traffic to","have no members to send traffic to"],total:r.length},{failing:t.filter(B_).length,noun:["backend group","backend groups"],predicate:Mi,total:t.length},{failing:Bi(s),noun:["health check","health checks"],predicate:Mi,total:s.length},{failing:Bi(a),noun:["member","members"],predicate:["is down","are down"],total:i.length}].filter((p)=>p.failing>0).map(M_);if(r.length===0)l.unshift("the load balancer has no listeners");else if(l.length===0&&!_t(e))l.push("the load balancer is unhealthy");let u=i.filter(Gi).map(G_);if(l.length===0)return{details:u,healthy:!0,verdict:"All listeners and members are healthy"};return{details:u,healthy:!1,verdict:al(Tt(l))}};var K_=v({availability_zone:f().optional(),created_at:f(),external_network:nr(),id:f(),name:f(),shared:nr(),status:f()}),V_=v({networks:j(K_)}),W_=(e)=>({createdAt:wt(e.created_at),external:e.external_network,id:e.id,name:e.name,shared:e.shared,status:e.status,zone:e.availability_zone||null}),ko=async(e)=>(await e.get("/v4/networks",V_)).networks.map(W_).toSorted((r,n)=>Date.parse(n.createdAt)-Date.parse(r.createdAt)),J_=v({device_id:f(),fixed_ips:j(v({ip_address:f()})),security_groups:j(f()).nullish()}),H_=v({ports:j(J_)}),tf=async(e)=>(await e.get("/v2/ports",H_)).ports.map((r)=>({addresses:r.fixed_ips.map((n)=>n.ip_address),deviceId:r.device_id,securityGroupIds:r.security_groups??[]}));var q_=v({direction:f(),ethertype:f(),id:f(),port_range_max:X().nullable(),port_range_min:X().nullable(),protocol:f().nullable(),remote_group_id:f().nullable(),remote_ip_prefix:f().nullable()}),Y_=v({created_at:f(),description:f().nullable(),id:f(),name:f(),security_group_rules:j(q_)}),X_=v({security_groups:j(Y_)}),Q_=(e)=>({direction:e.direction,ethertype:e.ethertype,id:e.id,portMax:e.port_range_max,portMin:e.port_range_min,protocol:e.protocol,remoteGroupId:e.remote_group_id,remoteIpPrefix:e.remote_ip_prefix}),ev=(e)=>({createdAt:wt(e.created_at),description:e.description||null,id:e.id,name:e.name,rules:e.security_group_rules.map(Q_)}),ir=async(e)=>(await e.get("/v4/security_groups",X_)).security_groups.map(ev).toSorted((r,n)=>Date.parse(n.createdAt)-Date.parse(r.createdAt));var tv=v({device:f(),serverId:f()}),rv=v({attachments:j(tv),availability_zone:f(),bootable:f(),created_at:f(),id:f(),name:f(),size:X(),status:f(),volume_type:f().nullable()}),nv=v({volumes:j(rv)}),ov=(e)=>({attachments:e.attachments,bootable:e.bootable==="true",createdAt:e.created_at,id:e.id,name:e.name,sizeGb:e.size,status:e.status,type:e.volume_type,zone:e.availability_zone}),Qr=async(e)=>(await e.get("/v4/volumes",nv)).volumes.map(ov).toSorted((r,n)=>Date.parse(n.createdAt)-Date.parse(r.createdAt));var en={list:We,lsCommand:"nipa server ls",noun:"server",plural:"servers"},Po={list:Qr,lsCommand:"nipa volume ls",noun:"volume",plural:"volumes"},Co={list:ko,lsCommand:"nipa network ls",noun:"network",plural:"networks"},ar={list:ir,lsCommand:"nipa sg ls",noun:"security group",plural:"security groups"},cr={list:So,lsCommand:"nipa lb ls",noun:"load balancer",plural:"load balancers"},lr={list:vo,lsCommand:"nipa db ls",noun:"database",plural:"databases"},at=async(e)=>{let{kind:t,projectName:r,ref:n}=e,o=await I(`Loading the ${t.plural} in ${r}…`,()=>t.list(e.space)),s=o.filter((c)=>c.id===n),[i,...a]=s.length>0?s:o.filter((c)=>c.name===n);if(!i)throw new E(`no ${t.noun} named or with ID "${n}" in ${r}`,{hint:`Run \`${t.lsCommand}\` to see your ${t.plural}.`});if(a.length>0){let c=[i,...a].map((l)=>l.id).join(", ");throw new E(`${a.length+1} ${t.plural} in ${r} are named "${n}"`,{hint:`Name one by its ID instead: ${c}.`})}return i},vt=(e)=>at({...e,kind:en});import{chmod as Ki,mkdir as nf,readFile as of,rename as sv,rm as sf,writeFile as iv}from"node:fs/promises";import{homedir as af}from"node:os";import $t from"node:path";var me="prod",ge={authUrl:"https://identity-api.nipa.cloud/v3",region:"NCP-TH",spaceUrl:"https://space.nipa.cloud/api",userDomain:"nipacloud"},rf=Wx({protocol:/^https?$/u}),ct=v({authUrl:rf,project:Wr.optional(),region:f().min(1),spaceUrl:rf.optional(),userDomain:f().min(1),username:f().optional()}),Vi=/^[a-z][\da-z-]{0,31}$/u,av=or(f().regex(Vi),ct),Wi=(e)=>new URL(sr(e)).href===ge.authUrl,cv=(e)=>{let{spaceUrl:t,...r}=e;if(Wi(e.authUrl))return{...r,spaceUrl:qr(t??ge.spaceUrl)};if(t===void 0||t===ge.spaceUrl)return r;return{...r,spaceUrl:qr(t)}},Ji=(e)=>({[me]:ge,...Object.fromEntries(Object.entries(e).map(([t,r])=>[t,cv(r)]))}),lv=v({currentProfile:f().default(me),profiles:av.default({})}).strict().transform((e)=>({...e,profiles:Ji(e.profiles)})),uv=ct.extend({authUrl:ct.shape.authUrl.default(ge.authUrl),region:ct.shape.region.default(ge.region),userDomain:ct.shape.userDomain.default(ge.userDomain)}).transform((e)=>({currentProfile:me,profiles:Ji({[me]:e})})),pv=or(f(),mo()),cf=(e,...t)=>{let r=pv.safeParse(e);return r.success&&t.some((n)=>Object.hasOwn(r.data,n))},dv=(e)=>!cf(e,"profiles","currentProfile"),mv=(e)=>dv(e)?uv:lv,lf=v({expiresAt:ho.datetime({offset:!0}),project:Wr,token:f().min(1),user:v({id:f(),name:f()})}),fv=or(f(),lf),hv=v({sessions:fv}).strict().transform((e)=>e.sessions),gv=lf.transform((e)=>({[me]:e})),yv=(e)=>!cf(e,"sessions"),bv=(e)=>yv(e)?gv:hv;class lt extends Error{hint;constructor(e,t){super(e);this.name="StoreError",this.hint=t}}var uf="Check that your user owns the file. A `sudo nipa …` run leaves it owned by root.",xv=60000,Eo=(e=process.env)=>e.NIPA_CONFIG_DIR??$t.join(e.XDG_CONFIG_HOME??$t.join(af(),".config"),"nipa"),Hi=()=>$t.join(Eo(),"config.json"),tn=()=>$t.join(Eo(),"auth.json"),pf=()=>[Hi(),tn()],df=(e,t=process.env)=>$t.join(t.XDG_CACHE_HOME??$t.join(af(),".cache"),"nipa",e),Je=async(e,t)=>{try{let r=await of(df(e),"utf-8"),n=t.safeParse(JSON.parse(r));return n.success?n.data:void 0}catch{return}},mf=async(e,t,r)=>{let n=`${e}.${process.pid}.tmp`;try{await iv(n,t,{mode:r}),await Ki(n,r),await sv(n,e)}catch(o){throw await sf(n,{force:!0}),o}},ut=async(e,t)=>{let r=df(e);await nf($t.dirname(r),{mode:448,recursive:!0}),await Ki($t.dirname(r),448),await mf(r,`${JSON.stringify(t)}
91
- `,384)},wv=async(e)=>{try{return await of(e,"utf-8")}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")return;let r=t instanceof Error?t.message:String(t);throw new lt(`can't read ${e}: ${r}`,uf)}},ff=async(e,t)=>{let r=await wv(e);if(r===void 0)return;let n;try{n=JSON.parse(r)}catch{throw new lt(`${e} isn't valid JSON`)}let o=t(n).safeParse(n);if(!o.success)throw new lt(`${e}: ${Xt(o.error)}`);return o.data},qi=async(e,t)=>{try{await nf(Eo(),{mode:448,recursive:!0}),await Ki(Eo(),448),await mf(e,`${JSON.stringify(t,null,2)}
92
- `,384)}catch(r){let n=r instanceof Error?r.message:String(r);throw new lt(`can't write ${e}: ${n}`,uf)}},ve=async()=>await ff(Hi(),mv)??{currentProfile:me,profiles:Ji({})},St=(e)=>qi(Hi(),e),Yi=async()=>await ff(tn(),bv)??{},pe=async(e)=>(await Yi())[e],hf=async(e)=>{let t=await Yi();await qi(tn(),{sessions:{...t,[e.profile]:e.session}})},zo=async(e)=>{let t=await Yi(),r=Object.fromEntries(Object.entries(t).filter(([n])=>n!==e));if(Object.keys(r).length===0){await sf(tn(),{force:!0});return}await qi(tn(),{sessions:r})},Dt=(e,t=Date.now())=>Date.parse(e.expiresAt)-t,de=(e,t=Date.now())=>e!==void 0&&Dt(e,t)>xv;var gf="names.json",_v=60000,Xi=v({name:f()}),vv=v({machine_types:j(Xi)}),$v=v({owned_images:j(Xi)}),Sv=v({public_images:j(v({images:j(Xi)}))}),pt=(e)=>e.map((t)=>t.name).filter((t)=>t!==""),kv=async(e,t)=>{switch(t){case"servers":return pt(await en.list(e));case"volumes":return pt(await Po.list(e));case"networks":return pt(await Co.list(e));case"security-groups":return pt(await ar.list(e));case"load-balancers":return pt(await cr.list(e));case"databases":return pt(await lr.list(e));case"flavors":{let r=await e.get("/v4/machine_types",vv);return pt(r.machine_types)}case"images":{let[r,n]=await Promise.all([e.get("/v4/public_images",Sv),e.get("/v4/images?table=owned_image",$v)]);return[...r.public_images.flatMap((o)=>pt(o.images)),...pt(n.owned_images)]}default:return t}},Pv=or(f(),v({at:X(),names:j(f())})),yf=async(e)=>{let t=e.now??Date.now(),r=`${e.scope}:${e.kind}`,n=await Je(gf,Pv)??{},o=n[r];if(o&&t-o.at<_v)return o.names;let s=await kv(await e.connect(),e.kind);return await ut(gf,{...n,[r]:{at:t,names:s}}),s};import{spawn as Av}from"node:child_process";import{once as Rv}from"node:events";import{stat as jv}from"node:fs/promises";import{text as Ov}from"node:stream/consumers";import{accessSync as Cv,constants as Ev}from"node:fs";import{homedir as zv}from"node:os";import rn from"node:path";var bf=(e)=>{try{return Cv(e,Ev.X_OK),!0}catch{return!1}},Iv=(e)=>process.platform==="win32"?[...(process.env.PATHEXT??".EXE;.CMD;.BAT").split(";").map((t)=>`${e}${t}`),e]:[e],dt=(e)=>{if(e.includes("/")||e.includes(rn.sep)){let r=rn.resolve(e);return bf(r)?r:void 0}return[...(process.env.PATH??"").split(rn.delimiter).filter(Boolean),rn.join(zv(),".local","bin")].flatMap((r)=>Iv(rn.join(r,e))).find(bf)},Io=(e)=>({OS_AUTH_TYPE:"v3token",OS_AUTH_URL:e.profile.authUrl,OS_IDENTITY_API_VERSION:"3",OS_INTERFACE:"public",OS_PROJECT_DOMAIN_ID:e.session.project.domainId??"",OS_PROJECT_ID:e.session.project.id,OS_PROJECT_NAME:e.session.project.name,OS_REGION_NAME:e.profile.region,OS_TOKEN:e.session.token}),wf=(e,t)=>({...Object.fromEntries(Object.entries(e).filter(([r])=>!r.startsWith("OS_"))),...t}),Qi=["bash","zsh","fish"],Tv=(e)=>Qi.some((t)=>t===e),xf=(e,t)=>`'${t==="fish"?e.replaceAll("\\","\\\\").replaceAll("'","\\'"):e.replaceAll("'","'\\''")}'`,_f=(e,t)=>Object.entries(e).map(([r,n])=>t==="fish"?`set -gx ${r} ${xf(n,t)}`:`export ${r}=${xf(n,t)}`).join(`
93
- `),vf=(e)=>{let t=e?.split("/").at(-1)??"";return Tv(t)?t:"bash"};var $f="openstack.json",Lv=20000,Dv=or(f(),j(f())),Nv=v({bin:f(),mtimeMs:X(),table:Dv}),Zv=/^\s*cmds(?:_(?<key>\S+))?='(?<words>[^']*)'$/u,Uv=(e)=>Object.fromEntries(e.split(`
94
- `).flatMap((t)=>{let r=Zv.exec(t)?.groups;if(!r)return[];let n=r.words?.split(" ").filter(Boolean)??[];return[[r.key??"",n]]})),Fv=(e,t)=>{let r=t.at(-1)??"",n="";for(let s of t.slice(0,-1)){let i=(n?`${n}_${s}`:s).replaceAll("-","_");if(s.startsWith("-")||!Object.hasOwn(e,i))break;n=i}let o=e[n]??[];if(r.startsWith("-"))return o.filter((s)=>s.startsWith(r));return o.filter((s)=>s.startsWith(r)&&!s.startsWith("-")&&!s.includes("_"))},Mv=async(e)=>{let{mtimeMs:t}=await jv(e),r=await Je($f,Nv);if(r?.bin===e&&r.mtimeMs===t)return r.table;let n=Av(e,["complete","--shell","none"],{stdio:["ignore","pipe","ignore"],timeout:Lv}),[o]=await Promise.all([Ov(n.stdout),Rv(n,"close")]);if(n.exitCode!==0)return;let s=Uv(o);return await ut($f,{bin:e,mtimeMs:t,table:s}),s},Sf=async(e)=>{let t=dt("openstack");if(!t)return[];let r=await Mv(t);return r?Fv(r,e):[]},Bv=["console log show","console url show","server delete","server lock","server pause","server reboot","server rescue","server resume","server show","server shelve","server ssh","server start","server stop","server suspend","server unlock","server unpause","server unrescue","server unshelve"].map((e)=>e.split(" ")),Gv=new Map([["--flavor","flavors"],["--image","images"],["--network","networks"]]),kf=(e)=>{let t=e.at(-2)??"";if(t.startsWith("-"))return Gv.get(t);if((e.at(-1)??"").startsWith("-"))return;return Bv.some((n)=>e.length>n.length&&n.every((o,s)=>e[s]===o))?"servers":void 0};import{spawn as Kv}from"node:child_process";import{once as Vv}from"node:events";import{text as Wv}from"node:stream/consumers";var Nt=async(e,t,r="")=>{let n=Kv(e,t,{stdio:["pipe","pipe","ignore"]});n.stdin.end(r);let[o]=await Promise.all([Wv(n.stdout),Vv(n,"close")]);return{code:n.exitCode,stdout:o}},Pf=(e)=>`nipa-cli/${new URL(e.authUrl).host}`,Cf=(e,t)=>new E(`the ${e} didn't save your password`,{hint:`${t}, or log in without \`--remember\`.`}),ea=(e)=>["-s",Pf(e),"-a",e.username],Jv=(e)=>({name:"macOS Keychain",read:async(r)=>{let{code:n,stdout:o}=await Nt(e,["find-generic-password",...ea(r),"-w"]);return n===0?Buffer.from(o.trim(),"base64").toString("utf-8"):void 0},remove:async(r)=>{let{code:n}=await Nt(e,["delete-generic-password",...ea(r)]);return n===0},save:async(r,n)=>{let o=Buffer.from(n,"utf-8").toString("base64"),s=Buffer.from(o,"ascii").toString("hex"),i=["add-generic-password","-U",...ea(r),"-X",s],{code:a}=await Nt(e,["-i"],`${i.join(" ")}
95
- `);if(a!==0)throw Cf("macOS Keychain","Check that your login keychain is unlocked")}}),To=(e)=>["service",Pf(e),"account",e.username],Hv=(e)=>({name:"secret service",read:async(r)=>{let{code:n,stdout:o}=await Nt(e,["lookup",...To(r)]);return n===0&&o!==""?o:void 0},remove:async(r)=>{let n=await Nt(e,["lookup",...To(r)]);return await Nt(e,["clear",...To(r)]),n.code===0},save:async(r,n)=>{let s=["store",`--label=${`nipa password for ${r.username}`}`,...To(r)],{code:i}=await Nt(e,s,n);if(i!==0)throw Cf("secret service","Check that a secret service, such as GNOME Keyring, is running")}}),Ao=(e=process.platform)=>{if(e==="darwin"){let t=dt("security");return t?Jv(t):void 0}if(e==="linux"){let t=dt("secret-tool");return t?Hv(t):void 0}return},Ef=(e=process.platform)=>{let t=Ao(e);if(t)return t;let r=e==="linux"?"Install secret-tool, such as with `sudo apt install libsecret-tools`, or log in without `--remember`.":"Log in without `--remember`. nipa saves passwords on macOS and Linux.";throw new E(`nipa can't save your password on ${e}`,{hint:r})},Ro=(e)=>{let t=Ao();if(!(t&&e.username))return Promise.resolve(!1);return t.remove({authUrl:e.authUrl,username:e.username})};import{mkdir as qv,readFile as Yv,rm as Xv,rmdir as Qv,writeFile as e$}from"node:fs/promises";import on from"node:path";var t$=".nipa",r$="project.json",n$=v({profile:f(),project:Wr}),zf=(e)=>on.join(e,t$,r$);class nn extends E{constructor(e,t){super(`${e} ${t}`,{hint:"Fix the file, or run `nipa unlink` and `nipa link` again."});this.name="LinkError"}}var o$=async(e)=>{let t;try{t=await Yv(e,"utf-8")}catch(o){if(o instanceof Error&&"code"in o&&o.code==="ENOENT")return;throw o}let r;try{r=JSON.parse(t)}catch{throw new nn(e,"isn't valid JSON")}let n=n$.safeParse(r);if(!n.success)throw new nn(e,`isn't a nipa link: ${Xt(n.error)}`);return n.data},Zt=async(e=process.cwd())=>{let t=zf(e),r=await o$(t);if(r)return{file:t,link:r};let n=on.dirname(e);return n===e?void 0:Zt(n)},If=async(e)=>{let t=zf(e.dir);return await qv(on.dirname(t),{recursive:!0}),await e$(t,`${JSON.stringify(e.link,null,2)}
96
- `),t},Tf=async(e)=>{await Xv(e,{force:!0});try{await Qv(on.dirname(e))}catch{}},ye=(e,t=process.cwd())=>on.relative(t,e);var ta=async(e)=>{let{link:t}=e,r=await ve(),n=[["flag",e.override],["env",process.env.NIPA_PROFILE],["link",t?.link.profile]],[o,s]=n.find((c)=>c[1]!==void 0)??["config",r.currentProfile],i=r.profiles[s];if(!i){let c=Object.keys(r.profiles).join(", "),l=t?.link.profile===s?` in ${ye(t.file)}`:"";throw new E(`no profile named "${s}"${l}`,{hint:`Your profiles: ${c}. Add one with \`nipa profile add ${s}\`.`})}let a=t?.link.profile===s?t:void 0;return{config:r,link:a,name:s,profile:i,source:o}},He=(e)=>e===me?"nipa login":`nipa login -P ${e}`,an=(e)=>{if(e.name!==me){let t=T(`(${new URL(e.profile.authUrl).host})`);w(`Using profile ${x(e.name)} ${t}`)}},s$=/^\d{6}$/u,Af=/^[\da-f]{32}$/u,i$=3,a$=(e)=>({email:(t)=>e.text({default:t,message:"Email",validate:(r)=>r.includes("@")||"Enter the email you log in to the portal with"}),otp:(t)=>e.text({message:t===1?"OTP code":"Next OTP code",validate:(r)=>s$.test(r)||"Enter the 6-digit code from your authenticator app"}),password:()=>e.secret("Password"),projectId:()=>e.text({message:"Project ID",validate:(t)=>Af.test(t)||"Enter the 32-character ID, as in OS_PROJECT_ID in your openrc file"})}),Rf=(e)=>{let{projects:t,wanted:r}=e,n=t.find((o)=>o.id===r||o.name===r);if(!n)throw new E(`no project named or with ID "${r}"`,{hint:`Your projects: ${t.map((o)=>o.name).join(", ")}`});return n},jo=(e)=>(t)=>e.prompts.choice({choices:t.map((r)=>({description:r.id,name:r.id===e.current.id?`${r.name} ${x("(current)")}`:r.name,value:r})),default:t.find((r)=>r.id===e.current.id),message:e.message}),Oo=(e)=>{let{projects:t,wanted:r}=e;if(r)return Promise.resolve(Rf({projects:t,wanted:r}));let[n,...o]=t;if(!n)throw new E("your account has no projects you can use");return o.length===0?Promise.resolve(n):e.ask(t)},sn=(e,t)=>({expiresAt:e.expiresAt,project:e.project??t,token:e.value,user:e.user}),jf=async(e)=>{let t=await e.ask(e.attempt);try{return await I("Checking the code…",()=>Mm({account:e.account,passcode:t,receipt:e.receipt}))}catch(r){if(!(r instanceof ae&&r.status===401)||e.attempt===i$)throw r;return w("That code didn't work. Each code works once, so wait for the next one."),jf({...e,attempt:e.attempt+1})}},c$=async(e)=>{let t=e.username??e.profile.username;if(!(t&&e.keychain))return;let r=await e.keychain.read({authUrl:e.profile.authUrl,username:t});return r===void 0?void 0:{password:r,username:t}},l$=async(e)=>{let{account:t,keychain:r,prompts:n,remembered:o}=e,s=async(i)=>({answer:await I("Checking your password…",()=>Fm(t,i)),password:i});if(o===void 0||!r)return s(await n.password());w(`Using the password saved in the ${r.name}`);try{return await s(o)}catch(i){if(!(i instanceof ae&&i.status===401))throw i;return await r.remove(t),w("The saved password didn't work, so nipa deleted it."),s(await n.password())}},u$=async(e)=>{let{keychain:t,profile:r,prompts:n,wantedProject:o}=e,s=await c$({keychain:t,profile:r,username:e.username}),i=s?.username??e.username??await n.email(r.username),a=o!==void 0&&Af.test(o)?o:void 0,c=a??r.project?.id??await n.projectId(),l={authUrl:r.authUrl,projectId:c,userDomain:r.userDomain,username:i},{answer:u,password:p}=await l$({account:l,keychain:t,prompts:n,remembered:s?.password}),d=u.kind==="token"?u.token:await jf({account:l,ask:n.otp,attempt:1,receipt:u.receipt});if(!d.project)throw new ae(`Keystone returned a token without project ${c}`,0);if(e.remember&&t)await t.save(l,p);let m=a?void 0:o;if(m===void 0||d.project.name===m)return sn(d,d.project);let h=await I("Loading your projects…",()=>Ue({authUrl:r.authUrl,token:d.value})),y=Rf({projects:h,wanted:m}),b=await I(`Switching to ${y.name}…`,()=>Hr({authUrl:r.authUrl,projectId:y.id,token:d.value}));return sn(b,y)},ra=async(e)=>{let{active:t,session:r}=e,n={...t.profile,project:r.project,username:r.user.name};await St({...t.config,profiles:{...t.config.profiles,[t.name]:n}}),await hf({profile:t.name,session:r})},na=async(e)=>{let{active:t,prompts:r}=e;if(!r.interactive)throw new E("`nipa login` needs a terminal to ask for your password",{hint:"Run it in a terminal, then run this command again."});let n=e.remember?Ef():Ao(),o=T(`(${new URL(t.profile.authUrl).host})`);w(`Logging in to ${x(t.name)} ${o}`);let s=await u$({keychain:n,profile:t.profile,prompts:a$(r),remember:e.remember,username:e.username,wantedProject:e.wantedProject});await ra({active:t,session:s});let i=x(s.user.name);if(Q(`Logged in as ${i}, project ${x(s.project.name)}`),e.remember&&n)w(`Saved your password in the ${n.name}, so the next login asks only for an OTP code.`);return s},oa=1800000,p$=(e)=>{let t=Dt(e.session);if(t<oa)G(`Your ${e.profile} session expires in ${Wt(t)}. Run \`${He(e.profile)}\` to start a new one.`)},d$=async(e)=>{let{active:t,prompts:r}=e,n=await pe(t.name);if(de(n))return p$({profile:t.name,session:n}),n;let o=`Run \`${He(t.name)}\`.`;if(!r.interactive)throw n?new E(`your ${t.name} session expired`,{hint:o}):new E(`you aren't logged in to ${t.name}`,{hint:o});return w(n?"Your session expired.":"You aren't logged in yet."),na({active:t,prompts:r})},m$=async(e)=>{let{active:t,session:r}=e,{file:n,link:o}=e.link,s;try{s=await I(`Switching to ${o.project.name}…`,()=>Hr({authUrl:t.profile.authUrl,projectId:o.project.id,token:r.token}))}catch(i){if(i instanceof ae&&i.status===401)throw new E(`can't use project ${o.project.name}, which ${ye(n)} links to`,{hint:`Run \`nipa link\` to pick another project. If Keystone revoked your session, run \`${He(t.name)}\`.`});throw i}return w(`Using project ${x(o.project.name)} from ${T(ye(n))}`),sn(s,o.project)},cn=async(e)=>{let{active:t,prompts:r}=e,n=await d$({active:t,prompts:r}),o=e.linked===!1?void 0:t.link;if(!o||o.link.project.id===n.project.id)return{active:t,session:n};return{active:t,session:await m$({active:t,link:o,session:n})}},f$=(e)=>async(t)=>{try{return await t()}catch(r){if((r instanceof he||r instanceof ae?r.status:void 0)===401)throw new E(`your ${e} session expired or was revoked`,{hint:`Run \`${He(e)}\`.`});throw r}},sa=(e)=>new E(`the ${e.name} profile has no Space API URL`,{hint:`Remove it with \`nipa profile rm ${e.name}\`, then add it again with \`--space-url\` and its Space portal URL. \`nipa -P ${e.name} os server list\` works without one.`}),ln=(e)=>{let{spaceUrl:t}=e.profile;if(!t)throw sa(e);return t},Lo=(e)=>{let{active:t,session:r}=e.signedIn,n=f$(t.name),o=xo({projectId:r.project.id,region:t.profile.region,token:r.token,url:e.spaceUrl}),s=(i)=>n(async()=>{try{return await i()}catch(a){if(a instanceof it)throw new E(a.message,{hint:"Check your network connection, or the profile's Space API URL."});throw a}});return{active:t,session:r,space:{get:(i,a)=>s(()=>o.get(i,a)),getLines:(i,a)=>s(()=>o.getLines(i,a)),post:(i)=>s(()=>o.post(i))}}};var Of=["bash","zsh","fish","pwsh"],Lf=["projects","profiles","openstack",...uc],Ut=(e)=>`nipa __complete ${e}`,Ft=Se(es),h$=(e)=>e.filter((t)=>t.kind==="passthrough").flatMap((t)=>xe(t)),ia=(e)=>[...e.flags,...$e],No=(e)=>{let t=e.args.findIndex((n)=>n.value.kind!=="text"),r=e.args[t];return r?{arg:r,position:t+1}:void 0},g$=(e)=>{switch(e.kind){case"none":return;case"text":return"return";case"choice":return`_nipa_reply ${e.choices.join(" ")}; return`;case"project":return`_nipa_reply_lines < <(${Ut("projects")} 2>/dev/null); return`;case"profile":return`_nipa_reply_lines < <(${Ut("profiles")} 2>/dev/null); return`;default:return e}},y$=(e)=>{switch(e.kind){case"text":return;case"project":return`_nipa_reply_lines < <(${Ut("projects")} 2>/dev/null)`;case"profile":return`_nipa_reply_lines < <(${Ut("profiles")} 2>/dev/null)`;case"resource":return`_nipa_reply_lines < <(${Ut(e.resource)} 2>/dev/null)`;case"choice":return`_nipa_reply ${e.choices.join(" ")}`;default:return e}},b$=(e)=>{switch(e.kind){case"program":return`COMP_WORDS[i]=${e.program}; _nipa_offset "$i"`;case"command":return'_nipa_offset "$((i + 1))"';case"openstack":return'_nipa_reply_lines < <(nipa __complete openstack -- "${COMP_WORDS[@]:i+1:COMP_CWORD-i}" 2>/dev/null)';default:return e}},Df=(e,t)=>{let r=" ".repeat(t*2+2),n=[];if(e.kind==="group"){let s=e.subcommands;n.push(`if [[ $COMP_CWORD -eq $((i + 1)) ]]; then _nipa_reply ${s.map((i)=>i.name).join(" ")}; return; fi`,"case ${COMP_WORDS[i + 1]} in",...s.map((i)=>Df(i,t+1)),"esac")}else if(e.kind==="passthrough")n.push(b$(e.target));else{let s=ia(e),i=s.flatMap((u)=>{let p=g$(u.value);return p===void 0?[]:[` ${Se(u).join("|")}) ${p} ;;`]});if(i.length>0)n.push('case "$prev" in',...i,"esac");let a=s.flatMap(Se).join(" ");n.push(`if [[ $cur == -* ]]; then _nipa_reply ${a}; return; fi`);let c=No(e),l=c&&y$(c.arg.value);if(l)n.push(l)}let o=n.map((s)=>`${r} ${s}`).join(`
97
- `);return`${r}${xe(e).join("|")})
93
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let i of e.seen.entries()){let a=i[1];if(t===i[0]){s(i);continue}if(e.external){let l=e.external.registry.get(i[0])?.id;if(t!==i[0]&&l){s(i);continue}}if(e.metadataRegistry.get(i[0])?.id){s(i);continue}if(a.cycle){s(i);continue}if(a.count>1){if(e.reused==="ref")s(i)}}if(e.external)e.sharedDefsExtractedFor=e.external}function Om(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let r=[];for(let n of t){if(!n||typeof n!=="object")return;Om(n);let o=Object.keys(n);if(o.length!==1||o[0]!=="type")return;let s=n.type;for(let i of Array.isArray(s)?s:[s]){if(typeof i!=="string")return;if(!r.includes(i))r.push(i)}}delete e.anyOf,e.type=r.length===1?r[0]:r}var Lm=new Set(["type","properties","required","additionalProperties"]),Tm=["oneOf","anyOf"];function zm(e){let t=e.additionalProperties;if(t===void 0||t===!1||typeof t!=="object"||t===null)return null;return Object.keys(t).length?t:null}function ra(e){let t=[];for(let s of e){if(typeof s!=="object"||s.type!=="object")return null;for(let i in s)if(!Lm.has(i))return null;t.push(s)}let r={},n=new Set;for(let s of t){for(let i in s.properties){if(Object.prototype.hasOwnProperty.call(r,i))continue;let a=[];for(let l of t){let u=l.properties?.[i]??zm(l);if(u===null||u===void 0)continue;if(!a.some((p)=>JSON.stringify(p)===JSON.stringify(u)))a.push(u)}let c=a.length===1?a[0]:ra(a)??{allOf:a};Fe(r,i,c)}for(let i of s.required??[])n.add(i)}let o={type:"object",properties:r};if(n.size)o.required=[...n];if(t.every((s)=>s.additionalProperties===!1))o.additionalProperties=!1;else{let s=[];for(let i of t){let a=zm(i);if(a&&!s.some((c)=>JSON.stringify(c)===JSON.stringify(a)))s.push(a)}if(s.length===1)o.additionalProperties=s[0];else if(s.length>1)o.additionalProperties={allOf:s}}return o}function wv(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let o of Lm)if(o in e)return;let r=t.filter((o)=>Tm.some((s)=>Array.isArray(o[s]))),n=null;if(!r.length)n=ra(t);else{let o=r[0],s=Tm.find((c)=>Array.isArray(o[c]));if(Object.keys(o).length!==1)return;let i=t.filter((c)=>c!==o),a=o[s].map((c)=>ra([...i,c]));if(a.some((c)=>!c))return;n={[s]:a}}if(!n)return;delete e.allOf,rn(e,n)}function sa(e,t){let r=e.seen.get(t);if(!r)throw Error("Unprocessed schema. This is a bug in Zod.");let n=(a)=>{let c=e.seen.get(a);if(c.ref===null)return;let l=c.def??c.schema,u={...l},p=c.ref;if(c.ref=null,p){n(p);let m=e.seen.get(p),h=m.schema;if(h.$ref&&(e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"))l.allOf=l.allOf??[],l.allOf.push(h);else rn(l,h);if(rn(l,u),a._zod.parent===p)for(let b in l){if(b==="$ref"||b==="allOf")continue;if(!(b in u))delete l[b]}if(h.$ref&&m.def)for(let b in l){if(b==="$ref"||b==="allOf")continue;if(b in m.def&&JSON.stringify(l[b])===JSON.stringify(m.def[b]))delete l[b]}}let d=a._zod.parent;if(d&&d!==p){n(d);let m=e.seen.get(d);if(m?.schema.$ref){if(l.$ref=m.schema.$ref,m.def)for(let h in l){if(h==="$ref"||h==="allOf")continue;if(h in m.def&&JSON.stringify(l[h])===JSON.stringify(m.def[h]))delete l[h]}}}e.override({zodSchema:a,jsonSchema:l,path:c.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let a of[...e.seen.entries()].reverse())n(a[0]);if(e.target!=="openapi-3.0")for(let a of e.seen.entries())Om(a[1].def??a[1].schema);for(let a of e.deferred)a();if(e.intersections.length){let a=new Map;for(let c of e.seen.values())for(let l of[c.schema,c.def]){let u=l?.allOf;if(!Array.isArray(u))continue;let p=a.get(u);if(p)p.push(l);else a.set(u,[l])}for(let c of e.intersections)for(let l of a.get(c)??[])wv(l)}}let o={};if(e.target==="draft-2020-12")o.$schema="https://json-schema.org/draft/2020-12/schema";else if(e.target==="draft-07")o.$schema="http://json-schema.org/draft-07/schema#";else if(e.target==="draft-04")o.$schema="http://json-schema.org/draft-04/schema#";else if(e.target==="openapi-3.0");if(e.external?.uri){let a=e.external.registry.get(t)?.id;if(!a)throw Error("Schema is missing an `id` property");o.$id=e.external.uri(a)}rn(o,r.defId?r.schema:r.def??r.schema);let s=e.metadataRegistry.get(t)?.id;if(s!==void 0&&o.id===s)delete o.id;let i=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let a of e.seen.entries()){let c=a[1];if(c.def&&c.defId){if(c.def.id===c.defId)delete c.def.id;Fe(i,c.defId,c.def)}}if(e.external)e.sharedEmitDoneFor=e.external;if(e.external);else if(Object.keys(i).length>0)if(e.target==="draft-2020-12")o.$defs=i;else o.definitions=i;try{let a=JSON.parse(JSON.stringify(o));return Object.defineProperty(a,"~standard",{value:{...t["~standard"],jsonSchema:{input:nn(t,"input",e.processors),output:nn(t,"output",e.processors)}},enumerable:!1,writable:!1}),a}catch(a){throw Error("Error converting schema to JSON.")}}function we(e,t){let r=t??{seen:new Set};if(r.seen.has(e))return!1;r.seen.add(e);let n=e._zod.def;if(n.type==="transform")return!0;if(n.type==="array")return we(n.element,r);if(n.type==="set")return we(n.valueType,r);if(n.type==="lazy")return we(n.getter(),r);if(n.type==="promise"||n.type==="optional"||n.type==="nonoptional"||n.type==="nullable"||n.type==="readonly"||n.type==="default"||n.type==="prefault"||n.type==="catch")return we(n.innerType,r);if(n.type==="intersection")return we(n.left,r)||we(n.right,r);if(n.type==="record"||n.type==="map")return we(n.keyType,r)||we(n.valueType,r);if(n.type==="pipe"){if(e._zod.traits.has("$ZodCodec"))return!0;return we(n.in,r)||we(n.out,r)}if(n.type==="object"){for(let o in n.shape)if(we(n.shape[o],r))return!0;return!1}if(n.type==="union"){for(let o of n.options)if(we(o,r))return!0;return!1}if(n.type==="tuple"){for(let o of n.items)if(we(o,r))return!0;if(n.rest&&we(n.rest,r))return!0;return!1}return!1}var Dm=(e,t={})=>(r)=>{let n=na({...r,processors:t});return ie(e,n),oa(n,e),sa(n,e)},nn=(e,t,r={})=>(n)=>{let{libraryOptions:o,target:s}=n??{},i=na({...o??{},target:s,io:t,processors:r});return ie(e,i),oa(i,e),sa(i,e)};var lr=(e,t,r)=>{if(e[t]===void 0||r>e[t])e[t]=r},ur=(e,t,r)=>{if(e[t]===void 0||r<e[t])e[t]=r},Nm=(e,t)=>{lr(e,"minimum",t),ur(e,"maximum",t)},Mm=(e,t)=>{if(e.multipleOf??(e.multipleOf=[]),!e.multipleOf.includes(t))e.multipleOf.push(t)},Bm=(e,t)=>{e.patterns??(e.patterns=new Set),e.patterns.add(t)},Gm=(e,t)=>{e.mime=e.mime?e.mime.filter((r)=>t.includes(r)):[...t]},Km=(e,t)=>{if(e.format=t,t.includes("int"))e.isInt=!0},Zm=(e,t)=>lr(e,"minimum",t.minimum),Um=(e,t)=>ur(e,"maximum",t.maximum),Fm=(e)=>(t,r)=>{Km(t,r.format);let[n,o]=e[r.format];lr(t,"minimum",n),ur(t,"maximum",o)},vv={greater_than:(e,t)=>lr(e,t.inclusive?"minimum":"exclusiveMinimum",t.value),less_than:(e,t)=>ur(e,t.inclusive?"maximum":"exclusiveMaximum",t.value),multiple_of:(e,t)=>Mm(e,t.value),number_format:Fm(ro),bigint_format:Fm(xi),min_length:Zm,max_length:Um,length_equals:(e,t)=>Nm(e,t.length),min_size:Zm,max_size:Um,size_equals:(e,t)=>Nm(e,t.size),string_format:(e,t)=>{if(Km(e,t.format),t.pattern)Bm(e,t.pattern);if(t.format==="base64"||t.format==="base64url")e.contentEncoding=t.format;if(t.local||t.precision===-1)e.laxFormat=!0},mime_type:(e,t)=>Gm(e,t.mime)};function ze(e){let t={},r=e._zod.def,n=e._zod.traits.has("$ZodCheck")?[e,...r.checks??[]]:r.checks??[];for(let s of n)vv[s._zod.def.check]?.(t,s._zod.def);let o=e._zod.bag;if(o.minimum!==void 0)lr(t,"minimum",o.minimum);if(o.exclusiveMinimum!==void 0)lr(t,"exclusiveMinimum",o.exclusiveMinimum);if(o.maximum!==void 0)ur(t,"maximum",o.maximum);if(o.exclusiveMaximum!==void 0)ur(t,"exclusiveMaximum",o.exclusiveMaximum);if(o.multipleOf!==void 0)Mm(t,o.multipleOf);if(o.format!==void 0){if(t.format??(t.format=o.format),o.format.includes("int"))t.isInt=!0}if(o.mime)Gm(t,o.mime);for(let s of o.patterns??[])Bm(t,s);return t}var _v={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Sv=new Map([[Di,gp],[bo,yp]]),Vm=(e)=>Sv.get(e)??e,Wm=(e,t,r,n)=>{let o=r;o.type="string";let{minimum:s,maximum:i,format:a,patterns:c,contentEncoding:l,laxFormat:u}=ze(e);if(typeof s==="number")o.minLength=s;if(typeof i==="number")o.maxLength=i;if(a){if(o.format=_v[a]??a,o.format==="")delete o.format;if(a==="time"||u)delete o.format}if(l)o.contentEncoding=l;if(c&&c.size>0){let p=[...c].map(Vm);if(p.length===1)o.pattern=p[0].source;else if(p.length>1)o.allOf=[...p.map((d)=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))]}},Jm=(e,t,r,n)=>{let o=r,{minimum:s,maximum:i,multipleOf:a,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=ze(e);o.type=u?"integer":"number";let p=typeof l==="number"&&l>=(s??Number.NEGATIVE_INFINITY),d=typeof c==="number"&&c<=(i??Number.POSITIVE_INFINITY),m=t.target==="draft-04"||t.target==="openapi-3.0";if(p)if(m)o.minimum=l,o.exclusiveMinimum=!0;else o.exclusiveMinimum=l;else if(typeof s==="number")o.minimum=s;if(d)if(m)o.maximum=c,o.exclusiveMaximum=!0;else o.exclusiveMaximum=c;else if(typeof i==="number")o.maximum=i;if(a){let h=new Set;for(let v of a)if(Number.isFinite(v)&&v!==0)h.add(Math.abs(v));else Ft(e,t,o,n,`A multipleOf divisor of ${v} cannot be represented in JSON Schema`);let[y,...b]=h;if(y!==void 0)o.multipleOf=y;if(b.length)o.allOf=[...o.allOf??[],...b.map((v)=>({multipleOf:v}))]}},Hm=(e,t,r,n)=>{r.type="boolean"};var qm=(e,t,r,n)=>{r.not={}};var Ym=(e,t,r,n)=>{};var Xm=(e,t,r,n)=>{let o=e._zod.def,s=Vr(o.entries);if(s.length===0){r.not={};return}if(s.every((i)=>typeof i==="number"))r.type="number";if(s.every((i)=>typeof i==="string"))r.type="string";r.enum=s};var Qm=(e,t,r,n)=>{Ft(e,t,r,n,"Custom types cannot be represented in JSON Schema")};var ef=(e,t,r,n)=>{Ft(e,t,r,n,"Transforms cannot be represented in JSON Schema")};var tf=(e,t,r,n)=>{let o=r,s=e._zod.def,{minimum:i,maximum:a}=ze(e);if(typeof i==="number")o.minItems=i;if(typeof a==="number")o.maxItems=a;o.type="array",o.items=ie(s.element,t,{...n,path:[...n.path,"items"]})};function Io(e){let t=e._zod.def;if(t.type==="pipe"&&t.in._zod.traits.has("$ZodTransform"))return Io(t.out);if(t.type==="catch")return Io(t.innerType);return e._zod.optin}var rf=(e,t,r,n)=>{let o=r,s=e._zod.def,i=s.shape;if(Object.getOwnPropertySymbols(i).length&&Ft(e,t,o,n,"Symbol keys cannot be represented in JSON Schema"))return;o.type="object",o.properties={};for(let l in i)Fe(o.properties,l,ie(i[l],t,{...n,path:[...n.path,"properties",l]}));let c=[];for(let l of Object.keys(i)){let u=s.shape[l];if(t.io==="input"?Io(u)===void 0:u._zod.optout===void 0)c.push(l)}if(c.length>0)o.required=c;if(s.catchall?._zod.def.type==="never")o.additionalProperties=!1;else if(!s.catchall){if(t.io==="output")o.additionalProperties=!1}else if(s.catchall)o.additionalProperties=ie(s.catchall,t,{...n,path:[...n.path,"additionalProperties"]})},nf=(e,t,r,n)=>{let o=e._zod.def,s=o.inclusive===!1,i=o.options.map((a,c)=>ie(a,t,{...n,path:[...n.path,s?"oneOf":"anyOf",c]}));if(s)r.oneOf=i;else r.anyOf=i},of=(e,t,r,n)=>{let o=e._zod.def,s=ie(o.left,t,{...n,path:[...n.path,"allOf",0]}),i=ie(o.right,t,{...n,path:[...n.path,"allOf",1]}),a=(l)=>("allOf"in l)&&Object.keys(l).length===1,c=[...a(s)?s.allOf:[s],...a(i)?i.allOf:[i]];r.allOf=c,t.intersections.push(c)};function ia(e,t,r){if(t.$ref){if(r.has(t))return t;r.add(t);let h=e.get(t)?.def;if(!h)return t;let y=ia(e,h,r);return y===h?t:y}for(let h of["anyOf","oneOf"]){let y=t[h];if(!Array.isArray(y))continue;let b=y.map((v)=>ia(e,v,r));if(b.some((v,E)=>v!==y[E]))t={...t,[h]:b}}let n=Array.isArray(t.type)?t.type:[t.type],o=!n.includes("string")&&n.some((h)=>h==="number"||h==="integer"),s=t.enum??(t.const!==void 0?[t.const]:void 0);if(!o&&!s?.some((h)=>typeof h==="number"))return t;let{minimum:i,maximum:a,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:p,id:d,...m}=t;if(m.enum)m.enum=m.enum.map((h)=>typeof h==="number"?String(h):h);else if(typeof m.const==="number")m.const=String(m.const);if(!o)return m;if(m.type="string",!s)m.pattern=(n.includes("number")?qr:Ai).source;return m}var aa=new WeakMap;function $v(e){let t=new Map;for(let n of e.seen.values())if(n.def&&!t.has(n.schema))t.set(n.schema,n);let r=new Map;for(let n of aa.get(e)??[]){let o=e.seen.get(n),s=(o?.def??o?.schema)?.propertyNames;if(!s||s===!0||r.has(s))continue;let i=ia(t,s,new Set);if(i!==s)r.set(s,i)}if(!r.size)return;for(let n of e.seen.values())for(let o of[n.schema,n.def]){let s=o&&r.get(o.propertyNames);if(s)o.propertyNames=s}}var sf=(e,t,r,n)=>{let o=r,s=e._zod.def;o.type="object";let i=s.keyType,a=ze(i).patterns;if(s.mode==="loose"&&a&&a.size>0){let u=ie(s.valueType,t,{...n,path:[...n.path,"patternProperties","*"]});o.patternProperties={};for(let p of a)Fe(o.patternProperties,Vm(p).source,u)}else{if(t.target==="draft-07"||t.target==="draft-2020-12"){o.propertyNames=ie(s.keyType,t,{...n,path:[...n.path,"propertyNames"]});let u=aa.get(t);if(!u)u=[],aa.set(t,u),t.deferred.push(()=>$v(t));u.push(e)}o.additionalProperties=ie(s.valueType,t,{...n,path:[...n.path,"additionalProperties"]})}let c=i._zod.values,l=t.io==="input"&&Io(s.valueType)!==void 0;if(c&&!s.partial&&!l){let u=[...c].filter((p)=>typeof p==="string"||typeof p==="number");if(u.length>0)o.required=u.map(String)}},af=(e,t,r,n)=>{let o=e._zod.def,s=ie(o.innerType,t,n),i=t.seen.get(e);if(t.target==="openapi-3.0")i.ref=o.innerType,r.nullable=!0;else r.anyOf=[s,{type:"null"}]},cf=(e,t,r,n)=>{let o=e._zod.def;ie(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType},ca=Symbol();function lf(e,t,r,n,o){let s=!1,i=JSON.stringify(e,(a,c)=>{if(typeof c!=="bigint")return c;return s=!0,null});if(!s)return JSON.parse(i);return Ft(t,r,n,o,"BigInt defaults cannot be represented in JSON Schema"),ca}var uf=(e,t,r,n)=>{let o=e._zod.def;ie(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType;let i=lf(o.defaultValue,e,t,r,n);if(i!==ca)r.default=i},pf=(e,t,r,n)=>{let o=e._zod.def;ie(o.innerType,t,n);let s=t.seen.get(e);if(s.ref=o.innerType,t.io!=="input")return;let i=lf(o.defaultValue,e,t,r,n);if(i!==ca)r._prefault=i},df=(e,t,r,n)=>{let o=e._zod.def;ie(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType;let i;try{i=o.catchValue(void 0)}catch{Ft(e,t,r,n,"Dynamic catch values are not supported in JSON Schema");return}r.default=i},mf=(e,t,r,n)=>{let o=e._zod.def,s=o.in._zod.traits.has("$ZodTransform"),i=t.io==="input"?s?o.out:o.in:o.out;ie(i,t,n);let a=t.seen.get(e);a.ref=i},ff=(e,t,r,n)=>{let o=e._zod.def;ie(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType,r.readOnly=!0};var la=(e,t,r,n)=>{let o=e._zod.def;ie(o.innerType,t,n);let s=t.seen.get(e);s.ref=o.innerType};var hf=new WeakSet([Object.prototype,Error.prototype]);function To(e,t,r){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let n=r(this);return Object.defineProperty(this,t,{value:n,configurable:!0,writable:!0}),n},set(n){Object.defineProperty(this,t,{value:n,configurable:!0,writable:!0})}})}var Tv=(e,t)=>{Ku.init(e,t),e.name="ZodError";let r=Object.getPrototypeOf(e);if(hf.has(r))return;hf.add(r),To(r,"format",(n)=>(o)=>ki(n,o)),To(r,"flatten",(n)=>(o)=>$i(n,o)),To(r,"addIssue",(n)=>(o)=>{n.issues.push(o),n.message=JSON.stringify(n.issues,Wr,2)}),To(r,"addIssues",(n)=>(o)=>{n.issues.push(...o),n.message=JSON.stringify(n.issues,Wr,2)}),Object.defineProperty(r,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}})};var Ie=g("ZodError",Tv,void 0,{Parent:Error});var gf=co(Ie),yf=lo(Ie),bf=uo(Ie),xf=po(Ie),wf=Wu(Ie),vf=Ju(Ie),_f=Hu(Ie),Sf=qu(Ie),$f=Yu(Ie),kf=Xu(Ie),Pf=Qu(Ie),Cf=ep(Ie);function Ov(){if(!Pe.localeError)Ce(Bi())}function Lo(){if(!Pe.memoizer)Ce({memoizer:Mi()})}var oe=g("ZodType",(e,t)=>(Ov(),X.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(Re(t,{checks:[...t.checks??[],...e.map((r)=>typeof r==="function"?{_zod:{check:r,def:{check:"custom"},onattach:[]}}:r)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Me(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(E_(e,t))},superRefine(e,t){return this.check(j_(e,t))},overwrite(e){return this.check(vt(e))},optional(){return jf(this)},exactOptional(){return h_(this)},nullable(){return Af(this)},nullish(){return jf(Af(this))},nonoptional(e){return v_(this,e)},array(){return O(this)},or(e){return l_([this,e])},and(e){return p_(this,e)},transform(e){return Rf(this,f_(e))},default(e){return b_(this,e)},prefault(e){return w_(this,e)},catch(e){return S_(this,e)},pipe(e){return Rf(this,e)},readonly(){return P_(this)},describe(e){let t=this.clone();return wt.add(t,{description:e}),t},meta(...e){if(e.length===0)return wt.get(this);let t=this.clone();return wt.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get "~standard"(){return io(this,"~standard",{...Li(this),jsonSchema:{input:nn(this,"input"),output:nn(this,"output")}})},set "~standard"(e){it(this,"~standard",e)},parse:function e(t,r){return gf(this,t,r,{callee:e})},parseAsync:async function e(t,r){return await yf(this,t,r,{callee:e})},safeParse(e,t){return bf(this,e,t)},async safeParseAsync(e,t){return xf(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){it(this,"spa",e)},validate(e,t){return Pi(this,e,t)},validateAsync(e,t){return Ci(this,e,t)},encode:function e(t,r){return wf(this,t,r,{callee:e})},decode:function e(t,r){return vf(this,t,r,{callee:e})},encodeAsync:async function e(t,r){return await _f(this,t,r,{callee:e})},decodeAsync:async function e(t,r){return await Sf(this,t,r,{callee:e})},safeEncode(e,t){return $f(this,e,t)},safeDecode(e,t){return kf(this,e,t)},async safeEncodeAsync(e,t){return Pf(this,e,t)},async safeDecodeAsync(e,t){return Cf(this,e,t)},toJSONSchema(e){return Dm(this,{})(e)},get description(){return wt.get(this)?.description},get _def(){return this._zod.def}}),If=g("_ZodString",(e,t)=>{yo.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Wm(e,r,n,o)},Zu({format:(e)=>ze(e).format??null,minLength:(e)=>ze(e).minimum??null,maxLength:(e)=>ze(e).maximum??null},{regex(...e){return this.check(Ki(...e))},includes(...e){return this.check(Ji(...e))},startsWith(...e){return this.check(Hi(...e))},endsWith(...e){return this.check(qi(...e))},min(...e){return this.check(cr(...e))},max(...e){return this.check(Ao(...e))},length(...e){return this.check(Ro(...e))},nonempty(...e){return this.check(cr(1,...e))},lowercase(e){return this.check(Vi(e))},uppercase(e){return this.check(Wi(e))},trim(){return this.check(Xi())},normalize(...e){return this.check(Yi(...e))},toLowerCase(){return this.check(Qi())},toUpperCase(){return this.check(ea())},slugify(){return this.check(ta())}})),Lv=g("ZodString",(e,t)=>{yo.init(e,t),If.init(e,t)},{email(e){return this.check(nm(Dv,e))},url(e){return this.check(Gi(Tf,e))},jwt(e){return this.check(Sm(e_,e))},emoji(e){return this.check(lm(Uv,e))},guid(e){return this.check(om(Nv,e))},uuid(e){return this.check(sm(zo,e))},uuidv4(e){return this.check(im(zo,e))},uuidv6(e){return this.check(am(zo,e))},uuidv7(e){return this.check(cm(zo,e))},nanoid(e){return this.check(um(Fv,e))},cuid(e){return this.check(pm(Mv,e))},cuid2(e){return this.check(dm(Bv,e))},ulid(e){return this.check(mm(Gv,e))},base64(e){return this.check(wm(Yv,e))},base64url(e){return this.check(vm(Xv,e))},xid(e){return this.check(fm(Kv,e))},ksuid(e){return this.check(hm(Vv,e))},ipv4(e){return this.check(gm(Wv,e))},ipv6(e){return this.check(ym(Jv,e))},cidrv4(e){return this.check(bm(Hv,e))},cidrv6(e){return this.check(xm(qv,e))},e164(e){return this.check(_m(Qv,e))},datetime(e){return this.check(So(sn,e))},date(e){return this.check($o(an,e))},time(e){return this.check(ko(cn,e))},duration(e){return this.check(Po(ln,e))}});function f(e){return rm(Lv,e)}var Q=g("ZodStringFormat",(e,t)=>{q.init(e,t),If.init(e,t)}),sn=g("ZodISODateTime",(e,t)=>{dd.init(e,t),Q.init(e,t)}),an=g("ZodISODate",(e,t)=>{md.init(e,t),Q.init(e,t)}),cn=g("ZodISOTime",(e,t)=>{fd.init(e,t),Q.init(e,t)}),ln=g("ZodISODuration",(e,t)=>{hd.init(e,t),Q.init(e,t)}),Dv=g("ZodEmail",(e,t)=>{td.init(e,t),Q.init(e,t)});var Nv=g("ZodGUID",(e,t)=>{Qp.init(e,t),Q.init(e,t)});var zo=g("ZodUUID",(e,t)=>{ed.init(e,t),Q.init(e,t)});var Tf=g("ZodURL",(e,t)=>{od.init(e,t),Q.init(e,t)});function Zv(e){return Gi(Tf,e)}var Uv=g("ZodEmoji",(e,t)=>{sd.init(e,t),Q.init(e,t)});var Fv=g("ZodNanoID",(e,t)=>{id.init(e,t),Q.init(e,t)});var Mv=g("ZodCUID",(e,t)=>{ad.init(e,t),Q.init(e,t)});var Bv=g("ZodCUID2",(e,t)=>{cd.init(e,t),Q.init(e,t)});var Gv=g("ZodULID",(e,t)=>{ld.init(e,t),Q.init(e,t)});var Kv=g("ZodXID",(e,t)=>{ud.init(e,t),Q.init(e,t)});var Vv=g("ZodKSUID",(e,t)=>{pd.init(e,t),Q.init(e,t)});var Wv=g("ZodIPv4",(e,t)=>{gd.init(e,t),Q.init(e,t)});var Jv=g("ZodIPv6",(e,t)=>{bd.init(e,t),Q.init(e,t)});var Hv=g("ZodCIDRv4",(e,t)=>{xd.init(e,t),Q.init(e,t)});var qv=g("ZodCIDRv6",(e,t)=>{wd.init(e,t),Q.init(e,t)});var Yv=g("ZodBase64",(e,t)=>{_d.init(e,t),Q.init(e,t)});var Xv=g("ZodBase64URL",(e,t)=>{Sd.init(e,t),Q.init(e,t)});var Qv=g("ZodE164",(e,t)=>{$d.init(e,t),Q.init(e,t)});var e_=g("ZodJWT",(e,t)=>{kd.init(e,t),Q.init(e,t)});var zf=g("ZodNumber",(e,t)=>{Ni.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Jm(e,r,n,o),e.isFinite=!0},Zu({minValue:(e)=>{let{minimum:t,exclusiveMinimum:r}=ze(e);return Math.max(t??Number.NEGATIVE_INFINITY,r??Number.NEGATIVE_INFINITY)},maxValue:(e)=>{let{maximum:t,exclusiveMaximum:r}=ze(e);return Math.min(t??Number.POSITIVE_INFINITY,r??Number.POSITIVE_INFINITY)},isInt:(e)=>{let{isInt:t,multipleOf:r}=ze(e);return!!t||!!r?.some(Number.isSafeInteger)},format:(e)=>ze(e).format??null},{gt(e,t){return this.check(Eo(e,t))},gte(e,t){return this.check(tn(e,t))},min(e,t){return this.check(tn(e,t))},lt(e,t){return this.check(Co(e,t))},lte(e,t){return this.check(en(e,t))},max(e,t){return this.check(en(e,t))},int(e){return this.check(Ef(e))},safe(e){return this.check(Ef(e))},positive(e){return this.check(Eo(0,e))},nonnegative(e){return this.check(tn(0,e))},negative(e){return this.check(Co(0,e))},nonpositive(e){return this.check(en(0,e))},multipleOf(e,t){return this.check(jo(e,t))},step(e,t){return this.check(jo(e,t))},finite(){return this}}));function ee(e){return $m(zf,e)}var t_=g("ZodNumberFormat",(e,t)=>{Pd.init(e,t),zf.init(e,t)});function Ef(e){return km(t_,e)}var r_=g("ZodBoolean",(e,t)=>{Cd.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Hm(e,r,n,o)});function pr(e){return Pm(r_,e)}var n_=g("ZodUnknown",(e,t)=>{Ed.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Ym(e,r,n,o)});function Oo(){return Cm(n_)}var o_=g("ZodNever",(e,t)=>{jd.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>qm(e,r,n,o)});function s_(e){return Em(o_,e)}var i_=g("ZodArray",(e,t)=>{Lo(),Ad.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>tf(e,r,n,o),e.element=t.element},{min(e,t){return this.check(cr(e,t))},nonempty(e){return this.check(cr(1,e))},max(e,t){return this.check(Ao(e,t))},length(e,t){return this.check(Ro(e,t))},unwrap(){return this.element}});function O(e,t){return jm(i_,e,t)}var a_=g("ZodObject",(e,t)=>{Lo(),Td.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>rf(e,r,n,o),Bw(e,"shape",(r)=>r._zod.def.shape,!1)},{keyof(){return Of(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(Re(this._zod.def,{catchall:e}))},passthrough(){return this.clone(Re(this._zod.def,{catchall:Oo()}))},loose(){return this.clone(Re(this._zod.def,{catchall:Oo()}))},strict(){return this.clone(Re(this._zod.def,{catchall:s_()}))},strip(){return this.clone(Re(this._zod.def,{catchall:void 0}))},extend(e){return Ow(this,e)},safeExtend(e){return Lw(this,e)},merge(e){return Dw(this,e)},pick(e){return Tw(this,e)},omit(e){return zw(this,e)},partial(...e){return Ou(Lf,this,e[0])},exactPartial(...e){return Ou(Df,this,e[0],"exactPartial")},required(...e){return Nw(Nf,this,e[0])}});function _(e,t){let r={type:"object",shape:e??{},...A(t)};return new a_(r)}var c_=g("ZodUnion",(e,t)=>{zd.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>nf(e,r,n,o),e.options=t.options});function l_(e,t){return new c_({type:"union",options:e,...A(t)})}var u_=g("ZodIntersection",(e,t)=>{Od.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>of(e,r,n,o)});function p_(e,t){return new u_({type:"intersection",left:e,right:t})}var ua=g("ZodRecord",(e,t)=>{Lo(),Ld.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>sf(e,r,n,o),e.keyType=t.keyType,e.valueType=t.valueType});function dr(e,t,r){if(!t||!t._zod)return new ua({type:"record",keyType:f(),valueType:e,...A(t)});return new ua({type:"record",keyType:e,valueType:t,...A(r)})}function d_(e,t,r){return new ua({type:"record",keyType:e,valueType:t,...A(r),partial:!0})}var pa=g("ZodEnum",(e,t)=>{Dd.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(n,o,s)=>Xm(e,n,o,s),e.enum=t.entries,e.options=[...e._zod.values];let r=new Set(Object.keys(t.entries));e.extract=(n,o)=>{let s={};for(let i of n)if(r.has(i))s[i]=t.entries[i];else throw Error(`Key ${i} not found in enum`);return new pa({...t,checks:[],...A(o),entries:s})},e.exclude=(n,o)=>{let s={...t.entries};for(let i of n)if(r.has(i))delete s[i];else throw Error(`Key ${i} not found in enum`);return new pa({...t,checks:[],...A(o),entries:s})}});function Of(e,t){let r=Array.isArray(e)?Object.fromEntries(e.map((n)=>[n,n])):e;return new pa({type:"enum",entries:r,...A(t)})}var m_=g("ZodTransform",(e,t)=>{Lo(),Nd.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ef(e,r,n,o),e._zod.parse=(r,n)=>{if(n.direction==="backward")throw new Jr(e.constructor.name);r.addIssue=(s)=>{if(typeof s==="string")r.issues.push(Ut(s,r.value,t));else{let i=s;if(i.fatal)i.continue=!1;if(i.code??(i.code="custom"),!("input"in i))i.input=r.value;i.inst??(i.inst=e),r.issues.push(Ut(i))}};let o=t.transform(r.value,r);if(o instanceof Promise)return o.then((s)=>(r.value=s,r));return r.value=o,r}});function f_(e){return new m_({type:"transform",transform:e})}var Lf=g("ZodOptional",(e,t)=>{Zi.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>la(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function jf(e){return new Lf({type:"optional",innerType:e})}var Df=g("ZodExactOptional",(e,t)=>{Zd.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>la(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function h_(e){return new Df({type:"optional",innerType:e})}var g_=g("ZodNullable",(e,t)=>{Ud.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>af(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function Af(e){return new g_({type:"nullable",innerType:e})}var y_=g("ZodDefault",(e,t)=>{Fd.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>uf(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function b_(e,t){return new y_({type:"default",innerType:e,get defaultValue(){return typeof t==="function"?t():yi(t)}})}var x_=g("ZodPrefault",(e,t)=>{Md.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>pf(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function w_(e,t){return new x_({type:"prefault",innerType:e,get defaultValue(){return typeof t==="function"?t():yi(t)}})}var Nf=g("ZodNonOptional",(e,t)=>{Bd.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>cf(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function v_(e,t){return new Nf({type:"nonoptional",innerType:e,...A(t)})}var __=g("ZodCatch",(e,t)=>{Gd.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>df(e,r,n,o),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function S_(e,t){return new __({type:"catch",innerType:e,catchValue:typeof t==="function"?t:Uu(t)})}var $_=g("ZodPipe",(e,t)=>{Kd.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>mf(e,r,n,o),e.in=t.in,e.out=t.out});function Rf(e,t){return new $_({type:"pipe",in:e,out:t})}var k_=g("ZodReadonly",(e,t)=>{Vd.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>ff(e,r,n,o),e.unwrap=()=>e._zod.def.innerType});function P_(e){return new k_({type:"readonly",innerType:e})}var C_=g("ZodCustom",(e,t)=>{Wd.init(e,t),oe.init(e,t),e._zod.processJSONSchema=(r,n,o)=>Qm(e,r,n,o)});function E_(e,t={}){return Am(C_,e,t)}function j_(e,t){return Rm(e,t)}function A_(e){return So(sn,e)}function R_(e){return $o(an,e)}function I_(e){return ko(cn,e)}function T_(e){return Po(ln,e)}var da=()=>process.env.NIPA_DEBUG==="1",at=(e)=>{if(da())V(P(`> [debug] [${new Date().toISOString()}] ${e}`))};class Be extends Error{url;constructor(e,t){super(`can't reach ${new URL(e).host}: ${t}`);this.name="NetworkError",this.url=e}}var ma=(e)=>e.cause instanceof Error?`${e.message} (${ma(e.cause)})`:e.message,z_=30000,O_=(e,t)=>{let r=e.headers.get("Location");if(!r)return;try{let{origin:n}=new URL(r,t);return n==="null"?void 0:n}catch{return}},qe=async(e,t={})=>{let r=t.method??"GET",n=t.redirect??"manual",o=performance.now();at(`${r} ${e}`);let s;try{s=await fetch(e,{...t,redirect:n,signal:t.signal??AbortSignal.timeout(z_)})}catch(i){throw new Be(e,i instanceof Error?ma(i):String(i))}if(at(`${s.status} ${r} ${e} [${T(performance.now()-o)}]`),n==="manual"&&s.status>=300&&s.status<400){let i=O_(s,e);throw new Be(e,i?`it redirects to ${i}`:"it redirects somewhere else")}return s},un=async(e)=>{try{return await e.text()}catch(t){throw new Be(e.url,t instanceof Error?ma(t):String(t))}};var pn=_({domainId:f().optional(),id:f(),name:f()});class ae extends Error{status;constructor(e,t){super(e);this.name="KeystoneError",this.status=t}}var mr=(e)=>{let t=e;while(t.endsWith("/"))t=t.slice(0,-1);if(t.endsWith("/v3"))t=t.slice(0,-3);return`${t}/v3`},fa=(e,t)=>t?{auth:{identity:e,scope:{project:{id:t}}}}:{auth:{identity:e}},Uf=(e)=>({domain:{name:e.userDomain},name:e.username}),L_=(e,t)=>fa({methods:["password"],password:{user:{...Uf(e),password:t}}},e.projectId),D_=(e,t)=>fa({methods:["totp"],totp:{user:{...Uf(e),passcode:t}}},e.projectId),N_=(e,t)=>fa({methods:["token"],token:{id:e}},t),Z_=_({error:_({message:f().optional()}).optional(),receipt:_({}).loose().optional(),required_auth_methods:O(O(f())).optional()}),Ff=async(e)=>{try{let t=Z_.safeParse(JSON.parse(await e.text()));return t.success?t.data:{}}catch{return{}}},Mf=(e)=>e.length>0?`this account needs ${e.map((t)=>t.join(" + ")).join(" or ")} to log in`:"this account's MFA rules don't allow this login method",U_=(e)=>{let{body:t,status:r}=e;if(t.receipt)return Mf(t.required_auth_methods??[]);if(r===401)return e.unauthorized;return t.error?.message??`Keystone returned HTTP ${r}`},dn=async(e,t)=>{let r=await Ff(e);throw new ae(U_({body:r,status:e.status,unauthorized:t}),e.status)},F_=_({token:_({expires_at:f(),project:_({domain:_({id:f()}).optional(),id:f(),name:f()}).optional(),user:_({id:f(),name:f()})})}),M_=(e,t)=>{let{expires_at:r,project:n,user:o}=t.token;return{expiresAt:r,project:n&&{domainId:n.domain?.id,id:n.id,name:n.name},user:o,value:e}},Bf="Openstack-Auth-Receipt",ha=(e,t,r={})=>{let{receipt:n,signal:o}=r,s=new Headers({"Content-Type":"application/json"});if(n!==void 0)s.set(Bf,n);return qe(`${mr(e)}/auth/tokens`,{body:JSON.stringify(t),headers:s,method:"POST",signal:o})},Gf=async(e,t,r)=>{let n=await un(e),o;try{o=r.safeParse(JSON.parse(n))}catch{throw new ae(`unexpected ${t}: the body isn't JSON`,e.status)}if(!o.success)throw new ae(`unexpected ${t}: ${Hr(o.error)}`,e.status);return o.data},ga=async(e)=>{let t=e.headers.get("X-Subject-Token");if(!t)throw new ae("Keystone didn't return a token",e.status);return M_(t,await Gf(e,"token response",F_))},Kf=async(e,t)=>{let r=await ha(e.authUrl,L_(e,t));if(r.ok)return{kind:"token",token:await ga(r)};let n=r.headers.get(Bf);if(r.status===401&&n){let s=(await Ff(r)).required_auth_methods;if(!s||s.some((i)=>i.includes("totp")))return{kind:"mfa",receipt:n};throw new ae(Mf(s),r.status)}return dn(r,"wrong email or password")},Vf=async(e)=>{let{account:t,passcode:r,receipt:n}=e,o=await ha(t.authUrl,D_(t,r),{receipt:n});return o.ok?ga(o):dn(o,"wrong OTP code")},ya="the session expired or was revoked",Mt=async(e)=>{let t=await ha(e.authUrl,N_(e.token,e.projectId),{signal:e.signal});return t.ok?ga(t):dn(t,ya)},B_=_({projects:O(_({domain_id:f().optional(),enabled:pr().optional(),id:f(),name:f()}))}),G_=(e)=>e.projects.filter((t)=>t.enabled!==!1).map((t)=>({domainId:t.domain_id,id:t.id,name:t.name})).toSorted((t,r)=>t.name.localeCompare(r.name)),Oe=async({authUrl:e,signal:t,token:r})=>{let n=await qe(`${mr(e)}/auth/projects`,{headers:{"X-Auth-Token":r},signal:t});if(!n.ok)return dn(n,ya);return G_(await Gf(n,"project list",B_))},No=async({authUrl:e,token:t})=>{let r=await qe(`${mr(e)}/auth/tokens`,{headers:{"X-Auth-Token":t,"X-Subject-Token":t},method:"DELETE"});if(!(r.ok||r.status===401||r.status===404))await dn(r,ya)},Zf=_({version:_({id:f(),status:f()})}),Zo=async(e)=>{let t=mr(e),r=await qe(t,{signal:AbortSignal.timeout(1e4)}),n;try{n=Zf.safeParse(await r.json())}catch{n=Zf.safeParse(null)}if(!(r.ok&&n.success))throw new ae(`${t} doesn't answer like Keystone v3 (HTTP ${r.status})`,r.status);return n.data.version.id};import{setTimeout as J_}from"node:timers/promises";class ce extends Error{status;constructor(e,t){super(e);this.name="ApiError",this.status=t}}var K_=_({message:f()}),Jf=async(e)=>{try{let t=K_.safeParse(JSON.parse(await e.text()));return t.success?t.data.message:void 0}catch{return}},V_=(e,t)=>{try{return t.safeParse(JSON.parse(e))}catch{return t.safeParse(null)}},Wf=(e,t,r)=>{let n=V_(e,t);if(!n.success)throw new ce(`unexpected Space API response: ${Hr(n.error)}`,r);return n.data},ba=(e)=>{let t=e;while(t.endsWith("/"))t=t.slice(0,-1);return t},mn=(e)=>{let{origin:t,pathname:r}=new URL(e),n=ba(r);return n===""?`${t}/api`:`${t}${n}`},Hf=(e)=>{let{origin:t,pathname:r}=new URL(e),n=ba(r);return n.endsWith("/api")?`${t}${n.slice(0,-4)}`:t},Uo=async(e)=>{let t=await qe(`${e}/v3/instances`,{headers:{Accept:"application/json"},signal:AbortSignal.timeout(1e4)}),r=await Jf(t);if(t.status!==401||r===void 0)throw new ce(`${e} doesn't answer like the Space API (HTTP ${t.status})`,t.status)},W_=/(?:Z|[+-]\d{2}:?\d{2})$/iu,_t=(e)=>W_.test(e)?e:`${e}Z`,Fo=(e)=>{let t=ba(e.url),r=async(o,s)=>{let i=await qe(`${t}${o}`,{headers:{Accept:"application/json","Project-Id":e.projectId,Region:e.region,"X-Auth-Token":e.token},method:s,signal:e.signal});if(!i.ok){let a=await Jf(i)??`the Space API returned HTTP ${i.status}`;throw new ce(a,i.status)}return i},n=async(o)=>{let s=await r(o,"GET");if(!s.headers.get("Content-Type")?.includes("json"))throw new C(`${t} doesn't answer like the Space API`,{hint:"Check the profile's `spaceUrl` with `nipa profile ls --json`. It's the portal URL with /api, such as https://space.nipa.cloud/api."});return s};return{get:async(o,s)=>{let i=await n(o);return Wf(await un(i),s,i.status)},getLines:async(o,s)=>{let i=await n(o);return(await un(i)).split(`
94
+ `).filter((l)=>l.trim()).map((l)=>Wf(l,s,i.status))},post:async(o)=>{await r(o,"POST")}}};var qf=_({address:f()}),H_=_({kube_version:f().optional(),magnum_cluster_id:f().optional(),magnum_role:f().optional()}),q_=_({attached_as:f().nullish(),id:f(),name:f().nullish(),size:ee(),volume_type:f().nullish()}),Y_=_({"OS-EXT-AZ:availability_zone":f().nullish(),created:f(),external_ips:O(qf),flavor:_({name:f(),ram:ee().optional(),vcpus:ee().optional()}),id:f(),internal_ips:O(qf),metadata:H_.optional(),name:f(),security_groups:O(f()).optional(),status:f(),volumes:O(q_).optional()}),X_=_({instances:O(Y_)}),Yf=(e,t)=>({address:e.address,type:t,version:e.address.includes(":")?6:4}),Q_=(e={})=>e.magnum_cluster_id===void 0?null:{clusterId:e.magnum_cluster_id,role:e.magnum_role??null,version:e.kube_version??null},eS=(e)=>({attachedAs:e.attached_as??null,id:e.id,name:e.name??null,sizeGb:e.size,type:e.volume_type??null}),tS=(e)=>({addresses:[...e.internal_ips.map((t)=>Yf(t,"fixed")),...e.external_ips.map((t)=>Yf(t,"floating"))],createdAt:e.created,flavor:e.flavor.name,id:e.id,kubernetes:Q_(e.metadata),name:e.name,ramMb:e.flavor.ram??null,securityGroups:e.security_groups??[],status:e.status,vcpus:e.flavor.vcpus??null,volumes:(e.volumes??[]).map(eS),zone:e["OS-EXT-AZ:availability_zone"]??null}),St=(e)=>{let t=e.addresses.filter((n)=>n.version===4);return(t.find((n)=>n.type==="floating")??t[0]??e.addresses[0])?.address},Ee=async(e)=>(await e.get("/v3/instances",X_)).instances.map(tS),rS=_({instance:_({locked:pr().nullish(),status:f(),task_state:f().nullable()})}),xa=async(e,t)=>{let{instance:r}=await e.get(`/v4/instances/${t}`,rS);return{locked:r.locked??null,status:r.status,taskState:r.task_state}},wa=(e,t,r)=>e.post(`/v4/instances/${t}/action/${r}`),Xf=(e)=>{let t=e.sleep??J_,r=e.now??Date.now,n=r()+e.timeoutMs,o=async()=>{let s=await xa(e.space,e.id);if(s.status==="ERROR")return{kind:"error"};if(s.status===e.status&&s.taskState===null)return{kind:"done"};if(r()>=n)return{kind:"timeout",state:s};return await t(e.intervalMs),o()};return o()},nS=_({logs:f()}),Qf=async(e,t)=>{try{return{kind:"log",text:(await e.get(`/v4/instances/${t}/logs`,nS)).logs}}catch(r){if(r instanceof ce&&r.status===406)return{kind:"none"};throw r}},oS=_({action:f(),id:f(),remark:f().nullish(),started_at:f(),user_name:f().nullish()}),sS=_({action_histories:O(oS)}),Mo=(e)=>e.remark==="Error",Bo=async(e,t)=>(await e.get(`/v4/instances/${t}/action_histories`,sS)).action_histories.map((o)=>({action:o.action,remark:o.remark??null,requestId:o.id,startedAt:_t(o.started_at),user:o.user_name??null})).toSorted((o,s)=>Date.parse(s.startedAt)-Date.parse(o.startedAt));var iS=_({allowed_cidrs:O(f()).nullish(),availability_zone:f().nullish(),datastore_type:f(),datastore_version:f(),external_ip_address:f().nullish(),id:f(),instance_status:f(),ip_address:f(),machine_type:_({name:f(),ram:ee().nullish(),vcpus:ee().nullish()}),operating_status:f(),service_status_updated:f().nullish(),volume_size:ee()}),aS=_({created_at:f(),id:f(),name:f(),primary:iS.nullish()}),cS=_({database_clusters:O(aS)}),lS=_({database_instances:O(_({database_cluster_id:f().nullish(),id:f(),instance_status:f(),ip_address:f().nullish(),name:f(),operating_status:f().nullish()}))}),uS=dr(f(),_({name:f(),published:ee().nullish(),status:f()})),pS=_({database_backups:O(_({created_at:f(),database_instance_id:f(),id:f(),name:f(),size:ee().nullish(),status:f()}))}),fr=(e)=>e.externalAddress??e.address,dS=new Map([["mariadb",3306],["mongodb",27017],["mysql",3306],["percona",3306],["postgresql",5432],["redis",6379]]),mS=(e)=>({address:e.ip_address,allowedCidrs:e.allowed_cidrs??[],engine:e.datastore_type,externalAddress:e.external_ip_address||null,flavor:e.machine_type.name,health:e.operating_status,healthCheckedAt:e.service_status_updated??null,id:e.id,ramMb:e.machine_type.ram??null,status:e.instance_status,storageGb:e.volume_size,vcpus:e.machine_type.vcpus??null,version:e.datastore_version,zone:e.availability_zone||null}),fS=(e)=>({createdAt:e.created_at,id:e.id,name:e.name,primary:e.primary?mS(e.primary):null}),Go=async(e)=>(await e.get("/v4/database/clusters?include_primary=true&include_machine_type=true",cS)).database_clusters.map(fS).toSorted((r,n)=>Date.parse(n.createdAt)-Date.parse(r.createdAt)),hS=async(e,t,r)=>(await e.get(`/v4/databases?database_cluster_id=${encodeURIComponent(t.id)}`,lS)).database_instances.filter((o)=>o.database_cluster_id===t.id&&o.id!==r).map((o)=>({address:o.ip_address||null,health:o.operating_status??"UNKNOWN",id:o.id,name:o.name,status:o.instance_status})),gS=new Set(["DISABLED","UNAVAILABLE"]),yS=async(e,t)=>{let r=await e.get(`/v4/database/${encodeURIComponent(t)}/logs`,uS);return Object.values(r).map((n)=>({enabled:!gS.has(n.status.toUpperCase()),name:n.name,publishedBytes:n.published??0,status:n.status}))},bS=async(e,t)=>(await e.get(`/v4/database/backups?database_instance_id=${encodeURIComponent(t)}`,pS)).database_backups.filter((n)=>n.database_instance_id===t).map((n)=>({createdAt:_t(n.created_at),id:n.id,name:n.name,sizeGb:n.size??null,status:n.status})).toSorted((n,o)=>Date.parse(o.createdAt)-Date.parse(n.createdAt)),va=(e)=>e.status==="fulfilled"?e.value:null,eh=async(e,t)=>{let{primary:r}=t;if(!r)return{...t,backups:[],defaultPort:null,logs:[],replicas:[]};let[n,o,s]=await Promise.allSettled([hS(e,t,r.id),yS(e,r.id),bS(e,r.id)]);return{...t,backups:va(s),defaultPort:dS.get(r.engine.toLowerCase())??null,logs:va(o),replicas:va(n)}};var xS=_({availability_zone:f(),external_ip_address:f(),id:f(),internal_ip_address:f().nullable(),name:f(),status:f()}),wS=_({external_ips:O(xS)}),vS=(e)=>({address:e.external_ip_address,id:e.id,internalAddress:e.internal_ip_address,name:e.name,status:e.status,zone:e.availability_zone}),Ko=async(e)=>(await e.get("/v4/external_ips",wS)).external_ips.map(vS);var _S=_({created_at:f(),id:f(),listeners:O(Oo()),name:f(),operating_status:f(),provisioning_status:f(),vip_address:f()}),SS=_({loadbalancers:O(_S)}),$S=(e)=>({address:e.vip_address,createdAt:e.created_at,health:e.operating_status,id:e.id,listeners:e.listeners.length,name:e.name,status:e.provisioning_status}),Vo=async(e)=>(await e.get("/v4/loadbalancers",SS)).loadbalancers.map($S).toSorted((r,n)=>Date.parse(n.createdAt)-Date.parse(r.createdAt)),hn=_({id:f(),operating_status:f(),provisioning_status:f()}),kS=_({loadbalancer:hn.extend({created_at:f(),external_ip_id:f().nullish(),flavor_id:f().nullish(),name:f(),vip_address:f()})}),PS=_({listeners:O(hn.extend({allowed_cidrs:O(f()).nullish(),backend_group_id:f().nullish(),name:f().nullish(),protocol:f(),protocol_port:ee()}))}),CS=hn.extend({delay:ee(),max_retries:ee(),timeout:ee(),type:f()}),ES=_({backend_groups:O(hn.extend({healthcheck:CS.nullish(),lb_algorithm:f(),name:f().nullish(),protocol:f()}))}),jS=_({members:O(hn.extend({address:f(),backup:pr().nullish(),name:f().nullish(),protocol_port:ee(),weight:ee().nullish()}))}),AS=_({loadbalancer_flavors:O(_({id:f(),name:f()}))}),fn=(e)=>({health:e.operating_status,id:e.id,status:e.provisioning_status}),RS=async(e,t)=>(await e.get(`${t}/members`,jS)).members.map((n)=>({...fn(n),address:n.address,backup:n.backup??!1,name:n.name??null,port:n.protocol_port,weight:n.weight??null})),IS=async(e,t)=>{if(!t)return null;return(await Ko(e)).find((n)=>n.id===t)?.address??null},TS=async(e,t)=>{if(!t)return null;let{loadbalancer_flavors:r}=await e.get("/v4/loadbalancerflavors",AS);return r.find((n)=>n.id===t)?.name??t},th=(e)=>e.status==="fulfilled"?e.value:null,nh=async(e,t)=>{let r=`/v4/loadbalancers/${encodeURIComponent(t)}`,[n,o,s]=await Promise.all([e.get(r,kS),e.get(`${r}/listeners`,PS),e.get(`${r}/backend_groups`,ES)]),i=n.loadbalancer,[a,c]=await Promise.all([Promise.all(s.backend_groups.map((p)=>RS(e,`${r}/backend_groups/${p.id}`))),Promise.allSettled([TS(e,i.flavor_id),IS(e,i.external_ip_id)])]),[l,u]=c;return{...fn(i),address:i.vip_address,backendGroups:s.backend_groups.map((p,d)=>({...fn(p),algorithm:p.lb_algorithm,healthCheck:p.healthcheck?{...fn(p.healthcheck),delaySeconds:p.healthcheck.delay,maxRetries:p.healthcheck.max_retries,timeoutSeconds:p.healthcheck.timeout,type:p.healthcheck.type}:null,members:a[d]??[],name:p.name??null,protocol:p.protocol})),createdAt:i.created_at,externalAddress:th(u),flavor:th(l),listenerDetails:o.listeners.map((p)=>({...fn(p),allowedCidrs:p.allowed_cidrs??[],backendGroupId:p.backend_group_id??null,name:p.name??null,port:p.protocol_port,protocol:p.protocol})),name:i.name}},zS=new Set(["ONLINE","NO_MONITOR"]),$t=(e)=>e.status==="ACTIVE"&&zS.has(e.health),OS=new Set(["OFFLINE","DRAINING"]),$a=(e)=>e.backup&&e.status==="ACTIVE"&&OS.has(e.health),rh=["listener","listeners"],_a=["is unhealthy","are unhealthy"],Sa=(e)=>e.filter((t)=>!$t(t)).length,LS=({failing:e,noun:t,predicate:r,total:n})=>{if(n===1)return`the ${t[0]} ${r[0]}`;let[o,s]=r;return`${e} of ${n} ${t[1]} ${e===1?o:s}`},DS=(e)=>{if($t(e)||e.members.length===0)return!1;if(e.healthCheck&&!$t(e.healthCheck))return!1;return!e.members.some((t)=>!($t(t)||$a(t)))},NS=(e)=>`Backup member ${e.name??e.id} is ${e.health.toLowerCase()} until the other members go down`,oh=(e)=>{let{backendGroups:t,listenerDetails:r}=e,n=new Map(t.map((p)=>[p.id,p.members.length])),o=r.filter((p)=>!n.get(p.backendGroupId??"")),s=t.flatMap((p)=>p.healthCheck??[]),i=t.flatMap((p)=>p.members),a=i.filter((p)=>!$a(p)),l=[{failing:Sa(r),noun:rh,predicate:_a,total:r.length},{failing:o.length,noun:rh,predicate:["has no members to send traffic to","have no members to send traffic to"],total:r.length},{failing:t.filter(DS).length,noun:["backend group","backend groups"],predicate:_a,total:t.length},{failing:Sa(s),noun:["health check","health checks"],predicate:_a,total:s.length},{failing:Sa(a),noun:["member","members"],predicate:["is down","are down"],total:i.length}].filter((p)=>p.failing>0).map(LS);if(r.length===0)l.unshift("the load balancer has no listeners");else if(l.length===0&&!$t(e))l.push("the load balancer is unhealthy");let u=i.filter($a).map(NS);if(l.length===0)return{details:u,healthy:!0,verdict:"All listeners and members are healthy"};return{details:u,healthy:!1,verdict:ou(Dt(l))}};var ZS=_({availability_zone:f().optional(),created_at:f(),external_network:pr(),id:f(),name:f(),shared:pr(),status:f()}),US=_({networks:O(ZS)}),FS=(e)=>({createdAt:_t(e.created_at),external:e.external_network,id:e.id,name:e.name,shared:e.shared,status:e.status,zone:e.availability_zone||null}),Wo=async(e)=>(await e.get("/v4/networks",US)).networks.map(FS).toSorted((r,n)=>Date.parse(n.createdAt)-Date.parse(r.createdAt)),MS=_({device_id:f(),fixed_ips:O(_({ip_address:f()})),security_groups:O(f()).nullish()}),BS=_({ports:O(MS)}),sh=async(e)=>(await e.get("/v2/ports",BS)).ports.map((r)=>({addresses:r.fixed_ips.map((n)=>n.ip_address),deviceId:r.device_id,securityGroupIds:r.security_groups??[]}));var GS=_({direction:f(),ethertype:f(),id:f(),port_range_max:ee().nullable(),port_range_min:ee().nullable(),protocol:f().nullable(),remote_group_id:f().nullable(),remote_ip_prefix:f().nullable()}),KS=_({created_at:f(),description:f().nullable(),id:f(),name:f(),security_group_rules:O(GS)}),VS=_({security_groups:O(KS)}),WS=(e)=>({direction:e.direction,ethertype:e.ethertype,id:e.id,portMax:e.port_range_max,portMin:e.port_range_min,protocol:e.protocol,remoteGroupId:e.remote_group_id,remoteIpPrefix:e.remote_ip_prefix}),JS=(e)=>({createdAt:_t(e.created_at),description:e.description||null,id:e.id,name:e.name,rules:e.security_group_rules.map(WS)}),hr=async(e)=>(await e.get("/v4/security_groups",VS)).security_groups.map(JS).toSorted((r,n)=>Date.parse(n.createdAt)-Date.parse(r.createdAt));var HS=new Set(["ACTIVE","AVAILABLE","COMPLETED","HEALTHY","IN-USE","ONLINE"]),qS=new Set(["DEGRADED","FAILED","OFFLINE","UNKNOWN"]),YS=new Set(["ATTACHING","BACKING-UP","BUILD","BUILDING","CREATING","DELETING","DETACHING","DOWNLOADING","EXTENDING","HARD_REBOOT","MIGRATING","NEW","PASSWORD","REBOOT","REBUILD","RESCUE","RESERVED","RESIZE","RESTORING-BACKUP","RETYPING","REVERT_RESIZE","UPLOADING","VERIFY_RESIZE"]),ka=(e)=>{let t=e.toUpperCase();return qS.has(t)||t.startsWith("ERROR")||t.endsWith("FAILED")},XS=(e)=>{let t=e.toUpperCase();if(HS.has(t))return Lt;if(ka(e))return xe;if(YS.has(t)||t.startsWith("PENDING_"))return Ve;return W},ve=(e)=>{let t=e.toLowerCase().replaceAll(/[_-]/gu," ");return`${t.charAt(0).toUpperCase()}${t.slice(1)}`},F=(e)=>{let t=XS(e);return{paint:(r)=>`${t("●")}${r.slice(1)}`,text:`● ${ve(e)}`}};var QS=_({device:f(),serverId:f()}),e$=_({attachments:O(QS),availability_zone:f(),bootable:f(),created_at:f(),id:f(),name:f(),size:ee(),status:f(),volume_type:f().nullable()}),t$=_({volumes:O(e$)}),r$=(e)=>({attachments:e.attachments,bootable:e.bootable==="true",createdAt:e.created_at,id:e.id,name:e.name,sizeGb:e.size,status:e.status,type:e.volume_type,zone:e.availability_zone}),gn=async(e)=>(await e.get("/v4/volumes",t$)).volumes.map(r$).toSorted((r,n)=>Date.parse(n.createdAt)-Date.parse(r.createdAt));var yn={describe:(e)=>{let t=F(e.status).text,r=St(e);return r===void 0?[t]:[t,r]},list:Ee,lsCommand:"nipa server ls",noun:"server",plural:"servers"},Jo={describe:(e)=>[F(e.status).text,`${e.sizeGb} GB`],list:gn,lsCommand:"nipa volume ls",noun:"volume",plural:"volumes"},Ho={describe:(e)=>[F(e.status).text,e.external?"external":"VPC",e.zone??""],list:Wo,lsCommand:"nipa network ls",noun:"network",plural:"networks"},gr={list:hr,lsCommand:"nipa sg ls",noun:"security group",plural:"security groups"},yr={describe:(e)=>[F(e.status).text,e.address],list:Vo,lsCommand:"nipa lb ls",noun:"load balancer",plural:"load balancers"},br={describe:({primary:e})=>e?[F(e.status).text,fr(e)]:[],list:Go,lsCommand:"nipa db ls",noun:"database",plural:"databases"},ih=5,n$=(e,t)=>{let r=t.slice(0,ih).map((i)=>[i.id,...e.describe?.(i)??[]].map(z)),n=Array.from({length:Math.max(...r.map((i)=>i.length))},(i,a)=>Math.max(...r.map((c)=>c[a]?.length??0))),o=r.map((i)=>` ${i.map((a,c)=>a.padEnd(n[c]??0)).join(" ").trimEnd()}`),s=t.length-ih;return s>0?[...o,` and ${s} more. Run \`${e.lsCommand} --json\` to get their IDs.`]:o},ct=async(e)=>{let{kind:t,projectName:r,ref:n}=e,o=await j(`Loading the ${t.plural} in ${r}…`,()=>t.list(e.space)),s=o.filter((c)=>c.id===n),[i,...a]=s.length>0?s:o.filter((c)=>c.name===n);if(!i)throw new C(`no ${t.noun} named or with ID "${n}" in ${r}`,{hint:`Run \`${t.lsCommand}\` to see your ${t.plural}.`,next:[t.lsCommand],reason:"not_found"});if(a.length>0){let c=[i,...a];throw new C(`${c.length} ${t.plural} in ${r} are named "${n}"`,{data:{ids:c.map((l)=>l.id)},hint:["Name one by its ID:",...n$(t,c)].join(`
95
+ `),reason:"ambiguous_name"})}return i},kt=(e)=>ct({...e,kind:yn});import{chmod as Pa,mkdir as ch,readFile as lh,rename as o$,rm as uh,writeFile as s$}from"node:fs/promises";import{homedir as ph}from"node:os";import Pt from"node:path";var be="prod",_e={authUrl:"https://identity-api.nipa.cloud/v3",region:"NCP-TH",spaceUrl:"https://space.nipa.cloud/api",userDomain:"nipacloud"},ah=Zv({protocol:/^https?$/u}),lt=_({authUrl:ah,project:pn.optional(),region:f().min(1),spaceUrl:ah.optional(),userDomain:f().min(1),username:f().optional()}),Ca=/^[a-z][\da-z-]{0,31}$/u,i$=dr(f().regex(Ca),lt),Ea=(e)=>new URL(mr(e)).href===_e.authUrl,a$=(e)=>{let{spaceUrl:t,...r}=e;if(Ea(e.authUrl))return{...r,spaceUrl:mn(t??_e.spaceUrl)};if(t===void 0||t===_e.spaceUrl)return r;return{...r,spaceUrl:mn(t)}},ja=(e)=>({[be]:_e,...Object.fromEntries(Object.entries(e).map(([t,r])=>[t,a$(r)]))}),c$=_({currentProfile:f().default(be),profiles:i$.default({})}).strict().transform((e)=>({...e,profiles:ja(e.profiles)})),l$=lt.extend({authUrl:lt.shape.authUrl.default(_e.authUrl),region:lt.shape.region.default(_e.region),userDomain:lt.shape.userDomain.default(_e.userDomain)}).transform((e)=>({currentProfile:be,profiles:ja({[be]:e})})),u$=dr(f(),Oo()),dh=(e,...t)=>{let r=u$.safeParse(e);return r.success&&t.some((n)=>Object.hasOwn(r.data,n))},p$=(e)=>!dh(e,"profiles","currentProfile"),d$=(e)=>p$(e)?l$:c$,mh=_({expiresAt:Do.datetime({offset:!0}),project:pn,token:f().min(1),user:_({id:f(),name:f()})}),m$=dr(f(),mh),f$=_({sessions:m$}).strict().transform((e)=>e.sessions),h$=mh.transform((e)=>({[be]:e})),g$=(e)=>!dh(e,"sessions"),y$=(e)=>g$(e)?h$:f$;class ut extends Error{hint;constructor(e,t){super(e);this.name="StoreError",this.hint=t}}var fh="Check that your user owns the file. A `sudo nipa …` run leaves it owned by root.",b$=60000,qo=(e=process.env)=>e.NIPA_CONFIG_DIR??Pt.join(e.XDG_CONFIG_HOME??Pt.join(ph(),".config"),"nipa"),Aa=()=>Pt.join(qo(),"config.json"),bn=()=>Pt.join(qo(),"auth.json"),hh=()=>[Aa(),bn()],gh=(e,t=process.env)=>Pt.join(t.XDG_CACHE_HOME??Pt.join(ph(),".cache"),"nipa",e),Ye=async(e,t)=>{try{let r=await lh(gh(e),"utf-8"),n=t.safeParse(JSON.parse(r));return n.success?n.data:void 0}catch{return}},yh=async(e,t,r)=>{let n=`${e}.${process.pid}.tmp`;try{await s$(n,t,{mode:r}),await Pa(n,r),await o$(n,e)}catch(o){throw await uh(n,{force:!0}),o}},pt=async(e,t)=>{let r=gh(e);await ch(Pt.dirname(r),{mode:448,recursive:!0}),await Pa(Pt.dirname(r),448),await yh(r,`${JSON.stringify(t)}
96
+ `,384)},x$=async(e)=>{try{return await lh(e,"utf-8")}catch(t){if(t instanceof Error&&"code"in t&&t.code==="ENOENT")return;let r=t instanceof Error?t.message:String(t);throw new ut(`can't read ${e}: ${r}`,fh)}},bh=async(e,t)=>{let r=await x$(e);if(r===void 0)return;let n;try{n=JSON.parse(r)}catch{throw new ut(`${e} isn't valid JSON`)}let o=t(n).safeParse(n);if(!o.success)throw new ut(`${e}: ${Hr(o.error)}`);return o.data},Ra=async(e,t)=>{try{await ch(qo(),{mode:448,recursive:!0}),await Pa(qo(),448),await yh(e,`${JSON.stringify(t,null,2)}
97
+ `,384)}catch(r){let n=r instanceof Error?r.message:String(r);throw new ut(`can't write ${e}: ${n}`,fh)}},je=async()=>await bh(Aa(),d$)??{currentProfile:be,profiles:ja({})},Ct=(e)=>Ra(Aa(),e),Ia=async()=>await bh(bn(),y$)??{},ge=async(e)=>(await Ia())[e],xh=async(e)=>{let t=await Ia();await Ra(bn(),{sessions:{...t,[e.profile]:e.session}})},Yo=async(e)=>{let t=await Ia(),r=Object.fromEntries(Object.entries(t).filter(([n])=>n!==e));if(Object.keys(r).length===0){await uh(bn(),{force:!0});return}await Ra(bn(),{sessions:r})},Bt=(e,t=Date.now())=>Date.parse(e.expiresAt)-t,ye=(e,t=Date.now())=>e!==void 0&&Bt(e,t)>b$;var wh="names.json",w$=60000,Ta=_({name:f()}),v$=_({machine_types:O(Ta)}),_$=_({owned_images:O(Ta)}),S$=_({public_images:O(_({images:O(Ta)}))}),dt=(e)=>e.map((t)=>t.name).filter((t)=>t!==""),$$=async(e,t)=>{switch(t){case"servers":return dt(await yn.list(e));case"volumes":return dt(await Jo.list(e));case"networks":return dt(await Ho.list(e));case"security-groups":return dt(await gr.list(e));case"load-balancers":return dt(await yr.list(e));case"databases":return dt(await br.list(e));case"flavors":{let r=await e.get("/v4/machine_types",v$);return dt(r.machine_types)}case"images":{let[r,n]=await Promise.all([e.get("/v4/public_images",S$),e.get("/v4/images?table=owned_image",_$)]);return[...r.public_images.flatMap((o)=>dt(o.images)),...dt(n.owned_images)]}default:return t}},k$=dr(f(),_({at:ee(),names:O(f())})),vh=async(e)=>{let t=e.now??Date.now(),r=`${e.scope}:${e.kind}`,n=await Ye(wh,k$)??{},o=n[r];if(o&&t-o.at<w$)return o.names;let s=await $$(await e.connect(),e.kind);return await pt(wh,{...n,[r]:{at:t,names:s}}),s};import{spawn as R$}from"node:child_process";import{once as I$}from"node:events";import{stat as T$}from"node:fs/promises";import{text as z$}from"node:stream/consumers";import{accessSync as P$,constants as C$}from"node:fs";import{homedir as E$}from"node:os";import xn from"node:path";var _h=(e)=>{try{return P$(e,C$.X_OK),!0}catch{return!1}},j$=(e)=>process.platform==="win32"?[...(process.env.PATHEXT??".EXE;.CMD;.BAT").split(";").map((t)=>`${e}${t}`),e]:[e],mt=(e)=>{if(e.includes("/")||e.includes(xn.sep)){let r=xn.resolve(e);return _h(r)?r:void 0}return[...(process.env.PATH??"").split(xn.delimiter).filter(Boolean),xn.join(E$(),".local","bin")].flatMap((r)=>j$(xn.join(r,e))).find(_h)},Xo=(e)=>({OS_AUTH_TYPE:"v3token",OS_AUTH_URL:e.profile.authUrl,OS_IDENTITY_API_VERSION:"3",OS_INTERFACE:"public",OS_PROJECT_DOMAIN_ID:e.session.project.domainId??"",OS_PROJECT_ID:e.session.project.id,OS_PROJECT_NAME:e.session.project.name,OS_REGION_NAME:e.profile.region,OS_TOKEN:e.session.token}),$h=(e,t)=>({...Object.fromEntries(Object.entries(e).filter(([r])=>!r.startsWith("OS_"))),...t}),za=["bash","zsh","fish"],A$=(e)=>za.some((t)=>t===e),Sh=(e,t)=>`'${t==="fish"?e.replaceAll("\\","\\\\").replaceAll("'","\\'"):e.replaceAll("'","'\\''")}'`,kh=(e,t)=>Object.entries(e).map(([r,n])=>t==="fish"?`set -gx ${r} ${Sh(n,t)}`:`export ${r}=${Sh(n,t)}`).join(`
98
+ `),Ph=(e)=>{let t=e?.split("/").at(-1)??"";return A$(t)?t:"bash"};var Ch="openstack.json",O$=20000,L$=dr(f(),O(f())),D$=_({bin:f(),mtimeMs:ee(),table:L$}),N$=/^\s*cmds(?:_(?<key>\S+))?='(?<words>[^']*)'$/u,Z$=(e)=>Object.fromEntries(e.split(`
99
+ `).flatMap((t)=>{let r=N$.exec(t)?.groups;if(!r)return[];let n=r.words?.split(" ").filter(Boolean)??[];return[[r.key??"",n]]})),U$=(e,t)=>{let r=t.at(-1)??"",n="";for(let s of t.slice(0,-1)){let i=(n?`${n}_${s}`:s).replaceAll("-","_");if(s.startsWith("-")||!Object.hasOwn(e,i))break;n=i}let o=e[n]??[];if(r.startsWith("-"))return o.filter((s)=>s.startsWith(r));return o.filter((s)=>s.startsWith(r)&&!s.startsWith("-")&&!s.includes("_"))},F$=async(e)=>{let{mtimeMs:t}=await T$(e),r=await Ye(Ch,D$);if(r?.bin===e&&r.mtimeMs===t)return r.table;let n=R$(e,["complete","--shell","none"],{stdio:["ignore","pipe","ignore"],timeout:O$}),[o]=await Promise.all([z$(n.stdout),I$(n,"close")]);if(n.exitCode!==0)return;let s=Z$(o);return await pt(Ch,{bin:e,mtimeMs:t,table:s}),s},Eh=async(e)=>{let t=mt("openstack");if(!t)return[];let r=await F$(t);return r?U$(r,e):[]},M$=["console log show","console url show","server delete","server lock","server pause","server reboot","server rescue","server resume","server show","server shelve","server ssh","server start","server stop","server suspend","server unlock","server unpause","server unrescue","server unshelve"].map((e)=>e.split(" ")),B$=new Map([["--flavor","flavors"],["--image","images"],["--network","networks"]]),jh=(e)=>{let t=e.at(-2)??"";if(t.startsWith("-"))return B$.get(t);if((e.at(-1)??"").startsWith("-"))return;return M$.some((n)=>e.length>n.length&&n.every((o,s)=>e[s]===o))?"servers":void 0};import{spawn as G$}from"node:child_process";import{once as K$}from"node:events";import{text as V$}from"node:stream/consumers";var Gt=async(e,t,r="")=>{let n=G$(e,t,{stdio:["pipe","pipe","ignore"]});n.stdin.end(r);let[o]=await Promise.all([V$(n.stdout),K$(n,"close")]);return{code:n.exitCode,stdout:o}},Ah=(e)=>`nipa-cli/${new URL(e.authUrl).host}`,Rh=(e,t)=>new C(`the ${e} didn't save your password`,{hint:`${t}, or log in without \`--remember\`.`}),Oa=(e)=>["-s",Ah(e),"-a",e.username],W$=(e)=>({name:"macOS Keychain",read:async(r)=>{let{code:n,stdout:o}=await Gt(e,["find-generic-password",...Oa(r),"-w"]);return n===0?Buffer.from(o.trim(),"base64").toString("utf-8"):void 0},remove:async(r)=>{let{code:n}=await Gt(e,["delete-generic-password",...Oa(r)]);return n===0},save:async(r,n)=>{let o=Buffer.from(n,"utf-8").toString("base64"),s=Buffer.from(o,"ascii").toString("hex"),i=["add-generic-password","-U",...Oa(r),"-X",s],{code:a}=await Gt(e,["-i"],`${i.join(" ")}
100
+ `);if(a!==0)throw Rh("macOS Keychain","Check that your login keychain is unlocked")}}),Qo=(e)=>["service",Ah(e),"account",e.username],J$=(e)=>({name:"secret service",read:async(r)=>{let{code:n,stdout:o}=await Gt(e,["lookup",...Qo(r)]);return n===0&&o!==""?o:void 0},remove:async(r)=>{let n=await Gt(e,["lookup",...Qo(r)]);return await Gt(e,["clear",...Qo(r)]),n.code===0},save:async(r,n)=>{let s=["store",`--label=${`nipa password for ${r.username}`}`,...Qo(r)],{code:i}=await Gt(e,s,n);if(i!==0)throw Rh("secret service","Check that a secret service, such as GNOME Keyring, is running")}}),es=(e=process.platform)=>{if(e==="darwin"){let t=mt("security");return t?W$(t):void 0}if(e==="linux"){let t=mt("secret-tool");return t?J$(t):void 0}return},Ih=(e=process.platform)=>{let t=es(e);if(t)return t;let r=e==="linux"?"Install secret-tool, such as with `sudo apt install libsecret-tools`, or log in without `--remember`.":"Log in without `--remember`. nipa saves passwords on macOS and Linux.";throw new C(`nipa can't save your password on ${e}`,{hint:r})},ts=(e)=>{let t=es();if(!(t&&e.username))return Promise.resolve(!1);return t.remove({authUrl:e.authUrl,username:e.username})};import{mkdir as H$,readFile as q$,rm as Y$,rmdir as X$,writeFile as Q$}from"node:fs/promises";import vn from"node:path";var ek=".nipa",tk="project.json",rk=_({profile:f(),project:pn}),Th=(e)=>vn.join(e,ek,tk);class wn extends C{constructor(e,t){super(`${e} ${t}`,{hint:"Fix the file, or run `nipa unlink` and `nipa link` again."});this.name="LinkError"}}var nk=async(e)=>{let t;try{t=await q$(e,"utf-8")}catch(o){if(o instanceof Error&&"code"in o&&o.code==="ENOENT")return;throw o}let r;try{r=JSON.parse(t)}catch{throw new wn(e,"isn't valid JSON")}let n=rk.safeParse(r);if(!n.success)throw new wn(e,`isn't a nipa link: ${Hr(n.error)}`);return n.data},Kt=async(e=process.cwd())=>{let t=Th(e),r=await nk(t);if(r)return{file:t,link:r};let n=vn.dirname(e);return n===e?void 0:Kt(n)},zh=async(e)=>{let t=Th(e.dir);return await H$(vn.dirname(t),{recursive:!0}),await Q$(t,`${JSON.stringify(e.link,null,2)}
101
+ `),t},Oh=async(e)=>{await Y$(e,{force:!0});try{await X$(vn.dirname(e))}catch{}},Se=(e,t=process.cwd())=>vn.relative(t,e);var La=async(e)=>{let{link:t}=e,r=await je(),n=[["flag",e.override],["env",process.env.NIPA_PROFILE],["link",t?.link.profile]],[o,s]=n.find((c)=>c[1]!==void 0)??["config",r.currentProfile],i=r.profiles[s];if(!i){let c=Object.keys(r.profiles).join(", "),l=t?.link.profile===s?` in ${Se(t.file)}`:"";throw new C(`no profile named "${s}"${l}`,{hint:`Your profiles: ${c}. Add one with \`nipa profile add ${s}\`.`,reason:"not_found"})}let a=t?.link.profile===s?t:void 0;return{config:r,link:a,name:s,profile:i,source:o}},Ge=(e)=>e===be?"nipa login":`nipa login -P ${e}`,Wt=(e)=>{if(e.name!==be){let t=P(`(${new URL(e.profile.authUrl).host})`);w(`Using profile ${x(e.name)} ${t}`)}},ok=/^\d{6}$/u,Da=/^[\da-f]{32}$/u,sk=3,ik=(e)=>({email:(t)=>e.text({default:t,message:"Email",validate:(r)=>r.includes("@")||"Enter the email you log in to the portal with"}),otp:(t)=>e.text({message:t===1?"OTP code":"Next OTP code",validate:(r)=>ok.test(r)||"Enter the 6-digit code from your authenticator app"}),password:()=>e.secret("Password"),projectId:()=>e.text({message:"Project ID",validate:(t)=>Da.test(t)||"Enter the 32-character ID, as in OS_PROJECT_ID in your openrc file"})}),Na=(e)=>{let{projects:t,wanted:r}=e,n=t.filter((i)=>i.id===r),[o,...s]=n.length>0?n:t.filter((i)=>i.name===r);if(!o)throw new C(`no project named or with ID "${z(r)}"`,{hint:`Your projects: ${t.map((i)=>z(i.name)).join(", ")}`,reason:"not_found"});if(s.length>0){let i=[o,...s],a=i.map((c)=>z(c.id)).join(", ");throw new C(`${s.length+1} projects are named "${z(r)}"`,{data:{ids:i.map((c)=>c.id)},hint:`Name one by its ID instead: ${a}.`,reason:"ambiguous_name"})}return o},rs=(e)=>(t)=>e.prompts.choice({choices:t.map((r)=>({description:r.id,name:r.id===e.current.id?`${r.name} ${x("(current)")}`:r.name,value:r})),default:t.find((r)=>r.id===e.current.id),message:e.message}),ns=(e)=>{let{projects:t,wanted:r}=e;if(r)return Promise.resolve(Na({projects:t,wanted:r}));let[n,...o]=t;if(!n)throw new C("your account has no projects you can use");return o.length===0?Promise.resolve(n):e.ask(t)},Vt=(e,t)=>({expiresAt:e.expiresAt,project:e.project??t,token:e.value,user:e.user}),Dh=async(e)=>{let t=await e.ask(e.attempt);try{return await j("Checking the code…",()=>Vf({account:e.account,passcode:t,receipt:e.receipt}))}catch(r){if(!(r instanceof ae&&r.status===401)||e.attempt===sk)throw r;return w("That code didn't work. Each code works once, so wait for the next one."),Dh({...e,attempt:e.attempt+1})}},ak=async(e)=>{let t=e.username??e.profile.username;if(!(t&&e.keychain))return;let r=await e.keychain.read({authUrl:e.profile.authUrl,username:t});return r===void 0?void 0:{password:r,username:t}},ck=async(e)=>{let{account:t,keychain:r,prompts:n,remembered:o}=e,s=async(i)=>({answer:await j("Checking your password…",()=>Kf(t,i)),password:i});if(o===void 0||!r)return s(await n.password());w(`Using the password saved in the ${r.name}`);try{return await s(o)}catch(i){if(!(i instanceof ae&&i.status===401))throw i;return await r.remove(t),w("The saved password didn't work, so nipa deleted it."),s(await n.password())}},lk=async(e)=>{let{keychain:t,profile:r,prompts:n,wantedProject:o}=e,s=await ak({keychain:t,profile:r,username:e.username}),i=s?.username??e.username??await n.email(r.username),a=o!==void 0&&Da.test(o)?o:void 0,c=a??r.project?.id??await n.projectId(),l={authUrl:r.authUrl,projectId:c,userDomain:r.userDomain,username:i},{answer:u,password:p}=await ck({account:l,keychain:t,prompts:n,remembered:s?.password}),d=u.kind==="token"?u.token:await Dh({account:l,ask:n.otp,attempt:1,receipt:u.receipt});if(!d.project)throw new ae(`Keystone returned a token without project ${c}`,0);if(e.remember&&t)await t.save(l,p);let m=a?void 0:o;if(m===void 0||d.project.name===m)return Vt(d,d.project);let h=await j("Loading your projects…",()=>Oe({authUrl:r.authUrl,token:d.value})),y=Na({projects:h,wanted:m}),b=await j(`Switching to ${z(y.name)}…`,()=>Mt({authUrl:r.authUrl,projectId:y.id,token:d.value}));return Vt(b,y)},Za=async(e)=>{let{active:t,session:r}=e,n={...t.profile,project:r.project,username:r.user.name};await Ct({...t.config,profiles:{...t.config.profiles,[t.name]:n}}),await xh({profile:t.name,session:r})},Ua=async(e)=>{let{active:t,prompts:r}=e;if(!r.interactive)throw new C("`nipa login` needs to ask for your password, and nipa can't prompt here",{hint:"Run it in a terminal without `--non-interactive` or `CI`, then run this command again."});let n=e.remember?Ih():es(),o=P(`(${new URL(t.profile.authUrl).host})`);w(`Logging in to ${x(t.name)} ${o}`);let s=await lk({keychain:n,profile:t.profile,prompts:ik(r),remember:e.remember,username:e.username,wantedProject:e.wantedProject});await Za({active:t,session:s});let i=x(s.user.name);if(te(`Logged in as ${i}, project ${x(s.project.name)}`),e.remember&&n)w(`Saved your password in the ${n.name}, so the next login asks only for an OTP code.`);return s},Fa=1800000,uk=(e)=>{let t=Bt(e.session);if(t<Fa)J(`Your ${e.profile} session expires in ${nr(t)}. Run \`${Ge(e.profile)}\` to start a new one.`)},pk=async(e)=>{let{active:t,prompts:r}=e,n=await ge(t.name);if(ye(n))return uk({profile:t.name,session:n}),n;let o=Ge(t.name),s=`Run \`${o}\`.`;if(!r.interactive)throw n?new C(`your ${t.name} session expired`,{hint:s,next:[o],reason:"token_expired"}):new C(`you aren't logged in to ${t.name}`,{hint:s,next:[o],reason:"login_required"});return w(n?"Your session expired.":"You aren't logged in yet."),Ua({active:t,prompts:r})},Nh=(e)=>async(t)=>{try{return await t()}catch(r){if((r instanceof ce||r instanceof ae?r.status:void 0)===401)throw new C(`your ${e} session expired or was revoked`,{hint:`Run \`${Ge(e)}\`.`,next:[Ge(e)],reason:"token_expired"});throw r}},Ma=(e,t)=>Nh(e.name)(()=>j("Loading your projects…",()=>Oe({authUrl:e.profile.authUrl,token:t.token}))),dk=(e)=>{let{active:t,project:r,target:n}=e,o=`If Keystone revoked your session, run \`${Ge(t.name)}\`.`;return n.from==="link"?new C(`can't use project ${z(r.name)}, which ${Se(n.link.file)} links to`,{hint:`Run \`nipa link\` to pick another project. ${o}`}):new C(`can't use project ${z(r.name)}`,{hint:`Check the name or ID of the project. ${o}`})},Lh=async(e)=>{let{active:t,project:r,session:n}=e;try{return await j(`Switching to ${z(r.name)}…`,()=>Mt({authUrl:t.profile.authUrl,projectId:r.id,token:n.token}))}catch(o){if(o instanceof ae&&o.status===401)return;throw o}},mk=async(e)=>{let{active:t,session:r,target:n}=e,o=async(p)=>Na({projects:await Ma(t,r),wanted:p}),s=n.from==="flag"&&Da.test(n.wanted),a=await(()=>{if(n.from==="link")return n.link.link.project;return s?{id:n.wanted,name:n.wanted}:o(n.wanted)})();if(a.id===r.project.id)return r;let c=await Lh({active:t,project:a,session:r});if(!c&&s&&n.from==="flag"){let p=await o(n.wanted);if(p.id===r.project.id)return r;c=p.id===a.id?void 0:await Lh({active:t,project:p,session:r}),a=p}if(!c)throw dk({active:t,project:a,target:n});let l=Vt(c,a),u=x(z(l.project.name));return w(n.from==="link"?`Using project ${u} from ${P(Se(n.link.file))}`:`Using project ${u}`),l},_n=async(e)=>{let{active:t,prompts:r}=e,n=await pk({active:t,prompts:r}),o;if(!e.saved){if(e.project!==void 0)o={from:"flag",wanted:e.project};else if(t.link)o={from:"link",link:t.link}}return{active:t,session:o?await mk({active:t,session:n,target:o}):n}},Ba=(e)=>new C(`the ${e.name} profile has no Space API URL`,{hint:`Remove it with \`nipa profile rm ${e.name}\`, then add it again with \`--space-url\` and its Space portal URL. \`nipa -P ${e.name} os server list\` works without one.`}),Jt=(e)=>{let{spaceUrl:t}=e.profile;if(!t)throw Ba(e);return t},xr=(e)=>{let{active:t,session:r}=e.signedIn,n=Nh(t.name),o=Fo({projectId:r.project.id,region:t.profile.region,signal:e.signal,token:r.token,url:e.spaceUrl}),s=(i)=>n(async()=>{try{return await i()}catch(a){if(a instanceof Be)throw new C(a.message,{hint:"Check your network connection, or the profile's Space API URL.",reason:"network_error"});throw a}});return{active:t,session:r,space:{get:(i,a)=>s(()=>o.get(i,a)),getLines:(i,a)=>s(()=>o.getLines(i,a)),post:(i)=>s(()=>o.post(i))}}};var Zh=["bash","zsh","fish","pwsh"],Uh=["projects","profiles","openstack",...Qc],Ht=(e)=>`nipa __complete ${e}`,ss=ke.filter((e)=>e.value.kind!=="none"),is=ss.flatMap(fe),Ga=(e)=>{switch(e.value.kind){case"profile":return{kind:"profiles",tag:"profile"};case"project":return{kind:"projects",tag:"project"};default:return}},fk=(e)=>e.filter((t)=>t.kind==="passthrough").flatMap((t)=>me(t)),Ka=(e)=>[...e.flags,...ke],as=(e)=>{let t=e.args.findIndex((n)=>n.value.kind!=="text"),r=e.args[t];return r?{arg:r,position:t+1}:void 0},hk=(e)=>{switch(e.kind){case"none":return;case"text":return"return";case"choice":return`_nipa_reply ${e.choices.join(" ")}; return`;case"project":return`_nipa_reply_lines < <(${Ht("projects")} 2>/dev/null); return`;case"profile":return`_nipa_reply_lines < <(${Ht("profiles")} 2>/dev/null); return`;default:return e}},gk=(e)=>{switch(e.kind){case"text":return;case"project":return`_nipa_reply_lines < <(${Ht("projects")} 2>/dev/null)`;case"profile":return`_nipa_reply_lines < <(${Ht("profiles")} 2>/dev/null)`;case"resource":return`_nipa_reply_lines < <(${Ht(e.resource)} 2>/dev/null)`;case"choice":return`_nipa_reply ${e.choices.join(" ")}`;default:return e}},yk=(e)=>{switch(e.kind){case"program":return`COMP_WORDS[i]=${e.program}; _nipa_offset "$i"`;case"command":return'_nipa_offset "$((i + 1))"';case"openstack":return'_nipa_reply_lines < <(nipa __complete openstack -- "${COMP_WORDS[@]:i+1:COMP_CWORD-i}" 2>/dev/null)';default:return e}},Fh=(e,t)=>{let r=" ".repeat(t*2+2),n=[];if(e.kind==="group"){let s=e.subcommands;n.push(`if [[ $COMP_CWORD -eq $((i + 1)) ]]; then _nipa_reply ${s.map((i)=>i.name).join(" ")}; return; fi`,"case ${COMP_WORDS[i + 1]} in",...s.map((i)=>Fh(i,t+1)),"esac")}else if(e.kind==="passthrough")n.push(yk(e.target));else{let s=Ka(e),i=s.flatMap((u)=>{let p=hk(u.value);return p===void 0?[]:[` ${fe(u).join("|")}) ${p} ;;`]});if(i.length>0)n.push('case "$prev" in',...i,"esac");let a=s.flatMap(fe).join(" ");n.push(`if [[ $cur == -* ]]; then _nipa_reply ${a}; return; fi`);let c=as(e),l=c&&gk(c.arg.value);if(l)n.push(l)}let o=n.map((s)=>`${r} ${s}`).join(`
102
+ `);return`${r}${me(e).join("|")})
98
103
  ${o}
99
- ${r} ;;`},x$=(e)=>{let t=yr(e),r=t.map((o)=>o.name).join(" "),n=$e.flatMap(Se).join(" ");return`# nipa completion for bash
104
+ ${r} ;;`},bk=(e)=>{let t=Ar(e),r=t.map((s)=>s.name).join(" "),n=ke.flatMap(fe).join(" "),o=ss.flatMap((s)=>{let i=Ga(s);return i?[` ${fe(s).join("|")}) _nipa_reply_lines < <(${Ht(i.kind)} 2>/dev/null); return ;;`]:[]}).join(`
105
+ `);return`# nipa completion for bash
100
106
  # Load it from ~/.bashrc: eval "$(nipa completion bash)"
101
107
 
102
108
  # One word per line, so project names with spaces stay whole.
@@ -130,32 +136,34 @@ _nipa() {
130
136
  local i=1 command=""
131
137
  while [[ $i -lt $COMP_CWORD ]]; do
132
138
  case \${COMP_WORDS[i]} in
133
- ${Ft.join("|")}) ((i += 2)) ;;
139
+ ${is.join("|")}) ((i += 2)) ;;
134
140
  -*) ((i += 1)) ;;
135
141
  *) command=\${COMP_WORDS[i]}; break ;;
136
142
  esac
137
143
  done
138
144
  if [[ -z $command ]]; then
139
145
  case $prev in
140
- ${Ft.join("|")}) _nipa_reply_lines < <(${Ut("profiles")} 2>/dev/null); return ;;
146
+ ${o}
141
147
  esac
142
148
  if [[ $cur == -* ]]; then _nipa_reply ${n}; else _nipa_reply ${r}; fi
143
149
  return
144
150
  fi
145
151
  case $command in
146
- ${t.map((o)=>Df(o,0)).join(`
152
+ ${t.map((s)=>Fh(s,0)).join(`
147
153
  `)}
148
154
  esac
149
155
  }
150
156
  complete -o default -F _nipa nipa
151
- `},Do=(e)=>e.replaceAll("'","'\\''").replaceAll(":","\\:"),w$=(e)=>{let{value:t}=e;switch(t.kind){case"none":return"";case"text":return`:${t.name}: `;case"choice":return`:${e.long}:(${t.choices.join(" ")})`;case"project":return":project:{_nipa_dynamic projects project}";case"profile":return":profile:{_nipa_dynamic profiles profile}";default:return t}},_$=(e)=>{let t=Se(e),r=t.length>1?`(${t.join(" ")})`:"",n=t.length>1?`{${t.join(",")}}`:t[0];return`'${r}'${n}'[${Do(e.description)}]${w$(e)}'`},v$=({arg:e,position:t})=>{let{value:r}=e;switch(r.kind){case"project":return`'${t}:project:{_nipa_dynamic projects project}'`;case"profile":return`'${t}:profile:{_nipa_dynamic profiles profile}'`;case"resource":return`'${t}:${e.name}:{_nipa_dynamic ${r.resource} ${e.name}}'`;case"choice":return`'${t}:${e.name}:(${r.choices.join(" ")})'`;case"text":return"";default:return r}},$$=(e,t)=>{switch(e.kind){case"program":return`${t} words[1]=${e.program}; _normal`;case"command":return`${t} shift words; (( CURRENT-- )); _normal`;case"openstack":return`${t} _nipa_openstack`;default:return e}},Nf=(e,t)=>{if(e.kind==="group"){let o=e.subcommands,s=o.map((a)=>`'${a.name}:${Do(a.summary)}'`).join(" "),i=o.map((a)=>{let c=Nf(a,`${t} `);return`${t} ${xe(a).join("|")})
157
+ `},os=(e)=>e.replaceAll("'","'\\''").replaceAll(":","\\:"),xk=(e)=>{let{value:t}=e;switch(t.kind){case"none":return"";case"text":return`:${t.name}: `;case"choice":return`:${e.long}:(${t.choices.join(" ")})`;case"project":return":project:{_nipa_dynamic projects project}";case"profile":return":profile:{_nipa_dynamic profiles profile}";default:return t}},wk=(e)=>{let t=fe(e),r=t.length>1?`(${t.join(" ")})`:"",n=t.length>1?`{${t.join(",")}}`:t[0];return`'${r}'${n}'[${os(e.description)}]${xk(e)}'`},vk=({arg:e,position:t})=>{let{value:r}=e;switch(r.kind){case"project":return`'${t}:project:{_nipa_dynamic projects project}'`;case"profile":return`'${t}:profile:{_nipa_dynamic profiles profile}'`;case"resource":return`'${t}:${e.name}:{_nipa_dynamic ${r.resource} ${e.name}}'`;case"choice":return`'${t}:${e.name}:(${r.choices.join(" ")})'`;case"text":return"";default:return r}},_k=(e,t)=>{switch(e.kind){case"program":return`${t} words[1]=${e.program}; _normal`;case"command":return`${t} shift words; (( CURRENT-- )); _normal`;case"openstack":return`${t} _nipa_openstack`;default:return e}},Mh=(e,t)=>{if(e.kind==="group"){let o=e.subcommands,s=o.map((a)=>`'${a.name}:${os(a.summary)}'`).join(" "),i=o.map((a)=>{let c=Mh(a,`${t} `);return`${t} ${me(a).join("|")})
152
158
  ${c}
153
159
  ${t} ;;`}).join(`
154
160
  `);return[`${t} if (( CURRENT == 2 )); then`,`${t} local -a subcommands; subcommands=(${s})`,`${t} _describe -t subcommands '${e.name} subcommand' subcommands; return`,`${t} fi`,`${t} shift words; (( CURRENT-- ))`,`${t} case $words[1] in`,i,`${t} esac`].join(`
155
- `)}if(e.kind==="passthrough")return $$(e.target,t);let r=No(e),n=[...ia(e).map(_$),r?v$(r):""];return`${t} _arguments -s ${n.filter(Boolean).join(" ")}`},S$=(e)=>{let t=yr(e),r=t.map((s)=>` '${s.name}:${Do(s.summary)}'`).join(`
156
- `),n=$e.flatMap((s)=>Se(s).map((i)=>` '${i}:${Do(s.description)}'`)).join(`
157
- `),o=t.map((s)=>` ${xe(s).join("|")})
158
- ${Nf(s," ")}
161
+ `)}if(e.kind==="passthrough")return _k(e.target,t);let r=as(e),n=[...Ka(e).map(wk),r?vk(r):""];return`${t} _arguments -s ${n.filter(Boolean).join(" ")}`},Sk=(e)=>{let t=Ar(e),r=t.map((i)=>` '${i.name}:${os(i.summary)}'`).join(`
162
+ `),n=ke.flatMap((i)=>fe(i).map((a)=>` '${a}:${os(i.description)}'`)).join(`
163
+ `),o=ss.flatMap((i,a)=>{let c=Ga(i);return c?[` ${a===0?"if":"elif"} [[ $words[CURRENT-1] == (${fe(i).join("|")}) ]]; then
164
+ _nipa_dynamic ${c.kind} ${c.tag}`]:[]}).join(`
165
+ `),s=t.map((i)=>` ${me(i).join("|")})
166
+ ${Mh(i," ")}
159
167
  ;;`).join(`
160
168
  `);return`#compdef nipa
161
169
  # nipa completion for zsh
@@ -179,14 +187,13 @@ _nipa() {
179
187
  local i=2 command=""
180
188
  while (( i < CURRENT )); do
181
189
  case $words[i] in
182
- ${Ft.join("|")}) (( i += 2 )) ;;
190
+ ${is.join("|")}) (( i += 2 )) ;;
183
191
  -*) (( i += 1 )) ;;
184
192
  *) command=$words[i]; break ;;
185
193
  esac
186
194
  done
187
195
  if [[ -z $command ]]; then
188
- if [[ $words[CURRENT-1] == (${Ft.join("|")}) ]]; then
189
- _nipa_dynamic profiles profile
196
+ ${o}
190
197
  elif [[ $PREFIX == -* ]]; then
191
198
  local -a globals; globals=(
192
199
  ${n}
@@ -203,7 +210,7 @@ ${r}
203
210
  # Drop nipa and any global options, so words[1] is the command.
204
211
  shift $(( i - 1 )) words; (( CURRENT -= i - 1 ))
205
212
  case $command in
206
- ${o}
213
+ ${s}
207
214
  esac
208
215
  }
209
216
 
@@ -212,7 +219,7 @@ if [[ $zsh_eval_context[-1] == loadautofunc ]]; then
212
219
  else
213
220
  compdef _nipa nipa
214
221
  fi
215
- `},kt=(e)=>`'${e.replaceAll("\\","\\\\").replaceAll("'","\\'")}'`,un=(e)=>`'(${Ut(e)} 2>/dev/null)'`,k$=(e)=>{switch(e.kind){case"none":return"";case"text":return" --exclusive";case"choice":return` --exclusive -a ${kt(e.choices.join(" "))}`;case"project":return` --exclusive -a ${un("projects")}`;case"profile":return` --exclusive -a ${un("profiles")}`;default:return e}},P$=(e)=>{switch(e.kind){case"text":return;case"project":return un("projects");case"profile":return un("profiles");case"resource":return un(e.resource);case"choice":return kt(e.choices.join(" "));default:return e}},C$=(e)=>{switch(e.kind){case"program":return`'(__nipa_complete_as ${e.program})'`;case"command":return"'(__nipa_complete_as)'";case"openstack":return"'(__nipa_openstack)'";default:return e}},E$=(e)=>{if(e.kind==="passthrough")return C$(e.target);let t=No(e);return t&&P$(t.arg.value)},Zf=(e,t)=>{let r=e.short?` -s ${e.short}`:"";return`complete -c nipa -n ${kt(t)}${r} -l ${e.long}${k$(e.value)} -d ${kt(e.description)}`},Uf=(e,t)=>{let r=`__nipa_using ${xe(t??e).join(" ")}`,n=t?`${r}; and __fish_seen_subcommand_from ${xe(e).join(" ")}`:r;if(e.kind==="group"){let c=e.subcommands,l=`${n}; and not __fish_seen_subcommand_from ${c.flatMap((u)=>xe(u)).join(" ")}`;return[...c.map((u)=>`complete -c nipa -n ${kt(l)} -a ${u.name} -d ${kt(u.summary)}`),...c.flatMap((u)=>Uf(u,e))]}let s=(e.kind==="leaf"?e.flags:[]).map((c)=>Zf(c,n)),i=E$(e),a=i?[`complete -c nipa -n ${kt(n)} -a ${i}`]:[];return[...s,...a]},z$=(e)=>{let t=yr(e),r=[...t,...e.hidden],n=`not __nipa_using ${h$(r).join(" ")}`,o=t.map((s)=>`complete -c nipa -n __nipa_needs_command -a ${s.name} -d ${kt(s.summary)}`);return`# nipa completion for fish
222
+ `},Et=(e)=>`'${e.replaceAll("\\","\\\\").replaceAll("'","\\'")}'`,Sn=(e)=>`'(${Ht(e)} 2>/dev/null)'`,$k=(e)=>{switch(e.kind){case"none":return"";case"text":return" --exclusive";case"choice":return` --exclusive -a ${Et(e.choices.join(" "))}`;case"project":return` --exclusive -a ${Sn("projects")}`;case"profile":return` --exclusive -a ${Sn("profiles")}`;default:return e}},kk=(e)=>{switch(e.kind){case"text":return;case"project":return Sn("projects");case"profile":return Sn("profiles");case"resource":return Sn(e.resource);case"choice":return Et(e.choices.join(" "));default:return e}},Pk=(e)=>{switch(e.kind){case"program":return`'(__nipa_complete_as ${e.program})'`;case"command":return"'(__nipa_complete_as)'";case"openstack":return"'(__nipa_openstack)'";default:return e}},Ck=(e)=>{if(e.kind==="passthrough")return Pk(e.target);let t=as(e);return t&&kk(t.arg.value)},Bh=(e,t)=>{let r=e.short?` -s ${e.short}`:"";return`complete -c nipa -n ${Et(t)}${r} -l ${e.long}${$k(e.value)} -d ${Et(e.description)}`},Gh=(e,t)=>{let r=`__nipa_using ${me(t??e).join(" ")}`,n=t?`${r}; and __fish_seen_subcommand_from ${me(e).join(" ")}`:r;if(e.kind==="group"){let c=e.subcommands,l=`${n}; and not __fish_seen_subcommand_from ${c.flatMap((u)=>me(u)).join(" ")}`;return[...c.map((u)=>`complete -c nipa -n ${Et(l)} -a ${u.name} -d ${Et(u.summary)}`),...c.flatMap((u)=>Gh(u,e))]}let s=(e.kind==="leaf"?e.flags:[]).map((c)=>Bh(c,n)),i=Ck(e),a=i?[`complete -c nipa -n ${Et(n)} -a ${i}`]:[];return[...s,...a]},Ek=(e)=>{let t=Ar(e),r=[...t,...e.hidden],n=`not __nipa_using ${fk(r).join(" ")}`,o=t.map((s)=>`complete -c nipa -n __nipa_needs_command -a ${s.name} -d ${Et(s.summary)}`);return`# nipa completion for fish
216
223
  # Save it: nipa completion fish > ~/.config/fish/completions/nipa.fish
217
224
 
218
225
  function __nipa_command_index
@@ -220,7 +227,7 @@ function __nipa_command_index
220
227
  set -l i 2
221
228
  while test $i -le (count $tokens)
222
229
  switch $tokens[$i]
223
- case ${Ft.join(" ")}
230
+ case ${is.join(" ")}
224
231
  set i (math $i + 2)
225
232
  case '-*'
226
233
  set i (math $i + 1)
@@ -261,21 +268,22 @@ function __nipa_openstack
261
268
  end
262
269
 
263
270
  complete -c nipa -f
264
- ${$e.map((s)=>Zf(s,n)).join(`
271
+ ${ke.map((s)=>Bh(s,n)).join(`
265
272
  `)}
266
273
  ${o.join(`
267
274
  `)}
268
- ${t.flatMap((s)=>Uf(s)).join(`
275
+ ${t.flatMap((s)=>Gh(s)).join(`
269
276
  `)}
270
- `},pn=(e)=>`'${e.replaceAll("'","''")}'`,qe=(e)=>`@(${e.map(pn).join(", ")})`,I$=(e)=>{switch(e.kind){case"none":case"text":return;case"choice":return qe(e.choices);case"project":return"(Dynamic projects)";case"profile":return"(Dynamic profiles)";default:return e}},T$=(e)=>{switch(e.kind){case"text":return;case"project":return"(Dynamic projects)";case"profile":return"(Dynamic profiles)";case"resource":return`(Dynamic ${e.resource})`;case"choice":return qe(e.choices);default:return e}},A$=(e)=>{switch(e.kind){case"openstack":return"(Openstack ($c + 1))";case"program":case"command":return;default:return e}},Ff=(e,t)=>{if(e.kind==="group"){let i=e.subcommands,a=i.map((l)=>`${pn(l.name)} = ${pn(l.summary)}`).join("; "),c=i.map((l)=>{let u=Ff(l,`${t} `);return`${t} { $_ -in ${qe(xe(l))} } {
277
+ `},$n=(e)=>`'${e.replaceAll("'","''")}'`,Xe=(e)=>`@(${e.map($n).join(", ")})`,jk=(e)=>{switch(e.kind){case"none":case"text":return;case"choice":return Xe(e.choices);case"project":return"(Dynamic projects)";case"profile":return"(Dynamic profiles)";default:return e}},Ak=(e)=>{switch(e.kind){case"text":return;case"project":return"(Dynamic projects)";case"profile":return"(Dynamic profiles)";case"resource":return`(Dynamic ${e.resource})`;case"choice":return Xe(e.choices);default:return e}},Rk=(e)=>{switch(e.kind){case"openstack":return"(Openstack ($c + 1))";case"program":case"command":return;default:return e}},Kh=(e,t)=>{if(e.kind==="group"){let i=e.subcommands,a=i.map((l)=>`${$n(l.name)} = ${$n(l.summary)}`).join("; "),c=i.map((l)=>{let u=Kh(l,`${t} `);return`${t} { $_ -cin ${Xe(me(l))} } {
271
278
  ${t} $c += 1
272
279
  ${u}
273
280
  ${t} }`}).join(`
274
- `);return[`${t} if ($index -eq $c + 1) { return Complete ${qe(i.map((l)=>l.name))} @{ ${a} } }`,`${t} switch ($words[$c + 1]) {`,c,`${t} }`].join(`
275
- `)}if(e.kind==="passthrough"){let i=A$(e.target);return i?`${t} return Complete ${i}`:`${t} return`}let r=ia(e),n=r.flatMap((i)=>{let a=I$(i.value);return a===void 0?[]:[`if ($prev -in ${qe(Se(i))}) { return Complete ${a} }`]});n.push(`if ($wordToComplete -like '-*') { return Complete ${qe(r.flatMap(Se))} }`);let o=No(e),s=o&&T$(o.arg.value);if(s)n.push(`Complete ${s}`);return n.map((i)=>`${t} ${i}`).join(`
276
- `)},R$=(e)=>{let t=yr(e),r=t.map((o)=>` ${pn(o.name)} = ${pn(o.summary)}`).join(`
277
- `),n=t.map((o)=>` { $_ -in ${qe(xe(o))} } {
278
- ${Ff(o," ")}
281
+ `);return[`${t} if ($index -eq $c + 1) { return Complete ${Xe(i.map((l)=>l.name))} @{ ${a} } }`,`${t} switch ($words[$c + 1]) {`,c,`${t} }`].join(`
282
+ `)}if(e.kind==="passthrough"){let i=Rk(e.target);return i?`${t} return Complete ${i}`:`${t} return`}let r=Ka(e),n=r.flatMap((i)=>{let a=jk(i.value);return a===void 0?[]:[`if ($prev -cin ${Xe(fe(i))}) { return Complete ${a} }`]});n.push(`if ($wordToComplete -like '-*') { return Complete ${Xe(r.flatMap(fe))} }`);let o=as(e),s=o&&Ak(o.arg.value);if(s)n.push(`Complete ${s}`);return n.map((i)=>`${t} ${i}`).join(`
283
+ `)},Ik=(e)=>{let t=Ar(e),r=t.map((s)=>` ${$n(s.name)} = ${$n(s.summary)}`).join(`
284
+ `),n=ss.flatMap((s)=>{let i=Ga(s);return i?[` if ($prev -cin ${Xe(fe(s))}) { return Complete (Dynamic ${i.kind}) }`]:[]}).join(`
285
+ `),o=t.map((s)=>` { $_ -cin ${Xe(me(s))} } {
286
+ ${Kh(s," ")}
279
287
  }`).join(`
280
288
  `);return`# nipa completion for PowerShell
281
289
  # Load it from your $PROFILE: nipa completion pwsh | Out-String | Invoke-Expression
@@ -302,32 +310,32 @@ ${r}
302
310
  $c = 1
303
311
  $command = $null
304
312
  while ($c -lt $index) {
305
- if ($words[$c] -in ${qe(Ft)}) { $c += 2 }
313
+ if ($words[$c] -cin ${Xe(is)}) { $c += 2 }
306
314
  elseif ($words[$c] -like '-*') { $c += 1 }
307
315
  else { $command = $words[$c]; break }
308
316
  }
309
317
  if (-not $command) {
310
- if ($prev -in ${qe(Ft)}) { return Complete (Dynamic profiles) }
311
- if ($wordToComplete -like '-*') { return Complete ${qe($e.flatMap(Se))} }
318
+ ${n}
319
+ if ($wordToComplete -like '-*') { return Complete ${Xe(ke.flatMap(fe))} }
312
320
  return Complete ([string[]]$commands.Keys) $commands
313
321
  }
314
322
  switch ($command) {
315
- ${n}
323
+ ${o}
316
324
  }
317
325
  }
318
- `},Zo=(e)=>{let{program:t,shell:r}=e;switch(r){case"bash":return x$(t);case"zsh":return S$(t);case"fish":return z$(t);case"pwsh":return R$(t);default:return r}};var Mf=z({args:[{arity:"one",name:"kind",value:{choices:Lf,kind:"choice"}},{arity:"rest",name:"words",value:{kind:"text"}}],flags:[],name:"__complete",summary:"Print values for the completion scripts",updateNotice:!1});var j$=async(e)=>{let t=await e.profile(),r=await pe(t.name);if(!de(r))return[];return(await Ue({authUrl:t.profile.authUrl,token:r.token})).map((o)=>o.name)},Bf=async(e,t)=>{let r=await e.profile(),n=await pe(r.name),{spaceUrl:o}=r.profile;if(!(de(n)&&o))return[];let s=r.link?.link.project??n.project;return yf({connect:async()=>{let i=await cn({active:r,prompts:{...e.prompts,interactive:!1}});return Lo({signedIn:i,spaceUrl:o}).space},kind:t,scope:`${r.name}:${s.id}`})},O$=async(e,t)=>{let r=kf(t);if(!r)return Sf(t);let n=t.at(-1)??"";return(await Bf(e,r)).filter((s)=>s.startsWith(n))},L$=async(e)=>{let{client:t,kind:r,words:n}=e;switch(r){case"projects":return await j$(t);case"profiles":{let o=await ve();return Object.keys(o.profiles).toSorted()}case"openstack":return await O$(t,n);default:return await Bf(t,r)}},Gf=k(Mf,async({args:e,client:t})=>{let r=await L$({client:t,kind:e.kind,words:e.words});return t.stdout.write(r.map((n)=>`${n}
319
- `).join("")),0});import{mkdir as D$,readFile as N$,writeFile as Z$}from"node:fs/promises";import{homedir as U$}from"node:os";import Pt from"node:path";var Kf=Im(["bash","zsh","fish"]),Uo="completion.json",F$=v({path:f(),version:f()}),Vf=ww(Kf,F$),Wf=(e=process.env)=>{let t=Pt.basename(e.SHELL??"");switch(t){case"bash":case"zsh":case"fish":case"pwsh":return t;default:return}},dn=(e)=>e.HOME??U$(),M$=(e,t=process.env)=>{switch(e){case"zsh":return Pt.join(t.ZDOTDIR??dn(t),".zfunc","_nipa");case"bash":{let r=t.XDG_DATA_HOME??Pt.join(dn(t),".local","share");return Pt.join(r,"bash-completion","completions","nipa")}case"fish":{let r=t.XDG_CONFIG_HOME??Pt.join(dn(t),".config");return Pt.join(r,"fish","completions","nipa.fish")}default:return e}},Jf=(e,t=process.env)=>{let r=dn(t);return e.startsWith(`${r}/`)?`~${e.slice(r.length)}`:e},Hf=async(e=process.env)=>{let t=Pt.join(e.ZDOTDIR??dn(e),".zshrc");try{return(await N$(t,"utf-8")).includes(".zfunc")}catch{return!1}},qf=async(e)=>{await D$(Pt.dirname(e.file),{recursive:!0}),await Z$(e.file,Zo({program:e.program,shell:e.shell}))},Yf=async(e)=>{let t=M$(e.shell);await qf({file:t,program:e.program,shell:e.shell});let r=await Je(Uo,Vf)??{};return await ut(Uo,{...r,[e.shell]:{path:t,version:e.version}}),t},B$=async(e)=>{let t=await Je(Uo,Vf);if(!t)return;let r=Kf.options.flatMap((o)=>{let s=t[o];return s&&s.version!==e.version?[{file:s.path,shell:o}]:[]});if(r.length===0)return;await Promise.all(r.map(({file:o,shell:s})=>qf({file:o,program:e.program,shell:s})));let n=r.map(({file:o,shell:s})=>[s,{path:o,version:e.version}]);await ut(Uo,{...t,...Object.fromEntries(n)})},Xf=async(e)=>{try{await B$(e)}catch(t){Lt(`can't refresh the completion scripts: ${t instanceof Error?t.message:String(t)}`)}};var Qf=z({args:[{arity:"optional",name:"shell",value:{choices:Of,kind:"choice"}}],description:"Prints the tab completion script for bash, zsh, fish or PowerShell. Without a shell, nipa uses the one in $SHELL. Load the script from your shell's startup file, or save it with --install where the shell loads it, and nipa rewrites it when nipa updates.",examples:[{command:`echo 'eval "$(nipa completion zsh)"' >> ~/.zshrc`,description:"Load it each time zsh starts"},{command:"nipa completion --install",description:"Save it for the shell in $SHELL"}],flags:[{description:"Save it where the shell loads it, instead of printing it",long:"install",value:{kind:"none"}}],name:"completion",summary:"Print or install the tab completion script for your shell",updateNotice:!1});var eh=k(Qf,async({args:e,client:t,flags:r})=>{let n=e.shell??Wf();if(!n)throw Z("missing <shell>","Pass bash, zsh, fish or pwsh, such as `nipa completion zsh`.");if(!r.install)return t.stdout.write(Zo({program:t.program,shell:n})),0;if(n==="pwsh")throw Z("can't install the completion for pwsh","PowerShell has no completion folder. Add `nipa completion pwsh | Out-String | Invoke-Expression` to your $PROFILE.");let o=await Yf({program:t.program,shell:n,version:mt.version});if(Q(`Installed the ${n} completion in ${Jf(o)}`),n==="zsh"&&!await Hf())w("Add `fpath=(~/.zfunc $fpath)` to ~/.zshrc before `compinit`, then open a new terminal.");else if(n==="bash")w("Open a new terminal to use it. It needs the bash-completion package.");else w("Open a new terminal to use it.");return 0});var th="List the databases in your project",aa=z({aliases:["list"],args:[],flags:[N],name:"ls",summary:th}),ca=z({args:[{arity:"one",name:"database",value:{kind:"resource",resource:"databases"}}],flags:[N],name:"inspect",summary:"Show a database's health, address, replicas, logs and backups"}),rh=ee({aliases:["database","databases"],default:"ls",description:"Lists and inspects the database clusters in your project. These are Nipa Cloud's managed databases, which `nipa server ls` doesn't show. Name a database by its name or ID. `inspect` shows its status and health, where to connect, the ranges allowed to connect, its replicas, logs and recent backups, and ends with whether it's healthy.",examples:[{command:"nipa db ls",description:th},{command:"nipa db inspect orders",description:"Check whether orders is healthy and where to connect"},{command:"nipa db ls --json | jq -r '.databases[].name'",description:"Print each database's name"}],name:"db",subcommands:[aa,ca],summary:"List and inspect your databases"});var G$=new Set(["ACTIVE","AVAILABLE","COMPLETED","HEALTHY","IN-USE","ONLINE"]),K$=new Set(["DEGRADED","FAILED","OFFLINE","UNKNOWN"]),V$=new Set(["ATTACHING","BACKING-UP","BUILD","BUILDING","CREATING","DELETING","DETACHING","DOWNLOADING","EXTENDING","HARD_REBOOT","MIGRATING","NEW","PASSWORD","REBOOT","REBUILD","RESCUE","RESERVED","RESIZE","RESTORING-BACKUP","RETYPING","REVERT_RESIZE","UPLOADING","VERIFY_RESIZE"]),la=(e)=>{let t=e.toUpperCase();return K$.has(t)||t.startsWith("ERROR")||t.endsWith("FAILED")},W$=(e)=>{let t=e.toUpperCase();if(G$.has(t))return Jt;if(la(e))return Pe;if(V$.has(t)||t.startsWith("PENDING_"))return ft;return K},Fe=(e)=>{let t=e.toLowerCase().replaceAll(/[_-]/gu," ");return`${t.charAt(0).toUpperCase()}${t.slice(1)}`},J=(e)=>{let t=W$(e);return{paint:(r)=>`${t("●")}${r.slice(1)}`,text:`● ${Fe(e)}`}};var nh=(e)=>e.toUpperCase()==="ACTIVE",oh=(e)=>e.toUpperCase()==="HEALTHY",sh=(e)=>{let{primary:t}=e;if(!t)return[{field:"primary",name:null,part:"cluster",value:null}];let r=[];if(!nh(t.status))r.push({field:"status",name:null,part:"primary",value:t.status});if(!oh(t.health))r.push({field:"health",name:null,part:"primary",value:t.health});for(let o of e.replicas??[])if(!nh(o.status))r.push({field:"status",name:o.name,part:"replica",value:o.status});else if(!oh(o.health))r.push({field:"health",name:o.name,part:"replica",value:o.health});let[n]=e.backups??[];if(n&&la(n.status))r.push({field:"status",name:n.name,part:"backup",value:n.status});return r},ih=(e)=>{if(e.part==="cluster")return"the cluster has no primary yet";if(e.part==="backup"){let r=Fe(e.value??"");return r==="Failed"?`the latest backup, ${e.name}, failed`:`the latest backup, ${e.name}, is ${r}`}return`${e.part==="primary"?"the primary":e.name}'s ${e.field} is ${Fe(e.value??"")}`};var ah=5,da=(e,t)=>`${V(t-Date.parse(e))} ago`,pa=(e,t)=>t===null?e:`${e}:${t}`,ma=(e,t,r)=>{let n=J(e),o=n.paint?.(n.text)??n.text,s=t?` ${t}`:"";return{paint:()=>`${o}${s}${T(r)}`,text:`${n.text}${s}${r}`}},J$=(e,t)=>e.healthCheckedAt?ma(e.health,"",` (checked ${da(e.healthCheckedAt,t)})`):J(e.health),H$=(e,t)=>{let r={text:pa(e.address,t)};if(!e.externalAddress)return[r];let n=pa(e.externalAddress,t);return[De(n," (external)"),r]},q$=(e)=>{let t=[e.status.toLowerCase()];if(e.publishedBytes>0){let r=Number((e.publishedBytes/1024/1024).toFixed(1));t.push(`${r} MB`)}return De(Fe(e.name),` (${t.join(", ")})`)},Y$=(e,t)=>{let n=[...e.sizeGb===null?[]:[`${Number(e.sizeGb.toFixed(2))} GB`],da(e.createdAt,t)].join(", ");return ma(e.status,e.name,` (${n})`)},ua={paint:T,text:"Unavailable"},X$=(e)=>ma(e.status,e.name,e.address?` (${e.address})`:""),Q$=(e)=>e.length===0?[{text:"None"}]:e.map(X$),eS=(e,t)=>{if(e.length===0)return[{text:"None"}];let r=e.slice(0,ah).map((o)=>Y$(o,t)),n=e.length-ah;if(n>0)r.push({paint:T,text:`and ${n} more in --json`});return r},tS=(e,t,r)=>[{label:"Engine",lines:[{text:`${t.engine} ${t.version}`}]},{label:"Status",lines:[J(t.status)]},{label:"Health",lines:[J$(t,r)]},{label:"Flavor",lines:[zn(t)]},{label:"Storage",lines:[{text:`${t.storageGb} GB`}]},{label:"Zone",lines:t.zone?[{text:t.zone}]:[]},{label:"Address",lines:H$(t,e.defaultPort)},{label:"Allowed CIDRs",lines:t.allowedCidrs.length===0?[{text:"None set"}]:t.allowedCidrs.map((n)=>({text:n}))},{label:"Replicas",lines:e.replicas?Q$(e.replicas):[ua]},{label:"Logs",lines:e.logs?.map(q$)??[ua]},{label:"Backups",lines:e.backups?eS(e.backups,r):[ua]}],rS=(e)=>["replicas","logs","backups"].filter((t)=>e[t]===null),nS=(e,t)=>[{label:"ID",lines:[{text:e.id}]},...e.primary?tS(e,e.primary,t):[{label:"Status",lines:[]}],{label:"Created",lines:[{paint:K,text:da(e.createdAt,t)}]}],oS=(e,t)=>{let r=x(e.name),n=rS(e);if(n.length>0)G(`The Space API didn't answer for the ${Tt(n)} of ${r}, so the verdict leaves them out. Run the command again, or with --debug to see the requests.`);if(t.length>0){G(`${r} needs attention: ${Tt(t.map(ih))}.`);return}let{primary:o}=e;if(o){let s=pa(o.externalAddress??o.address,e.defaultPort);w(`${r} is healthy. Connect to it at ${x(s)}.`)}},ch=k(ca,async({args:e,client:t,flags:r})=>{let{active:n,session:o,space:s}=await t.cloud(),{project:i}=o,a=performance.now(),c=await at({kind:lr,projectName:i.name,ref:e.database,space:s}),l=await I(`Loading the replicas, logs and backups of ${c.name}…`,()=>qm(s,c)),u=sh(l);if(r.json)return t.stdout.json({database:{...l,problems:u},profile:n.name,project:i}),0;let p=T(`[${R(performance.now()-a)}]`);if(w(`Database ${x(l.name)} in ${x(i.name)} ${p}`),ht(nS(l,Date.now())),oS(l,u),!t.stdout.isTTY)t.stdout.line(l.id);return 0});var sS=(e,t)=>{M({headings:["Name","Engine","Status","Address","Flavor","Age"],rows:e.map(({createdAt:r,name:n,primary:o})=>[{text:n},{text:o?`${o.engine} ${o.version}`:"-"},o?J(o.status):{text:"-"},{text:o?o.externalAddress??o.address:"-"},{text:o?.flavor??"-"},{paint:K,text:V(t-Date.parse(r))}])})},lh=k(aa,async({client:e,flags:t})=>{let{active:r,session:n,space:o}=await e.cloud(),{project:s}=n,i=performance.now(),a=await I(`Loading the databases in ${s.name}…`,()=>vo(o));if(t.json)return e.stdout.json({databases:a,profile:r.name,project:s}),0;let c=T(`[${R(performance.now()-i)}]`);if(a.length===0)return w(`No databases in ${x(s.name)} ${c}`),0;if(w(`Databases in ${x(s.name)} ${c}`),sS(a,Date.now()),!e.stdout.isTTY)e.stdout.line(a.map((l)=>l.id).join(`
320
- `));return 0});var uh=te(rh,{inspect:ch,ls:lh});var iS="Run it again with --debug to see each request.",Fo=(e)=>{if(e instanceof E)return e;if(e instanceof ae||e instanceof he){let t=e.status===0||e.status>=500;return new E(e.message,{hint:t&&!Ri()?iS:void 0})}if(e instanceof it)return new E(e.message,{hint:"Check the Keystone URL with `nipa profile ls`, or your network connection."});if(e instanceof lt)return new E(e.message,{hint:e.hint??"Fix the file, or delete it and run `nipa login` again."});return};var be=(e)=>({status:"pass",summary:e}),mn=(e,t)=>({hint:t,status:"warn",summary:e}),Te=(e,t)=>({hint:t,status:"fail",summary:e}),aS=(e)=>({status:"skip",summary:e}),Mt=(e)=>`${e.charAt(0).toUpperCase()}${e.slice(1)}`,cS=(e)=>e?.status==="pass"||e?.status==="warn",lS=async(e)=>{try{return await e()}catch(t){let r=t instanceof Error?Fo(t):void 0;if(!r)throw t;return Te(Mt(r.message),r.hint)}},ph=async(e,t)=>{let r=e.checks[t.length];if(!r)return[...t];let n=new Map(t.map((c)=>[c.id,c])),o=r.needs?.find((c)=>!cS(n.get(c))),s=e.checks.find((c)=>c.id===o)?.title??o,a={...o===void 0?await lS(()=>r.run(e.context,n)):aS(`Skipped because ${s} didn't pass`),id:r.id,title:r.title};return e.onReport?.(a),ph(e,[...t,a])},dh=(e)=>ph(e,[]),uS=[["pass","passed"],["warn","warning"],["fail","failed"],["skip","skipped"]],mh=(e)=>uS.flatMap(([t,r])=>{let n=e.filter((o)=>o===t).length;if(n===0)return[];return t==="warn"?[ke(n,r)]:[`${n} ${r}`]}).join(", ");import{existsSync as kS}from"node:fs";import{homedir as PS}from"node:os";import ba from"node:path";var pS=v({cpu_policy:f().nullish(),id:f(),name:f(),ram:X(),resource:f().nullish(),type:f().nullish(),vcpus:X()}),dS=v({machine_types:j(pS)}),mS=(e)=>({cpuPolicy:e.cpu_policy??null,id:e.id,name:e.name,ramMb:e.ram,type:e.type??null,vcpus:e.vcpus}),fS=(e,t)=>e.vcpus-t.vcpus||e.ramMb-t.ramMb||e.name.localeCompare(t.name),Mo=async(e)=>(await e.get("/v4/machine_types",dS)).machine_types.filter((r)=>r.resource!=="dbaas").map(mS).toSorted(fS);import{spawn as hS}from"node:child_process";import{once as gS}from"node:events";import{constants as fh}from"node:os";var fa=new Map([["openstack","Install it with `pipx install python-openstackclient`."],["terraform","Install it with `brew install hashicorp/tap/terraform`."]]),ur=async({args:e,command:t,signIn:r})=>{let n=dt(t);if(!n)throw new E(`command not found: ${t}`,{exitCode:127,hint:fa.get(t)});let{active:o,session:s}=await r(),i=hS(n,e,{env:wf(process.env,Io({profile:o.profile,session:s})),stdio:"inherit"}),a=!1,c=()=>{a=!0},l=()=>i.kill("SIGTERM");process.on("SIGINT",c),process.on("SIGTERM",l);try{await gS(i,"exit")}catch(d){let m=d instanceof Error?d.message:String(d);throw new E(`can't run ${t}: ${m}`,{exitCode:126,hint:"Check that the file runs on its own, such as its `#!` line."})}finally{process.off("SIGINT",c),process.off("SIGTERM",l)}let{exitCode:u,signalCode:p}=i;if(p)return 128+fh.signals[p];return a&&u===0?128+fh.signals.SIGINT:u??1};var Bo=Gt(fr(),1);var yS="https://github.com/PunGrumpy/nipa/releases",bS="https://api.github.com/repos/PunGrumpy/nipa/releases/latest",xS=86400000,gh=v({checkedAt:ho.datetime(),latest:f()}),ha="update.json",wS=v({tag_name:f()}),hh=(e)=>e.replace(/^v/u,"").split("-")[0]?.split(".").map(Number)??[],yh=(e,t)=>{let r=hh(e),n=hh(t);for(let o=0;o<Math.max(r.length,n.length);o+=1){let s=(r[o]??0)-(n[o]??0);if(s!==0)return s>0}return!1},_S=(e)=>e.isTTY&&e.version!=="0.0.0"&&!e.env.CI&&!e.env.NIPA_NO_UPDATE_CHECK,vS=async()=>{try{let e=await Ve(bS,{signal:AbortSignal.timeout(1500)}),t=wS.safeParse(await e.json());return t.success?t.data.tag_name.replace(/^v/u,""):void 0}catch(e){Lt(`update check failed: ${e instanceof Error?e.message:String(e)}`);return}},ga=(e)=>`${yS}/tag/v${e}`,bh=async(e)=>{let t=await Je(ha,gh);return t&&yh(t.latest,e)?t.latest:void 0},$S=(e,t)=>{let r=ga(e),n=Bo.default.dim(`v${t}`),o=Bo.default.green(`v${e}`),s=[`Update available! ${n} ≫ ${o}`,`Release notes: ${Bo.default.cyan(r)}`],i=[`Update available! v${t} ≫ v${e}`,`Release notes: ${r}`],a=Math.max(...i.map((l)=>l.length)),c=(l,u)=>` │ ${l}${" ".repeat(a-u.length)} │`;return["",` ╭${"─".repeat(a+4)}╮`,...s.map((l,u)=>c(l,i[u]??l)),` ╰${"─".repeat(a+4)}╯`,""].join(`
321
- `)},SS=async(e,t)=>{let r=t.env??process.env,n=t.isTTY??process.stderr.isTTY===!0;if(!_S({env:r,isTTY:n,version:e}))return;let o=await Je(ha,gh);if(o&&yh(o.latest,e))oe($S(o.latest,e));if(o&&Date.now()-Date.parse(o.checkedAt)<xS)return;let s=await(t.latest??vS)(),i={checkedAt:new Date().toISOString(),latest:s??o?.latest??e};await ut(ha,i)},xh=async(e,t={})=>{try{await SS(e,t)}catch(r){Lt(`update check failed: ${r instanceof Error?r.message:String(r)}`)}};var CS=(e)=>{let t=PS();return e.startsWith(`${t}${ba.sep}`)?`~${e.slice(t.length)}`:e},xa=async(e)=>{let t=performance.now(),r=await e();return{elapsed:R(performance.now()-t),value:r}},wa=(e)=>new URL(e).host,wh=1e4,ES=async()=>{try{await Promise.all([ve(),pe(me)])}catch(o){if(o instanceof lt)return Te(Mt(o.message),"Fix the file, or delete it and run `nipa login` again.");throw o}let e=pf(),t=CS(ba.dirname(e[0]??"")),r=e.filter((o)=>kS(o));if(r.length===0)return be(`No files in ${t} yet, so nipa uses prod`);let n=r.map((o)=>ba.basename(o)).join(" and ");return be(`${n} in ${t} ${r.length===1?"is":"are"} valid`)},zS={config:()=>"the current profile",env:()=>"from NIPA_PROFILE",flag:()=>"from --profile",link:(e)=>`from ${e.link?ye(e.link.file):"the folder's link"}`},IS=async(e)=>{let t=await e.profile(),r=wa(t.profile.authUrl);return be(`${t.name} (${r}), ${zS[t.source](t)}`)},TS=async(e)=>{let{profile:t}=await e.profile();try{let{elapsed:r,value:n}=await xa(()=>yo(t.authUrl));return be(`${wa(t.authUrl)} answers as Keystone ${n} [${r}]`)}catch(r){if(r instanceof it||r instanceof ae)return Te(Mt(r.message),"Check the Keystone URL with `nipa profile ls`, or your network connection.");throw r}},AS=async(e)=>{let t=await e.profile(),r=t.profile.spaceUrl;if(!r){let{hint:n,message:o}=sa(t);return mn(Mt(o),n)}try{let{elapsed:n}=await xa(()=>bo(r));return be(`${wa(r)} answers as the Space API [${n}]`)}catch(n){if(n instanceof it)return Te(Mt(n.message),"Check your network connection, or the profile's Space API URL.");if(n instanceof he)return Te(Mt(n.message),"Check the profile's `spaceUrl` with `nipa profile ls --json`. It's the portal URL with /api, such as https://space.nipa.cloud/api.");throw n}},RS=async(e)=>{let{name:t}=await e.profile(),r=await e.session(),n=`Run \`${He(t)}\`.`;if(!r)return Te(`You aren't logged in to ${t}`,n);if(!de(r))return Te(`Your ${t} session expired`,n);let o=Dt(r),s=`Logged in as ${r.user.name} to ${r.project.name}, expires in ${Wt(o)}`;return o<oa?mn(s,`Run \`${He(t)}\` to start a new one.`):be(s)},jS=async(e,t)=>{let r=await e.profile(),n=await e.session();if(!n)return Te(`You aren't logged in to ${r.name}`);let o=`Run \`${He(r.name)}\`.`,{spaceUrl:s}=r.profile,i=s&&t.get("space")?.status==="pass";try{let{elapsed:a}=await xa(async()=>{if(await Ue({authUrl:r.profile.authUrl,signal:AbortSignal.timeout(wh),token:n.token}),i)await Mo(xo({projectId:n.project.id,region:r.profile.region,signal:AbortSignal.timeout(wh),token:n.token,url:s}))});return be(`${i?"Keystone and the Space API accept":"Keystone accepts"} the token [${a}]`)}catch(a){if(a instanceof ae&&a.status===401)return Te("Keystone refuses the token, so it was revoked",o);if(a instanceof he&&a.status===401)return Te("The Space API refuses the token that Keystone accepts","The Space API may belong to another Keystone. Check the profile's `authUrl` and `spaceUrl` with `nipa profile ls --json`.");throw a}},OS=async(e,t)=>{let r=await Zt();if(!r)return be("This folder isn't linked");let n=await e.profile(),o=ye(r.file),{profile:s,project:i}=r.link;if(s!==n.name)return be(`${o} links ${s}, which this run doesn't use`);let a=await e.session();if(!a||t.get("token")?.status!=="pass")return be(`${o} links ${i.name}`);if(i.id===a.project.id)return be(`${o} links ${i.name}, the session's project`);return(await Ue({authUrl:n.profile.authUrl,token:a.token})).some((l)=>l.id===i.id)?be(`${o} links ${i.name}, so commands here switch to it for each run`):Te(`${o} links ${i.name}, which your account can't use`,"Run `nipa link` to pick another project.")},_h=[{command:"openstack",runner:"nipa os"},{command:"terraform",runner:"nipa tf"}],ya=(e)=>e.join(" and "),LS=()=>{let e=_h.filter(({command:o})=>!dt(o));if(e.length===0)return Promise.resolve(be(`Found ${ya(_h.map(({command:o})=>o))}`));let t=ya(e.map(({command:o})=>o)),r=ya(e.map(({runner:o})=>`\`${o}\``)),n=e.map(({command:o})=>fa.get(o)).join(" ");return Promise.resolve(mn(`Can't find ${t}, so ${r} won't run`,n))},DS=async(e)=>{let t=await bh(e.version);if(!t)return be(`You have nipa ${e.version}`);return mn(`nipa ${t} is out, and you have ${e.version}`,`Run \`npm install -g nipa-cli\`, or download it from ${ga(t)}.`)},_a=[{id:"config",run:ES,title:"Config files"},{id:"profile",needs:["config"],run:IS,title:"Profile"},{id:"keystone",needs:["profile"],run:TS,title:"Keystone"},{id:"space",needs:["profile"],run:AS,title:"Space API"},{id:"session",needs:["profile"],run:RS,title:"Session"},{id:"token",needs:["keystone","session"],run:jS,title:"Token"},{id:"link",needs:["profile"],run:OS,title:"Linked folder"},{id:"tools",run:LS,title:"Tools"},{id:"update",run:DS,title:"Update"}];var vh=z({args:[],description:"Checks the config files, the profile, Keystone, the Space API, the session and its token, the folder's link, openstack and terraform, and the last update check, then says how to fix each problem. It changes nothing and never asks for a password. It exits with code 1 when a check fails.",examples:[{command:"nipa doctor",description:"Check the current profile"},{command:"nipa -P staging doctor --json",description:"Check the staging profile and print JSON"}],flags:[N],name:"doctor",summary:"Check your setup and say what to fix",updateNotice:!1});var NS={fail:{glyph:"✖",paint:Pe},pass:{glyph:"✔",paint:Jt},skip:{glyph:"-",paint:T},warn:{glyph:"!",paint:ft}},$h=Math.max(..._a.map((e)=>e.title.length)),Sh=" ",ZS=(e)=>{let{glyph:t,paint:r}=NS[e.status],n=x(e.title.padEnd($h)),o=e.status==="skip"?T(e.summary):e.summary;if(oe(`${r(t)} ${n}${Sh}${o}`),"hint"in e&&e.hint){let s=" ".repeat(2+$h+Sh.length);oe(`${s}${T(">")} ${e.hint}`)}},kh=k(vh,async({client:e,flags:t})=>{let r=e.profileWithoutBrokenLink,n={profile:r,session:async()=>{let s=await r();return pe(s.name)},version:mt.version},o=await dh({checks:_a,context:n,onReport:t.json?void 0:ZS});if(t.json){let i=o.some((a)=>a.id==="profile"&&a.status==="pass")?await r():void 0;e.stdout.json({checks:o.map((a)=>({hint:"hint"in a&&a.hint||null,id:a.id,status:a.status,summary:a.summary,title:a.title})),profile:i?.name??null})}else oe(""),w(mh(o.map((s)=>s.status)));return o.some((s)=>s.status==="fail")?1:0});var Ph=z({args:[],description:'Prints the session\'s OS_* variables as shell commands. Load them with `eval "$(nipa env)"` in bash or zsh, or with `nipa env | source` in fish.',flags:[{description:"Shell syntax to print (default: from $SHELL)",long:"shell",value:{choices:Qi,kind:"choice"}}],name:"env",summary:"Print the OS_* variables for your shell"});var Ch=k(Ph,async({client:e,flags:t})=>{let r=t.shell??vf(process.env.SHELL),{active:n,session:o}=await e.session();return e.stdout.line(_f(Io({profile:n.profile,session:o}),r)),0});var Eh=Ht({description:"Runs a command with the session's OS_* variables. nipa removes any OS_* variable already in your shell first, so a stale OS_PASSWORD from an old openrc can't override the token. nipa exits with the command's exit code.",examples:[{command:"nipa exec ansible-playbook site.yml",description:"Run an Ansible playbook"}],name:"exec",summary:"Run any command with the session",target:{kind:"command"}});var zh=qt(Eh,({args:e,client:t,command:r})=>ur({args:e,command:r,signIn:t.toolSession}));var va="List the flavors a server can have",$a=z({aliases:["list"],args:[],flags:[N],name:"ls",summary:va}),Ih=ee({aliases:["flavors","machine-types"],default:"ls",description:"Lists the flavors a server can have, smallest first, with their vCPUs, RAM and type. The Space portal calls them machine types. The ones only database clusters use don't show.",examples:[{command:"nipa flavor ls",description:va},{command:"nipa flavor ls --json | jq -r '.flavors[] | select(.vcpus == 4) | .name'",description:"Print the flavors with 4 vCPUs"}],name:"flavor",subcommands:[$a],summary:va});var US=(e)=>{M({headings:["Name","vCPUs","RAM","Type"],rows:e.map((t)=>[{text:t.name},{text:String(t.vcpus)},{text:Er(t.ramMb)},{text:t.type??"-"}])})},Th=k($a,async({client:e,flags:t})=>{let{active:r,session:n,space:o}=await e.cloud(),{project:s}=n,i=performance.now(),a=await I(`Loading the flavors in ${s.name}…`,()=>Mo(o));if(t.json)return e.stdout.json({flavors:a,profile:r.name,project:s}),0;let c=T(`[${R(performance.now()-i)}]`);if(a.length===0)return w(`No flavors in ${x(s.name)} ${c}`),0;if(w(`Flavors in ${x(s.name)} ${c}`),US(a),!e.stdout.isTTY)e.stdout.line(a.map((l)=>l.name).join(`
322
- `));return 0});var Ah=te(Ih,{ls:Th});var Sa="List the external IPs in your project",ka=z({aliases:["list"],args:[],flags:[N],name:"ls",summary:Sa}),Rh=ee({aliases:["ips"],default:"ls",description:"Lists the external IPs in your project with their status, the internal IP each one forwards to, zone and name. An IP without an internal IP isn't attached to anything.",examples:[{command:"nipa ip ls",description:Sa},{command:"nipa ip ls --json | jq -r '.ips[] | select(.internalAddress == null) | .address'",description:"Print the IPs that aren't attached"}],name:"ip",subcommands:[ka],summary:Sa});var FS=(e)=>{M({headings:["Address","Status","Internal IP","Zone","Name"],rows:e.map((t)=>[{text:t.address},J(t.status),{text:t.internalAddress??"-"},{text:t.zone},{text:t.name}])})},jh=k(ka,async({client:e,flags:t})=>{let{active:r,session:n,space:o}=await e.cloud(),{project:s}=n,i=performance.now(),a=await I(`Loading the external IPs in ${s.name}…`,()=>$o(o));if(t.json)return e.stdout.json({ips:a,profile:r.name,project:s}),0;let c=T(`[${R(performance.now()-i)}]`);if(a.length===0)return w(`No external IPs in ${x(s.name)} ${c}`),0;if(w(`External IPs in ${x(s.name)} ${c}`),FS(a),!e.stdout.isTTY)e.stdout.line(a.map((l)=>l.address).join(`
323
- `));return 0});var Oh=te(Rh,{ls:jh});var Pa="List the Kubernetes clusters in your project",Ca=z({aliases:["list"],args:[],flags:[N],name:"ls",summary:Pa}),Lh=ee({aliases:["kubernetes","coe"],default:"ls",description:"Lists the Kubernetes clusters in your project with their Kubernetes version, nodes, active node count and age. The Space API has no Kubernetes endpoint, and `nipa os coe` can't find Magnum on Nipa Cloud production, so nipa finds each cluster through the servers Magnum made for it. A cluster without servers doesn't show.",examples:[{command:"nipa k8s ls",description:Pa},{command:"nipa k8s ls --json | jq -r '.clusters[0].nodes[].name'",description:"Print the node names of the newest cluster"}],name:"k8s",subcommands:[Ca],summary:Pa});var MS=(e,t)=>{let r=Number(t.role==="master")-Number(e.role==="master");return r===0?e.name.localeCompare(t.name):r},BS=(e)=>{let t=new Map;for(let r of e){if(!r.kubernetes)continue;let{clusterId:n,role:o,version:s}=r.kubernetes,i=t.get(n)??{createdAt:r.createdAt,id:n,nodes:[],version:null};if(i.nodes.push({id:r.id,name:r.name,role:o,status:r.status}),i.version??=s,Date.parse(r.createdAt)<Date.parse(i.createdAt))i.createdAt=r.createdAt;t.set(n,i)}return[...t.values()].map((r)=>({...r,nodes:r.nodes.toSorted(MS)})).toSorted((r,n)=>Date.parse(n.createdAt)-Date.parse(r.createdAt))},Dh=async(e)=>BS(await We(e));var GS=(e)=>{let t=new Map;for(let r of e.nodes){let n=r.role??"node";t.set(n,(t.get(n)??0)+1)}return[...t].map(([r,n])=>ke(n,r)).join(", ")},KS=(e)=>`${e.nodes.filter((r)=>r.status==="ACTIVE").length} of ${e.nodes.length}`,VS=(e,t)=>{M({headings:["Cluster","Version","Nodes","Active","Age"],rows:e.map((r)=>[{text:r.id},{text:r.version??"-"},{text:GS(r)},{text:KS(r)},{paint:K,text:V(t-Date.parse(r.createdAt))}])})},Nh=k(Ca,async({client:e,flags:t})=>{let{active:r,session:n,space:o}=await e.cloud(),{project:s}=n,i=performance.now(),a=await I(`Loading the Kubernetes clusters in ${s.name}…`,()=>Dh(o));if(t.json)return e.stdout.json({clusters:a,profile:r.name,project:s}),0;let c=T(`[${R(performance.now()-i)}]`);if(a.length===0)return w(`No Kubernetes clusters in ${x(s.name)} ${c}`),0;if(w(`Kubernetes clusters in ${x(s.name)} ${c}`),VS(a,Date.now()),!e.stdout.isTTY)e.stdout.line(a.map((l)=>l.id).join(`
324
- `));return 0});var Zh=te(Lh,{ls:Nh});var Uh="List the load balancers in your project",Ea=z({aliases:["list"],args:[],flags:[N],name:"ls",summary:Uh}),za=z({args:[{arity:"one",name:"lb",value:{kind:"resource",resource:"load-balancers"}}],flags:[N],name:"inspect",summary:"Show a load balancer's listeners, backend groups and members"}),Fh=ee({aliases:["loadbalancer","loadbalancers"],default:"ls",description:"Lists and inspects the load balancers in your project. Name a load balancer by its name or ID. `inspect` shows each listener, backend group and member with its status, and ends with what stops the load balancer from serving, such as a listener in error or members that are down.",examples:[{command:"nipa lb ls",description:Uh},{command:"nipa lb inspect web-lb",description:"Show why web-lb isn't serving"},{command:"nipa lb ls --json | jq -r '.loadBalancers[].address'",description:"Print each load balancer's virtual IP"}],name:"lb",subcommands:[Ea,za],summary:"List and inspect your load balancers"});var Ia="Backend group",Ta=(e,t)=>({paint:_t(e)?void 0:Pe,text:t??e.id}),Aa=(e)=>[J(e.status),J(e.health)],WS=(e,t)=>{let r=`${V(t-Date.parse(e.createdAt))} ago`;return[{label:"ID",lines:[{text:e.id}]},{label:"Status",lines:[J(e.status)]},{label:"Health",lines:[J(e.health)]},{label:"Address",lines:[{text:e.address}]},{label:"External IP",lines:e.externalAddress?[{text:e.externalAddress}]:[]},{label:"Flavor",lines:e.flavor?[{text:e.flavor}]:[]},{label:"Created",lines:[{paint:K,text:r}]}]},JS=(e,t)=>{let r=(n)=>{let o=t.find((s)=>s.id===n);return o?o.name??o.id:"-"};w(ke(e.length,"listener")),M({headings:["Listener","Port","Status","Health","Allowed CIDRs",Ia],rows:e.map((n)=>[Ta(n,n.name),{text:`${n.protocol}:${n.port}`},...Aa(n),{text:n.allowedCidrs.join(", ")||"Any"},{text:r(n.backendGroupId)}])})},HS=(e)=>{if(!e)return{text:"-"};let t=e.maxRetries===1?"retry":"retries",r=`${e.type} every ${e.delaySeconds}s, ${e.timeoutSeconds}s timeout, ${e.maxRetries} ${t}`;if(_t(e))return{text:r};let n=`${Fe(e.status)}, ${Fe(e.health)}`;return{paint:Pe,text:`${r} (${n})`}},qS=(e)=>{w(ke(e.length,"backend group")),M({headings:[Ia,"Algorithm","Status","Health","Members","Health check"],rows:e.map((t)=>[Ta(t,t.name),{text:t.algorithm},...Aa(t),{text:String(t.members.length)},HS(t.healthCheck)])})},YS=(e)=>{let t=e.flatMap((r)=>r.members.map((n)=>({group:r,member:n})));w(ke(t.length,"member")),M({headings:["Member","Address",Ia,"Weight","Backup","Status","Health"],rows:t.map(({group:r,member:n})=>[Ta(n,n.name),{text:`${n.address}:${n.port}`},{text:r.name??r.id},{text:n.weight===null?"-":String(n.weight)},{text:n.backup?"Yes":"No"},...Aa(n)])})},Mh=k(za,async({args:e,client:t,flags:r})=>{let{active:n,session:o,space:s}=await t.cloud(),{project:i}=o,a=performance.now(),{id:c,name:l}=await at({kind:cr,projectName:i.name,ref:e.lb,space:s}),u=await I(`Loading ${l}'s listeners and members…`,()=>Qm(s,c));if(r.json)return t.stdout.json({loadBalancer:u,profile:n.name,project:i}),0;let p=T(`[${R(performance.now()-a)}]`);if(w(`Load balancer ${x(l)} in ${x(i.name)} ${p}`),ht(WS(u,Date.now())),u.listenerDetails.length>0)JS(u.listenerDetails,u.backendGroups);let d=u.backendGroups;if(d.length>0)qS(d);if(d.some((b)=>b.members.length>0))YS(d);let{details:m,healthy:h,verdict:y}=ef(u);(h?w:G)(`${y}.`);for(let b of m)w(`${b}.`);if(!t.stdout.isTTY)t.stdout.line(c);return 0});var XS=(e,t)=>{M({headings:["Name","Status","Health","Address","Listeners","Age"],rows:e.map((r)=>[{text:r.name},J(r.status),J(r.health),{text:r.address},{text:String(r.listeners)},{paint:K,text:V(t-Date.parse(r.createdAt))}])})},Bh=k(Ea,async({client:e,flags:t})=>{let{active:r,session:n,space:o}=await e.cloud(),{project:s}=n,i=performance.now(),a=await I(`Loading the load balancers in ${s.name}…`,()=>So(o));if(t.json)return e.stdout.json({loadBalancers:a,profile:r.name,project:s}),0;let c=T(`[${R(performance.now()-i)}]`);if(a.length===0)return w(`No load balancers in ${x(s.name)} ${c}`),0;if(w(`Load balancers in ${x(s.name)} ${c}`),XS(a,Date.now()),!e.stdout.isTTY)e.stdout.line(a.map((l)=>l.id).join(`
325
- `));return 0});var Gh=te(Fh,{inspect:Mh,ls:Bh});import Vh from"node:path";var Kh=z({args:[{arity:"optional",name:"project",value:{kind:"project"}}],description:"Links this folder to a project, by name or ID, like the Vercel CLI's `vercel link`. nipa saves the profile and the project in .nipa/project.json, and every command in this folder and the folders below it uses them, without changing the project other folders use. Without a project, nipa lists your projects to pick from.",examples:[{command:"nipa -P staging link Prototype",description:"Use staging's Prototype project in this folder"},{command:"nipa tf plan",description:"Run terraform with the linked project"}],flags:[],name:"link",summary:"Use a project in this folder"});var Wh=k(Kh,async({args:e,client:t})=>{let{project:r}=e,{active:n,session:o}=await t.savedSession(),s=await I("Loading your projects…",()=>Ue({authUrl:n.profile.authUrl,token:o.token}));if(r===void 0&&!t.prompts.interactive)throw new E("tell nipa which project to link",{exitCode:2,hint:`Run \`nipa link <project>\`. Your projects: ${s.map((d)=>d.name).join(", ")}`});let i=process.cwd(),a=n.link?.link.project??o.project,c=await Oo({ask:jo({current:a,message:"Link to:",prompts:t.prompts}),projects:s,wanted:r});if(n.link&&Vh.dirname(Vh.dirname(n.link.file))===i&&n.link?.link.project.id===c.id)return G(`This folder is already linked to ${x(c.name)}`),0;let u=await If({dir:i,link:{profile:n.name,project:c}}),p=T(`(${n.name})`);return Q(`Linked ${ye(u)} to ${x(c.name)} ${p}`),w(`Commands in this folder now use ${c.name}. Run \`nipa unlink\` to stop.`),0});var Jh=z({args:[],description:"Asks for your email and password, then for an OTP code when your account uses MFA. nipa saves a token for the current profile, scoped to a project, and reuses it until Keystone expires it after 24 hours. With `--remember`, nipa saves your password in the macOS Keychain or Linux's secret service, and later logins ask only for an OTP code. `nipa logout` deletes it.",examples:[{command:"nipa login",description:"Log in to the current profile"},{command:"nipa -P staging login",description:"Log in to the staging profile"},{command:"nipa login --remember",description:"Log in, and ask only for an OTP code next time"}],flags:[{description:"Log in as this user instead of the last one",long:"username",short:"u",value:{kind:"text",name:"email"}},{description:"Use this project instead of the last one",long:"project",short:"p",value:{kind:"project"}},{description:"Save your password in the OS keychain for the next login",long:"remember",value:{kind:"none"}}],name:"login",summary:"Log in with your password and an OTP code"});var Hh=k(Jh,async({client:e,flags:t})=>(await na({active:await e.profile(),prompts:e.prompts,remember:t.remember,username:t.username,wantedProject:t.project}),0));var qh=z({args:[],description:"Revokes the current profile's token and deletes its session. nipa keeps your email and last project for the next login.",flags:[],name:"logout",summary:"Revoke the token and forget the session"});var Yh=k(qh,async({client:e})=>{let t=await e.profile(),r=await pe(t.name),n=await Ro(t.profile);if(r){if(de(r))try{await I("Logging out…",()=>go({authUrl:t.profile.authUrl,token:r.token}))}catch{}if(await zo(t.name),Q(`Logged out of ${x(t.name)}`),n)w("Deleted your saved password.")}else if(n)Q(`Deleted your saved password for ${x(t.name)}`);else G(`Not logged in to ${t.name}, so \`nipa logout\` did nothing`);return 0});var Ra="List the networks in your project",ja=z({aliases:["list"],args:[],flags:[N],name:"ls",summary:Ra}),Xh=ee({aliases:["networks"],default:"ls",description:"Lists the networks your project can use with their status, type, zone and age. A VPC network is one of your project's private networks, and an external network is a shared pool of external IPs.",examples:[{command:"nipa network ls",description:Ra},{command:"nipa network ls --json | jq -r '.networks[] | select(.external | not) | .name'",description:"Print the names of your VPC networks"}],name:"network",subcommands:[ja],summary:Ra});var QS=(e,t)=>{M({headings:["Name","Status","Type","Zone","Age"],rows:e.map((r)=>[{text:r.name},J(r.status),{text:r.external?"external":"VPC"},{text:r.zone??"-"},{paint:K,text:V(t-Date.parse(r.createdAt))}])})},Qh=k(ja,async({client:e,flags:t})=>{let{active:r,session:n,space:o}=await e.cloud(),{project:s}=n,i=performance.now(),a=await I(`Loading the networks in ${s.name}…`,()=>ko(o));if(t.json)return e.stdout.json({networks:a,profile:r.name,project:s}),0;let c=T(`[${R(performance.now()-i)}]`);if(a.length===0)return w(`No networks in ${x(s.name)} ${c}`),0;if(w(`Networks in ${x(s.name)} ${c}`),QS(a,Date.now()),!e.stdout.isTTY)e.stdout.line(a.map((l)=>l.id).join(`
326
- `));return 0});var eg=te(Xh,{ls:Qh});import{spawn as ek}from"node:child_process";import{once as tk}from"node:events";var rk=(e,t)=>{switch(e){case"darwin":return{args:[t],command:"open"};case"win32":return{args:["/c","start",'""',t.replaceAll("&","^&")],command:"cmd",verbatim:!0};default:return{args:[t],command:"xdg-open"}}},nk=async({args:e,command:t,verbatim:r})=>{let n=ek(t,e,{detached:!0,stdio:"ignore",windowsVerbatimArguments:r});await tk(n,"spawn"),n.unref()},tg=async(e,t={})=>{let r=rk(t.platform??process.platform,e),n=t.launch??nk;try{await n(r)}catch{throw new E(`couldn't open a browser with ${r.command}`,{hint:"Open the URL above in your browser, or add `--url` to print only the URL."})}};var ok=["server","volume","network","sg","lb","db"],rg=z({args:[{arity:"optional",name:"resource",value:{choices:ok,kind:"choice"}},{arity:"optional",name:"name",value:{kind:"text"}}],description:"Opens the Nipa Cloud Space portal of the profile this run uses, like the Vercel CLI's `vercel open`. Name a kind of resource, `server`, `volume`, `network`, `sg`, `lb` or `db`, to open its list, and a name or ID after it to open that resource's page, which needs a session. The portal keeps its own login and opens the project you last used in it, so a link can't pick the project. When the output goes to a pipe, or with `--url`, nipa prints only the URL and doesn't open a browser.",examples:[{command:"nipa open",description:"Open the Space portal"},{command:"nipa open server web-1",description:"Open web-1's page"},{command:"nipa open lb",description:"Open the list of load balancers"},{command:"nipa open db orders --url",description:"Print the orders database's URL"}],flags:[{description:"Print the URL instead of opening a browser",long:"url",value:{kind:"none"}}],name:"open",summary:"Open the Space portal in your browser"});var pr=(e,t,r)=>({find:async(n)=>{let o=await at({...n,kind:t});return{name:o.name||o.id,path:r(o)}},list:e}),Oa={db:pr("/sql_databases",lr,(e)=>`/sql_databases/${e.id}/overview`),lb:pr("/load_balancers",cr,(e)=>`/load_balancers/${e.id}/details`),network:pr("/networks",Co,(e)=>`/networks/${e.id}`),server:pr("/compute_instances",en,(e)=>`/compute_instances/${e.id}/overview`),sg:pr("/security_group",ar,(e)=>`/security_group/${e.id}`),volume:pr("/volumes",Po,(e)=>`/volumes?search=${encodeURIComponent(e.name||e.id)}`)},ng="/project";var sk=async(e,t,r)=>{if(t!==void 0&&r!==void 0){let{active:s,session:i,space:a}=await e.cloud(),c=i.project.name;return{path:(await Oa[t].find({projectName:c,ref:r,space:a})).path,projectName:c,spaceUrl:ln(s)}}let n=await e.profile(),o=ln(n);return an(n),{path:t===void 0?ng:Oa[t].list,projectName:n.link?.link.project.name??n.profile.project?.name,spaceUrl:o}},og=k(rg,async({args:e,client:t,flags:r})=>{let n=await sk(t,e.resource,e.name),o=`${Km(n.spaceUrl)}${n.path}`;if(r.url||!t.stdout.isTTY)return t.stdout.line(o),0;if(w(`Opening ${Is(o)}`),await tg(o),n.projectName)w(`The portal opens the project you last used in it. Switch to ${x(n.projectName)} there if it shows another one.`);return 0});var sg=Ht({aliases:["openstack"],description:"Runs `openstack <args...>` with the session. It's the same as `nipa exec openstack <args...>`.",examples:[{command:"nipa os volume list",description:"List the volumes in your project"}],name:"os",summary:"Run openstack with the session",target:{kind:"openstack"}});var ig=qt(sg,({args:e,client:t,command:r})=>ur({args:e,command:r,signIn:t.toolSession}));var La=z({aliases:["list"],args:[],flags:[N],name:"ls",summary:"List your profiles and who is logged in to each"}),Da=z({args:[{arity:"optional",name:"name",value:{kind:"text"}}],flags:[{description:"Keystone URL, ending in /v3",long:"auth-url",value:{kind:"text",name:"url"}},{description:"User domain (default: nipacloud)",long:"user-domain",value:{kind:"text",name:"domain"}},{description:"Region (default: NCP-TH)",long:"region",value:{kind:"text",name:"region"}},{description:"Space portal URL, such as https://space.nipa.cloud (default: production's for production's Keystone)",long:"space-url",value:{kind:"text",name:"url"}},{description:"Make it the current profile",long:"use",value:{kind:"none"}}],name:"add",summary:"Add a profile, asking for missing values"}),Na=z({args:[{arity:"optional",name:"name",value:{kind:"profile"}}],flags:[],name:"use",summary:"Make a profile the current one"}),Za=z({args:[{arity:"one",name:"name",value:{kind:"profile"}}],flags:[{...hr,description:"Remove it without asking"}],name:"rm",summary:"Remove a profile and log out of it"}),ag=ee({default:"ls",description:"A profile is a Keystone URL, user domain, region and Space API URL with its own session. nipa starts with prod, which is Nipa Cloud production. Add a profile for staging or any other Keystone, then use it with `nipa profile use <name>` or `-P <name>`.",examples:[{command:"nipa profile add staging --auth-url https://keystone.example.com/v3",description:"Add a staging profile"},{command:"nipa profile use staging",description:"Make staging the current profile"}],name:"profile",subcommands:[La,Da,Na,Za],summary:"Manage Keystone profiles, such as staging"});var ik=(e)=>(t)=>{if(!Vi.test(t))return"Use lowercase letters, digits and hyphens, starting with a letter";return e.profiles[t]?`A profile named ${t} already exists`:!0},cg=(e)=>ct.shape.authUrl.safeParse(e).success||"Enter an http or https URL, such as https://keystone.example.com/v3",ug="Enter the http or https URL of the Space portal, such as https://space.nipa.cloud",ak=async(e)=>{if(e.flag!==void 0)return e.flag;if(Wi(e.authUrl))return ge.spaceUrl;if(!e.prompts.interactive)return;let t=await e.prompts.text({message:"Space portal URL (Enter to skip)",required:!1,validate:(r)=>r===""||ct.shape.authUrl.safeParse(r).success||ug});return t===""?void 0:t},lg=(e)=>{if(e.value!==void 0)return Promise.resolve(e.value);if(!e.prompts.interactive)throw Z(`missing ${e.flag}`,"Pass every value as a flag when there is no terminal.");return e.ask()},pg=k(Da,async({args:e,client:t,flags:r})=>{let{prompts:n}=t,o=await ve(),s=ik(o),i=await lg({ask:()=>n.text({message:"Profile name",validate:s}),flag:"<name>",prompts:n,value:e.name}),a=s(i);if(a!==!0)throw Z(`can't add profile "${i}"`,a);let c=await lg({ask:()=>n.text({message:"Keystone URL",validate:cg}),flag:"--auth-url",prompts:n,value:r["auth-url"]}),l=cg(c);if(l!==!0)throw Z(`invalid --auth-url "${c}"`,l);let u=r["user-domain"]??(n.interactive?await n.text({default:ge.userDomain,message:"User domain"}):ge.userDomain),p=r.region??(n.interactive?await n.text({default:ge.region,message:"Region"}):ge.region),d=await ak({authUrl:c,flag:r["space-url"],prompts:n});if(d!==void 0&&!ct.shape.authUrl.safeParse(d).success)throw Z(`invalid --space-url "${d}"`,ug);let m=d===void 0?void 0:qr(d),h=performance.now(),y=await I(`Checking ${c}…`,()=>yo(c));if(m!==void 0)await I(`Checking ${m}…`,()=>bo(m));let b={authUrl:c,region:p,spaceUrl:m,userDomain:u},_=r.use??(n.interactive&&await n.confirm({default:!0,message:`Use ${i} now?`}));await St({currentProfile:_?i:o.currentProfile,profiles:{...o.profiles,[i]:b}});let P=m===void 0?"":`, Space API ${new URL(m).host}`;if(Q(`Added profile ${x(i)} (Keystone ${y}${P})`,performance.now()-h),m===void 0)G(`${i} has no Space API URL, so \`nipa server ls\` and the other resource commands don't work with it. Pass \`--space-url\` with its Space portal URL when you add it.`);return w(_?`Now using ${x(i)}. Run \`nipa login\` to log in to it.`:`Run \`nipa login -P ${i}\` to log in to it.`),0});var dg=k(La,async({client:e,flags:t})=>{let r=await ve(),n=Object.keys(r.profiles).toSorted(),o=await Promise.all(n.map((i)=>pe(i)));if(t.json)return e.stdout.json(n.map((i,a)=>{let c=o[a];return{current:i===r.currentProfile,loggedIn:de(c),name:i,...r.profiles[i],user:de(c)?c.user.name:void 0}})),0;let s=n.map((i,a)=>{let c=r.profiles[i]??ge,l=o[a],u=de(l)?`${l.user.name} (${l.project.name})`:"-";return[i,new URL(c.authUrl).host,c.region,u].map((p)=>({text:p}))});return w(`${n.length} ${n.length===1?"profile":"profiles"}`),M({headings:["Name","Keystone","Region","Logged in as"],marks:n.map((i)=>i===r.currentProfile?Jt("✔"):" "),rows:s}),0});var mg=k(Za,async({args:e,client:t,flags:r})=>{let{name:n}=e,o=await ve(),s=o.profiles[n];if(!s)throw new E(`no profile named "${n}"`);if(n===me)throw new E(`can't remove ${me}`,{hint:"nipa always has the Nipa Cloud production profile."});if(!r.yes){if(!t.prompts.interactive)throw Z(`removing ${n} needs confirmation`,"Add --yes to remove it without asking.");if(!await t.prompts.confirm({default:!1,message:`Remove profile ${n} and log out of it?`}))throw new E("Canceled",{exitCode:130})}let i=await pe(n);if(de(i))try{await go({authUrl:s.authUrl,token:i.token})}catch{}await zo(n),await Ro(s);let a=Object.fromEntries(Object.entries(o.profiles).filter(([l])=>l!==n)),c=o.currentProfile===n;if(await St({currentProfile:c?me:o.currentProfile,profiles:a}),Q(`Removed profile ${x(n)}`),c)w(`Now using ${x(me)}`);return 0});var fg=k(Na,async({args:e,client:t})=>{let r=await ve(),n=Object.keys(r.profiles).toSorted(),{name:o}=e;if(o===void 0){if(!t.prompts.interactive)throw Z("missing <name>",`Your profiles: ${n.join(", ")}`);o=await t.prompts.choice({choices:n.map((s)=>({name:s===r.currentProfile?`${s} ${x("(current)")}`:s,value:s})),default:r.currentProfile,message:"Use profile:"})}if(!r.profiles[o])throw new E(`no profile named "${o}"`,{hint:`Your profiles: ${n.join(", ")}`});if(o===r.currentProfile)return G(`You're already using ${x(o)}`),0;return await St({...r,currentProfile:o}),Q(`Now using profile ${x(o)}`),0});var hg=te(ag,{add:pg,ls:dg,rm:mg,use:fg});var Ua="Show how much of each quota your project uses",Fa=z({aliases:["list"],args:[],flags:[N],name:"ls",summary:Ua}),gg=ee({aliases:["quotas","limits"],default:"ls",description:"Shows each quota of your project, such as servers, vCPUs and RAM, with how much it uses, its limit, and the percent used. A quota at 80% or more is near its limit. One at 100% is at its limit, so creating one more of that resource fails. The command exits 0 either way. When the output goes to a pipe, nipa prints one tab-separated line per quota: its group and name, such as `compute/ram`, the amount used, the limit or `unlimited`, and the unit, such as `MB`, or `-` for a count.",examples:[{command:"nipa quota",description:Ua},{command:"nipa quota --json | jq '.quotas[] | select(.limit != null and .used >= .limit)'",description:"Print the quotas at their limit"}],name:"quota",subcommands:[Fa],summary:Ua});var ck=v({group:f(),limit:X(),name:f(),unit:f().nullish(),unlimited:nr(),usage:X()}),lk=(e)=>({group:e.group,limit:e.unlimited?null:e.limit,name:e.name,unit:e.unit??null,used:e.usage}),yg=async(e)=>(await e.getLines("/v4/limits",ck)).map(lk);var Wo=new Map([["compute",{label:"Compute",names:[["instances","Servers"],["cores","vCPUs"],["ram","RAM"],["key_pairs","Key pairs"]]}],["storage",{label:"Block storage",names:[["volumes","Volumes"],["volume_size","Volume size"],["snapshots","Snapshots"],["backups","Backups"]]}],["network",{label:"Network",names:[["network","Networks"],["router","Routers"],["port","Ports"],["floatingip","External IPs"],["security_group","Security groups"],["security_group_rule","Security group rules"]]}],["loadBalancer",{label:"Load balancers",names:[["load_balancer","Load balancers"],["listener","Listeners"],["pool","Pools"]]}],["sqlDatabase",{label:"Databases",names:[["database_instances","Databases"],["ram","RAM"],["volume_size","Storage"],["backups","Backups"]]}],["container",{label:"Kubernetes",names:[["kubernetes_cluster","Clusters"]]}],["objectStorage",{label:"Object storage",names:[["storage_size","Storage"],["objects","Objects"]]}],["internetNatGateway",{label:"NAT gateways",names:[["ing_instance","Gateways"],["ing_reserved_ip","Reserved IPs"]]}]]),uk=[...Wo.keys()],pk=/[_\s]+|(?<=[a-z\d])(?=[A-Z])/u,wg=(e)=>{let t=e.split(pk).join(" ").toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)},_g=(e)=>Wo.get(e)?.label??wg(e),bg=(e)=>Wo.get(e)?.names.map(([t])=>t)??[],vg=(e)=>Wo.get(e.group)?.names.find(([t])=>t===e.name)?.[1]??wg(e.name),Go=(e,t)=>{let r=e.indexOf(t);return r===-1?e.length:r},dk=(e)=>{let t=[...uk];for(let{group:r}of e)if(!t.includes(r))t.push(r);return t},$g=(e)=>{let t=dk(e);return e.toSorted((r,n)=>Go(t,r.group)-Go(t,n.group)||Go(bg(r.group),r.name)-Go(bg(n.group),n.name))},xg=["B","KB","MB","GB","TB"],mk=(e)=>{let t=Math.min(xg.length-1,Math.floor(Math.log(Math.max(e,1))/Math.log(1024)));return`${Number((e/1024**t).toFixed(1))} ${xg[t]}`},fk=new Map([["Bytes",mk],["GB",(e)=>`${e} GB`],["MB",Er]]),Ma=(e,t)=>{if(t===null)return String(e);return fk.get(t)?.(e)??`${e} ${t}`},hk=0.8,Vo=(e)=>{if(e.limit===null)return"ok";if(e.used>=e.limit)return"full";return e.used>=e.limit*hk?"near":"ok"},Sg={full:Pe,near:ft},kg=(e)=>{if(e.limit===null)return"-";if(e.limit===0)return"100%";return`${Math.floor(e.used*100/e.limit)}%`},Ko=(e)=>e===1?"is":"are",Pg=(e)=>{let t=e.filter((n)=>Vo(n)==="full").length,r=e.filter((n)=>Vo(n)==="near").length;if(t>0&&r>0)return`${ke(t,"quota")} ${Ko(t)} at the limit, and ${r} ${Ko(r)} near it.`;if(t>0)return`${ke(t,"quota")} ${Ko(t)} at the limit.`;if(r>0)return`${ke(r,"quota")} ${Ko(r)} near the limit.`;return null},Cg=(e)=>[`${e.group}/${e.name}`,e.used,e.limit??"unlimited",e.unit??"-"].join("\t");var gk=(e)=>{M({headings:["Group","Quota","Used","Limit","%"],rows:e.map((t,r)=>{let n=Sg[Vo(t)];return[{text:e[r-1]?.group!==t.group?_g(t.group):""},{text:vg(t)},{paint:n,text:Ma(t.used,t.unit)},{text:t.limit===null?"unlimited":Ma(t.limit,t.unit)},{paint:n,text:kg(t)}]})})},Eg=k(Fa,async({client:e,flags:t})=>{let{active:r,session:n,space:o}=await e.cloud(),{project:s}=n,i=performance.now(),a=$g(await I(`Loading the quotas of ${s.name}…`,()=>yg(o)));if(t.json)return e.stdout.json({profile:r.name,project:s,quotas:a}),0;let c=T(`[${R(performance.now()-i)}]`);if(a.length===0)return w(`No quotas for ${x(s.name)} ${c}`),0;w(`Quotas of ${x(s.name)} ${c}`),gk(a);let l=Pg(a);if(l)G(l);if(!e.stdout.isTTY)e.stdout.line(a.map(Cg).join(`
327
- `));return 0});var zg=te(gg,{ls:Eg});var Ig="List the servers in your project",dr={arity:"one",name:"server",value:{kind:"resource",resource:"servers"}},Ba=[{description:"Return once the Space API takes the action, without waiting",long:"no-wait",value:{kind:"none"}},{description:"How long to wait, such as 90s or 10m (default: 5m)",long:"timeout",value:{kind:"text",name:"duration"}}],Ga=z({aliases:["list"],args:[],flags:[N],name:"ls",summary:Ig}),Ka=z({args:[dr],flags:[N],name:"inspect",summary:"Show a server's flavor, addresses, volumes and security groups"}),Va=z({args:[dr],flags:[{description:"Print only the last n lines",long:"tail",short:"n",value:{kind:"text",name:"n"}},N],name:"logs",summary:"Print a server's console log"}),Wa=z({aliases:["events"],args:[dr],flags:[N],name:"history",summary:"List what was done to a server, newest first"}),Ja=z({args:[dr],flags:[...Ba],name:"start",summary:"Start a stopped server"}),Ha=z({args:[dr],flags:[hr,...Ba],name:"stop",summary:"Stop a server"}),qa=z({aliases:["reboot"],args:[dr],flags:[hr,...Ba],name:"restart",summary:"Restart a server"}),Tg=ee({aliases:["servers"],default:"ls",description:"Lists, inspects, starts, stops and restarts the servers in your project, and shows what was done to a server and its console log. Name a server by its name or ID. `logs` prints the last 100 lines of the console log, which is what the Space API sends. nipa calls the Space API, the one the Nipa Cloud Space portal uses, so you don't need the OpenStack client. start, stop and restart wait until the server finishes, for 5 minutes or `--timeout`. `--no-wait` returns once the Space API takes the action.",examples:[{command:"nipa server ls",description:Ig},{command:"nipa server inspect web-1",description:"Show web-1's addresses, volumes and security groups"},{command:"nipa server history web-1",description:"List web-1's actions, such as a create that failed"},{command:"nipa server logs web-1 --tail 20",description:"Print the last 20 lines of web-1's console log"},{command:"nipa server stop web-1 --yes",description:"Stop web-1 without asking"},{command:"nipa server start web-1 --no-wait",description:"Start web-1 without waiting for it"},{command:"nipa server ls --json | jq -r '.servers[].name'",description:"Print each server's name"}],name:"server",subcommands:[Ga,Ka,Wa,Va,Ja,Ha,qa],summary:"List, inspect, start, stop and restart your servers, and read their history and logs"});var yk=(e,t)=>{M({headings:["Age","Action","User","Result","Request ID"],rows:e.map((r)=>[{paint:K,text:V(t-Date.parse(r.startedAt))},{text:r.action},{text:r.user??"-"},wo(r)?{paint:Pe,text:r.remark??""}:{text:r.remark??"-"},{paint:T,text:r.requestId}])})},Ag=k(Wa,async({args:e,client:t,flags:r})=>{let{active:n,session:o,space:s}=await t.cloud(),{project:i}=o,a=performance.now(),c=await vt({projectName:i.name,ref:e.server,space:s}),l=await I(`Loading ${c.name}'s history…`,()=>_o(s,c.id));if(r.json)return t.stdout.json({actions:l,profile:n.name,project:i,server:{id:c.id,name:c.name}}),0;let u=T(`[${R(performance.now()-a)}]`),p=`${x(c.name)} in ${x(i.name)}`;if(l.length===0)return w(`No actions on ${p} ${u}`),0;if(w(`Actions on ${p} ${u}`),yk(l,Date.now()),!t.stdout.isTTY)t.stdout.line(l.map((d)=>d.requestId).join(`
328
- `));return 0});var Rg=(e)=>{let t=e.addresses.filter((n)=>n.version===4);return(t.find((n)=>n.type==="floating")??t[0]??e.addresses[0])?.address},Jo=(e)=>{if(!e.kubernetes)return{text:e.name};let t=e.kubernetes.role??"node";return{paint:(r)=>`${e.name}${T(r.slice(e.name.length))}`,text:`${e.name} (Kubernetes ${t})`}},jg=(e)=>{let t=e.addresses.filter((n)=>n.type==="floating"),r=e.addresses.filter((n)=>n.type==="fixed");return[...t.map((n)=>De(n.address," (external)")),...r.map((n)=>({text:n.address}))]},bk=(e)=>{let r=[[`${e.sizeGb} GB`,e.type].filter(Boolean).join(" "),e.attachedAs].filter(Boolean).join(", ");return De(e.name??e.id,` (${r})`)},Og=(e)=>e.volumes.map(bk);var xk=(e,t)=>{let r=wo(e),n=r?`${e.action} failed`:e.action,o=r||e.remark===null?"":` (${e.remark})`,s=e.user===null?"":` by ${e.user}`,i=V(t-Date.parse(e.startedAt));return{paint:r?(a)=>`${Pe(n)}${a.slice(n.length)}`:void 0,text:`${n}${o} ${i} ago${s}`}},Lg=(e)=>{if(e.status==="fulfilled")return{ok:!0,value:e.value};let{reason:t}=e;return{ok:!1,reason:t instanceof Error?t.message:String(t)}},Ya={paint:T,text:"unavailable"},wk=(e)=>{let{actions:t,now:r,server:n,state:o}=e,s=[{label:"ID",lines:[{text:n.id}]},{label:"Status",lines:[J(n.status)]}];if(!o.ok)s.push({label:"Task",lines:[Ya]},{label:"Locked",lines:[Ya]});else if(o.value.taskState!==null)s.push({label:"Task",lines:[{text:o.value.taskState}]});if(o.ok&&o.value.locked===!0)s.push({label:"Locked",lines:[{text:"yes"}]});let i=t.ok?t.value[0]:void 0;if(!t.ok)s.push({label:"Last action",lines:[Ya]});else if(i)s.push({label:"Last action",lines:[xk(i,r)]});if(s.push({label:"Flavor",lines:[zn(n)]},{label:"Zone",lines:n.zone?[{text:n.zone}]:[]},{label:"Addresses",lines:jg(n)},{label:"Volumes",lines:Og(n)},{label:"Security groups",lines:n.securityGroups.map((c)=>({text:c}))}),n.kubernetes){let{clusterId:c,role:l}=n.kubernetes;s.push({label:"Kubernetes",lines:[De(l??"node",` (cluster ${c})`)]})}let a=`${V(r-Date.parse(n.createdAt))} ago`;return s.push({label:"Created",lines:[{paint:K,text:a}]}),s},Dg=k(Ka,async({args:e,client:t,flags:r})=>{let{active:n,session:o,space:s}=await t.cloud(),{project:i}=o,a=performance.now(),c=await vt({projectName:i.name,ref:e.server,space:s}),[l,u]=await I(`Loading ${c.name}'s state…`,()=>Promise.allSettled([Zi(s,c.id),_o(s,c.id)])),p=Lg(l),d=Lg(u),m=()=>{let y=[["state",p],["actions",d]];for(let[b,_]of y)if(!_.ok)w(`Couldn't load ${c.name}'s ${b}: ${_.reason}. Run the command again, or add \`--debug\` to see the request.`)};if(r.json)return m(),t.stdout.json({profile:n.name,project:i,server:{...c,lastAction:d.ok?d.value[0]??null:null,locked:p.ok?p.value.locked:null,taskState:p.ok?p.value.taskState:null}}),0;let h=T(`[${R(performance.now()-a)}]`);if(w(`Server ${x(c.name)} in ${x(i.name)} ${h}`),ht(wk({actions:d,now:Date.now(),server:c,state:p})),m(),c.status==="ERROR")w(`Run \`nipa server history ${e.server}\` to see what failed, and \`nipa server logs ${e.server}\` for its console log.`);if(!t.stdout.isTTY)t.stdout.line(c.id);return 0});var _k=(e)=>{let t=Number(e);if(!/^\d+$/u.test(e)||t===0)throw Z(`"${e}" isn't a number of lines`,"Write it as a whole number above 0, such as `--tail 50`.");return t},vk=(e,t)=>{if(t===void 0)return e;let r=e.split(`
326
+ `},cs=(e)=>{let{program:t,shell:r}=e;switch(r){case"bash":return bk(t);case"zsh":return Sk(t);case"fish":return Ek(t);case"pwsh":return Ik(t);default:return r}};var Vh=R({args:[{arity:"one",name:"kind",value:{choices:Uh,kind:"choice"}},{arity:"rest",name:"words",value:{kind:"text"}}],flags:[],name:"__complete",summary:"Print values for the completion scripts",updateNotice:!1});var Tk=async(e)=>{let t=await e.profile(),r=await ge(t.name);if(!ye(r))return[];return(await Oe({authUrl:t.profile.authUrl,token:r.token})).map((o)=>o.name)},Wh=async(e,t)=>{let r=await e.profile(),n=await ge(r.name),{spaceUrl:o}=r.profile;if(!(ye(n)&&o))return[];let s=r.link?.link.project??n.project;return vh({connect:async()=>{let i=await _n({active:r,prompts:{...e.prompts,interactive:!1}});return xr({signedIn:i,spaceUrl:o}).space},kind:t,scope:`${r.name}:${s.id}`})},zk=async(e,t)=>{let r=jh(t);if(!r)return Eh(t);let n=t.at(-1)??"";return(await Wh(e,r)).filter((s)=>s.startsWith(n))},Ok=async(e)=>{let{client:t,kind:r,words:n}=e;switch(r){case"projects":return await Tk(t);case"profiles":{let o=await je();return Object.keys(o.profiles).toSorted()}case"openstack":return await zk(t,n);default:return await Wh(t,r)}},Jh=S(Vh,async({args:e,client:t})=>{let r=await Ok({client:t,kind:e.kind,words:e.words});return t.stdout.write(r.map((n)=>`${n}
327
+ `).join("")),0});import{mkdir as Lk,readFile as Dk,writeFile as Nk}from"node:fs/promises";import{homedir as Zk}from"node:os";import jt from"node:path";var Hh=Of(["bash","zsh","fish"]),ls="completion.json",Uk=_({path:f(),version:f()}),qh=d_(Hh,Uk),Yh=(e=process.env)=>{let t=jt.basename(e.SHELL??"");switch(t){case"bash":case"zsh":case"fish":case"pwsh":return t;default:return}},kn=(e)=>e.HOME??Zk(),Fk=(e,t=process.env)=>{switch(e){case"zsh":return jt.join(t.ZDOTDIR??kn(t),".zfunc","_nipa");case"bash":{let r=t.XDG_DATA_HOME??jt.join(kn(t),".local","share");return jt.join(r,"bash-completion","completions","nipa")}case"fish":{let r=t.XDG_CONFIG_HOME??jt.join(kn(t),".config");return jt.join(r,"fish","completions","nipa.fish")}default:return e}},Xh=(e,t=process.env)=>{let r=kn(t);return e.startsWith(`${r}/`)?`~${e.slice(r.length)}`:e},Qh=async(e=process.env)=>{let t=jt.join(e.ZDOTDIR??kn(e),".zshrc");try{return(await Dk(t,"utf-8")).includes(".zfunc")}catch{return!1}},eg=async(e)=>{await Lk(jt.dirname(e.file),{recursive:!0}),await Nk(e.file,cs({program:e.program,shell:e.shell}))},tg=async(e)=>{let t=Fk(e.shell);await eg({file:t,program:e.program,shell:e.shell});let r=await Ye(ls,qh)??{};return await pt(ls,{...r,[e.shell]:{path:t,version:e.version}}),t},Mk=async(e)=>{let t=await Ye(ls,qh);if(!t)return;let r=Hh.options.flatMap((o)=>{let s=t[o];return s&&s.version!==e.version?[{file:s.path,shell:o}]:[]});if(r.length===0)return;await Promise.all(r.map(({file:o,shell:s})=>eg({file:o,program:e.program,shell:s})));let n=r.map(({file:o,shell:s})=>[s,{path:o,version:e.version}]);await pt(ls,{...t,...Object.fromEntries(n)})},rg=async(e)=>{try{await Mk(e)}catch(t){at(`can't refresh the completion scripts: ${t instanceof Error?t.message:String(t)}`)}};var ng=R({args:[{arity:"optional",name:"shell",value:{choices:Zh,kind:"choice"}}],description:"Prints the tab completion script for bash, zsh, fish or PowerShell. Without a shell, nipa uses the one in $SHELL. Load the script from your shell's startup file, or save it with --install where the shell loads it, and nipa rewrites it when nipa updates.",examples:[{command:`echo 'eval "$(nipa completion zsh)"' >> ~/.zshrc`,description:"Load it each time zsh starts"},{command:"nipa completion --install",description:"Save it for the shell in $SHELL"}],flags:[{description:"Save it where the shell loads it, instead of printing it",long:"install",value:{kind:"none"}}],name:"completion",summary:"Print or install the tab completion script for your shell",updateNotice:!1,usesProfile:!1,usesProject:!1});var og=S(ng,async({args:e,client:t,flags:r})=>{let n=e.shell??Yh();if(!n)throw Z("missing <shell>","Pass bash, zsh, fish or pwsh, such as `nipa completion zsh`.");if(!r.install)return t.stdout.write(cs({program:t.program,shell:n})),0;if(n==="pwsh")throw Z("can't install the completion for pwsh","PowerShell has no completion folder. Add `nipa completion pwsh | Out-String | Invoke-Expression` to your $PROFILE.");let o=await tg({program:t.program,shell:n,version:ft.version});if(te(`Installed the ${n} completion in ${Xh(o)}`),n==="zsh"&&!await Qh())w("Add `fpath=(~/.zfunc $fpath)` to ~/.zshrc before `compinit`, then open a new terminal.");else if(n==="bash")w("Open a new terminal to use it. It needs the bash-completion package.");else w("Open a new terminal to use it.");return 0});var sg="List the databases in your project",Va=R({aliases:["list"],args:[],flags:[D],name:"ls",summary:sg}),Wa=R({args:[{arity:"one",name:"database",value:{kind:"resource",resource:"databases"}}],flags:[D],name:"inspect",summary:"Show a database's health, address, replicas, logs and backups"}),ig=re({aliases:["database","databases"],default:"ls",description:"Lists and inspects the database clusters in your project. These are Nipa Cloud's managed databases, which `nipa server ls` doesn't show. Name a database by its name or ID. `inspect` shows its status and health, where to connect, the ranges allowed to connect, its replicas, logs and recent backups, and ends with whether it's healthy.",examples:[{command:"nipa db ls",description:sg},{command:"nipa db inspect orders",description:"Check whether orders is healthy and where to connect"},{command:"nipa db ls --json | jq -r '.databases[].name'",description:"Print each database's name"}],name:"db",subcommands:[Va,Wa],summary:"List and inspect your databases"});var ag=(e)=>e.toUpperCase()==="ACTIVE",cg=(e)=>e.toUpperCase()==="HEALTHY",lg=(e)=>{let{primary:t}=e;if(!t)return[{field:"primary",name:null,part:"cluster",value:null}];let r=[];if(!ag(t.status))r.push({field:"status",name:null,part:"primary",value:t.status});if(!cg(t.health))r.push({field:"health",name:null,part:"primary",value:t.health});for(let o of e.replicas??[])if(!ag(o.status))r.push({field:"status",name:o.name,part:"replica",value:o.status});else if(!cg(o.health))r.push({field:"health",name:o.name,part:"replica",value:o.health});let[n]=e.backups??[];if(n&&ka(n.status))r.push({field:"status",name:n.name,part:"backup",value:n.status});return r},ug=(e)=>{if(e.part==="cluster")return"the cluster has no primary yet";if(e.part==="backup"){let r=ve(e.value??"");return r==="Failed"?`the latest backup, ${e.name}, failed`:`the latest backup, ${e.name}, is ${r}`}return`${e.part==="primary"?"the primary":e.name}'s ${e.field} is ${ve(e.value??"")}`};var pg=5,qa=(e,t)=>`${H(t-Date.parse(e))} ago`,Ha=(e,t)=>t===null?e:`${e}:${t}`,Ya=(e,t,r)=>{let n=F(z(e)),o=n.paint?.(n.text)??n.text,s=t?` ${z(t)}`:"",i=z(r);return{paint:()=>`${o}${s}${P(i)}`,text:`${n.text}${s}${i}`}},Bk=(e,t)=>e.healthCheckedAt?Ya(e.health,"",` (checked ${qa(e.healthCheckedAt,t)})`):F(e.health),Gk=(e,t)=>{let r={text:Ha(e.address,t)};if(!e.externalAddress)return[r];let n=Ha(e.externalAddress,t);return[Ae(n," (external)"),r]},Kk=(e)=>{let t=[e.status.toLowerCase()];if(e.publishedBytes>0){let r=Number((e.publishedBytes/1024/1024).toFixed(1));t.push(`${r} MB`)}return Ae(ve(e.name),` (${t.join(", ")})`)},Vk=(e,t)=>{let n=[...e.sizeGb===null?[]:[`${Number(e.sizeGb.toFixed(2))} GB`],qa(e.createdAt,t)].join(", ");return Ya(e.status,e.name,` (${n})`)},Ja={paint:P,text:"Unavailable"},Wk=(e)=>Ya(e.status,e.name,e.address?` (${e.address})`:""),Jk=(e)=>e.length===0?[{text:"None"}]:e.map(Wk),Hk=(e,t)=>{if(e.length===0)return[{text:"None"}];let r=e.slice(0,pg).map((o)=>Vk(o,t)),n=e.length-pg;if(n>0)r.push({paint:P,text:`and ${n} more in --json`});return r},qk=(e,t,r)=>[{label:"Engine",lines:[{text:`${t.engine} ${t.version}`}]},{label:"Status",lines:[F(t.status)]},{label:"Health",lines:[Bk(t,r)]},{label:"Flavor",lines:[qn(t)]},{label:"Storage",lines:[{text:`${t.storageGb} GB`}]},{label:"Zone",lines:t.zone?[{text:t.zone}]:[]},{label:"Address",lines:Gk(t,e.defaultPort)},{label:"Allowed CIDRs",lines:t.allowedCidrs.length===0?[{text:"None set"}]:t.allowedCidrs.map((n)=>({text:n}))},{label:"Replicas",lines:e.replicas?Jk(e.replicas):[Ja]},{label:"Logs",lines:e.logs?.map(Kk)??[Ja]},{label:"Backups",lines:e.backups?Hk(e.backups,r):[Ja]}],Yk=(e)=>["replicas","logs","backups"].filter((t)=>e[t]===null),Xk=(e,t)=>[{label:"ID",lines:[{text:e.id}]},...e.primary?qk(e,e.primary,t):[{label:"Status",lines:[]}],{label:"Created",lines:[{paint:W,text:qa(e.createdAt,t)}]}],Qk=(e,t)=>{let r=x(e.name),n=Yk(e);if(n.length>0)J(`The Space API didn't answer for the ${Dt(n)} of ${r}, so the verdict leaves them out. Run the command again, or with --debug to see the requests.`);if(t.length>0){J(`${r} needs attention: ${Dt(t.map(ug))}.`);return}let{primary:o}=e;if(o){let s=Ha(fr(o),e.defaultPort);w(`${r} is healthy. Connect to it at ${x(s)}.`)}},dg=S(Wa,async({args:e,client:t,flags:r})=>{let{active:n,session:o,space:s}=await t.cloud(),{project:i}=o,a=performance.now(),c=await ct({kind:br,projectName:i.name,ref:e.database,space:s}),l=await j(`Loading the replicas, logs and backups of ${c.name}…`,()=>eh(s,c)),u=lg(l);if(r.json)return t.stdout.json({database:{...l,problems:u},profile:n.name,project:i}),0;let p=P(`[${T(performance.now()-a)}]`);if(w(`Database ${x(l.name)} in ${x(i.name)} ${p}`),yt(Xk(l,Date.now())),Qk(l,u),!t.stdout.isTTY)t.stdout.line(l.id);return 0});var eP=(e,t)=>{G({headings:["Name","Engine","Status","Address","Flavor","Age"],rows:e.map(({createdAt:r,name:n,primary:o})=>[{text:n},{text:o?`${o.engine} ${o.version}`:"-"},o?F(o.status):{text:"-"},{text:o?fr(o):"-"},{text:o?.flavor??"-"},{paint:W,text:H(t-Date.parse(r))}])})},mg=S(Va,async({client:e,flags:t})=>{let{active:r,session:n,space:o}=await e.cloud(),{project:s}=n,i=performance.now(),a=await j(`Loading the databases in ${s.name}…`,()=>Go(o));if(t.json)return e.stdout.json({databases:a,profile:r.name,project:s}),0;let c=P(`[${T(performance.now()-i)}]`);if(a.length===0)return w(`No databases in ${x(s.name)} ${c}`),0;if(w(`Databases in ${x(s.name)} ${c}`),eP(a,Date.now()),!e.stdout.isTTY)e.stdout.line(a.map((l)=>l.id).join(`
328
+ `));return 0});var fg=ne(ig,{inspect:dg,ls:mg});var tP="Run it again with --debug to see each request.",rP=(e)=>{if(e instanceof ce&&e.status===401)return"token_expired";if(e instanceof ce&&e.status===404)return"not_found";return"api_error"},wr=(e)=>{if(e instanceof C)return e;if(e instanceof ae||e instanceof ce){let t=e.status===0||e.status>=500;return new C(e.message,{hint:t&&!da()?tP:void 0,reason:rP(e)})}if(e instanceof Be)return new C(e.message,{hint:"Check the Keystone URL with `nipa profile ls`, or your network connection.",reason:"network_error"});if(e instanceof ut)return new C(e.message,{hint:e.hint??"Fix the file, or delete it and run `nipa login` again.",reason:"invalid_config"});return},nP=(e)=>e.exitCode===2||e.reason==="ambiguous_name"||e.reason==="login_required"||e.reason==="token_expired",oP=(e,t)=>{let r={message:e.message,reason:e.reason,status:nP(e)?"action_required":"error"};if(e.hint&&!e.next?.length)r.hint=ni(e.hint,t);if(e.data)r.data=e.data;if(e.next&&e.next.length>0)r.next=e.next.map((n)=>Mr(n,t));return r},hg=(e)=>{V(JSON.stringify(oP(e,Fr())))},gg=()=>new C("Unexpected error in nipa. This is a bug.",{reason:"internal_error"});var $e=(e)=>({status:"pass",summary:e}),Pn=(e,t)=>({hint:t,status:"warn",summary:e}),Le=(e,t)=>({hint:t,status:"fail",summary:e}),sP=(e)=>({status:"skip",summary:e}),qt=(e)=>`${e.charAt(0).toUpperCase()}${e.slice(1)}`,iP=(e)=>e?.status==="pass"||e?.status==="warn",aP=async(e)=>{try{return await e()}catch(t){let r=t instanceof Error?wr(t):void 0;if(!r)throw t;return Le(qt(r.message),r.hint)}},yg=async(e,t)=>{let r=e.checks[t.length];if(!r)return[...t];let n=new Map(t.map((c)=>[c.id,c])),o=r.needs?.find((c)=>!iP(n.get(c))),s=e.checks.find((c)=>c.id===o)?.title??o,a={...o===void 0?await aP(()=>r.run(e.context,n)):sP(`Skipped because ${s} didn't pass`),id:r.id,title:r.title};return e.onReport?.(a),yg(e,[...t,a])},bg=(e)=>yg(e,[]),cP=[["pass","passed"],["warn","warning"],["fail","failed"],["skip","skipped"]],xg=(e)=>cP.flatMap(([t,r])=>{let n=e.filter((o)=>o===t).length;if(n===0)return[];return t==="warn"?[le(n,r)]:[`${n} ${r}`]}).join(", ");import{existsSync as $P}from"node:fs";import{homedir as kP}from"node:os";import rc from"node:path";var lP=_({cpu_policy:f().nullish(),id:f(),name:f(),ram:ee(),resource:f().nullish(),type:f().nullish(),vcpus:ee()}),uP=_({machine_types:O(lP)}),pP=(e)=>({cpuPolicy:e.cpu_policy??null,id:e.id,name:e.name,ramMb:e.ram,type:e.type??null,vcpus:e.vcpus}),dP=(e,t)=>e.vcpus-t.vcpus||e.ramMb-t.ramMb||e.name.localeCompare(t.name),us=async(e)=>(await e.get("/v4/machine_types",uP)).machine_types.filter((r)=>r.resource!=="dbaas").map(pP).toSorted(dP);import{spawn as mP}from"node:child_process";import{once as fP}from"node:events";import{constants as wg}from"node:os";var Xa=new Map([["openstack","Install it with `pipx install python-openstackclient`."],["terraform","Install it with `brew install hashicorp/tap/terraform`."]]),hP="Put nipa's options, such as `--project`, before `exec`, because the words after it belong to the command.",vr=async({args:e,command:t,signIn:r})=>{let n=mt(t);if(!n)throw new C(`command not found: ${t}`,{exitCode:127,hint:Xa.get(t)??(t.startsWith("-")?hP:void 0)});let{active:o,session:s}=await r(),i=mP(n,e,{env:$h(process.env,Xo({profile:o.profile,session:s})),stdio:"inherit"}),a=!1,c=()=>{a=!0},l=()=>i.kill("SIGTERM");process.on("SIGINT",c),process.on("SIGTERM",l);try{await fP(i,"exit")}catch(d){let m=d instanceof Error?d.message:String(d);throw new C(`can't run ${t}: ${m}`,{exitCode:126,hint:"Check that the file runs on its own, such as its `#!` line."})}finally{process.off("SIGINT",c),process.off("SIGTERM",l)}let{exitCode:u,signalCode:p}=i;if(p)return 128+wg.signals[p];return a&&u===0?128+wg.signals.SIGINT:u??1};var gP="https://github.com/PunGrumpy/nipa/releases",yP="https://api.github.com/repos/PunGrumpy/nipa/releases/latest",bP=86400000,_g=_({checkedAt:Do.datetime(),latest:f()}),Qa="update.json",xP=_({tag_name:f()}),vg=(e)=>e.replace(/^v/u,"").split("-")[0]?.split(".").map(Number)??[],Sg=(e,t)=>{let r=vg(e),n=vg(t);for(let o=0;o<Math.max(r.length,n.length);o+=1){let s=(r[o]??0)-(n[o]??0);if(s!==0)return s>0}return!1},wP=(e)=>e.interactive&&e.version!=="0.0.0"&&!e.env.NIPA_NO_UPDATE_CHECK&&!e.env.NO_UPDATE_NOTIFIER,vP=async()=>{try{let e=await qe(yP,{redirect:"follow",signal:AbortSignal.timeout(1500)}),t=xP.safeParse(await e.json());return t.success?t.data.tag_name.replace(/^v/u,""):void 0}catch(e){at(`update check failed: ${e instanceof Error?e.message:String(e)}`);return}},ec=(e)=>`${gP}/tag/v${e}`,$g=async(e)=>{let t=await Ye(Qa,_g);return t&&Sg(t.latest,e)?t.latest:void 0},_P=(e,t)=>["",`nipa ${e} is available. You have ${t}.`,`Release notes: ${ec(e)}`].join(`
329
+ `),SP=async(e,t)=>{let r=t.env??process.env;if(!wP({env:r,interactive:t.interactive,version:e}))return;let n=await Ye(Qa,_g);if(n&&Sg(n.latest,e))V(_P(n.latest,e));if(n&&Date.now()-Date.parse(n.checkedAt)<bP)return;let o=await(t.latest??vP)(),s={checkedAt:new Date().toISOString(),latest:o??n?.latest??e};await pt(Qa,s)},kg=async(e,t)=>{try{await SP(e,t)}catch(r){at(`update check failed: ${r instanceof Error?r.message:String(r)}`)}};var PP=(e)=>{let t=kP();return e.startsWith(`${t}${rc.sep}`)?`~${e.slice(t.length)}`:e},nc=async(e)=>{let t=performance.now(),r=await e();return{elapsed:T(performance.now()-t),value:r}},oc=(e)=>new URL(e).host,Pg=1e4,CP=async()=>{try{await Promise.all([je(),ge(be)])}catch(o){if(o instanceof ut)return Le(qt(o.message),"Fix the file, or delete it and run `nipa login` again.");throw o}let e=hh(),t=PP(rc.dirname(e[0]??"")),r=e.filter((o)=>$P(o));if(r.length===0)return $e(`No files in ${t} yet, so nipa uses prod`);let n=r.map((o)=>rc.basename(o)).join(" and ");return $e(`${n} in ${t} ${r.length===1?"is":"are"} valid`)},EP={config:()=>"the current profile",env:()=>"from NIPA_PROFILE",flag:()=>"from --profile",link:(e)=>`from ${e.link?Se(e.link.file):"the folder's link"}`},jP=async(e)=>{let t=await e.profile(),r=oc(t.profile.authUrl);return $e(`${t.name} (${r}), ${EP[t.source](t)}`)},AP=async(e)=>{let{profile:t}=await e.profile();try{let{elapsed:r,value:n}=await nc(()=>Zo(t.authUrl));return $e(`${oc(t.authUrl)} answers as Keystone ${n} [${r}]`)}catch(r){if(r instanceof Be||r instanceof ae)return Le(qt(r.message),"Check the Keystone URL with `nipa profile ls`, or your network connection.");throw r}},RP=async(e)=>{let t=await e.profile(),r=t.profile.spaceUrl;if(!r){let{hint:n,message:o}=Ba(t);return Pn(qt(o),n)}try{let{elapsed:n}=await nc(()=>Uo(r));return $e(`${oc(r)} answers as the Space API [${n}]`)}catch(n){if(n instanceof Be)return Le(qt(n.message),"Check your network connection, or the profile's Space API URL.");if(n instanceof ce)return Le(qt(n.message),"Check the profile's `spaceUrl` with `nipa profile ls --json`. It's the portal URL with /api, such as https://space.nipa.cloud/api.");throw n}},IP=async(e)=>{let{name:t}=await e.profile(),r=await e.session(),n=`Run \`${Ge(t)}\`.`;if(!r)return Le(`You aren't logged in to ${t}`,n);if(!ye(r))return Le(`Your ${t} session expired`,n);let o=Bt(r),s=`Logged in as ${r.user.name} to ${r.project.name}, expires in ${nr(o)}`;return o<Fa?Pn(s,`Run \`${Ge(t)}\` to start a new one.`):$e(s)},TP=async(e,t)=>{let r=await e.profile(),n=await e.session();if(!n)return Le(`You aren't logged in to ${r.name}`);let o=`Run \`${Ge(r.name)}\`.`,{spaceUrl:s}=r.profile,i=s&&t.get("space")?.status==="pass";try{let{elapsed:a}=await nc(async()=>{if(await Oe({authUrl:r.profile.authUrl,signal:AbortSignal.timeout(Pg),token:n.token}),i)await us(Fo({projectId:n.project.id,region:r.profile.region,signal:AbortSignal.timeout(Pg),token:n.token,url:s}))});return $e(`${i?"Keystone and the Space API accept":"Keystone accepts"} the token [${a}]`)}catch(a){if(a instanceof ae&&a.status===401)return Le("Keystone refuses the token, so it was revoked",o);if(a instanceof ce&&a.status===401)return Le("The Space API refuses the token that Keystone accepts","The Space API may belong to another Keystone. Check the profile's `authUrl` and `spaceUrl` with `nipa profile ls --json`.");throw a}},zP=async(e,t)=>{let r=await Kt();if(!r)return $e("This folder isn't linked");let n=await e.profile(),o=Se(r.file),{profile:s,project:i}=r.link;if(s!==n.name)return $e(`${o} links ${s}, which this run doesn't use`);let a=await e.session();if(!a||t.get("token")?.status!=="pass")return $e(`${o} links ${i.name}`);if(i.id===a.project.id)return $e(`${o} links ${i.name}, the session's project`);return(await Oe({authUrl:n.profile.authUrl,token:a.token})).some((l)=>l.id===i.id)?$e(`${o} links ${i.name}, so commands here switch to it for each run`):Le(`${o} links ${i.name}, which your account can't use`,"Run `nipa link` to pick another project.")},Cg=[{command:"openstack",runner:"nipa os"},{command:"terraform",runner:"nipa tf"}],tc=(e)=>e.join(" and "),OP=()=>{let e=Cg.filter(({command:o})=>!mt(o));if(e.length===0)return Promise.resolve($e(`Found ${tc(Cg.map(({command:o})=>o))}`));let t=tc(e.map(({command:o})=>o)),r=tc(e.map(({runner:o})=>`\`${o}\``)),n=e.map(({command:o})=>Xa.get(o)).join(" ");return Promise.resolve(Pn(`Can't find ${t}, so ${r} won't run`,n))},LP=async(e)=>{let t=await $g(e.version);if(!t)return $e(`You have nipa ${e.version}`);return Pn(`nipa ${t} is out, and you have ${e.version}`,`Run \`npm install -g nipa-cli\`, or download it from ${ec(t)}.`)},sc=[{id:"config",run:CP,title:"Config files"},{id:"profile",needs:["config"],run:jP,title:"Profile"},{id:"keystone",needs:["profile"],run:AP,title:"Keystone"},{id:"space",needs:["profile"],run:RP,title:"Space API"},{id:"session",needs:["profile"],run:IP,title:"Session"},{id:"token",needs:["keystone","session"],run:TP,title:"Token"},{id:"link",needs:["profile"],run:zP,title:"Linked folder"},{id:"tools",run:OP,title:"Tools"},{id:"update",run:LP,title:"Update"}];var Eg=R({args:[],description:"Checks the config files, the profile, Keystone, the Space API, the session and its token, the folder's link, openstack and terraform, and the last update check, then says how to fix each problem. It changes nothing and never asks for a password. It exits with code 1 when a check fails.",examples:[{command:"nipa doctor",description:"Check the current profile"},{command:"nipa -P staging doctor --json",description:"Check the staging profile and print JSON"}],flags:[D],name:"doctor",summary:"Check your setup and say what to fix",updateNotice:!1,usesProject:!1});var DP={fail:{glyph:"✖",paint:xe},pass:{glyph:"✔",paint:Lt},skip:{glyph:"-",paint:P},warn:{glyph:"!",paint:Ve}},jg=Math.max(...sc.map((e)=>e.title.length)),Ag=" ",NP=(e)=>{let{glyph:t,paint:r}=DP[e.status],n=x(e.title.padEnd(jg)),o=e.status==="skip"?P(e.summary):e.summary;if(V(`${r(t)} ${n}${Ag}${o}`),"hint"in e&&e.hint){let s=" ".repeat(2+jg+Ag.length);V(`${s}${P(">")} ${e.hint}`)}},Rg=S(Eg,async({client:e,flags:t})=>{let r=e.profileWithoutBrokenLink,n={profile:r,session:async()=>{let s=await r();return ge(s.name)},version:ft.version},o=await bg({checks:sc,context:n,onReport:t.json?void 0:NP});if(t.json){let i=o.some((a)=>a.id==="profile"&&a.status==="pass")?await r():void 0;e.stdout.json({checks:o.map((a)=>({hint:"hint"in a&&a.hint||null,id:a.id,status:a.status,summary:a.summary,title:a.title})),profile:i?.name??null})}else V(""),w(xg(o.map((s)=>s.status)));return o.some((s)=>s.status==="fail")?1:0});var Ig=R({args:[],description:'Prints the session\'s OS_* variables as shell commands. Load them with `eval "$(nipa env)"` in bash or zsh, or with `nipa env | source` in fish.',flags:[{description:"Shell syntax to print (default: from $SHELL)",long:"shell",value:{choices:za,kind:"choice"}}],name:"env",summary:"Print the OS_* variables for your shell"});var Tg=S(Ig,async({client:e,flags:t})=>{let r=t.shell??Ph(process.env.SHELL),{active:n,session:o}=await e.session();return e.stdout.line(kh(Xo({profile:n.profile,session:o}),r)),0});var zg=or({description:"Runs a command with the session's OS_* variables. nipa removes any OS_* variable already in your shell first, so a stale OS_PASSWORD from an old openrc can't override the token. nipa exits with the command's exit code.",examples:[{command:"nipa exec ansible-playbook site.yml",description:"Run an Ansible playbook"}],name:"exec",summary:"Run any command with the session",target:{kind:"command"}});var Og=sr(zg,({args:e,client:t,command:r})=>vr({args:e,command:r,signIn:t.toolSession}));var ic="List the flavors a server can have",ac=R({aliases:["list"],args:[],flags:[D],name:"ls",summary:ic}),Lg=re({aliases:["flavors","machine-types"],default:"ls",description:"Lists the flavors a server can have, smallest first, with their vCPUs, RAM and type. The Space portal calls them machine types. The ones only database clusters use don't show.",examples:[{command:"nipa flavor ls",description:ic},{command:"nipa flavor ls --json | jq -r '.flavors[] | select(.vcpus == 4) | .name'",description:"Print the flavors with 4 vCPUs"}],name:"flavor",subcommands:[ac],summary:ic});var ZP=(e)=>{G({headings:["Name","vCPUs","RAM","Type"],rows:e.map((t)=>[{text:t.name},{text:String(t.vcpus)},{text:Br(t.ramMb)},{text:t.type??"-"}])})},Dg=S(ac,async({client:e,flags:t})=>{let{active:r,session:n,space:o}=await e.cloud(),{project:s}=n,i=performance.now(),a=await j(`Loading the flavors in ${s.name}…`,()=>us(o));if(t.json)return e.stdout.json({flavors:a,profile:r.name,project:s}),0;let c=P(`[${T(performance.now()-i)}]`);if(a.length===0)return w(`No flavors in ${x(s.name)} ${c}`),0;if(w(`Flavors in ${x(s.name)} ${c}`),ZP(a),!e.stdout.isTTY)e.stdout.line(a.map((l)=>l.name).join(`
330
+ `));return 0});var Ng=ne(Lg,{ls:Dg});var cc="List the external IPs in your project",lc=R({aliases:["list"],args:[],flags:[D],name:"ls",summary:cc}),Zg=re({aliases:["ips"],default:"ls",description:"Lists the external IPs in your project with their status, the internal IP each one forwards to, zone and name. An IP without an internal IP isn't attached to anything.",examples:[{command:"nipa ip ls",description:cc},{command:"nipa ip ls --json | jq -r '.ips[] | select(.internalAddress == null) | .address'",description:"Print the IPs that aren't attached"}],name:"ip",subcommands:[lc],summary:cc});var UP=(e)=>{G({headings:["Address","Status","Internal IP","Zone","Name"],rows:e.map((t)=>[{text:t.address},F(t.status),{text:t.internalAddress??"-"},{text:t.zone},{text:t.name}])})},Ug=S(lc,async({client:e,flags:t})=>{let{active:r,session:n,space:o}=await e.cloud(),{project:s}=n,i=performance.now(),a=await j(`Loading the external IPs in ${s.name}…`,()=>Ko(o));if(t.json)return e.stdout.json({ips:a,profile:r.name,project:s}),0;let c=P(`[${T(performance.now()-i)}]`);if(a.length===0)return w(`No external IPs in ${x(s.name)} ${c}`),0;if(w(`External IPs in ${x(s.name)} ${c}`),UP(a),!e.stdout.isTTY)e.stdout.line(a.map((l)=>l.address).join(`
331
+ `));return 0});var Fg=ne(Zg,{ls:Ug});var uc="List the Kubernetes clusters in your project",pc=R({aliases:["list"],args:[],flags:[D],name:"ls",summary:uc}),Mg=re({aliases:["kubernetes","coe"],default:"ls",description:"Lists the Kubernetes clusters in your project with their Kubernetes version, nodes, active node count and age. The Space API has no Kubernetes endpoint, and `nipa os coe` can't find Magnum on Nipa Cloud production, so nipa finds each cluster through the servers Magnum made for it. A cluster without servers doesn't show.",examples:[{command:"nipa k8s ls",description:uc},{command:"nipa k8s ls --json | jq -r '.clusters[0].nodes[].name'",description:"Print the node names of the newest cluster"}],name:"k8s",subcommands:[pc],summary:uc});var FP=(e,t)=>{let r=Number(t.role==="master")-Number(e.role==="master");return r===0?e.name.localeCompare(t.name):r},MP=(e)=>{let t=new Map;for(let r of e){if(!r.kubernetes)continue;let{clusterId:n,role:o,version:s}=r.kubernetes,i=t.get(n)??{createdAt:r.createdAt,id:n,nodes:[],version:null};if(i.nodes.push({id:r.id,name:r.name,role:o,status:r.status}),i.version??=s,Date.parse(r.createdAt)<Date.parse(i.createdAt))i.createdAt=r.createdAt;t.set(n,i)}return[...t.values()].map((r)=>({...r,nodes:r.nodes.toSorted(FP)})).toSorted((r,n)=>Date.parse(n.createdAt)-Date.parse(r.createdAt))},Bg=async(e)=>MP(await Ee(e));var BP=(e)=>{let t=new Map;for(let r of e.nodes){let n=r.role??"node";t.set(n,(t.get(n)??0)+1)}return[...t].map(([r,n])=>le(n,r)).join(", ")},GP=(e)=>`${e.nodes.filter((r)=>r.status==="ACTIVE").length} of ${e.nodes.length}`,KP=(e,t)=>{G({headings:["Cluster","Version","Nodes","Active","Age"],rows:e.map((r)=>[{text:r.id},{text:r.version??"-"},{text:BP(r)},{text:GP(r)},{paint:W,text:H(t-Date.parse(r.createdAt))}])})},Gg=S(pc,async({client:e,flags:t})=>{let{active:r,session:n,space:o}=await e.cloud(),{project:s}=n,i=performance.now(),a=await j(`Loading the Kubernetes clusters in ${s.name}…`,()=>Bg(o));if(t.json)return e.stdout.json({clusters:a,profile:r.name,project:s}),0;let c=P(`[${T(performance.now()-i)}]`);if(a.length===0)return w(`No Kubernetes clusters in ${x(s.name)} ${c}`),0;if(w(`Kubernetes clusters in ${x(s.name)} ${c}`),KP(a,Date.now()),!e.stdout.isTTY)e.stdout.line(a.map((l)=>l.id).join(`
332
+ `));return 0});var Kg=ne(Mg,{ls:Gg});var Vg="List the load balancers in your project",dc=R({aliases:["list"],args:[],flags:[D],name:"ls",summary:Vg}),mc=R({args:[{arity:"one",name:"lb",value:{kind:"resource",resource:"load-balancers"}}],flags:[D],name:"inspect",summary:"Show a load balancer's listeners, backend groups and members"}),Wg=re({aliases:["loadbalancer","loadbalancers"],default:"ls",description:"Lists and inspects the load balancers in your project. Name a load balancer by its name or ID. `inspect` shows each listener, backend group and member with its status, and ends with what stops the load balancer from serving, such as a listener in error or members that are down.",examples:[{command:"nipa lb ls",description:Vg},{command:"nipa lb inspect web-lb",description:"Show why web-lb isn't serving"},{command:"nipa lb ls --json | jq -r '.loadBalancers[].address'",description:"Print each load balancer's virtual IP"}],name:"lb",subcommands:[dc,mc],summary:"List and inspect your load balancers"});var fc="Backend group",hc=(e,t)=>({paint:$t(e)?void 0:xe,text:t??e.id}),gc=(e)=>[F(e.status),F(e.health)],VP=(e,t)=>{let r=`${H(t-Date.parse(e.createdAt))} ago`;return[{label:"ID",lines:[{text:e.id}]},{label:"Status",lines:[F(e.status)]},{label:"Health",lines:[F(e.health)]},{label:"Address",lines:[{text:e.address}]},{label:"External IP",lines:e.externalAddress?[{text:e.externalAddress}]:[]},{label:"Flavor",lines:e.flavor?[{text:e.flavor}]:[]},{label:"Created",lines:[{paint:W,text:r}]}]},WP=(e,t)=>{let r=(n)=>{let o=t.find((s)=>s.id===n);return o?o.name??o.id:"-"};w(le(e.length,"listener")),G({headings:["Listener","Port","Status","Health","Allowed CIDRs",fc],rows:e.map((n)=>[hc(n,n.name),{text:`${n.protocol}:${n.port}`},...gc(n),{text:n.allowedCidrs.join(", ")||"Any"},{text:r(n.backendGroupId)}])})},JP=(e)=>{if(!e)return{text:"-"};let t=e.maxRetries===1?"retry":"retries",r=`${e.type} every ${e.delaySeconds}s, ${e.timeoutSeconds}s timeout, ${e.maxRetries} ${t}`;if($t(e))return{text:r};let n=`${ve(e.status)}, ${ve(e.health)}`;return{paint:xe,text:`${r} (${n})`}},HP=(e)=>{w(le(e.length,"backend group")),G({headings:[fc,"Algorithm","Status","Health","Members","Health check"],rows:e.map((t)=>[hc(t,t.name),{text:t.algorithm},...gc(t),{text:String(t.members.length)},JP(t.healthCheck)])})},qP=(e)=>{let t=e.flatMap((r)=>r.members.map((n)=>({group:r,member:n})));w(le(t.length,"member")),G({headings:["Member","Address",fc,"Weight","Backup","Status","Health"],rows:t.map(({group:r,member:n})=>[hc(n,n.name),{text:`${n.address}:${n.port}`},{text:r.name??r.id},{text:n.weight===null?"-":String(n.weight)},{text:n.backup?"Yes":"No"},...gc(n)])})},Jg=S(mc,async({args:e,client:t,flags:r})=>{let{active:n,session:o,space:s}=await t.cloud(),{project:i}=o,a=performance.now(),{id:c,name:l}=await ct({kind:yr,projectName:i.name,ref:e.lb,space:s}),u=await j(`Loading ${l}'s listeners and members…`,()=>nh(s,c));if(r.json)return t.stdout.json({loadBalancer:u,profile:n.name,project:i}),0;let p=P(`[${T(performance.now()-a)}]`);if(w(`Load balancer ${x(l)} in ${x(i.name)} ${p}`),yt(VP(u,Date.now())),u.listenerDetails.length>0)WP(u.listenerDetails,u.backendGroups);let d=u.backendGroups;if(d.length>0)HP(d);if(d.some((b)=>b.members.length>0))qP(d);let{details:m,healthy:h,verdict:y}=oh(u);(h?w:J)(`${y}.`);for(let b of m)w(`${b}.`);if(!t.stdout.isTTY)t.stdout.line(c);return 0});var YP=(e,t)=>{G({headings:["Name","Status","Health","Address","Listeners","Age"],rows:e.map((r)=>[{text:r.name},F(r.status),F(r.health),{text:r.address},{text:String(r.listeners)},{paint:W,text:H(t-Date.parse(r.createdAt))}])})},Hg=S(dc,async({client:e,flags:t})=>{let{active:r,session:n,space:o}=await e.cloud(),{project:s}=n,i=performance.now(),a=await j(`Loading the load balancers in ${s.name}…`,()=>Vo(o));if(t.json)return e.stdout.json({loadBalancers:a,profile:r.name,project:s}),0;let c=P(`[${T(performance.now()-i)}]`);if(a.length===0)return w(`No load balancers in ${x(s.name)} ${c}`),0;if(w(`Load balancers in ${x(s.name)} ${c}`),YP(a,Date.now()),!e.stdout.isTTY)e.stdout.line(a.map((l)=>l.id).join(`
333
+ `));return 0});var qg=ne(Wg,{inspect:Jg,ls:Hg});import Xg from"node:path";var Yg=R({args:[{arity:"optional",name:"project",value:{kind:"project"}}],description:"Links this folder to a project, by name or ID, like the Vercel CLI's `vercel link`. nipa saves the profile and the project in .nipa/project.json, and every command in this folder and the folders below it uses them, without changing the project other folders use. Without a project, nipa lists your projects to pick from.",examples:[{command:"nipa -P staging link Prototype",description:"Use staging's Prototype project in this folder"},{command:"nipa tf plan",description:"Run terraform with the linked project"}],flags:[],name:"link",summary:"Use a project in this folder",usesProject:!1});var Qg=S(Yg,async({args:e,client:t})=>{let{project:r}=e,{active:n,session:o}=await t.savedSession(),s=await j("Loading your projects…",()=>Oe({authUrl:n.profile.authUrl,token:o.token}));if(r===void 0&&!t.prompts.interactive)throw new C("tell nipa which project to link",{exitCode:2,hint:`Run \`nipa link <project>\`. Your projects: ${s.map((d)=>d.name).join(", ")}`});let i=process.cwd(),a=n.link?.link.project??o.project,c=await ns({ask:rs({current:a,message:"Link to:",prompts:t.prompts}),projects:s,wanted:r});if(n.link&&Xg.dirname(Xg.dirname(n.link.file))===i&&n.link?.link.project.id===c.id)return J(`This folder is already linked to ${x(c.name)}`),0;let u=await zh({dir:i,link:{profile:n.name,project:c}}),p=P(`(${n.name})`);return te(`Linked ${Se(u)} to ${x(c.name)} ${p}`),w(`Commands in this folder now use ${c.name}. Run \`nipa unlink\` to stop.`),0});var ey=R({args:[],description:"Asks for your email and password, then for an OTP code when your account uses MFA. nipa saves a token for the current profile, scoped to a project, and reuses it until Keystone expires it after 24 hours. `--project` names the project to scope the token to and save, instead of the last one. It is the one command where the option saves the project, not just uses it for this run. With `--remember`, nipa saves your password in the macOS Keychain or Linux's secret service, and later logins ask only for an OTP code. `nipa logout` deletes it.",examples:[{command:"nipa login",description:"Log in to the current profile"},{command:"nipa -P staging login",description:"Log in to the staging profile"},{command:"nipa login --remember",description:"Log in, and ask only for an OTP code next time"}],flags:[{description:"Log in as this user instead of the last one",long:"username",short:"u",value:{kind:"text",name:"email"}},{description:"Save your password in the OS keychain for the next login",long:"remember",value:{kind:"none"}}],name:"login",summary:"Log in with your password and an OTP code",usesProject:"saves"});var ty=S(ey,async({client:e,flags:t})=>(await Ua({active:await e.profile(),prompts:e.prompts,remember:t.remember,username:t.username,wantedProject:e.project}),0));var ry=R({args:[],description:"Revokes the current profile's token and deletes its session. nipa keeps your email and last project for the next login.",flags:[],name:"logout",summary:"Revoke the token and forget the session",usesProject:!1});var ny=S(ry,async({client:e})=>{let t=await e.profile(),r=await ge(t.name),n=await ts(t.profile);if(r){if(ye(r))try{await j("Logging out…",()=>No({authUrl:t.profile.authUrl,token:r.token}))}catch{}if(await Yo(t.name),te(`Logged out of ${x(t.name)}`),n)w("Deleted your saved password.")}else if(n)te(`Deleted your saved password for ${x(t.name)}`);else J(`Not logged in to ${t.name}, so \`nipa logout\` did nothing`);return 0});var yc="List the networks in your project",bc=R({aliases:["list"],args:[],flags:[D],name:"ls",summary:yc}),oy=re({aliases:["networks"],default:"ls",description:"Lists the networks your project can use with their status, type, zone and age. A VPC network is one of your project's private networks, and an external network is a shared pool of external IPs.",examples:[{command:"nipa network ls",description:yc},{command:"nipa network ls --json | jq -r '.networks[] | select(.external | not) | .name'",description:"Print the names of your VPC networks"}],name:"network",subcommands:[bc],summary:yc});var XP=(e,t)=>{G({headings:["Name","Status","Type","Zone","Age"],rows:e.map((r)=>[{text:r.name},F(r.status),{text:r.external?"external":"VPC"},{text:r.zone??"-"},{paint:W,text:H(t-Date.parse(r.createdAt))}])})},sy=S(bc,async({client:e,flags:t})=>{let{active:r,session:n,space:o}=await e.cloud(),{project:s}=n,i=performance.now(),a=await j(`Loading the networks in ${s.name}…`,()=>Wo(o));if(t.json)return e.stdout.json({networks:a,profile:r.name,project:s}),0;let c=P(`[${T(performance.now()-i)}]`);if(a.length===0)return w(`No networks in ${x(s.name)} ${c}`),0;if(w(`Networks in ${x(s.name)} ${c}`),XP(a,Date.now()),!e.stdout.isTTY)e.stdout.line(a.map((l)=>l.id).join(`
334
+ `));return 0});var iy=ne(oy,{ls:sy});import{spawn as QP}from"node:child_process";import{once as eC}from"node:events";var tC=(e,t)=>{switch(e){case"darwin":return{args:[t],command:"open"};case"win32":return{args:["/c","start",'""',t.replaceAll("&","^&")],command:"cmd",verbatim:!0};default:return{args:[t],command:"xdg-open"}}},rC=async({args:e,command:t,verbatim:r})=>{let n=QP(t,e,{detached:!0,stdio:"ignore",windowsVerbatimArguments:r});await eC(n,"spawn"),n.unref()},ay=async(e,t={})=>{let r=tC(t.platform??process.platform,e),n=t.launch??rC;try{await n(r)}catch{throw new C(`couldn't open a browser with ${r.command}`,{hint:"Open the URL above in your browser, or add `--url` to print only the URL."})}};var nC=["server","volume","network","sg","lb","db"],cy=R({args:[{arity:"optional",name:"resource",value:{choices:nC,kind:"choice"}},{arity:"optional",name:"name",value:{kind:"text"}}],description:"Opens the Nipa Cloud Space portal of the profile this run uses, like the Vercel CLI's `vercel open`. Name a kind of resource, `server`, `volume`, `network`, `sg`, `lb` or `db`, to open its list, and a name or ID after it to open that resource's page, which needs a session. The portal keeps its own login and opens the project you last used in it, so a link or `--project` can't pick the project: nipa names the one to switch to there, and `--project` must name a project you can use. When the output goes to a pipe, or with `--url`, nipa prints only the URL and doesn't open a browser.",examples:[{command:"nipa open",description:"Open the Space portal"},{command:"nipa open server web-1",description:"Open web-1's page"},{command:"nipa open lb",description:"Open the list of load balancers"},{command:"nipa open db orders --url",description:"Print the orders database's URL"}],flags:[{description:"Print the URL instead of opening a browser",long:"url",value:{kind:"none"}}],name:"open",summary:"Open the Space portal in your browser"});var _r=(e,t,r)=>({find:async(n)=>{let o=await ct({...n,kind:t});return{name:o.name||o.id,path:r(o)}},list:e}),xc={db:_r("/sql_databases",br,(e)=>`/sql_databases/${e.id}/overview`),lb:_r("/load_balancers",yr,(e)=>`/load_balancers/${e.id}/details`),network:_r("/networks",Ho,(e)=>`/networks/${e.id}`),server:_r("/compute_instances",yn,(e)=>`/compute_instances/${e.id}/overview`),sg:_r("/security_group",gr,(e)=>`/security_group/${e.id}`),volume:_r("/volumes",Jo,(e)=>`/volumes?search=${encodeURIComponent(e.name||e.id)}`)},ly="/project";var oC=async(e,t)=>{if(e.project!==void 0){let{session:r}=await e.session();return r.project.name}return t.link?.link.project.name??t.profile.project?.name},sC=async(e,t,r)=>{if(t!==void 0&&r!==void 0){let{active:s,session:i,space:a}=await e.cloud(),c=i.project.name;return{path:(await xc[t].find({projectName:c,ref:r,space:a})).path,projectName:c,spaceUrl:Jt(s)}}let n=await e.profile(),o=Jt(n);return Wt(n),{path:t===void 0?ly:xc[t].list,projectName:await oC(e,n),spaceUrl:o}},uy=S(cy,async({args:e,client:t,flags:r})=>{let n=await sC(t,e.resource,e.name),o=`${Hf(n.spaceUrl)}${n.path}`;if(r.url||!t.stdout.isTTY)return t.stdout.line(o),0;if(w(`Opening ${Ot(o)}`),await ay(o),n.projectName)w(`The portal opens the project you last used in it. Switch to ${x(n.projectName)} there if it shows another one.`);return 0});var py=or({aliases:["openstack"],description:"Runs `openstack <args...>` with the session. It's the same as `nipa exec openstack <args...>`.",examples:[{command:"nipa os volume list",description:"List the volumes in your project"}],name:"os",summary:"Run openstack with the session",target:{kind:"openstack"}});var dy=sr(py,({args:e,client:t,command:r})=>vr({args:e,command:r,signIn:t.toolSession}));var wc=R({aliases:["list"],args:[],flags:[D],name:"ls",summary:"List your profiles and who is logged in to each"}),vc=R({args:[{arity:"optional",name:"name",value:{kind:"text"}}],flags:[{description:"Keystone URL, ending in /v3",long:"auth-url",value:{kind:"text",name:"url"}},{description:"User domain (default: nipacloud)",long:"user-domain",value:{kind:"text",name:"domain"}},{description:"Region (default: NCP-TH)",long:"region",value:{kind:"text",name:"region"}},{description:"Space portal URL, such as https://space.nipa.cloud (default: production's for production's Keystone)",long:"space-url",value:{kind:"text",name:"url"}},{description:"Make it the current profile",long:"use",value:{kind:"none"}}],name:"add",summary:"Add a profile, asking for missing values"}),_c=R({args:[{arity:"optional",name:"name",value:{kind:"profile"}}],flags:[],name:"use",summary:"Make a profile the current one"}),Sc=R({args:[{arity:"one",name:"name",value:{kind:"profile"}}],flags:[{...Cr,description:"Remove it without asking"}],name:"rm",summary:"Remove a profile and log out of it"}),my=re({default:"ls",description:"A profile is a Keystone URL, user domain, region and Space API URL with its own session. nipa starts with prod, which is Nipa Cloud production. Add a profile for staging or any other Keystone, then use it with `nipa profile use <name>` or `-P <name>`.",examples:[{command:"nipa profile add staging --auth-url https://keystone.example.com/v3",description:"Add a staging profile"},{command:"nipa profile use staging",description:"Make staging the current profile"}],name:"profile",subcommands:[wc,vc,_c,Sc],summary:"Manage Keystone profiles, such as staging",usesProfile:!1,usesProject:!1});var iC=(e)=>(t)=>{if(!Ca.test(t))return"Use lowercase letters, digits and hyphens, starting with a letter";return e.profiles[t]?`A profile named ${t} already exists`:!0},fy=(e)=>lt.shape.authUrl.safeParse(e).success||"Enter an http or https URL, such as https://keystone.example.com/v3",gy="Enter the http or https URL of the Space portal, such as https://space.nipa.cloud",aC=async(e)=>{if(e.flag!==void 0)return e.flag;if(Ea(e.authUrl))return _e.spaceUrl;if(!e.prompts.interactive)return;let t=await e.prompts.text({message:"Space portal URL (Enter to skip)",required:!1,validate:(r)=>r===""||lt.shape.authUrl.safeParse(r).success||gy});return t===""?void 0:t},hy=(e)=>{if(e.value!==void 0)return Promise.resolve(e.value);if(!e.prompts.interactive)throw Z(`missing ${e.flag}`,"Pass every value as a flag when nipa can't prompt.");return e.ask()},yy=S(vc,async({args:e,client:t,flags:r})=>{let{prompts:n}=t,o=await je(),s=iC(o),i=await hy({ask:()=>n.text({message:"Profile name",validate:s}),flag:"<name>",prompts:n,value:e.name}),a=s(i);if(a!==!0)throw Z(`can't add profile "${i}"`,a);let c=await hy({ask:()=>n.text({message:"Keystone URL",validate:fy}),flag:"--auth-url",prompts:n,value:r["auth-url"]}),l=fy(c);if(l!==!0)throw Z(`invalid --auth-url "${c}"`,l);let u=r["user-domain"]??(n.interactive?await n.text({default:_e.userDomain,message:"User domain"}):_e.userDomain),p=r.region??(n.interactive?await n.text({default:_e.region,message:"Region"}):_e.region),d=await aC({authUrl:c,flag:r["space-url"],prompts:n});if(d!==void 0&&!lt.shape.authUrl.safeParse(d).success)throw Z(`invalid --space-url "${d}"`,gy);let m=d===void 0?void 0:mn(d),h=performance.now(),y=await j(`Checking ${c}…`,()=>Zo(c));if(m!==void 0)await j(`Checking ${m}…`,()=>Uo(m));let b={authUrl:c,region:p,spaceUrl:m,userDomain:u},v=r.use??(n.interactive&&await n.confirm({default:!0,message:`Use ${i} now?`}));await Ct({currentProfile:v?i:o.currentProfile,profiles:{...o.profiles,[i]:b}});let E=m===void 0?"":`, Space API ${new URL(m).host}`;if(te(`Added profile ${x(i)} (Keystone ${y}${E})`,performance.now()-h),m===void 0)J(`${i} has no Space API URL, so \`nipa server ls\` and the other resource commands don't work with it. Pass \`--space-url\` with its Space portal URL when you add it.`);return w(v?`Now using ${x(i)}. Run \`nipa login\` to log in to it.`:`Run \`nipa login -P ${i}\` to log in to it.`),0});var by=S(wc,async({client:e,flags:t})=>{let r=await je(),n=Object.keys(r.profiles).toSorted(),o=await Promise.all(n.map((i)=>ge(i)));if(t.json)return e.stdout.json(n.map((i,a)=>{let c=o[a];return{current:i===r.currentProfile,loggedIn:ye(c),name:i,...r.profiles[i],user:ye(c)?c.user.name:void 0}})),0;let s=n.map((i,a)=>{let c=r.profiles[i]??_e,l=o[a],u=ye(l)?`${l.user.name} (${l.project.name})`:"-";return[i,new URL(c.authUrl).host,c.region,u].map((p)=>({text:p}))});return w(`${n.length} ${n.length===1?"profile":"profiles"}`),G({headings:["Name","Keystone","Region","Logged in as"],marks:n.map((i)=>i===r.currentProfile?Lt("✔"):" "),rows:s}),0});var xy=S(Sc,async({args:e,client:t,flags:r})=>{let{name:n}=e,o=await je(),s=o.profiles[n];if(!s)throw new C(`no profile named "${n}"`);if(n===be)throw new C(`can't remove ${be}`,{hint:"nipa always has the Nipa Cloud production profile."});if(!r.yes){if(!t.prompts.interactive)throw Z(`removing ${n} needs confirmation`,"Add --yes to remove it without asking.");if(!await t.prompts.confirm({default:!1,message:`Remove profile ${n} and log out of it?`}))throw new C("Canceled",{exitCode:130})}let i=await ge(n);if(ye(i))try{await No({authUrl:s.authUrl,token:i.token})}catch{}await Yo(n),await ts(s);let a=Object.fromEntries(Object.entries(o.profiles).filter(([l])=>l!==n)),c=o.currentProfile===n;if(await Ct({currentProfile:c?be:o.currentProfile,profiles:a}),te(`Removed profile ${x(n)}`),c)w(`Now using ${x(be)}`);return 0});var wy=S(_c,async({args:e,client:t})=>{let r=await je(),n=Object.keys(r.profiles).toSorted(),{name:o}=e;if(o===void 0){if(!t.prompts.interactive)throw Z("missing <name>",`Your profiles: ${n.join(", ")}`);o=await t.prompts.choice({choices:n.map((s)=>({name:s===r.currentProfile?`${s} ${x("(current)")}`:s,value:s})),default:r.currentProfile,message:"Use profile:"})}if(!r.profiles[o])throw new C(`no profile named "${o}"`,{hint:`Your profiles: ${n.join(", ")}`});if(o===r.currentProfile)return J(`You're already using ${x(o)}`),0;return await Ct({...r,currentProfile:o}),te(`Now using profile ${x(o)}`),0});var vy=ne(my,{add:yy,ls:by,rm:xy,use:wy});var $c="Show how much of each quota your project uses",kc=R({aliases:["list"],args:[],flags:[D],name:"ls",summary:$c}),_y=re({aliases:["quotas","limits"],default:"ls",description:"Shows each quota of your project, such as servers, vCPUs and RAM, with how much it uses, its limit, and the percent used. A quota at 80% or more is near its limit. One at 100% is at its limit, so creating one more of that resource fails. The command exits 0 either way. When the output goes to a pipe, nipa prints one tab-separated line per quota: its group and name, such as `compute/ram`, the amount used, the limit or `unlimited`, and the unit, such as `MB`, or `-` for a count.",examples:[{command:"nipa quota",description:$c},{command:"nipa quota --json | jq '.quotas[] | select(.limit != null and .used >= .limit)'",description:"Print the quotas at their limit"}],name:"quota",subcommands:[kc],summary:$c});var cC=_({group:f(),limit:ee(),name:f(),unit:f().nullish(),unlimited:pr(),usage:ee()}),lC=(e)=>({group:e.group,limit:e.unlimited?null:e.limit,name:e.name,unit:e.unit??null,used:e.usage}),Sy=async(e)=>(await e.getLines("/v4/limits",cC)).map(lC);var fs=new Map([["compute",{label:"Compute",names:[["instances","Servers"],["cores","vCPUs"],["ram","RAM"],["key_pairs","Key pairs"]]}],["storage",{label:"Block storage",names:[["volumes","Volumes"],["volume_size","Volume size"],["snapshots","Snapshots"],["backups","Backups"]]}],["network",{label:"Network",names:[["network","Networks"],["router","Routers"],["port","Ports"],["floatingip","External IPs"],["security_group","Security groups"],["security_group_rule","Security group rules"]]}],["loadBalancer",{label:"Load balancers",names:[["load_balancer","Load balancers"],["listener","Listeners"],["pool","Pools"]]}],["sqlDatabase",{label:"Databases",names:[["database_instances","Databases"],["ram","RAM"],["volume_size","Storage"],["backups","Backups"]]}],["container",{label:"Kubernetes",names:[["kubernetes_cluster","Clusters"]]}],["objectStorage",{label:"Object storage",names:[["storage_size","Storage"],["objects","Objects"]]}],["internetNatGateway",{label:"NAT gateways",names:[["ing_instance","Gateways"],["ing_reserved_ip","Reserved IPs"]]}]]),uC=[...fs.keys()],pC=/[_\s]+|(?<=[a-z\d])(?=[A-Z])/u,Py=(e)=>{let t=e.split(pC).join(" ").toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)},Cy=(e)=>fs.get(e)?.label??Py(e),$y=(e)=>fs.get(e)?.names.map(([t])=>t)??[],Ey=(e)=>fs.get(e.group)?.names.find(([t])=>t===e.name)?.[1]??Py(e.name),ps=(e,t)=>{let r=e.indexOf(t);return r===-1?e.length:r},dC=(e)=>{let t=[...uC];for(let{group:r}of e)if(!t.includes(r))t.push(r);return t},jy=(e)=>{let t=dC(e);return e.toSorted((r,n)=>ps(t,r.group)-ps(t,n.group)||ps($y(r.group),r.name)-ps($y(n.group),n.name))},ky=["B","KB","MB","GB","TB"],mC=(e)=>{let t=Math.min(ky.length-1,Math.floor(Math.log(Math.max(e,1))/Math.log(1024)));return`${Number((e/1024**t).toFixed(1))} ${ky[t]}`},fC=new Map([["Bytes",mC],["GB",(e)=>`${e} GB`],["MB",Br]]),Pc=(e,t)=>{if(t===null)return String(e);return fC.get(t)?.(e)??`${e} ${t}`},hC=0.8,ms=(e)=>{if(e.limit===null)return"ok";if(e.used>=e.limit)return"full";return e.used>=e.limit*hC?"near":"ok"},Ay={full:xe,near:Ve},Ry=(e)=>{if(e.limit===null)return"-";if(e.limit===0)return"100%";return`${Math.floor(e.used*100/e.limit)}%`},ds=(e)=>e===1?"is":"are",Iy=(e)=>{let t=e.filter((n)=>ms(n)==="full").length,r=e.filter((n)=>ms(n)==="near").length;if(t>0&&r>0)return`${le(t,"quota")} ${ds(t)} at the limit, and ${r} ${ds(r)} near it.`;if(t>0)return`${le(t,"quota")} ${ds(t)} at the limit.`;if(r>0)return`${le(r,"quota")} ${ds(r)} near the limit.`;return null},Ty=(e)=>[`${e.group}/${e.name}`,e.used,e.limit??"unlimited",e.unit??"-"].join("\t");var gC=(e)=>{G({headings:["Group","Quota","Used","Limit","%"],rows:e.map((t,r)=>{let n=Ay[ms(t)];return[{text:e[r-1]?.group!==t.group?Cy(t.group):""},{text:Ey(t)},{paint:n,text:Pc(t.used,t.unit)},{text:t.limit===null?"unlimited":Pc(t.limit,t.unit)},{paint:n,text:Ry(t)}]})})},zy=S(kc,async({client:e,flags:t})=>{let{active:r,session:n,space:o}=await e.cloud(),{project:s}=n,i=performance.now(),a=jy(await j(`Loading the quotas of ${s.name}…`,()=>Sy(o)));if(t.json)return e.stdout.json({profile:r.name,project:s,quotas:a}),0;let c=P(`[${T(performance.now()-i)}]`);if(a.length===0)return w(`No quotas for ${x(s.name)} ${c}`),0;w(`Quotas of ${x(s.name)} ${c}`),gC(a);let l=Iy(a);if(l)J(l);if(!e.stdout.isTTY)e.stdout.line(a.map(Ty).join(`
335
+ `));return 0});var Oy=ne(_y,{ls:zy});var Ly="List the servers in your project",Sr={arity:"one",name:"server",value:{kind:"resource",resource:"servers"}},Cc=[{description:"Return once the Space API takes the action, without waiting",long:"no-wait",value:{kind:"none"}},{description:"How long to wait, such as 90s or 10m (default: 5m)",long:"timeout",value:{kind:"text",name:"duration"}}],Ec=R({aliases:["list"],args:[],flags:[D],name:"ls",summary:Ly}),jc=R({args:[{arity:"optional",name:"query",value:{kind:"text"}}],description:"Looks in every project you can use for servers whose name, ID or address contains the query, ignoring case. The query is plain text, not a pattern, and without one nipa lists every server. nipa asks each project live and saves nothing, so a server that the portal, Terraform or Kubernetes just made shows up. It reads four projects at a time and gives up on one that takes more than 15 seconds. A folder's link doesn't narrow it. With `-p`, nipa searches only that project. When a project fails, nipa still prints the servers it found, then lists the projects it couldn't read and exits with code 1.",examples:[{command:"nipa server search web",description:"Find the servers named like web in every project"},{command:"nipa server search 203.0.113.10",description:"Find the server that has an address, in any project"},{command:"nipa -p Beta server search web",description:"Search only the Beta project"},{command:"nipa server search web --json | jq -r '.servers[].id'",description:"Print the ID of each match"}],flags:[D],name:"search",summary:"Find servers by name, ID or address in every project"}),Ac=R({args:[Sr],flags:[D],name:"inspect",summary:"Show a server's flavor, addresses, volumes and security groups"}),Rc=R({args:[Sr],flags:[{description:"Print only the last n lines",long:"tail",short:"n",value:{kind:"text",name:"n"}},D],name:"logs",summary:"Print a server's console log"}),Ic=R({aliases:["events"],args:[Sr],flags:[D],name:"history",summary:"List what was done to a server, newest first"}),Tc=R({args:[Sr],flags:[...Cc],name:"start",summary:"Start a stopped server"}),zc=R({args:[Sr],flags:[Cr,...Cc],name:"stop",summary:"Stop a server"}),Oc=R({aliases:["reboot"],args:[Sr],flags:[Cr,...Cc],name:"restart",summary:"Restart a server"}),Dy=re({aliases:["servers"],default:"ls",description:"Lists, searches, inspects, starts, stops and restarts the servers in your project, and shows what was done to a server and its console log. Name a server by its name or ID. `logs` prints the last 100 lines of the console log, which is what the Space API sends. nipa calls the Space API, the one the Nipa Cloud Space portal uses, so you don't need the OpenStack client. start, stop and restart wait until the server finishes, for 5 minutes or `--timeout`. `--no-wait` returns once the Space API takes the action.",examples:[{command:"nipa server ls",description:Ly},{command:"nipa server search web",description:"Find the servers named like web in every project"},{command:"nipa server inspect web-1",description:"Show web-1's addresses, volumes and security groups"},{command:"nipa server history web-1",description:"List web-1's actions, such as a create that failed"},{command:"nipa server logs web-1 --tail 20",description:"Print the last 20 lines of web-1's console log"},{command:"nipa server stop web-1 --yes",description:"Stop web-1 without asking"},{command:"nipa server start web-1 --no-wait",description:"Start web-1 without waiting for it"},{command:"nipa server ls | grep web",description:"Find the lines with web in any field"},{command:"nipa server ls | tail -n +2 | cut -f1",description:"Print each server's ID"},{command:"nipa server ls | awk -F'\\t' '$2 ~ /^web/ {print $1}' | xargs -n1 nipa server stop --yes",description:"Stop the servers whose name starts with web, by ID"},{command:"nipa server ls --json | jq -r '.servers[].name'",description:"Print each server's name"}],name:"server",subcommands:[Ec,jc,Ac,Ic,Rc,Tc,zc,Oc],summary:"List, search, inspect, start, stop and restart your servers, and read their history and logs"});var yC=(e,t)=>{G({headings:["Age","Action","User","Result","Request ID"],rows:e.map((r)=>[{paint:W,text:H(t-Date.parse(r.startedAt))},{text:r.action},{text:r.user??"-"},Mo(r)?{paint:xe,text:r.remark??""}:{text:r.remark??"-"},{paint:P,text:r.requestId}])})},Ny=S(Ic,async({args:e,client:t,flags:r})=>{let{active:n,session:o,space:s}=await t.cloud(),{project:i}=o,a=performance.now(),c=await kt({projectName:i.name,ref:e.server,space:s}),l=await j(`Loading ${c.name}'s history…`,()=>Bo(s,c.id));if(r.json)return t.stdout.json({actions:l,profile:n.name,project:i,server:{id:c.id,name:c.name}}),0;let u=P(`[${T(performance.now()-a)}]`),p=`${x(c.name)} in ${x(i.name)}`;if(l.length===0)return w(`No actions on ${p} ${u}`),0;if(w(`Actions on ${p} ${u}`),yC(l,Date.now()),!t.stdout.isTTY)t.stdout.line(l.map((d)=>d.requestId).join(`
336
+ `));return 0});var $r=(e)=>{if(!e.kubernetes)return{text:e.name};let t=e.kubernetes.role??"node";return{...Ae(e.name,` (Kubernetes ${t})`),short:Ae(e.name,` (${t})`)}},Zy=(e)=>{let t=e.addresses.filter((n)=>n.type==="floating"),r=e.addresses.filter((n)=>n.type==="fixed");return[...t.map((n)=>Ae(n.address," (external)")),...r.map((n)=>({text:n.address}))]},bC=(e)=>{let r=[[`${e.sizeGb} GB`,e.type].filter(Boolean).join(" "),e.attachedAs].filter(Boolean).join(", ");return Ae(e.name??e.id,` (${r})`)},Uy=(e)=>e.volumes.map(bC);var xC=(e,t)=>{let r=Mo(e),n=z(e.action),o=r?`${n} failed`:n,s=r||e.remark===null?"":` (${e.remark})`,i=e.user===null?"":` by ${e.user}`,a=H(t-Date.parse(e.startedAt));return{paint:r?(c)=>`${xe(o)}${c.slice(o.length)}`:void 0,text:`${o}${s} ${a} ago${i}`}},Fy=(e)=>{if(e.status==="fulfilled")return{ok:!0,value:e.value};let{reason:t}=e;return{ok:!1,reason:t instanceof Error?t.message:String(t)}},Lc={paint:P,text:"unavailable"},wC=(e)=>{let{actions:t,now:r,server:n,state:o}=e,s=[{label:"ID",lines:[{text:n.id}]},{label:"Status",lines:[F(n.status)]}];if(!o.ok)s.push({label:"Task",lines:[Lc]},{label:"Locked",lines:[Lc]});else if(o.value.taskState!==null)s.push({label:"Task",lines:[{text:o.value.taskState}]});if(o.ok&&o.value.locked===!0)s.push({label:"Locked",lines:[{text:"yes"}]});let i=t.ok?t.value[0]:void 0;if(!t.ok)s.push({label:"Last action",lines:[Lc]});else if(i)s.push({label:"Last action",lines:[xC(i,r)]});if(s.push({label:"Flavor",lines:[qn(n)]},{label:"Zone",lines:n.zone?[{text:n.zone}]:[]},{label:"Addresses",lines:Zy(n)},{label:"Volumes",lines:Uy(n)},{label:"Security groups",lines:n.securityGroups.map((c)=>({text:c}))}),n.kubernetes){let{clusterId:c,role:l}=n.kubernetes;s.push({label:"Kubernetes",lines:[Ae(l??"node",` (cluster ${c})`)]})}let a=`${H(r-Date.parse(n.createdAt))} ago`;return s.push({label:"Created",lines:[{paint:W,text:a}]}),s},My=S(Ac,async({args:e,client:t,flags:r})=>{let{active:n,session:o,space:s}=await t.cloud(),{project:i}=o,a=performance.now(),c=await kt({projectName:i.name,ref:e.server,space:s}),[l,u]=await j(`Loading ${c.name}'s state…`,()=>Promise.allSettled([xa(s,c.id),Bo(s,c.id)])),p=Fy(l),d=Fy(u),m=()=>{let y=[["state",p],["actions",d]];for(let[b,v]of y)if(!v.ok)w(`Couldn't load ${c.name}'s ${b}: ${v.reason}. Run the command again, or add \`--debug\` to see the request.`)};if(r.json)return t.stdout.json({profile:n.name,project:i,server:{...c,lastAction:d.ok?d.value[0]??null:null,locked:p.ok?p.value.locked:null,taskState:p.ok?p.value.taskState:null}}),0;let h=P(`[${T(performance.now()-a)}]`);if(w(`Server ${x(c.name)} in ${x(i.name)} ${h}`),yt(wC({actions:d,now:Date.now(),server:c,state:p})),m(),c.status==="ERROR")w(`Run \`nipa server history ${e.server}\` to see what failed, and \`nipa server logs ${e.server}\` for its console log.`);if(!t.stdout.isTTY)t.stdout.line(c.id);return 0});var vC=(e)=>{let t=Number(e);if(!/^\d+$/u.test(e)||t===0)throw Z(`"${e}" isn't a number of lines`,"Write it as a whole number above 0, such as `--tail 50`.");return t},_C=(e,t)=>{if(t===void 0)return e;let r=e.split(`
329
337
  `);if(r.at(-1)==="")r.pop();return r.slice(-t).map((n)=>`${n}
330
- `).join("")},Ng=k(Va,async({args:e,client:t,flags:r})=>{let n=r.tail===void 0?void 0:_k(r.tail),{active:o,session:s,space:i}=await t.cloud(),{project:a}=s,c=performance.now(),l=await vt({projectName:a.name,ref:e.server,space:i}),u=await I(`Loading ${l.name}'s console log…`,()=>Hm(i,l.id));if(u.kind==="none")throw new E(`${l.name} has no console log yet`,{hint:`A server has one once it boots, so this one most likely never booted. Run \`nipa server history ${e.server}\` to see what failed.`});let p=vk(u.text,n);if(r.json)return t.stdout.json({logs:p,profile:o.name,project:a,server:{id:l.id,name:l.name}}),0;let d=T(`[${R(performance.now()-c)}]`);if(p==="")return w(`${x(l.name)}'s console log is empty ${d}`),0;return w(`Console log of ${x(l.name)} in ${x(a.name)} ${d}`),t.stdout.write(p),0});var $k=(e,t)=>{M({headings:["Name","Status","Address","Flavor","Age"],rows:e.map((r)=>[Jo(r),J(r.status),{text:Rg(r)??"-"},{text:r.flavor},{paint:K,text:V(t-Date.parse(r.createdAt))}])})},Zg=k(Ga,async({client:e,flags:t})=>{let{active:r,session:n,space:o}=await e.cloud(),{project:s}=n,i=performance.now(),a=await I(`Loading the servers in ${s.name}…`,()=>We(o));if(t.json)return e.stdout.json({profile:r.name,project:s,servers:a}),0;let c=T(`[${R(performance.now()-i)}]`);if(a.length===0)return w(`No servers in ${x(s.name)} ${c}`),0;if(w(`Servers in ${x(s.name)} ${c}`),$k(a,Date.now()),!e.stdout.isTTY)e.stdout.line(a.map((l)=>l.id).join(`
331
- `));return 0});var Sk="5m",kk=2000,Pk=(e)=>{let t=/^(?<count>\d+)(?<unit>[hms])$/u.exec(e)?.groups,r=Number(t?.count);switch(t?.unit){case"h":return r*3600000;case"m":return r*60000;case"s":return r*1000;default:throw Z(`"${e}" isn't a duration`,"Write it as a number and a unit, such as `--timeout 90s` or `--timeout 10m`.")}},Ug={restart:{confirm:!0,doing:"Restarting",done:"Restarted",status:"ACTIVE"},start:{confirm:!1,doing:"Starting",done:"Started",status:"ACTIVE"},stop:{confirm:!0,doing:"Stopping",done:"Stopped",status:"SHUTOFF"}},Ck=async(e)=>{let{action:t,client:r,server:n}=e;if(!r.prompts.interactive)throw Z(`${Ug[t].doing.toLowerCase()} ${n.name} needs confirmation`,`Add \`--yes\` to ${t} it without asking.`);let o=`${t.charAt(0).toUpperCase()}${t.slice(1)}`;if(!await r.prompts.confirm({default:!1,message:`${o} server ${Jo(n).text} in ${e.projectName}?`}))throw new E("Canceled",{exitCode:130})},Xa=async(e)=>{let{action:t,client:r,flags:n}=e,o=Ug[t];if(n["no-wait"]&&n.timeout!==void 0)throw Z("--no-wait and --timeout don't go together","Drop `--timeout`, or drop `--no-wait` to wait for the server.");let s=n.timeout??Sk,i=Pk(s),{session:a,space:c}=await r.cloud(),l=a.project.name,u=await vt({projectName:l,ref:e.ref,space:c}),p=x(u.name);if(t==="restart"&&u.status==="SHUTOFF")throw new E(`${u.name} is stopped`,{hint:`Run \`nipa server start ${u.name}\` to start it.`});if(t!=="restart"&&u.status===o.status)return G(`${p} is already ${t==="stop"?"stopped":"running"}`),0;if(o.confirm&&!n.yes)await Ck({action:t,client:r,projectName:l,server:u});let d=performance.now(),m=`\`nipa server inspect ${u.name}\``;if(n["no-wait"])return await I(`Asking to ${t} ${u.name}…`,()=>Ui(c,u.id,t)),Q(`Asked to ${t} ${p} in ${x(l)}`,performance.now()-d),w(`Run ${m} to check on it.`),0;let h=await I(`${o.doing} ${u.name}…`,async()=>{await Ui(c,u.id,t);try{return await Jm({id:u.id,intervalMs:kk,space:c,status:o.status,timeoutMs:i})}catch(y){if(y instanceof E||y instanceof he)throw new E(y.message,{hint:`nipa asked to ${t} ${u.name} before this failed. Run ${m} to check it.`});throw y}});if(h.kind==="error")throw new E(`${u.name} went into an error state`,{hint:`Run ${m}, or check the server in the Space portal.`});if(h.kind==="timeout"){let y=Fe(h.state.status);throw new E(`${u.name} is still ${y} after ${s}`,{hint:`Run ${m} to check it again, or wait longer with \`--timeout\`.`})}return Q(`${o.done} ${p} in ${x(l)}`,performance.now()-d),0},Fg=k(Ja,({args:e,client:t,flags:r})=>Xa({action:"start",client:t,flags:r,ref:e.server})),Mg=k(Ha,({args:e,client:t,flags:r})=>Xa({action:"stop",client:t,flags:r,ref:e.server})),Bg=k(qa,({args:e,client:t,flags:r})=>Xa({action:"restart",client:t,flags:r,ref:e.server}));var Gg=te(Tg,{history:Ag,inspect:Dg,logs:Ng,ls:Zg,restart:Bg,start:Fg,stop:Mg});var Kg="List the security groups in your project",Qa=z({aliases:["list"],args:[],flags:[N],name:"ls",summary:Kg}),ec=z({args:[{arity:"one",name:"group",value:{kind:"resource",resource:"security-groups"}}],flags:[N],name:"inspect",summary:"Show a security group's rules and the servers that use it"}),Vg=ee({aliases:["security-group","security-groups"],default:"ls",description:"Lists and inspects the security groups in your project. Name a group by its name or ID. `nipa sg inspect` shows a group's inbound and outbound rules and the servers that use it, found through the network ports in your project, so a server in another project doesn't show. It notes when a rule opens SSH, RDP or a database port to the internet. `--json` prints each rule's direction, protocol, ports and remote, and `exposed`, true for such a rule.",examples:[{command:"nipa sg ls",description:Kg},{command:"nipa sg inspect web",description:"Show the rules of the web security group and its servers"},{command:"nipa sg inspect web --json | jq -r '.securityGroup.servers[].name'",description:"Print the name of each server that uses web"}],name:"sg",subcommands:[Qa,ec],summary:"List and inspect your security groups"});var Ek=new Set(["icmp","icmpv6","ipv6-icmp"]),zk=new Map([["1","icmp"],["6","tcp"],["17","udp"],["58","ipv6-icmp"]]),Ik=(e)=>e===null||e==="any"?null:zk.get(e)??e,Tk=new Set(["0.0.0.0/0","::/0"]),Ak=65535,Rk=(e,t)=>{let{portMax:r,portMin:n}=t;if(e===null||n===null)return{kind:"any"};if(Ek.has(e))return{code:r,kind:"icmp",type:n};let o=r??n;return n<=1&&o>=Ak?{kind:"any"}:{from:n,kind:"range",to:o}},jk=(e,t)=>{if(e.remoteGroupId){let r=e.remoteGroupId;return{id:r,kind:"group",name:t.get(r)??null}}return e.remoteIpPrefix?{cidr:e.remoteIpPrefix,kind:"cidr"}:{kind:"any"}},rc=(e,t)=>{let r=Ik(e.protocol);return{direction:e.direction,ethertype:e.ethertype,ports:Rk(r,e),protocol:r,remote:jk(e,t)}},Ok=(e)=>{switch(e.kind){case"any":return"any";case"range":return e.from===e.to?String(e.from):`${e.from}-${e.to}`;case"icmp":{let t=e.code===null?"":` code ${e.code}`;return`type ${e.type}${t}`}default:return e}},tc=(e)=>{switch(e.kind){case"any":return"any";case"cidr":return e.cidr;case"group":return`group ${e.name??e.id}`;default:return e}},Jg=(e)=>[{text:e.protocol??"any"},{text:Ok(e.ports)},{text:tc(e.remote)},{text:e.ethertype}],Wg=(e)=>{switch(e.kind){case"range":return e.from;case"icmp":return e.type;default:return-1}},Hg=(e,t)=>Wg(e.ports)-Wg(t.ports)||(e.protocol??"").localeCompare(t.protocol??"")||e.ethertype.localeCompare(t.ethertype)||tc(e.remote).localeCompare(tc(t.remote)),qg=[{name:"SSH",port:22},{name:"MySQL",port:3306},{name:"RDP",port:3389},{name:"PostgreSQL",port:5432},{name:"Redis",port:6379},{name:"MongoDB",port:27017}],Lk=(e)=>e.kind==="any"||e.kind==="cidr"&&Tk.has(e.cidr),Dk=(e)=>e.direction==="ingress"&&Lk(e.remote)&&(e.protocol===null||e.protocol==="tcp"),Yg=(e,t)=>e.kind==="any"||e.kind==="range"&&e.from<=t&&t<=e.to,Ho=(e)=>Dk(e)&&qg.some(({port:t})=>Yg(e.ports,t)),Xg=(e)=>{let t=e.filter(Ho);if(t.some((o)=>o.ports.kind==="any"))return"Every port is open to the internet.";let r=qg.filter(({port:o})=>t.some((s)=>Yg(s.ports,o))).map(({name:o,port:s})=>`${o} (${s})`);if(r.length===0)return;let n=r.length===1?"is":"are";return`${Tt(r)} ${n} open to the internet.`};var Nk=(e,t,r)=>r.flatMap((n)=>{let o=t.filter((s)=>s.deviceId===n.id&&s.securityGroupIds.includes(e));return o.length>0?[{addresses:o.flatMap((s)=>s.addresses),id:n.id,name:n.name}]:[]}),Zk=(e)=>De(e.name,` (${e.addresses.length>0?e.addresses.join(", "):"-"})`),Uk=[{direction:"ingress",empty:"No inbound rules, so this group lets no traffic in.",remote:"Source",title:"Inbound rules"},{direction:"egress",empty:"No outbound rules, so this group lets no traffic out.",remote:"Destination",title:"Outbound rules"}],Fk=(e,t)=>{let r=e.rules.map((n)=>rc(n,t)).toSorted(Hg);for(let{direction:n,empty:o,remote:s,title:i}of Uk){let a=r.filter((l)=>l.direction===n);if(a.length===0){w(o);continue}w(i),M({headings:["Protocol","Ports",s,"Ethertype"],marks:a.map((l)=>Ho(l)?ft("!"):" "),rows:a.map(Jg)});let c=Xg(a);if(c)G(c)}},Qg=k(ec,async({args:e,client:t,flags:r})=>{let{active:n,session:o,space:s}=await t.cloud(),{project:i}=o,a=performance.now(),c=ir(s),l=await at({kind:{...ar,list:()=>c},projectName:i.name,ref:e.group,space:s}),[u,p]=await I(`Loading the servers in ${i.name}…`,()=>Promise.all([tf(s),We(s)])),d=await c,m=new Map(d.map((_)=>[_.id,_.name])),h=Nk(l.id,u,p);if(r.json){let _=l.rules.map((P)=>({...P,exposed:Ho(rc(P,m)),remoteGroupName:P.remoteGroupId?m.get(P.remoteGroupId)??null:null}));return t.stdout.json({profile:n.name,project:i,securityGroup:{...l,rules:_,servers:h}}),0}let y=T(`[${R(performance.now()-a)}]`);w(`Security group ${x(l.name)} in ${x(i.name)} ${y}`);let b=`${V(Date.now()-Date.parse(l.createdAt))} ago`;if(ht([{label:"ID",lines:[{text:l.id}]},{label:"Description",lines:l.description?[{text:l.description}]:[]},{label:"Servers",lines:h.map(Zk)},{label:"Created",lines:[{paint:K,text:b}]}]),Fk(l,m),!t.stdout.isTTY)t.stdout.line(l.id);return 0});var ey=(e,t)=>e.rules.filter((r)=>r.direction===t).length,Mk=(e,t)=>{M({headings:["Name","Inbound","Outbound","Age","Description"],rows:e.map((r)=>[{text:r.name},{text:String(ey(r,"ingress"))},{text:String(ey(r,"egress"))},{paint:K,text:V(t-Date.parse(r.createdAt))},{text:r.description??"-"}])})},ty=k(Qa,async({client:e,flags:t})=>{let{active:r,session:n,space:o}=await e.cloud(),{project:s}=n,i=performance.now(),a=await I(`Loading the security groups in ${s.name}…`,()=>ir(o));if(t.json)return e.stdout.json({profile:r.name,project:s,securityGroups:a}),0;let c=T(`[${R(performance.now()-i)}]`);if(a.length===0)return w(`No security groups in ${x(s.name)} ${c}`),0;if(w(`Security groups in ${x(s.name)} ${c}`),Mk(a,Date.now()),!e.stdout.isTTY)e.stdout.line(a.map((l)=>l.id).join(`
332
- `));return 0});var ry=te(Vg,{inspect:Qg,ls:ty});var ny=z({args:[{arity:"optional",name:"project",value:{kind:"project"}}],description:"Scopes the session to another project, by name or ID, without a password or OTP code. Without a project, nipa lists your projects to pick from.",flags:[],name:"switch",summary:"Use another project"});var oy=k(ny,async({args:e,client:t})=>{let{project:r}=e,{active:n,session:o}=await t.savedSession(),{authUrl:s}=n.profile,i=await I("Loading your projects…",()=>Ue({authUrl:s,token:o.token}));if(r===void 0&&!t.prompts.interactive)throw new E("tell nipa which project to use",{exitCode:2,hint:`Run \`nipa switch <project>\`. Your projects: ${i.map((p)=>p.name).join(", ")}`});let a=await Oo({ask:jo({current:o.project,message:"Switch to:",prompts:t.prompts}),projects:i,wanted:r});if(a.id===o.project.id)return G(`You're already using ${x(a.name)}`),0;let c=performance.now(),l=await I(`Switching to ${a.name}…`,()=>Hr({authUrl:s,projectId:a.id,token:o.token}));await ra({active:n,session:sn(l,a)}),Q(`Switched to ${x(a.name)}`,performance.now()-c);let u=n.link;if(u&&u.link.project.id!==a.id)G(`Commands in this folder still use ${x(u.link.project.name)}, from ${ye(u.file)}. Run \`nipa unlink\` to use ${a.name} here too.`);return 0});var sy=Ht({aliases:["terraform"],description:"Runs `terraform <args...>` with the session. It's the same as `nipa exec terraform <args...>`.",examples:[{command:"nipa -P staging tf plan",description:"Plan against the staging profile"}],name:"tf",summary:"Run terraform with the session",target:{kind:"program",program:"terraform"}});var iy=qt(sy,({args:e,client:t,command:r})=>ur({args:e,command:r,signIn:t.toolSession}));var ay=z({args:[],description:"Deletes the .nipa/project.json that links this folder, or the closest folder above it, so commands here use the current profile and project again.",flags:[],name:"unlink",summary:"Stop using a linked project in this folder"});var cy=k(ay,async()=>{let e=await Zt();if(!e)return G("This folder isn't linked to a project"),0;return await Tf(e.file),Q(`Unlinked ${ye(e.file)} from ${x(e.link.project.name)}`),0});var nc="List the volumes in your project",oc=z({aliases:["list"],args:[],flags:[N],name:"ls",summary:nc}),ly=ee({aliases:["volumes"],default:"ls",description:"Lists the block storage volumes in your project with their status, size, type, the server each one is attached to, and age.",examples:[{command:"nipa volume ls",description:nc},{command:`nipa volume ls --json | jq -r '.volumes[] | select(.status == "available") | .id'`,description:"Print the volumes that no server uses"}],name:"volume",subcommands:[oc],summary:nc});var Bk=(e)=>{let{now:t,serverNames:r,volumes:n}=e;M({headings:["Name","Status","Size","Type","Server","Age"],rows:n.map((o)=>{let s=o.attachments.map(({serverId:i})=>r.get(i)??i);return[{text:o.name||"-"},J(o.status),{text:`${o.sizeGb} GB`},{text:o.type??"-"},{text:s.length>0?s.join(", "):"-"},{paint:K,text:V(t-Date.parse(o.createdAt))}]})})},uy=k(oc,async({client:e,flags:t})=>{let{active:r,session:n,space:o}=await e.cloud(),{project:s}=n,i=performance.now(),a=`Loading the volumes in ${s.name}…`;if(t.json){let p=await I(a,()=>Qr(o));return e.stdout.json({profile:r.name,project:s,volumes:p}),0}let[c,l]=await I(a,()=>Promise.all([Qr(o),We(o)])),u=T(`[${R(performance.now()-i)}]`);if(c.length===0)return w(`No volumes in ${x(s.name)} ${u}`),0;if(w(`Volumes in ${x(s.name)} ${u}`),Bk({now:Date.now(),serverNames:new Map(l.map((p)=>[p.id,p.name])),volumes:c}),!e.stdout.isTTY)e.stdout.line(c.map((p)=>p.id).join(`
333
- `));return 0});var py=te(ly,{ls:uy});var dy=z({args:[],description:"Prints your user, profile, project and when the session expires. When the output goes to a pipe, nipa prints only your user name.",flags:[N],name:"whoami",summary:"Show who you're logged in as"});var my=k(dy,async({client:e,flags:t})=>{let r=await e.profile(),n=await pe(r.name);if(!de(n)){if(t.json)e.stdout.line(JSON.stringify({loggedIn:!1,profile:r.name}));throw new E(`you aren't logged in to ${r.name}`,{hint:`Run \`${He(r.name)}\`.`})}if(t.json)return e.stdout.json({authUrl:r.profile.authUrl,expiresAt:n.expiresAt,link:r.link?{file:r.link.file,project:r.link.link.project}:null,loggedIn:!0,profile:r.name,project:n.project,region:r.profile.region,user:n.user}),0;if(!e.stdout.isTTY)return e.stdout.line(n.user.name),0;let{host:o}=new URL(r.profile.authUrl),s=Wt(Dt(n));w(`Logged in as ${x(n.user.name)}`);let i=T(`(${o}, ${r.profile.region})`),a=T(`(${n.project.id})`);if(w(`Profile: ${x(r.name)} ${i}`),w(`Project: ${x(n.project.name)} ${a}`),r.link&&r.link.link.project.id!==n.project.id){let{file:c,link:l}=r.link,u=T(`(${ye(c)})`);w(`This folder uses ${x(l.project.name)} ${u}`)}return w(`The session expires in ${s}`),0});var sc={examples:[{command:"nipa login",description:"Log in and pick a project"},{command:"nipa server ls",description:"List the servers in your project"},{command:"nipa os volume list",description:"Run any openstack command with the session"},{command:"nipa -P staging tf plan",description:"Run terraform against the staging profile"}],hidden:[Gf],sections:[{commands:[Hh,Yh,my,oy,Wh,cy],title:"Session"},{commands:[Gg,Ah,py,eg,ry,Oh,Gh,Zh,uh,zg,og],title:"Resources"},{commands:[ig,iy,zh,Ch],title:"Run tools"},{commands:[hg,kh,eh],title:"Setup"}],summary:"Log in to Nipa Cloud once, then list your servers, volumes, networks, security groups, external IPs, load balancers, Kubernetes clusters, databases and quotas, open them in the Space portal, or run openstack and terraform with the session."};var Bt=(e)=>{let t;return()=>(t??=e(),t)},fy=(e)=>{let{globals:t,program:r}=e;if(t.debug)process.env.NIPA_DEBUG="1";let n=ll({stderr:process.stderr,stdin:process.stdin}),o=Bt(()=>Zt()),s=Bt(async()=>ta({link:await o(),override:t.profile})),i=Bt(async()=>{try{return await s()}catch(p){if(!(p instanceof nn))throw p;return ta({override:t.profile})}}),a=Bt(async()=>cn({active:await s(),prompts:n})),c=Bt(async()=>cn({active:await s(),linked:!1,prompts:n})),l=Bt(async()=>{let p=await s();return an(p),a()});return{cloud:Bt(async()=>{let p=await s(),d=ln(p);return an(p),Lo({signedIn:await a(),spaceUrl:d})}),profile:s,profileWithoutBrokenLink:i,program:r,prompts:n,savedSession:c,session:a,stdout:ul(process.stdout),toolSession:l}};var fn=(e)=>({kind:"print",text:e}),hy=(e,t)=>({exitCode:e,kind:"ran",updateNotice:t.every((r)=>r.updateNotice!==!1)}),Gk=(e)=>new Map([...e.sections.flatMap((t)=>t.commands),...e.hidden].flatMap((t)=>xe(t.spec).map((r)=>[r,t]))),Kk=(e)=>{let t=e.at(-1)??"",r=e.slice(0,-1);return r.length===0?t:`${r.join(", ")} or ${t}`},Vk=(e,t)=>Z(`unknown subcommand "${e.spec.name} ${t}"`,`Use ${Kk(e.spec.subcommands.map((r)=>r.name))}.`),Wk=(e,t)=>{let{rest:r}=js({unknown:"stop",words:t}),[n]=r;if(n===void 0||n.startsWith("-"))return{kind:"leaf",leaf:e.fallback,path:[e.spec],words:t};let o=e.subcommands.get(n);if(!o)return{group:e,kind:"unknown",word:n};return{kind:"leaf",leaf:o,path:[e.spec,o.spec],words:t.toSpliced(t.length-r.length,1)}},Jk=(e,t)=>{let[r,n]=t,o=r===void 0?void 0:e.get(r);if(!o)return;let s=o.kind==="group"&&n!==void 0?o.subcommands.get(n):void 0;return o.kind==="group"&&s?[o.spec,s.spec]:[o.spec]},Hk=(e,t)=>{let r=Array.from({length:t.length+1},(n,o)=>o);for(let n=1;n<=e.length;n+=1){let o=[n];for(let s=1;s<=t.length;s+=1){let i=e[n-1]===t[s-1]?0:1;o[s]=Math.min((r[s]??0)+1,(o[s-1]??0)+1,(r[s-1]??0)+i)}r=o}return r[t.length]??0},qk=(e)=>{let[t]=e.program.sections.flatMap((n)=>n.commands).map((n)=>({name:n.name,score:Hk(e.word,n.name)})).toSorted((n,o)=>n.score-o.score),r=t&&t.score<=2?`Did you mean \`nipa ${t.name}\`?`:"Run `nipa --help` to see the commands.";return new E(`unknown command "${e.word}"`,{exitCode:2,hint:r})},gy=async(e)=>{let t=In(e.program),r=Gk(e.program),n=js({unknown:"reject",words:e.argv});if(n.globals.version)return fn(e.version);let[o,...s]=n.rest;if(o===void 0)return fn(ss({program:t,version:e.version}));if(o==="help"){let p=Jk(r,s);return fn(p?xn(p):ss({program:t,version:e.version}))}let i=r.get(o);if(!i)throw qk({program:t,word:o});if(i.kind==="passthrough"){if(n.globals.help)return fn(xn([i.spec]));let p=e.createClient({globals:n.globals,program:t});return hy(await i.run({client:p,words:s}),[i.spec])}let a=i.kind==="group"?Wk(i,s):{kind:"leaf",leaf:i,path:[i.spec],words:s};if(n.globals.help||yl(s))return fn(xn(a.kind==="leaf"?a.path:[i.spec]));if(a.kind==="unknown")throw Vk(a.group,a.word);let c=a.leaf.prepare({path:a.path,words:a.words}),l={...n.globals,...c.globals},u=e.createClient({globals:l,program:t});return hy(await c.run(u),a.path)};try{let e=await gy({argv:process.argv.slice(2),createClient:fy,program:sc,version:mt.version});switch(e.kind){case"print":{console.log(e.text),process.exitCode=0;break}case"ran":{if(process.exitCode=e.exitCode,e.updateNotice)await Xf({program:In(sc),version:mt.version}),await xh(mt.version);break}default:throw Error(`unknown outcome ${String(e)}`)}}catch(e){let t=e instanceof Error?Fo(e):void 0;if(!t)throw e;cl(t),process.exitCode=t.exitCode}
338
+ `).join("")},By=S(Rc,async({args:e,client:t,flags:r})=>{let n=r.tail===void 0?void 0:vC(r.tail),{active:o,session:s,space:i}=await t.cloud(),{project:a}=s,c=performance.now(),l=await kt({projectName:a.name,ref:e.server,space:i}),u=await j(`Loading ${l.name}'s console log…`,()=>Qf(i,l.id));if(u.kind==="none")throw new C(`${l.name} has no console log yet`,{hint:`A server has one once it boots, so this one most likely never booted. Run \`nipa server history ${e.server}\` to see what failed.`});let p=_C(u.text,n);if(r.json)return t.stdout.json({logs:p,profile:o.name,project:a,server:{id:l.id,name:l.name}}),0;let d=P(`[${T(performance.now()-c)}]`);if(p==="")return w(`${x(l.name)}'s console log is empty ${d}`),0;return w(`Console log of ${x(l.name)} in ${x(a.name)} ${d}`),t.stdout.write(p),0});var SC=["ID","Name","Status","Address","Flavor","Created"],$C=3,kC=4,PC=(e,t,r)=>{G({fit:{droppable:[$C,kC],width:r},headings:["Name","Status","Address","Flavor","Age"],rows:e.map((n)=>[$r(n),F(n.status),{text:St(n)??"-"},{text:n.flavor},{paint:W,text:H(t-Date.parse(n.createdAt))}])})},Dc=(e)=>{let t=Date.parse(e);return Number.isNaN(t)?e:new Date(t).toISOString()},CC=(e)=>e.map((t)=>[t.id,t.name,ve(t.status),St(t)??"",t.flavor,Dc(t.createdAt)]),Gy=S(Ec,async({client:e,flags:t})=>{let{active:r,session:n,space:o}=await e.cloud(),{project:s}=n,i=performance.now(),a=await j(`Loading the servers in ${s.name}…`,()=>Ee(o));if(t.json)return e.stdout.json({profile:r.name,project:s,servers:a}),0;let c=P(`[${T(performance.now()-i)}]`);if(w(a.length===0?`No servers in ${x(z(s.name))} ${c}`:`Servers in ${x(z(s.name))} ${c}`),!e.stdout.isTTY)e.stdout.line(Yn(SC,CC(a)));else if(a.length>0)PC(a,Date.now(),Jn());return 0});var EC="5m",jC=2000,AC=(e)=>{let t=/^(?<count>\d+)(?<unit>[hms])$/u.exec(e)?.groups,r=Number(t?.count);switch(t?.unit){case"h":return r*3600000;case"m":return r*60000;case"s":return r*1000;default:throw Z(`"${e}" isn't a duration`,"Write it as a number and a unit, such as `--timeout 90s` or `--timeout 10m`.")}},Ky={restart:{confirm:!0,doing:"Restarting",done:"Restarted",status:"ACTIVE"},start:{confirm:!1,doing:"Starting",done:"Started",status:"ACTIVE"},stop:{confirm:!0,doing:"Stopping",done:"Stopped",status:"SHUTOFF"}},RC=async(e)=>{let{action:t,client:r,server:n}=e;if(!r.prompts.interactive)throw Z(`${Ky[t].doing.toLowerCase()} ${n.name} needs confirmation`,`Add \`--yes\` to ${t} it without asking.`);let o=`${t.charAt(0).toUpperCase()}${t.slice(1)}`;if(!await r.prompts.confirm({default:!1,message:`${o} server ${$r(n).text} in ${e.projectName}?`}))throw new C("Canceled",{exitCode:130})},Nc=async(e)=>{let{action:t,client:r,flags:n}=e,o=Ky[t];if(n["no-wait"]&&n.timeout!==void 0)throw Z("--no-wait and --timeout don't go together","Drop `--timeout`, or drop `--no-wait` to wait for the server.");let s=n.timeout??EC,i=AC(s),{session:a,space:c}=await r.cloud(),l=a.project.name,u=await kt({projectName:l,ref:e.ref,space:c}),p=x(u.name);if(t==="restart"&&u.status==="SHUTOFF")throw new C(`${u.name} is stopped`,{hint:`Run \`nipa server start ${u.name}\` to start it.`});if(t!=="restart"&&u.status===o.status)return J(`${p} is already ${t==="stop"?"stopped":"running"}`),0;if(o.confirm&&!n.yes)await RC({action:t,client:r,projectName:l,server:u});let d=performance.now(),m=`\`nipa server inspect ${u.name}\``;if(n["no-wait"])return await j(`Asking to ${t} ${u.name}…`,()=>wa(c,u.id,t)),te(`Asked to ${t} ${p} in ${x(l)}`,performance.now()-d),w(`Run ${m} to check on it.`),0;let h=await j(`${o.doing} ${u.name}…`,async()=>{await wa(c,u.id,t);try{return await Xf({id:u.id,intervalMs:jC,space:c,status:o.status,timeoutMs:i})}catch(y){if(y instanceof C||y instanceof ce)throw new C(y.message,{hint:`nipa asked to ${t} ${u.name} before this failed. Run ${m} to check it.`});throw y}});if(h.kind==="error")throw new C(`${u.name} went into an error state`,{hint:`Run ${m}, or check the server in the Space portal.`});if(h.kind==="timeout"){let y=ve(h.state.status);throw new C(`${u.name} is still ${y} after ${s}`,{hint:`Run ${m} to check it again, or wait longer with \`--timeout\`.`})}return te(`${o.done} ${p} in ${x(l)}`,performance.now()-d),0},Vy=S(Tc,({args:e,client:t,flags:r})=>Nc({action:"start",client:t,flags:r,ref:e.server})),Wy=S(zc,({args:e,client:t,flags:r})=>Nc({action:"stop",client:t,flags:r,ref:e.server})),Jy=S(Oc,({args:e,client:t,flags:r})=>Nc({action:"restart",client:t,flags:r,ref:e.server}));import{setTimeout as IC}from"node:timers/promises";var TC=async(e,t,r)=>{let n=new AbortController,o=new AbortController,s=async()=>(await IC(r,void 0,{signal:o.signal}),n.abort(),{kind:"timeout"}),i=async()=>{try{return{kind:"done",value:await t(e,n.signal)}}catch(a){return{error:a,kind:"failed"}}};try{return await Promise.race([i(),s()])}finally{o.abort()}},Hy=async(e,t,r)=>{let n=[],o=e.entries(),s=async()=>{let a=o.next();if(a.done)return;let[c,l]=a.value;n[c]=await TC(l,t,r.deadlineMs),await s()},i=Math.max(1,Math.min(r.limit,e.length));return await Promise.all(Array.from({length:i},s)),n};var zC=4,OC=15000,LC=(e,t)=>{if(t===void 0||t==="")return!0;let r=t.toLowerCase();return[e.name,e.id,...e.addresses.map((n)=>n.address)].map((n)=>n.toLowerCase()).some((n)=>n.includes(r))},kr=(e)=>("failure"in e),qy=(e)=>!kr(e),DC=(e)=>{let t=new Set,r=new Set;for(let{name:n}of e)(t.has(n)?r:t).add(n);return r},NC=(e)=>e.toSorted((t,r)=>t.project.name.localeCompare(r.project.name)||t.project.id.localeCompare(r.project.id)),hs=(e,t)=>({cause:e,message:e.message,status:t}),ZC=(e)=>{if(e instanceof ae&&e.status===401)return hs(new C("Keystone refused the project",{reason:"api_error"}),401);let t=wr(e);if(!t)throw e;if(e instanceof ce||e instanceof ae)return hs(t,e.status);return hs(t,t.reason==="token_expired"?401:null)},UC=(e,t,r)=>{switch(t.kind){case"done":return t.value;case"timeout":{let n=new C(`didn't answer in ${T(r)}`,{reason:"timeout"});return{failure:hs(n,null),project:e}}case"failed":{if(!(t.error instanceof Error))throw t.error;return{failure:ZC(t.error),project:e}}default:return t}},Zc=(e,t,r)=>({project:e,repeated:DC(t),servers:t.filter((n)=>LC(n,r))}),FC=async(e,t,r)=>{let{active:n,query:o,session:s,spaceUrl:i}=e,a=t.id===s.project.id?s:Vt(await Mt({authUrl:n.profile.authUrl,projectId:t.id,signal:r,token:s.token}),t),{space:c}=xr({signal:r,signedIn:{active:n,session:a},spaceUrl:i});return Zc(t,await Ee(c),o)},Yy=async(e)=>{let t=e.deadlineMs??OC,r=await Hy(e.projects,(n,o)=>FC(e,n,o),{deadlineMs:t,limit:e.limit??zC});return NC(r.flatMap((n,o)=>{let s=e.projects[o];return s?[UC(s,n,t)]:[]}))},MC=new Set(["token_expired","network_error"]),Xy=(e)=>{let t=e.filter(kr),[r]=t;if(!r||t.length!==e.length)return;let{message:n,reason:o}=r.failure.cause;return t.every(({failure:{cause:i}})=>i.reason===o&&i.message===n)&&MC.has(o)?r.failure.cause:void 0};var eb=(e)=>e.filter(qy).flatMap(({project:t,repeated:r,servers:n})=>n.map((o)=>({nameRepeats:r.has(o.name),project:t,server:o}))),BC=(e)=>{if(e.kind==="project")return x(z(e.name));return e.searched===e.total?le(e.total,"project"):`${e.searched} of ${e.total} projects`},tb=(e)=>{let{elapsed:t,hits:r,query:n,scope:o}=e,s=n===void 0||n===""?void 0:`"${z(n)}"`,i=P(`[${t}]`),a=BC(o);if(r===0)return`${s?`No servers match ${s} in ${a}.`:`No servers in ${a}.`} ${i}`;let c=le(r,"server");return`${s?`${c} ${r===1?"matches":"match"} ${s} in ${a}`:`${c} in ${a}`} ${i}`},Cn=" ".repeat(3),Fc=" ",rb=" ",nb=(e)=>({...e,short:e.short&&nb(e.short),text:z(e.text)}),GC=(e)=>({address:z(St(e.server)??"-"),id:e.nameRepeats?z(e.server.id):void 0,name:nb($r(e.server)),status:F(e.server.status)}),gs=(e,t=0)=>{let r=e.text.padEnd(t);return e.paint?e.paint(r):r},Uc=(e)=>Math.max(0,...e.map((t)=>t.length)),ob=(e)=>{if(e.id===void 0)return[];let t=P(`ID ${e.id}`);return[`${rb}${t}`]},KC=(e)=>{let t=new Map;for(let r of e){let n=t.get(r.project.id)??{project:r.project,rows:[]};n.rows.push(GC(r)),t.set(r.project.id,n)}return[...t.values()]},sb=(e,t)=>t.some((r)=>r.id!==e.id&&r.name===e.name),ib=(e,t,r)=>{let{id:n,name:o}=e.project,s=sb(e.project,r)?` ${P(z(n))}`:"",i=n===t?` ${P("(current)")}`:"";return` ${x(z(o))}${s}${i}`},VC=(e)=>{let{current:t,groups:r,names:n,projects:o}=e,s=r.flatMap((p)=>p.rows),i=(p)=>n==="short"?p.name.short??p.name:p.name,a=Uc(s.map((p)=>i(p).text)),c=Uc(s.map((p)=>p.status.text)),l=Fc.length+a+Cn.length+c+Cn.length+Uc(s.map((p)=>p.address));return{lines:r.flatMap((p)=>["",ib(p,t,o),...p.rows.flatMap((d)=>[`${Fc}${gs(i(d),a)}${Cn}${gs(d.status,c)}${Cn}${d.address}`,...ob(d)])]),width:l}},WC=(e,t,r)=>e.flatMap((n)=>["",ib(n,t,r),...n.rows.flatMap((o)=>[`${Fc}${gs(o.name.short??o.name)}`,`${rb}${gs(o.status)}${Cn}${o.address}`,...ob(o)])]),ab=(e)=>{let t=KC(e.hits);if(t.length===0)return[];let{current:r,projects:n,width:o}=e;return[...["full","short"].map((a)=>VC({current:r,groups:t,names:a,projects:n})).find((a)=>a.width<=o)?.lines??WC(t,r,n),""]},cb=["ID","Name","Project","Project ID","Status","Address","Flavor","Created"],lb=(e)=>e.map(({project:t,server:r})=>[r.id,r.name,t.name,t.id,ve(r.status),St(r)??"",r.flavor,Dc(r.createdAt)]),Qy=5,JC=(e)=>{let t=e.slice(0,Qy).map(({failure:n,project:o})=>` ${z(o.name)}: ${z(n.message)}`),r=e.length-Qy;return r>0?[...t,` and ${r} more`]:t},ub=(e)=>{let{failed:t,total:r}=e;return[`Searched ${r-t.length} of ${r} projects. ${t.length} failed.`,...JC(t)].join(`
339
+ `)},pb=(e)=>/[\n\r]/u.test(e),Mc=(e,t)=>sb(e,t)||pb(e.name)?e.id:e.name,Bc=(e)=>{let{command:t,project:r,scope:n}=e;if(!n)return t;let o=r===void 0?n:{...n,project:r};return Mr(t,o).command},db=(e)=>ri(e.nameRepeats||pb(e.server.name)?e.server.id:e.server.name);var HC=async(e,t)=>{let{active:r,session:n,space:o}=await e.cloud(),{project:s}=n;return{narrowed:!0,outcomes:[await j(`Searching ${z(s.name)}…`,async()=>Zc(s,await Ee(o),t))],profile:r.name,projects:[s],scope:{kind:"project",name:s.name}}},qC=async(e,t)=>{let r=await e.profile(),n=Jt(r);Wt(r);let{session:o}=await e.savedSession(),s=await Ma(r,o),i=r.link?.link.project.id??o.project.id;if(s.length===0)throw new C("your account has no projects you can use");let a=await j(`Searching ${le(s.length,"project")}…`,()=>Yy({active:r,projects:s,query:t,session:o,spaceUrl:n})),c=a.filter(kr).length;return{current:i,narrowed:!1,outcomes:a,profile:r.name,projects:s,scope:{kind:"projects",searched:s.length-c,total:s.length}}},YC=(e,t)=>{let[r]=t,n=Fr(),o=(s)=>e.narrowed?void 0:Mc(s.project,e.projects);if(r&&t.length===1){let s=Bc({command:`nipa server inspect ${db(r)}`,project:o(r),scope:n});w(`Run \`${s}\` to see its details.`)}else if(t.length>1)w(e.narrowed?"Act on one with `nipa server <verb> <name or ID>`.":"Act on one with `nipa -p <project> server <verb> <name or ID>`.")},XC=(e)=>{let t=e.outcomes.filter(kr);if(t.length===0)return 0;let[r]=t,n=r?Bc({command:"nipa server ls",project:Mc(r.project,e.projects),scope:Fr()}):"nipa server ls";return Hn(new C(ub({failed:t,total:e.projects.length}),{hint:`Try ${t.length===1?"it":"one"} again with \`${n}\`.`})),1},mb=S(jc,async({args:e,client:t,flags:r})=>{let{query:n}=e,o=performance.now(),s=await(t.project===void 0?qC(t,n):HC(t,n)),i=Xy(s.outcomes);if(i)throw i;let a=T(performance.now()-o),c=eb(s.outcomes),l=s.outcomes.filter(kr);if(r.json)return t.stdout.json({failed:l.map(({failure:u,project:p})=>({message:u.message,project:p,reason:u.cause.reason,status:u.status})),profile:s.profile,projects:{searched:s.outcomes.length-l.length,total:s.outcomes.length},query:n===void 0||n===""?null:n,servers:c.map(({project:u,server:p})=>({...p,project:u}))}),l.length>0?1:0;if(s.outcomes.length>l.length)w(tb({elapsed:a,hits:c.length,query:n,scope:s.scope}));if(t.stdout.isTTY){for(let u of ab({current:s.current,hits:c,projects:s.projects,width:Jn()}))V(u);YC(s,c)}else t.stdout.line(Yn(cb,lb(c)));return XC(s)});var fb=ne(Dy,{history:Ny,inspect:My,logs:By,ls:Gy,restart:Jy,search:mb,start:Vy,stop:Wy});var hb="List the security groups in your project",Gc=R({aliases:["list"],args:[],flags:[D],name:"ls",summary:hb}),Kc=R({args:[{arity:"one",name:"group",value:{kind:"resource",resource:"security-groups"}}],flags:[D],name:"inspect",summary:"Show a security group's rules and the servers that use it"}),gb=re({aliases:["security-group","security-groups"],default:"ls",description:"Lists and inspects the security groups in your project. Name a group by its name or ID. `nipa sg inspect` shows a group's inbound and outbound rules and the servers that use it, found through the network ports in your project, so a server in another project doesn't show. It notes when a rule opens SSH, RDP or a database port to the internet. `--json` prints each rule's direction, protocol, ports and remote, and `exposed`, true for such a rule.",examples:[{command:"nipa sg ls",description:hb},{command:"nipa sg inspect web",description:"Show the rules of the web security group and its servers"},{command:"nipa sg inspect web --json | jq -r '.securityGroup.servers[].name'",description:"Print the name of each server that uses web"}],name:"sg",subcommands:[Gc,Kc],summary:"List and inspect your security groups"});var QC=new Set(["icmp","icmpv6","ipv6-icmp"]),eE=new Map([["1","icmp"],["6","tcp"],["17","udp"],["58","ipv6-icmp"]]),tE=(e)=>e===null||e==="any"?null:eE.get(e)??e,rE=new Set(["0.0.0.0/0","::/0"]),nE=65535,oE=(e,t)=>{let{portMax:r,portMin:n}=t;if(e===null||n===null)return{kind:"any"};if(QC.has(e))return{code:r,kind:"icmp",type:n};let o=r??n;return n<=1&&o>=nE?{kind:"any"}:{from:n,kind:"range",to:o}},sE=(e,t)=>{if(e.remoteGroupId){let r=e.remoteGroupId;return{id:r,kind:"group",name:t.get(r)??null}}return e.remoteIpPrefix?{cidr:e.remoteIpPrefix,kind:"cidr"}:{kind:"any"}},Wc=(e,t)=>{let r=tE(e.protocol);return{direction:e.direction,ethertype:e.ethertype,ports:oE(r,e),protocol:r,remote:sE(e,t)}},iE=(e)=>{switch(e.kind){case"any":return"any";case"range":return e.from===e.to?String(e.from):`${e.from}-${e.to}`;case"icmp":{let t=e.code===null?"":` code ${e.code}`;return`type ${e.type}${t}`}default:return e}},Vc=(e)=>{switch(e.kind){case"any":return"any";case"cidr":return e.cidr;case"group":return`group ${e.name??e.id}`;default:return e}},bb=(e)=>[{text:e.protocol??"any"},{text:iE(e.ports)},{text:Vc(e.remote)},{text:e.ethertype}],yb=(e)=>{switch(e.kind){case"range":return e.from;case"icmp":return e.type;default:return-1}},xb=(e,t)=>yb(e.ports)-yb(t.ports)||(e.protocol??"").localeCompare(t.protocol??"")||e.ethertype.localeCompare(t.ethertype)||Vc(e.remote).localeCompare(Vc(t.remote)),wb=[{name:"SSH",port:22},{name:"MySQL",port:3306},{name:"RDP",port:3389},{name:"PostgreSQL",port:5432},{name:"Redis",port:6379},{name:"MongoDB",port:27017}],aE=(e)=>e.kind==="any"||e.kind==="cidr"&&rE.has(e.cidr),cE=(e)=>e.direction==="ingress"&&aE(e.remote)&&(e.protocol===null||e.protocol==="tcp"),vb=(e,t)=>e.kind==="any"||e.kind==="range"&&e.from<=t&&t<=e.to,ys=(e)=>cE(e)&&wb.some(({port:t})=>vb(e.ports,t)),_b=(e)=>{let t=e.filter(ys);if(t.some((o)=>o.ports.kind==="any"))return"Every port is open to the internet.";let r=wb.filter(({port:o})=>t.some((s)=>vb(s.ports,o))).map(({name:o,port:s})=>`${o} (${s})`);if(r.length===0)return;let n=r.length===1?"is":"are";return`${Dt(r)} ${n} open to the internet.`};var lE=(e,t,r)=>r.flatMap((n)=>{let o=t.filter((s)=>s.deviceId===n.id&&s.securityGroupIds.includes(e));return o.length>0?[{addresses:o.flatMap((s)=>s.addresses),id:n.id,name:n.name}]:[]}),uE=(e)=>Ae(e.name,` (${e.addresses.length>0?e.addresses.join(", "):"-"})`),pE=[{direction:"ingress",empty:"No inbound rules, so this group lets no traffic in.",remote:"Source",title:"Inbound rules"},{direction:"egress",empty:"No outbound rules, so this group lets no traffic out.",remote:"Destination",title:"Outbound rules"}],dE=(e,t)=>{let r=e.rules.map((n)=>Wc(n,t)).toSorted(xb);for(let{direction:n,empty:o,remote:s,title:i}of pE){let a=r.filter((l)=>l.direction===n);if(a.length===0){w(o);continue}w(i),G({headings:["Protocol","Ports",s,"Ethertype"],marks:a.map((l)=>ys(l)?Ve("!"):" "),rows:a.map(bb)});let c=_b(a);if(c)J(c)}},Sb=S(Kc,async({args:e,client:t,flags:r})=>{let{active:n,session:o,space:s}=await t.cloud(),{project:i}=o,a=performance.now(),c=hr(s),l=await ct({kind:{...gr,list:()=>c},projectName:i.name,ref:e.group,space:s}),[u,p]=await j(`Loading the servers in ${i.name}…`,()=>Promise.all([sh(s),Ee(s)])),d=await c,m=new Map(d.map((v)=>[v.id,v.name])),h=lE(l.id,u,p);if(r.json){let v=l.rules.map((E)=>({...E,exposed:ys(Wc(E,m)),remoteGroupName:E.remoteGroupId?m.get(E.remoteGroupId)??null:null}));return t.stdout.json({profile:n.name,project:i,securityGroup:{...l,rules:v,servers:h}}),0}let y=P(`[${T(performance.now()-a)}]`);w(`Security group ${x(l.name)} in ${x(i.name)} ${y}`);let b=`${H(Date.now()-Date.parse(l.createdAt))} ago`;if(yt([{label:"ID",lines:[{text:l.id}]},{label:"Description",lines:l.description?[{text:l.description}]:[]},{label:"Servers",lines:h.map(uE)},{label:"Created",lines:[{paint:W,text:b}]}]),dE(l,m),!t.stdout.isTTY)t.stdout.line(l.id);return 0});var $b=(e,t)=>e.rules.filter((r)=>r.direction===t).length,mE=(e,t)=>{G({headings:["Name","Inbound","Outbound","Age","Description"],rows:e.map((r)=>[{text:r.name},{text:String($b(r,"ingress"))},{text:String($b(r,"egress"))},{paint:W,text:H(t-Date.parse(r.createdAt))},{text:r.description??"-"}])})},kb=S(Gc,async({client:e,flags:t})=>{let{active:r,session:n,space:o}=await e.cloud(),{project:s}=n,i=performance.now(),a=await j(`Loading the security groups in ${s.name}…`,()=>hr(o));if(t.json)return e.stdout.json({profile:r.name,project:s,securityGroups:a}),0;let c=P(`[${T(performance.now()-i)}]`);if(a.length===0)return w(`No security groups in ${x(s.name)} ${c}`),0;if(w(`Security groups in ${x(s.name)} ${c}`),mE(a,Date.now()),!e.stdout.isTTY)e.stdout.line(a.map((l)=>l.id).join(`
340
+ `));return 0});var Pb=ne(gb,{inspect:Sb,ls:kb});var Cb=R({args:[{arity:"optional",name:"project",value:{kind:"project"}}],description:"Scopes the session to another project, by name or ID, without a password or OTP code. Without a project, nipa lists your projects to pick from.",flags:[],name:"switch",summary:"Use another project",usesProject:!1});var Eb=S(Cb,async({args:e,client:t})=>{let{project:r}=e,{active:n,session:o}=await t.savedSession(),{authUrl:s}=n.profile,i=await j("Loading your projects…",()=>Oe({authUrl:s,token:o.token}));if(r===void 0&&!t.prompts.interactive)throw new C("tell nipa which project to use",{exitCode:2,hint:`Run \`nipa switch <project>\`. Your projects: ${i.map((p)=>p.name).join(", ")}`});let a=await ns({ask:rs({current:o.project,message:"Switch to:",prompts:t.prompts}),projects:i,wanted:r});if(a.id===o.project.id)return J(`You're already using ${x(a.name)}`),0;let c=performance.now(),l=await j(`Switching to ${a.name}…`,()=>Mt({authUrl:s,projectId:a.id,token:o.token}));await Za({active:n,session:Vt(l,a)}),te(`Switched to ${x(a.name)}`,performance.now()-c);let u=n.link;if(u&&u.link.project.id!==a.id)J(`Commands in this folder still use ${x(u.link.project.name)}, from ${Se(u.file)}. Run \`nipa unlink\` to use ${a.name} here too.`);return 0});var jb=or({aliases:["terraform"],description:"Runs `terraform <args...>` with the session. It's the same as `nipa exec terraform <args...>`.",examples:[{command:"nipa -P staging tf plan",description:"Plan against the staging profile"}],name:"tf",summary:"Run terraform with the session",target:{kind:"program",program:"terraform"}});var Ab=sr(jb,({args:e,client:t,command:r})=>vr({args:e,command:r,signIn:t.toolSession}));var Rb=R({args:[],description:"Deletes the .nipa/project.json that links this folder, or the closest folder above it, so commands here use the current profile and project again.",flags:[],name:"unlink",summary:"Stop using a linked project in this folder",usesProject:!1});var Ib=S(Rb,async()=>{let e=await Kt();if(!e)return J("This folder isn't linked to a project"),0;return await Oh(e.file),te(`Unlinked ${Se(e.file)} from ${x(e.link.project.name)}`),0});var Jc="List the volumes in your project",Hc=R({aliases:["list"],args:[],flags:[D],name:"ls",summary:Jc}),Tb=re({aliases:["volumes"],default:"ls",description:"Lists the block storage volumes in your project with their status, size, type, the server each one is attached to, and age.",examples:[{command:"nipa volume ls",description:Jc},{command:`nipa volume ls --json | jq -r '.volumes[] | select(.status == "available") | .id'`,description:"Print the volumes that no server uses"}],name:"volume",subcommands:[Hc],summary:Jc});var fE=(e)=>{let{now:t,serverNames:r,volumes:n}=e;G({headings:["Name","Status","Size","Type","Server","Age"],rows:n.map((o)=>{let s=o.attachments.map(({serverId:i})=>r.get(i)??i);return[{text:o.name||"-"},F(o.status),{text:`${o.sizeGb} GB`},{text:o.type??"-"},{text:s.length>0?s.join(", "):"-"},{paint:W,text:H(t-Date.parse(o.createdAt))}]})})},zb=S(Hc,async({client:e,flags:t})=>{let{active:r,session:n,space:o}=await e.cloud(),{project:s}=n,i=performance.now(),a=`Loading the volumes in ${s.name}…`;if(t.json){let p=await j(a,()=>gn(o));return e.stdout.json({profile:r.name,project:s,volumes:p}),0}let[c,l]=await j(a,()=>Promise.all([gn(o),Ee(o)])),u=P(`[${T(performance.now()-i)}]`);if(c.length===0)return w(`No volumes in ${x(s.name)} ${u}`),0;if(w(`Volumes in ${x(s.name)} ${u}`),fE({now:Date.now(),serverNames:new Map(l.map((p)=>[p.id,p.name])),volumes:c}),!e.stdout.isTTY)e.stdout.line(c.map((p)=>p.id).join(`
341
+ `));return 0});var Ob=ne(Tb,{ls:zb});var Lb=R({args:[],description:"Prints your user, profile, project and when the session expires. When the output goes to a pipe, nipa prints only your user name.",flags:[D],name:"whoami",summary:"Show who you're logged in as",usesProject:!1});var Db=S(Lb,async({client:e,flags:t})=>{let r=await e.profile(),n=await ge(r.name);if(!ye(n)){if(t.json)return e.stdout.line(JSON.stringify({loggedIn:!1,profile:r.name})),1;throw new C(`you aren't logged in to ${r.name}`,{hint:`Run \`${Ge(r.name)}\`.`})}if(t.json)return e.stdout.json({authUrl:r.profile.authUrl,expiresAt:n.expiresAt,link:r.link?{file:r.link.file,project:r.link.link.project}:null,loggedIn:!0,profile:r.name,project:n.project,region:r.profile.region,user:n.user}),0;if(!e.stdout.isTTY)return e.stdout.line(n.user.name),0;let{host:o}=new URL(r.profile.authUrl),s=nr(Bt(n));w(`Logged in as ${x(n.user.name)}`);let i=P(`(${o}, ${r.profile.region})`),a=P(`(${n.project.id})`);if(w(`Profile: ${x(r.name)} ${i}`),w(`Project: ${x(n.project.name)} ${a}`),r.link&&r.link.link.project.id!==n.project.id){let{file:c,link:l}=r.link,u=P(`(${Se(c)})`);w(`This folder uses ${x(l.project.name)} ${u}`)}return w(`The session expires in ${s}`),0});var qc={examples:[{command:"nipa login",description:"Log in and pick a project"},{command:"nipa server ls",description:"List the servers in your project"},{command:"nipa os volume list",description:"Run any openstack command with the session"},{command:"nipa -P staging tf plan",description:"Run terraform against the staging profile"}],hidden:[Jh],sections:[{commands:[ty,ny,Db,Eb,Qg,Ib],title:"Session"},{commands:[fb,Ng,Ob,iy,Pb,Fg,qg,Kg,fg,Oy,uy],title:"Resources"},{commands:[dy,Ab,Og,Tg],title:"Run tools"},{commands:[vy,Rg,og],title:"Setup"}],summary:"Log in to Nipa Cloud once, then list your servers, volumes, networks, security groups, external IPs, load balancers, Kubernetes clusters, databases and quotas, open them in the Space portal, or run openstack and terraform with the session."};var Yt=(e)=>{let t;return()=>(t??=e(),t)},Nb=(e)=>{let{globals:t,json:r,program:n}=e;if(t.debug)process.env.NIPA_DEBUG="1";let o=uu({env:process.env,json:r,nonInteractive:t["non-interactive"]===!0,stderr:process.stderr,stdin:process.stdin});lu(o.interactive&&process.env.TERM!=="dumb");let s=Yt(()=>Kt()),i=Yt(async()=>La({link:await s(),override:t.profile})),a=Yt(async()=>{try{return await i()}catch(d){if(!(d instanceof wn))throw d;return La({override:t.profile})}}),c=Yt(async()=>_n({active:await i(),project:t.project,prompts:o})),l=Yt(async()=>_n({active:await i(),prompts:o,saved:!0})),u=Yt(async()=>{let d=await i();return Wt(d),c()});return{cloud:Yt(async()=>{let d=await i(),m=Jt(d);return Wt(d),xr({signedIn:await c(),spaceUrl:m})}),profile:i,profileWithoutBrokenLink:a,program:n,project:t.project,prompts:o,savedSession:l,session:c,stdout:pu(process.stdout),toolSession:u}};var bs=(e)=>{let{globals:t,path:r,program:n}=e;return{profile:r&&jn(r)===!1?void 0:t.profile,program:n,project:r&&jr(r)!==void 0?void 0:t.project}},En=(e)=>({kind:"print",text:e}),Zb=(e)=>({exitCode:e.exitCode,interactive:e.client.prompts.interactive,kind:"ran",updateNotice:e.path.every((t)=>t.updateNotice!==!1)}),hE=(e)=>new Map([...e.sections.flatMap((t)=>t.commands),...e.hidden].flatMap((t)=>me(t.spec).map((r)=>[r,t]))),gE=(e)=>{let t=e.at(-1)??"",r=e.slice(0,-1);return r.length===0?t:`${r.join(", ")} or ${t}`},yE=(e,t)=>Z(`unknown subcommand "${e.spec.name} ${t}"`,`Use ${gE(e.spec.subcommands.map((r)=>r.name))}.`,"unknown_command"),bE=(e,t)=>{let{rest:r}=di({unknown:"stop",words:t}),[n]=r;if(n===void 0||n.startsWith("-"))return{kind:"leaf",leaf:e.fallback,path:[e.spec],words:t};let o=e.subcommands.get(n);if(!o)return{group:e,kind:"unknown",word:n};return{kind:"leaf",leaf:o,path:[e.spec,o.spec],words:t.toSpliced(t.length-r.length,1)}},xE=(e,t)=>{let[r,n]=t,o=r===void 0?void 0:e.get(r);if(!o)return;let s=o.kind==="group"&&n!==void 0?o.subcommands.get(n):void 0;return o.kind==="group"&&s?[o.spec,s.spec]:[o.spec]},wE=(e,t)=>{let r=Array.from({length:t.length+1},(n,o)=>o);for(let n=1;n<=e.length;n+=1){let o=[n];for(let s=1;s<=t.length;s+=1){let i=e[n-1]===t[s-1]?0:1;o[s]=Math.min((r[s]??0)+1,(o[s-1]??0)+1,(r[s-1]??0)+i)}r=o}return r[t.length]??0},vE=(e)=>{let[t]=e.program.sections.flatMap((n)=>n.commands).map((n)=>({name:n.name,score:wE(e.word,n.name)})).toSorted((n,o)=>n.score-o.score),r=t&&t.score<=2?`Did you mean \`nipa ${t.name}\`?`:"Run `nipa --help` to see the commands.";return new C(`unknown command "${e.word}"`,{exitCode:2,hint:r,reason:"unknown_command"})},Ub=async(e)=>{ai(mi(e.argv)),tr(void 0);let t=Xn(e.program),r=hE(e.program),n=di({unknown:"reject",words:e.argv});if(tr(bs({globals:n.globals,program:t})),n.globals.version)return En(e.version);let[o,...s]=n.rest;if(o===void 0)return En(js({program:t,version:e.version}));if(o==="help"){let p=xE(r,s);return En(p?Tn(p):js({program:t,version:e.version}))}let i=r.get(o);if(!i)throw tr(bs({globals:{...n.globals,profile:n.globals.profile??tu(s),project:n.globals.project??ru(s)},program:t})),vE({program:t,word:o});if(i.kind==="passthrough"){if(n.globals.help)return En(Tn([i.spec]));ai(!1),tr(bs({globals:n.globals,path:[i.spec],program:t}));let p=e.createClient({globals:n.globals,json:!1,program:t});return Zb({client:p,exitCode:await i.run({client:p,words:s}),path:[i.spec]})}let a=i.kind==="group"?bE(i,s):{kind:"leaf",leaf:i,path:[i.spec],words:s};if(n.globals.help||vu(s))return En(Tn(a.kind==="leaf"?a.path:[i.spec]));if(a.kind==="unknown")throw yE(a.group,a.word);let c=a.leaf.prepare({path:a.path,words:a.words}),l={...n.globals,...c.globals};if(tr(bs({globals:l,path:a.path,program:t})),l.project!==void 0&&jr(a.path)===!1)throw Z(`--project doesn't apply to ${Xt(a.path)}`,`Usage: ${Rt(a.path)}`);let u=e.createClient({globals:l,json:mi(a.words),program:t});return Zb({client:u,exitCode:await c.run(u),path:a.path})};for(let e of[process.stdout,process.stderr])e.on("error",(t)=>{if(t.code!=="EPIPE")throw t});try{let e=await Ub({argv:process.argv.slice(2),createClient:Nb,program:qc,version:ft.version});switch(e.kind){case"print":{console.log(e.text),process.exitCode=0;break}case"ran":{if(process.exitCode=e.exitCode,e.updateNotice)await rg({program:Xn(qc),version:ft.version}),await kg(ft.version,{interactive:e.interactive});break}default:throw Error(`unknown outcome ${String(e)}`)}}catch(e){let t=e instanceof Error?wr(e):void 0;if(au()){if(!t)at(e instanceof Error?e.stack??e.message:`${e}`);let r=t??gg();hg(r),process.exitCode=r.exitCode}else if(t)Hn(t),process.exitCode=t.exitCode;else throw e}