arkenv 1.0.0-alpha.4 → 1.0.0-alpha.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/index.cjs +164 -286
  2. package/package.json +2 -1
package/dist/index.cjs CHANGED
@@ -2,74 +2,74 @@
2
2
  const e=require(`./chunk-i8uDWG73.cjs`);let t=require(`radashi`),n=require(`node:util`),r=require(`node:process`);r=e.r(r,1);let i=require(`node:readline`);i=e.r(i,1);let a=require(`node:tty`);require(`node:fs`);let o=require(`node:path`);o=e.r(o,1);let s=require(`node:fs/promises`);s=e.r(s,1);let c=require(`dedent`);c=e.r(c,1);let l=require(`node:child_process`),u=require(`node:module`),d=require(`jsonc-parser`),f=require(`magicast`),p=require(`yaml`);const m=(e,t=2,{dontDetectNewlines:n=!1}={})=>n?`${` `.repeat(t)}${e}`:e.split(`
3
3
  `).map(e=>`${` `.repeat(t)}${e}`).join(`
4
4
  `),h={red:`\x1B[31m`,yellow:`\x1B[33m`,cyan:`\x1B[36m`,reset:`\x1B[0m`},g=()=>typeof process<`u`&&process.versions!=null&&process.versions.node!=null,_=()=>!!(!g()||process.env.NO_COLOR!==void 0||process.env.CI!==void 0||process.stdout&&!process.stdout.isTTY),v=(e,t)=>g()&&!_()?`${h[e]}${t}${h.reset}`:t;function y(e){return e.map(e=>`${v(`yellow`,e.path)} ${e.message.trimStart()}`).join(`
5
- `)}Object.defineProperty(class extends Error{constructor(e,t=`Errors found while validating environment variables`){let n=y(e);super(`${v(`red`,t)}\n${m(n)}\n`),this.name=`ArkEnvError`,this.issues=e}},`name`,{value:`ArkEnvError`});const b=`[ArkEnv]`;function x(e){return`${b} ${e}`}function S(e){console.error(`❌ ${b} ${e}`)}function C(e){console.error(e)}function w(e){return e instanceof Error?e.stack??e.message:String(e)}function ee(e,t){S(e),C(w(t))}function T(e,t,n){e(`${t}: ${n instanceof Error?n.message:String(n)}`),n instanceof Error&&n.stack&&e(n.stack)}var E=e.t(((e,t)=>{let n=process||{},r=n.argv||[],i=n.env||{},a=!(i.NO_COLOR||r.includes(`--no-color`))&&(!!i.FORCE_COLOR||r.includes(`--color`)||n.platform===`win32`||(n.stdout||{}).isTTY&&i.TERM!==`dumb`||!!i.CI),o=(e,t,n=e)=>r=>{let i=``+r,a=i.indexOf(t,e.length);return~a?e+s(i,t,n,a)+t:e+i+t},s=(e,t,n,r)=>{let i=``,a=0;do i+=e.substring(a,r)+n,a=r+t.length,r=e.indexOf(t,a);while(~r);return i+e.substring(a)},c=(e=a)=>{let t=e?o:()=>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`)}};t.exports=c(),t.exports.createColors=c})),D=e.r(E(),1),O=class{info(e){process.stderr.write(`${D.default.blue(`ℹ ${e}`)}\n`)}warn(e){process.stderr.write(`${D.default.yellow(`⚠ ${e}`)}\n`)}error(e){process.stderr.write(`${D.default.red(`✘ ${e}`)}\n`)}success(e){process.stderr.write(`${D.default.green(`✔ ${e}`)}\n`)}step(e){process.stderr.write(`○ ${e}\n`)}note(e,t){process.stderr.write(`${D.default.dim(`○ ${t?`${t}: `:``}${e}`)}\n`)}log(e){process.stderr.write(`${e}\n`)}spinner(){return{start:e=>process.stderr.write(`${D.default.dim(`○ ${e}...`)}\n`),stop:e=>process.stderr.write(`${D.default.green(`✔ ${e}`)}\n`),message:e=>process.stderr.write(`${D.default.dim(`○ ${e}...`)}\n`)}}json(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}cancel(e){this.json({status:`cancelled`,message:e})}fatal(e,t){throw this.json({status:`error`,details:{message:e,error:t instanceof Error?t.message:t?String(t):void 0}}),t instanceof Error?t:Error(e)}finish(e,t){this.json({status:`success`,message:e,details:t})}async flush(){return new Promise(e=>{process.stdout.write(``,()=>e())})}},k=class{stripAnsi(e){return e.replace(/\x1B\[[0-9;]*[JKmsu]/g,``)}info(e){}warn(e){}error(e){}success(e){}step(e){}note(e,t){}log(e){process.stdout.write(`${this.stripAnsi(e)}\n`)}spinner(){return{start:e=>{},stop:e=>{},message:e=>{}}}json(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}cancel(e){process.stderr.write(`✘ Cancelled: ${e}\n`)}fatal(e,t){throw process.stderr.write(`✘ Fatal: ${e}\n`),t&&process.stderr.write(`${t instanceof Error?t.stack??t.message:String(t)}\n`),t instanceof Error?t:Error(e)}finish(e,t){}async flush(){return new Promise(e=>{process.stderr.write(``,()=>e())})}};const A=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return t=>{let n=0;for(e.lastIndex=0;e.test(t);)n+=1;return t.length-n}})(),j=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,te=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,ne=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,re=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,ie=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,ae=/\t{1,1000}/y,oe=/[\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?))*/uy,se=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,ce=/\p{M}+/gu,le={limit:1/0,ellipsis:``},ue=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?ue(i,le,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[se,l],[ne,0],[re,o],[ae,s],[oe,c],[ie,u]],f=0,p=0,m=e.length,h=0,g=!1,_=m,v=Math.max(0,r-a),y=0,b=0,x=0,S=0;outer:for(;;){if(b>y||p>=m&&p>f){let t=e.slice(y,b)||e.slice(f,p);h=0;for(let e of t.replaceAll(ce,``)){let t=e.codePointAt(0)||0;if(S=j(t)?2:te(t)?u:l,x+S>v&&(_=Math.min(_,Math.max(y,f)+h)),x+S>r){g=!0;break outer}h+=e.length,x+=S}y=b=0}if(p>=m)break outer;for(let t=0,n=d.length;t<n;t++){let[n,i]=d[t];if(n.lastIndex=p,n.test(e)){if(h=n===ie?A(e.slice(p,n.lastIndex)):n===oe?1:n.lastIndex-p,S=h*i,x+S>v&&(_=Math.min(_,p+Math.floor((v-x)/i))),x+S>r){g=!0;break outer}x+=S,y=f,b=p,p=f=n.lastIndex;continue outer}}p+=1}return{width:g?v:x,index:g?_:m,truncated:g,ellipsed:g&&r>=a}},de={limit:1/0,ellipsis:``,ellipsisWidth:0},M=(e,t={})=>ue(e,de,t).width,fe=`]8;;`,pe=RegExp(`(?:\\[(?<code>\\d+)m|\\${fe}(?<uri>.*))`,`y`),me=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},he=e=>`[${e}m`,ge=e=>`${fe}${e}`,_e=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:M(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=M(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===`›`)&&(i=!0,a=t.startsWith(fe,u+1)),i?a?o===`\x07`&&(i=!1,a=!1):o===`m`&&(i=!1):(s+=d,s===n&&!l.done&&(e.push(``),s=0)),c=l,l=r.next(),u+=o.length}o=e.at(-1),!s&&o!==void 0&&o.length&&e.length>1&&(e[e.length-2]+=e.pop())},ve=e=>{let t=e.split(` `),n=t.length;for(;n&&!M(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},ye=(e,t,n={})=>{if(n.trim!==!1&&e.trim()===``)return``;let r=``,i,a,o=e.split(` `),s=[``],c=0;for(let e=0;e<o.length;e++){let r=o[e];if(n.trim!==!1){let e=s.at(-1)??``,t=e.trimStart();e.length!==t.length&&(s[s.length-1]=t,c=M(t))}e!==0&&(c>=t&&(n.wordWrap===!1||n.trim===!1)&&(s.push(``),c=0),(c||n.trim===!1)&&(s[s.length-1]+=` `,c++));let i=M(r);if(n.hard&&i>t){let e=t-c,n=1+Math.floor((i-e-1)/t);Math.floor((i-1)/t)<n&&s.push(``),_e(s,r,t),c=M(s.at(-1)??``);continue}if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){_e(s,r,t),c=M(s.at(-1)??``);continue}s.push(``),c=0}if(c+i>t&&n.wordWrap===!1){_e(s,r,t),c=M(s.at(-1)??``);continue}s[s.length-1]+=r,c+=i}n.trim!==!1&&(s=s.map(e=>ve(e)));let l=s.join(`
6
- `),u=!1;for(let e=0;e<l.length;e++){let t=l[e];if(r+=t,u)u=!1;else if(u=t>=`\ud800`&&t<=`\udbff`,u)continue;if(t===`\x1B`||t===`›`){pe.lastIndex=e+1;let t=pe.exec(l)?.groups;if(t?.code!==void 0){let e=Number.parseFloat(t.code);i=e===39?void 0:e}else t?.uri!==void 0&&(a=t.uri.length===0?void 0:t.uri)}if(l[e+1]===`
7
- `){a&&(r+=ge(``));let e=i?me(i):void 0;i&&e&&(r+=he(e))}else t===`
8
- `&&(i&&me(i)&&(r+=he(i)),a&&(r+=ge(a)))}return r},be=/\r?\n/;function N(e,t,n){return String(e).normalize().split(be).map(e=>ye(e,t,n)).join(`
9
- `)}var P=e.t(((e,t)=>{let n={to(e,t){return t?`[${t+1};${e+1}H`:`[${e+1}G`},move(e,t){let n=``;return e<0?n+=`[${-e}D`:e>0&&(n+=`[${e}C`),t<0?n+=`[${-t}A`:t>0&&(n+=`[${t}B`),n},up:(e=1)=>`[${e}A`,down:(e=1)=>`[${e}B`,forward:(e=1)=>`[${e}C`,backward:(e=1)=>`[${e}D`,nextLine:(e=1)=>`\x1B[E`.repeat(e),prevLine:(e=1)=>`\x1B[F`.repeat(e),left:`\x1B[G`,hide:`\x1B[?25l`,show:`\x1B[?25h`,save:`\x1B7`,restore:`\x1B8`};t.exports={cursor:n,scroll:{up:(e=1)=>`\x1B[S`.repeat(e),down:(e=1)=>`\x1B[T`.repeat(e)},erase:{screen:`\x1B[2J`,up:(e=1)=>`\x1B[1J`.repeat(e),down:(e=1)=>`\x1B[J`.repeat(e),line:`\x1B[2K`,lineEnd:`\x1B[K`,lineStart:`\x1B[1K`,lines(e){let t=``;for(let r=0;r<e;r++)t+=this.line+(r<e-1?n.up():``);return e&&(t+=n.left),t}},beep:`\x07`}}))();function xe(e,t,n){if(!n.some(e=>!e.disabled))return e;let r=e+t,i=Math.max(n.length-1,0),a=r<0?i:r>i?0:r;return n[a].disabled?xe(a,t<0?-1:1,n):a}const F={actions:new Set([`up`,`down`,`left`,`right`,`space`,`enter`,`cancel`]),aliases:new Map([[`k`,`up`],[`j`,`down`],[`h`,`left`],[`l`,`right`],[``,`cancel`],[`escape`,`cancel`]]),messages:{cancel:`Canceled`,error:`Something went wrong`},withGuide:!0,date:{monthNames:[...[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`]],messages:{required:`Please enter a valid date`,invalidMonth:`There are only 12 months in a year`,invalidDay:(e,t)=>`There are only ${e} days in ${t}`,afterMin:e=>`Date must be on or after ${e.toISOString().slice(0,10)}`,beforeMax:e=>`Date must be on or before ${e.toISOString().slice(0,10)}`}}};function Se(e,t){if(typeof e==`string`)return F.aliases.get(e)===t;for(let n of e)if(n!==void 0&&Se(n,t))return!0;return!1}function Ce(e,t){if(e===t)return;let n=e.split(`
5
+ `)}Object.defineProperty(class extends Error{constructor(e,t=`Errors found while validating environment variables`){let n=y(e);super(`${v(`red`,t)}\n${m(n)}\n`),this.name=`ArkEnvError`,this.issues=e}},`name`,{value:`ArkEnvError`});function b(e){return`[ArkEnv] ${e}`}var x=e.t(((e,t)=>{let n=process||{},r=n.argv||[],i=n.env||{},a=!(i.NO_COLOR||r.includes(`--no-color`))&&(!!i.FORCE_COLOR||r.includes(`--color`)||n.platform===`win32`||(n.stdout||{}).isTTY&&i.TERM!==`dumb`||!!i.CI),o=(e,t,n=e)=>r=>{let i=``+r,a=i.indexOf(t,e.length);return~a?e+s(i,t,n,a)+t:e+i+t},s=(e,t,n,r)=>{let i=``,a=0;do i+=e.substring(a,r)+n,a=r+t.length,r=e.indexOf(t,a);while(~r);return i+e.substring(a)},c=(e=a)=>{let t=e?o:()=>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`)}};t.exports=c(),t.exports.createColors=c})),S=e.r(x(),1);const C={REQUIREMENTS_NOT_MET:`REQUIREMENTS_NOT_MET`,GIT_TREE_DIRTY:`GIT_TREE_DIRTY`,NON_EMPTY_DIR:`NON_EMPTY_DIR`,INTERNAL:`INTERNAL`};var ee=class{info(e){process.stderr.write(`${S.default.blue(`ℹ ${e}`)}\n`)}warn(e){process.stderr.write(`${S.default.yellow(`⚠ ${e}`)}\n`)}error(e){process.stderr.write(`${S.default.red(`✘ ${e}`)}\n`)}success(e){process.stderr.write(`${S.default.green(`✔ ${e}`)}\n`)}step(e){process.stderr.write(`○ ${e}\n`)}note(e,t){process.stderr.write(`${S.default.dim(`○ ${t?`${t}: `:``}${e}`)}\n`)}log(e){process.stderr.write(`${e}\n`)}spinner(){return{start:e=>process.stderr.write(`${S.default.dim(`○ ${e}...`)}\n`),stop:e=>process.stderr.write(`${S.default.green(`✔ ${e}`)}\n`),message:e=>process.stderr.write(`${S.default.dim(`○ ${e}...`)}\n`)}}json(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}cancel(e){this.json({status:`cancelled`,message:e})}fatal(e,t){let n=t instanceof Error?t.message:t?String(t):void 0;throw this.json({status:`error`,code:C.INTERNAL,message:e,retryWith:[],...n===void 0?{}:{details:{error:n}}}),t instanceof Error?t:Error(e)}refuse(e){this.json({status:`error`,code:e.code,message:e.message,retryWith:e.retryWith,...e.details===void 0?{}:{details:e.details}})}finish(e,t){this.json({status:`success`,message:e,details:t})}async flush(){return new Promise(e=>{process.stdout.write(``,()=>e())})}},w=class{stripAnsi(e){return e.replace(/\x1B\[[0-9;]*[JKmsu]/g,``)}info(e){}warn(e){}error(e){}success(e){}step(e){}note(e,t){}log(e){process.stdout.write(`${this.stripAnsi(e)}\n`)}spinner(){return{start:e=>{},stop:e=>{},message:e=>{}}}json(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}cancel(e){process.stderr.write(`✘ Cancelled: ${e}\n`)}fatal(e,t){throw process.stderr.write(`✘ Fatal: ${e}\n`),t&&process.stderr.write(`${t instanceof Error?t.stack??t.message:String(t)}\n`),t instanceof Error?t:Error(e)}refuse(e){}finish(e,t){}async flush(){return new Promise(e=>{process.stderr.write(``,()=>e())})}};const T=(()=>{let e=/[\uD800-\uDBFF][\uDC00-\uDFFF]/g;return t=>{let n=0;for(e.lastIndex=0;e.test(t);)n+=1;return t.length-n}})(),E=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,D=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,te=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,O=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,k=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,A=/\t{1,1000}/y,j=/[\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?))*/uy,ne=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,re=/\p{M}+/gu,ie={limit:1/0,ellipsis:``},ae=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?ae(i,ie,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[ne,l],[te,0],[O,o],[A,s],[j,c],[k,u]],f=0,p=0,m=e.length,h=0,g=!1,_=m,v=Math.max(0,r-a),y=0,b=0,x=0,S=0;outer:for(;;){if(b>y||p>=m&&p>f){let t=e.slice(y,b)||e.slice(f,p);h=0;for(let e of t.replaceAll(re,``)){let t=e.codePointAt(0)||0;if(S=E(t)?2:D(t)?u:l,x+S>v&&(_=Math.min(_,Math.max(y,f)+h)),x+S>r){g=!0;break outer}h+=e.length,x+=S}y=b=0}if(p>=m)break outer;for(let t=0,n=d.length;t<n;t++){let[n,i]=d[t];if(n.lastIndex=p,n.test(e)){if(h=n===k?T(e.slice(p,n.lastIndex)):n===j?1:n.lastIndex-p,S=h*i,x+S>v&&(_=Math.min(_,p+Math.floor((v-x)/i))),x+S>r){g=!0;break outer}x+=S,y=f,b=p,p=f=n.lastIndex;continue outer}}p+=1}return{width:g?v:x,index:g?_:m,truncated:g,ellipsed:g&&r>=a}},oe={limit:1/0,ellipsis:``,ellipsisWidth:0},M=(e,t={})=>ae(e,oe,t).width,se=`]8;;`,ce=RegExp(`(?:\\[(?<code>\\d+)m|\\${se}(?<uri>.*))`,`y`),le=e=>{if(e>=30&&e<=37||e>=90&&e<=97)return 39;if(e>=40&&e<=47||e>=100&&e<=107)return 49;if(e===1||e===2)return 22;if(e===3)return 23;if(e===4)return 24;if(e===7)return 27;if(e===8)return 28;if(e===9)return 29;if(e===0)return 0},ue=e=>`[${e}m`,de=e=>`${se}${e}`,fe=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:M(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=M(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===`›`)&&(i=!0,a=t.startsWith(se,u+1)),i?a?o===`\x07`&&(i=!1,a=!1):o===`m`&&(i=!1):(s+=d,s===n&&!l.done&&(e.push(``),s=0)),c=l,l=r.next(),u+=o.length}o=e.at(-1),!s&&o!==void 0&&o.length&&e.length>1&&(e[e.length-2]+=e.pop())},pe=e=>{let t=e.split(` `),n=t.length;for(;n&&!M(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},me=(e,t,n={})=>{if(n.trim!==!1&&e.trim()===``)return``;let r=``,i,a,o=e.split(` `),s=[``],c=0;for(let e=0;e<o.length;e++){let r=o[e];if(n.trim!==!1){let e=s.at(-1)??``,t=e.trimStart();e.length!==t.length&&(s[s.length-1]=t,c=M(t))}e!==0&&(c>=t&&(n.wordWrap===!1||n.trim===!1)&&(s.push(``),c=0),(c||n.trim===!1)&&(s[s.length-1]+=` `,c++));let i=M(r);if(n.hard&&i>t){let e=t-c,n=1+Math.floor((i-e-1)/t);Math.floor((i-1)/t)<n&&s.push(``),fe(s,r,t),c=M(s.at(-1)??``);continue}if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){fe(s,r,t),c=M(s.at(-1)??``);continue}s.push(``),c=0}if(c+i>t&&n.wordWrap===!1){fe(s,r,t),c=M(s.at(-1)??``);continue}s[s.length-1]+=r,c+=i}n.trim!==!1&&(s=s.map(e=>pe(e)));let l=s.join(`
6
+ `),u=!1;for(let e=0;e<l.length;e++){let t=l[e];if(r+=t,u)u=!1;else if(u=t>=`\ud800`&&t<=`\udbff`,u)continue;if(t===`\x1B`||t===`›`){ce.lastIndex=e+1;let t=ce.exec(l)?.groups;if(t?.code!==void 0){let e=Number.parseFloat(t.code);i=e===39?void 0:e}else t?.uri!==void 0&&(a=t.uri.length===0?void 0:t.uri)}if(l[e+1]===`
7
+ `){a&&(r+=de(``));let e=i?le(i):void 0;i&&e&&(r+=ue(e))}else t===`
8
+ `&&(i&&le(i)&&(r+=ue(i)),a&&(r+=de(a)))}return r},he=/\r?\n/;function N(e,t,n){return String(e).normalize().split(he).map(e=>me(e,t,n)).join(`
9
+ `)}var P=e.t(((e,t)=>{let n={to(e,t){return t?`[${t+1};${e+1}H`:`[${e+1}G`},move(e,t){let n=``;return e<0?n+=`[${-e}D`:e>0&&(n+=`[${e}C`),t<0?n+=`[${-t}A`:t>0&&(n+=`[${t}B`),n},up:(e=1)=>`[${e}A`,down:(e=1)=>`[${e}B`,forward:(e=1)=>`[${e}C`,backward:(e=1)=>`[${e}D`,nextLine:(e=1)=>`\x1B[E`.repeat(e),prevLine:(e=1)=>`\x1B[F`.repeat(e),left:`\x1B[G`,hide:`\x1B[?25l`,show:`\x1B[?25h`,save:`\x1B7`,restore:`\x1B8`};t.exports={cursor:n,scroll:{up:(e=1)=>`\x1B[S`.repeat(e),down:(e=1)=>`\x1B[T`.repeat(e)},erase:{screen:`\x1B[2J`,up:(e=1)=>`\x1B[1J`.repeat(e),down:(e=1)=>`\x1B[J`.repeat(e),line:`\x1B[2K`,lineEnd:`\x1B[K`,lineStart:`\x1B[1K`,lines(e){let t=``;for(let r=0;r<e;r++)t+=this.line+(r<e-1?n.up():``);return e&&(t+=n.left),t}},beep:`\x07`}}))();function ge(e,t,n){if(!n.some(e=>!e.disabled))return e;let r=e+t,i=Math.max(n.length-1,0),a=r<0?i:r>i?0:r;return n[a].disabled?ge(a,t<0?-1:1,n):a}const F={actions:new Set([`up`,`down`,`left`,`right`,`space`,`enter`,`cancel`]),aliases:new Map([[`k`,`up`],[`j`,`down`],[`h`,`left`],[`l`,`right`],[``,`cancel`],[`escape`,`cancel`]]),messages:{cancel:`Canceled`,error:`Something went wrong`},withGuide:!0,date:{monthNames:[...[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`]],messages:{required:`Please enter a valid date`,invalidMonth:`There are only 12 months in a year`,invalidDay:(e,t)=>`There are only ${e} days in ${t}`,afterMin:e=>`Date must be on or after ${e.toISOString().slice(0,10)}`,beforeMax:e=>`Date must be on or before ${e.toISOString().slice(0,10)}`}}};function _e(e,t){if(typeof e==`string`)return F.aliases.get(e)===t;for(let n of e)if(n!==void 0&&_e(n,t))return!0;return!1}function ve(e,t){if(e===t)return;let n=e.split(`
10
10
  `),r=t.split(`
11
- `),i=Math.max(n.length,r.length),a=[];for(let e=0;e<i;e++)n[e]!==r[e]&&a.push(e);return{lines:a,numLinesBefore:n.length,numLinesAfter:r.length,numLines:i}}const we=globalThis.process.platform.startsWith(`win`),Te=Symbol(`clack:cancel`);function I(e){return e===Te}function L(e,t){let n=e;n.isTTY&&n.setRawMode(t)}function Ee({input:e=r.stdin,output:t=r.stdout,overwrite:n=!0,hideCursor:o=!0}={}){let s=i.createInterface({input:e,output:t,prompt:``,tabSize:1});i.emitKeypressEvents(e,s),e instanceof a.ReadStream&&e.isTTY&&e.setRawMode(!0);let c=(r,{name:a,sequence:s})=>{if(Se([String(r),a,s],`cancel`)){o&&t.write(P.cursor.show),process.exit(0);return}if(!n)return;let l=a===`return`?0:-1,u=a===`return`?-1:0;i.moveCursor(t,l,u,()=>{i.clearLine(t,1,()=>{e.once(`keypress`,c)})})};return o&&t.write(P.cursor.hide),e.once(`keypress`,c),()=>{e.off(`keypress`,c),o&&t.write(P.cursor.show),e instanceof a.ReadStream&&e.isTTY&&!we&&e.setRawMode(!1),s.terminal=!1,s.close()}}const R=e=>`columns`in e&&typeof e.columns==`number`?e.columns:80,De=e=>`rows`in e&&typeof e.rows==`number`?e.rows:20;function z(e,t,n,i=n,a){return N(t,R(e??r.stdout)-n.length,{hard:!0,trim:!1}).split(`
11
+ `),i=Math.max(n.length,r.length),a=[];for(let e=0;e<i;e++)n[e]!==r[e]&&a.push(e);return{lines:a,numLinesBefore:n.length,numLinesAfter:r.length,numLines:i}}const ye=globalThis.process.platform.startsWith(`win`),be=Symbol(`clack:cancel`);function I(e){return e===be}function xe(e,t){let n=e;n.isTTY&&n.setRawMode(t)}function Se({input:e=r.stdin,output:t=r.stdout,overwrite:n=!0,hideCursor:o=!0}={}){let s=i.createInterface({input:e,output:t,prompt:``,tabSize:1});i.emitKeypressEvents(e,s),e instanceof a.ReadStream&&e.isTTY&&e.setRawMode(!0);let c=(r,{name:a,sequence:s})=>{if(_e([String(r),a,s],`cancel`)){o&&t.write(P.cursor.show),process.exit(0);return}if(!n)return;let l=a===`return`?0:-1,u=a===`return`?-1:0;i.moveCursor(t,l,u,()=>{i.clearLine(t,1,()=>{e.once(`keypress`,c)})})};return o&&t.write(P.cursor.hide),e.once(`keypress`,c),()=>{e.off(`keypress`,c),o&&t.write(P.cursor.show),e instanceof a.ReadStream&&e.isTTY&&!ye&&e.setRawMode(!1),s.terminal=!1,s.close()}}const Ce=e=>`columns`in e&&typeof e.columns==`number`?e.columns:80,we=e=>`rows`in e&&typeof e.rows==`number`?e.rows:20;function Te(e,t,n,i=n,a){return N(t,Ce(e??r.stdout)-n.length,{hard:!0,trim:!1}).split(`
12
12
  `).map((e,t)=>{let r=a?a(e,t):e;return`${t===0?i:n}${r}`}).join(`
13
- `)}let Oe=class{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame=``;_subscribers=new Map;_cursor=0;state=`initial`;error=``;value;userInput=``;constructor(e,t=!0){let{input:n=r.stdin,output:i=r.stdout,render:a,signal:o,...s}=e;this.opts=s,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=a.bind(this),this._track=t,this._abortSignal=o,this.input=n,this.output=i}unsubscribe(){this._subscribers.clear()}setSubscriber(e,t){let n=this._subscribers.get(e)??[];n.push(t),this._subscribers.set(e,n)}on(e,t){this.setSubscriber(e,{cb:t})}once(e,t){this.setSubscriber(e,{cb:t,once:!0})}emit(e,...t){let n=this._subscribers.get(e)??[],r=[];for(let e of n)e.cb(...t),e.once&&r.push(()=>n.splice(n.indexOf(e),1));for(let e of r)e()}prompt(){return new Promise(e=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state=`cancel`,this.close(),e(Te);this._abortSignal.addEventListener(`abort`,()=>{this.state=`cancel`,this.close()},{once:!0})}this.rl=i.default.createInterface({input:this.input,tabSize:2,prompt:``,escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on(`keypress`,this.onKeypress),L(this.input,!0),this.output.on(`resize`,this.render),this.render(),this.once(`submit`,()=>{this.output.write(P.cursor.show),this.output.off(`resize`,this.render),L(this.input,!1),e(this.value)}),this.once(`cancel`,()=>{this.output.write(P.cursor.show),this.output.off(`resize`,this.render),L(this.input,!1),e(Te)})})}_isActionKey(e,t){return e===` `}_shouldSubmit(e,t){return!0}_setValue(e){this.value=e,this.emit(`value`,this.value)}_setUserInput(e,t){this.userInput=e??``,this.emit(`userInput`,this.userInput),t&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:`u`}),this._setUserInput(``)}onKeypress(e,t){if(this._track&&t.name!==`return`&&(t.name&&this._isActionKey(e,t)&&this.rl?.write(null,{ctrl:!0,name:`h`}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state===`error`&&(this.state=`active`),t?.name&&(!this._track&&F.aliases.has(t.name)&&this.emit(`cursor`,F.aliases.get(t.name)),F.actions.has(t.name)&&this.emit(`cursor`,t.name)),e&&(e.toLowerCase()===`y`||e.toLowerCase()===`n`)&&this.emit(`confirm`,e.toLowerCase()===`y`),this.emit(`key`,e?.toLowerCase(),t),t?.name===`return`&&this._shouldSubmit(e,t)){if(this.opts.validate){let e=this.opts.validate(this.value);e&&(this.error=e instanceof Error?e.message:e,this.state=`error`,this.rl?.write(this.userInput))}this.state!==`error`&&(this.state=`submit`)}Se([e,t?.name,t?.sequence],`cancel`)&&(this.state=`cancel`),(this.state===`submit`||this.state===`cancel`)&&this.emit(`finalize`),this.render(),(this.state===`submit`||this.state===`cancel`)&&this.close()}close(){this.input.unpipe(),this.input.removeListener(`keypress`,this.onKeypress),this.output.write(`
14
- `),L(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=N(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
15
- `).length-1;this.output.write(P.cursor.move(-999,e*-1))}render(){let e=N(this._render(this)??``,process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state===`initial`)this.output.write(P.cursor.hide);else{let t=Ce(this._prevFrame,e),n=De(this.output);if(this.restoreCursor(),t){let r=Math.max(0,t.numLinesAfter-n),i=Math.max(0,t.numLinesBefore-n),a=t.lines.find(e=>e>=r);if(a===void 0){this._prevFrame=e;return}if(t.lines.length===1){this.output.write(P.cursor.move(0,a-i)),this.output.write(P.erase.lines(1));let t=e.split(`
13
+ `)}let Ee=class{input;output;_abortSignal;rl;opts;_render;_track=!1;_prevFrame=``;_subscribers=new Map;_cursor=0;state=`initial`;error=``;value;userInput=``;constructor(e,t=!0){let{input:n=r.stdin,output:i=r.stdout,render:a,signal:o,...s}=e;this.opts=s,this.onKeypress=this.onKeypress.bind(this),this.close=this.close.bind(this),this.render=this.render.bind(this),this._render=a.bind(this),this._track=t,this._abortSignal=o,this.input=n,this.output=i}unsubscribe(){this._subscribers.clear()}setSubscriber(e,t){let n=this._subscribers.get(e)??[];n.push(t),this._subscribers.set(e,n)}on(e,t){this.setSubscriber(e,{cb:t})}once(e,t){this.setSubscriber(e,{cb:t,once:!0})}emit(e,...t){let n=this._subscribers.get(e)??[],r=[];for(let e of n)e.cb(...t),e.once&&r.push(()=>n.splice(n.indexOf(e),1));for(let e of r)e()}prompt(){return new Promise(e=>{if(this._abortSignal){if(this._abortSignal.aborted)return this.state=`cancel`,this.close(),e(be);this._abortSignal.addEventListener(`abort`,()=>{this.state=`cancel`,this.close()},{once:!0})}this.rl=i.default.createInterface({input:this.input,tabSize:2,prompt:``,escapeCodeTimeout:50,terminal:!0}),this.rl.prompt(),this.opts.initialUserInput!==void 0&&this._setUserInput(this.opts.initialUserInput,!0),this.input.on(`keypress`,this.onKeypress),xe(this.input,!0),this.output.on(`resize`,this.render),this.render(),this.once(`submit`,()=>{this.output.write(P.cursor.show),this.output.off(`resize`,this.render),xe(this.input,!1),e(this.value)}),this.once(`cancel`,()=>{this.output.write(P.cursor.show),this.output.off(`resize`,this.render),xe(this.input,!1),e(be)})})}_isActionKey(e,t){return e===` `}_shouldSubmit(e,t){return!0}_setValue(e){this.value=e,this.emit(`value`,this.value)}_setUserInput(e,t){this.userInput=e??``,this.emit(`userInput`,this.userInput),t&&this._track&&this.rl&&(this.rl.write(this.userInput),this._cursor=this.rl.cursor)}_clearUserInput(){this.rl?.write(null,{ctrl:!0,name:`u`}),this._setUserInput(``)}onKeypress(e,t){if(this._track&&t.name!==`return`&&(t.name&&this._isActionKey(e,t)&&this.rl?.write(null,{ctrl:!0,name:`h`}),this._cursor=this.rl?.cursor??0,this._setUserInput(this.rl?.line)),this.state===`error`&&(this.state=`active`),t?.name&&(!this._track&&F.aliases.has(t.name)&&this.emit(`cursor`,F.aliases.get(t.name)),F.actions.has(t.name)&&this.emit(`cursor`,t.name)),e&&(e.toLowerCase()===`y`||e.toLowerCase()===`n`)&&this.emit(`confirm`,e.toLowerCase()===`y`),this.emit(`key`,e?.toLowerCase(),t),t?.name===`return`&&this._shouldSubmit(e,t)){if(this.opts.validate){let e=this.opts.validate(this.value);e&&(this.error=e instanceof Error?e.message:e,this.state=`error`,this.rl?.write(this.userInput))}this.state!==`error`&&(this.state=`submit`)}_e([e,t?.name,t?.sequence],`cancel`)&&(this.state=`cancel`),(this.state===`submit`||this.state===`cancel`)&&this.emit(`finalize`),this.render(),(this.state===`submit`||this.state===`cancel`)&&this.close()}close(){this.input.unpipe(),this.input.removeListener(`keypress`,this.onKeypress),this.output.write(`
14
+ `),xe(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=N(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
15
+ `).length-1;this.output.write(P.cursor.move(-999,e*-1))}render(){let e=N(this._render(this)??``,process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state===`initial`)this.output.write(P.cursor.hide);else{let t=ve(this._prevFrame,e),n=we(this.output);if(this.restoreCursor(),t){let r=Math.max(0,t.numLinesAfter-n),i=Math.max(0,t.numLinesBefore-n),a=t.lines.find(e=>e>=r);if(a===void 0){this._prevFrame=e;return}if(t.lines.length===1){this.output.write(P.cursor.move(0,a-i)),this.output.write(P.erase.lines(1));let t=e.split(`
16
16
  `);this.output.write(t[a]),this._prevFrame=e,this.output.write(P.cursor.move(0,t.length-a-1));return}else if(t.lines.length>1){if(r<i)a=r;else{let e=a-i;e>0&&this.output.write(P.cursor.move(0,e))}this.output.write(P.erase.down());let t=e.split(`
17
17
  `).slice(a);this.output.write(t.join(`
18
- `)),this._prevFrame=e;return}}this.output.write(P.erase.down())}this.output.write(e),this.state===`initial`&&(this.state=`active`),this._prevFrame=e}}};var ke=class extends Oe{get cursor(){return+!this.value}get _value(){return this.cursor===0}constructor(e){super(e,!1),this.value=!!e.initialValue,this.on(`userInput`,()=>{this.value=this._value}),this.on(`confirm`,e=>{this.output.write(P.cursor.move(0,-1)),this.value=e,this.state=`submit`,this.close()}),this.on(`cursor`,()=>{this.value=!this.value})}},Ae=class extends Oe{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}constructor(e){super(e,!1),this.options=e.options;let t=this.options.findIndex(({value:t})=>t===e.initialValue),n=t===-1?0:t;this.cursor=this.options[n].disabled?xe(n,1,this.options):n,this.changeValue(),this.on(`cursor`,e=>{switch(e){case`left`:case`up`:this.cursor=xe(this.cursor,-1,this.options);break;case`down`:case`right`:this.cursor=xe(this.cursor,1,this.options);break}this.changeValue()})}},je=class extends Oe{get userInputWithCursor(){if(this.state===`submit`)return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${this.userInput}\u2588`;let t=e.slice(0,this.cursor),[r,...i]=e.slice(this.cursor);return`${t}${(0,n.styleText)(`inverse`,r)}${i.join(``)}`}get cursor(){return this._cursor}constructor(e){super({...e,initialUserInput:e.initialUserInput??e.initialValue}),this.on(`userInput`,e=>{this._setValue(e)}),this.on(`finalize`,()=>{this.value||=e.defaultValue,this.value===void 0&&(this.value=``)})}};function Me(){return r.default.platform===`win32`?!!r.default.env.CI||!!r.default.env.WT_SESSION||!!r.default.env.TERMINUS_SUBLIME||r.default.env.ConEmuTask===`{cmd::Cmder}`||r.default.env.TERM_PROGRAM===`Terminus-Sublime`||r.default.env.TERM_PROGRAM===`vscode`||r.default.env.TERM===`xterm-256color`||r.default.env.TERM===`alacritty`||r.default.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:r.default.env.TERM!==`linux`}const Ne=Me(),Pe=()=>process.env.CI===`true`,B=(e,t)=>Ne?e:t,Fe=B(`◆`,`*`),Ie=B(`■`,`x`),Le=B(`▲`,`x`),V=B(`◇`,`o`),H=B(`│`,`|`),U=B(`└`,`—`),Re=B(`●`,`>`),W=B(`○`,` `),ze=B(`─`,`-`),Be=B(`╮`,`+`),Ve=B(`├`,`+`),He=B(`╯`,`+`),Ue=B(`╰`,`+`),We=B(`●`,`•`),Ge=B(`◆`,`*`),Ke=B(`▲`,`!`),qe=B(`■`,`x`),Je=e=>{switch(e){case`initial`:case`active`:return(0,n.styleText)(`cyan`,Fe);case`cancel`:return(0,n.styleText)(`red`,Ie);case`error`:return(0,n.styleText)(`yellow`,Le);case`submit`:return(0,n.styleText)(`green`,V)}},Ye=e=>{switch(e){case`initial`:case`active`:return(0,n.styleText)(`cyan`,H);case`cancel`:return(0,n.styleText)(`red`,H);case`error`:return(0,n.styleText)(`yellow`,H);case`submit`:return(0,n.styleText)(`green`,H)}},Xe=(e,t,n,r,i)=>{let a=t,o=0;for(let t=n;t<r;t++){let n=e[t];if(a-=n.length,o++,a<=i)break}return{lineCount:a,removals:o}},Ze=({cursor:e,options:t,style:r,output:i=process.stdout,maxItems:a=1/0,columnPadding:o=0,rowPadding:s=4})=>{let c=R(i)-o,l=De(i),u=(0,n.styleText)(`dim`,`...`),d=Math.max(l-s,0),f=Math.max(Math.min(a,d),5),p=0;e>=f-3&&(p=Math.max(Math.min(e-f+3,t.length-f),0));let m=f<t.length&&p>0,h=f<t.length&&p+f<t.length,g=Math.min(p+f,t.length),_=[],v=0;m&&v++,h&&v++;let y=p+ +!!m,b=g-+!!h;for(let n=y;n<b;n++){let i=N(r(t[n],n===e),c,{hard:!0,trim:!1}).split(`
19
- `);_.push(i),v+=i.length}if(v>d){let t=0,n=0,r=v,i=e-y,a=(e,t)=>Xe(_,r,e,t,d);m?({lineCount:r,removals:t}=a(0,i),r>d&&({lineCount:r,removals:n}=a(i+1,_.length))):({lineCount:r,removals:n}=a(i+1,_.length),r>d&&({lineCount:r,removals:t}=a(0,i))),t>0&&(m=!0,_.splice(0,t)),n>0&&(h=!0,_.splice(_.length-n,n))}let x=[];m&&x.push(u);for(let e of _)for(let t of e)x.push(t);return h&&x.push(u),x},G=e=>{let t=e.active??`Yes`,r=e.inactive??`No`;return new ke({active:t,inactive:r,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let i=e.withGuide??F.withGuide,a=`${Je(this.state)} `,o=i?`${(0,n.styleText)(`gray`,H)} `:``,s=z(e.output,e.message,o,a),c=`${i?`${(0,n.styleText)(`gray`,H)}
18
+ `)),this._prevFrame=e;return}}this.output.write(P.erase.down())}this.output.write(e),this.state===`initial`&&(this.state=`active`),this._prevFrame=e}}};var De=class extends Ee{get cursor(){return+!this.value}get _value(){return this.cursor===0}constructor(e){super(e,!1),this.value=!!e.initialValue,this.on(`userInput`,()=>{this.value=this._value}),this.on(`confirm`,e=>{this.output.write(P.cursor.move(0,-1)),this.value=e,this.state=`submit`,this.close()}),this.on(`cursor`,()=>{this.value=!this.value})}},Oe=class extends Ee{options;cursor=0;get _selectedValue(){return this.options[this.cursor]}changeValue(){this.value=this._selectedValue.value}constructor(e){super(e,!1),this.options=e.options;let t=this.options.findIndex(({value:t})=>t===e.initialValue),n=t===-1?0:t;this.cursor=this.options[n].disabled?ge(n,1,this.options):n,this.changeValue(),this.on(`cursor`,e=>{switch(e){case`left`:case`up`:this.cursor=ge(this.cursor,-1,this.options);break;case`down`:case`right`:this.cursor=ge(this.cursor,1,this.options);break}this.changeValue()})}},ke=class extends Ee{get userInputWithCursor(){if(this.state===`submit`)return this.userInput;let e=this.userInput;if(this.cursor>=e.length)return`${this.userInput}\u2588`;let t=e.slice(0,this.cursor),[r,...i]=e.slice(this.cursor);return`${t}${(0,n.styleText)(`inverse`,r)}${i.join(``)}`}get cursor(){return this._cursor}constructor(e){super({...e,initialUserInput:e.initialUserInput??e.initialValue}),this.on(`userInput`,e=>{this._setValue(e)}),this.on(`finalize`,()=>{this.value||=e.defaultValue,this.value===void 0&&(this.value=``)})}};function Ae(){return r.default.platform===`win32`?!!r.default.env.CI||!!r.default.env.WT_SESSION||!!r.default.env.TERMINUS_SUBLIME||r.default.env.ConEmuTask===`{cmd::Cmder}`||r.default.env.TERM_PROGRAM===`Terminus-Sublime`||r.default.env.TERM_PROGRAM===`vscode`||r.default.env.TERM===`xterm-256color`||r.default.env.TERM===`alacritty`||r.default.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:r.default.env.TERM!==`linux`}const je=Ae(),Me=()=>process.env.CI===`true`,L=(e,t)=>je?e:t,Ne=L(`◆`,`*`),Pe=L(`■`,`x`),Fe=L(`▲`,`x`),R=L(`◇`,`o`),z=L(`│`,`|`),B=L(`└`,`—`),Ie=L(`●`,`>`),V=L(`○`,` `),Le=L(`─`,`-`),Re=L(`╮`,`+`),ze=L(`├`,`+`),Be=L(`╯`,`+`),Ve=L(`╰`,`+`),He=L(`●`,`•`),Ue=L(`◆`,`*`),We=L(`▲`,`!`),Ge=L(`■`,`x`),Ke=e=>{switch(e){case`initial`:case`active`:return(0,n.styleText)(`cyan`,Ne);case`cancel`:return(0,n.styleText)(`red`,Pe);case`error`:return(0,n.styleText)(`yellow`,Fe);case`submit`:return(0,n.styleText)(`green`,R)}},qe=e=>{switch(e){case`initial`:case`active`:return(0,n.styleText)(`cyan`,z);case`cancel`:return(0,n.styleText)(`red`,z);case`error`:return(0,n.styleText)(`yellow`,z);case`submit`:return(0,n.styleText)(`green`,z)}},Je=(e,t,n,r,i)=>{let a=t,o=0;for(let t=n;t<r;t++){let n=e[t];if(a-=n.length,o++,a<=i)break}return{lineCount:a,removals:o}},Ye=({cursor:e,options:t,style:r,output:i=process.stdout,maxItems:a=1/0,columnPadding:o=0,rowPadding:s=4})=>{let c=Ce(i)-o,l=we(i),u=(0,n.styleText)(`dim`,`...`),d=Math.max(l-s,0),f=Math.max(Math.min(a,d),5),p=0;e>=f-3&&(p=Math.max(Math.min(e-f+3,t.length-f),0));let m=f<t.length&&p>0,h=f<t.length&&p+f<t.length,g=Math.min(p+f,t.length),_=[],v=0;m&&v++,h&&v++;let y=p+ +!!m,b=g-+!!h;for(let n=y;n<b;n++){let i=N(r(t[n],n===e),c,{hard:!0,trim:!1}).split(`
19
+ `);_.push(i),v+=i.length}if(v>d){let t=0,n=0,r=v,i=e-y,a=(e,t)=>Je(_,r,e,t,d);m?({lineCount:r,removals:t}=a(0,i),r>d&&({lineCount:r,removals:n}=a(i+1,_.length))):({lineCount:r,removals:n}=a(i+1,_.length),r>d&&({lineCount:r,removals:t}=a(0,i))),t>0&&(m=!0,_.splice(0,t)),n>0&&(h=!0,_.splice(_.length-n,n))}let x=[];m&&x.push(u);for(let e of _)for(let t of e)x.push(t);return h&&x.push(u),x},H=e=>{let t=e.active??`Yes`,r=e.inactive??`No`;return new De({active:t,inactive:r,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let i=e.withGuide??F.withGuide,a=`${Ke(this.state)} `,o=i?`${(0,n.styleText)(`gray`,z)} `:``,s=Te(e.output,e.message,o,a),c=`${i?`${(0,n.styleText)(`gray`,z)}
20
20
  `:``}${s}
21
- `,l=this.value?t:r;switch(this.state){case`submit`:return`${c}${i?`${(0,n.styleText)(`gray`,H)} `:``}${(0,n.styleText)(`dim`,l)}`;case`cancel`:return`${c}${i?`${(0,n.styleText)(`gray`,H)} `:``}${(0,n.styleText)([`strikethrough`,`dim`],l)}${i?`
22
- ${(0,n.styleText)(`gray`,H)}`:``}`;default:{let a=i?`${(0,n.styleText)(`cyan`,H)} `:``,o=i?(0,n.styleText)(`cyan`,U):``;return`${c}${a}${this.value?`${(0,n.styleText)(`green`,Re)} ${t}`:`${(0,n.styleText)(`dim`,W)} ${(0,n.styleText)(`dim`,t)}`}${e.vertical?i?`
23
- ${(0,n.styleText)(`cyan`,H)} `:`
24
- `:` ${(0,n.styleText)(`dim`,`/`)} `}${this.value?`${(0,n.styleText)(`dim`,W)} ${(0,n.styleText)(`dim`,r)}`:`${(0,n.styleText)(`green`,Re)} ${r}`}
21
+ `,l=this.value?t:r;switch(this.state){case`submit`:return`${c}${i?`${(0,n.styleText)(`gray`,z)} `:``}${(0,n.styleText)(`dim`,l)}`;case`cancel`:return`${c}${i?`${(0,n.styleText)(`gray`,z)} `:``}${(0,n.styleText)([`strikethrough`,`dim`],l)}${i?`
22
+ ${(0,n.styleText)(`gray`,z)}`:``}`;default:{let a=i?`${(0,n.styleText)(`cyan`,z)} `:``,o=i?(0,n.styleText)(`cyan`,B):``;return`${c}${a}${this.value?`${(0,n.styleText)(`green`,Ie)} ${t}`:`${(0,n.styleText)(`dim`,V)} ${(0,n.styleText)(`dim`,t)}`}${e.vertical?i?`
23
+ ${(0,n.styleText)(`cyan`,z)} `:`
24
+ `:` ${(0,n.styleText)(`dim`,`/`)} `}${this.value?`${(0,n.styleText)(`dim`,V)} ${(0,n.styleText)(`dim`,r)}`:`${(0,n.styleText)(`green`,Ie)} ${r}`}
25
25
  ${o}
26
- `}}}}).prompt()},K={message:(e=[],{symbol:t=(0,n.styleText)(`gray`,H),secondarySymbol:r=(0,n.styleText)(`gray`,H),output:i=process.stdout,spacing:a=1,withGuide:o}={})=>{let s=[],c=o??F.withGuide,l=c?r:``,u=c?`${t} `:``,d=c?`${r} `:``;for(let e=0;e<a;e++)s.push(l);let f=Array.isArray(e)?e:e.split(`
26
+ `}}}}).prompt()},U={message:(e=[],{symbol:t=(0,n.styleText)(`gray`,z),secondarySymbol:r=(0,n.styleText)(`gray`,z),output:i=process.stdout,spacing:a=1,withGuide:o}={})=>{let s=[],c=o??F.withGuide,l=c?r:``,u=c?`${t} `:``,d=c?`${r} `:``;for(let e=0;e<a;e++)s.push(l);let f=Array.isArray(e)?e:e.split(`
27
27
  `);if(f.length>0){let[e,...n]=f;e.length>0?s.push(`${u}${e}`):s.push(c?t:``);for(let e of n)e.length>0?s.push(`${d}${e}`):s.push(c?r:``)}i.write(`${s.join(`
28
28
  `)}
29
- `)},info:(e,t)=>{K.message(e,{...t,symbol:(0,n.styleText)(`blue`,We)})},success:(e,t)=>{K.message(e,{...t,symbol:(0,n.styleText)(`green`,Ge)})},step:(e,t)=>{K.message(e,{...t,symbol:(0,n.styleText)(`green`,V)})},warn:(e,t)=>{K.message(e,{...t,symbol:(0,n.styleText)(`yellow`,Ke)})},warning:(e,t)=>{K.warn(e,t)},error:(e,t)=>{K.message(e,{...t,symbol:(0,n.styleText)(`red`,qe)})}},Qe=(e=``,t)=>{let r=t?.output??process.stdout,i=t?.withGuide??F.withGuide?`${(0,n.styleText)(`gray`,U)} `:``;r.write(`${i}${(0,n.styleText)(`red`,e)}
29
+ `)},info:(e,t)=>{U.message(e,{...t,symbol:(0,n.styleText)(`blue`,He)})},success:(e,t)=>{U.message(e,{...t,symbol:(0,n.styleText)(`green`,Ue)})},step:(e,t)=>{U.message(e,{...t,symbol:(0,n.styleText)(`green`,R)})},warn:(e,t)=>{U.message(e,{...t,symbol:(0,n.styleText)(`yellow`,We)})},warning:(e,t)=>{U.warn(e,t)},error:(e,t)=>{U.message(e,{...t,symbol:(0,n.styleText)(`red`,Ge)})}},Xe=(e=``,t)=>{let r=t?.output??process.stdout,i=t?.withGuide??F.withGuide?`${(0,n.styleText)(`gray`,B)} `:``;r.write(`${i}${(0,n.styleText)(`red`,e)}
30
30
 
31
- `)},$e=(e=``,t)=>{let r=t?.output??process.stdout,i=t?.withGuide??F.withGuide?`${(0,n.styleText)(`gray`,H)}
32
- ${(0,n.styleText)(`gray`,U)} `:``;r.write(`${i}${e}
31
+ `)},Ze=(e=``,t)=>{let r=t?.output??process.stdout,i=t?.withGuide??F.withGuide?`${(0,n.styleText)(`gray`,z)}
32
+ ${(0,n.styleText)(`gray`,B)} `:``;r.write(`${i}${e}
33
33
 
34
- `)},et=e=>(0,n.styleText)(`dim`,e),tt=(e,t,n)=>{let r={hard:!0,trim:!1},i=N(e,t,r).split(`
35
- `),a=i.reduce((e,t)=>Math.max(M(t),e),0);return N(e,t-(i.map(n).reduce((e,t)=>Math.max(M(t),e),0)-a),r)},nt=(e=``,t=``,i)=>{let a=i?.output??r.default.stdout,o=i?.withGuide??F.withGuide,s=i?.format??et,c=[``,...tt(e,R(a)-6,s).split(`
36
- `).map(s),``],l=M(t),u=Math.max(c.reduce((e,t)=>{let n=M(t);return n>e?n:e},0),l)+2,d=c.map(e=>`${(0,n.styleText)(`gray`,H)} ${e}${` `.repeat(u-M(e))}${(0,n.styleText)(`gray`,H)}`).join(`
37
- `),f=o?`${(0,n.styleText)(`gray`,H)}
38
- `:``,p=o?Ve:Ue;a.write(`${f}${(0,n.styleText)(`green`,V)} ${(0,n.styleText)(`reset`,t)} ${(0,n.styleText)(`gray`,ze.repeat(Math.max(u-l-1,1))+Be)}
34
+ `)},Qe=e=>(0,n.styleText)(`dim`,e),$e=(e,t,n)=>{let r={hard:!0,trim:!1},i=N(e,t,r).split(`
35
+ `),a=i.reduce((e,t)=>Math.max(M(t),e),0);return N(e,t-(i.map(n).reduce((e,t)=>Math.max(M(t),e),0)-a),r)},et=(e=``,t=``,i)=>{let a=i?.output??r.default.stdout,o=i?.withGuide??F.withGuide,s=i?.format??Qe,c=[``,...$e(e,Ce(a)-6,s).split(`
36
+ `).map(s),``],l=M(t),u=Math.max(c.reduce((e,t)=>{let n=M(t);return n>e?n:e},0),l)+2,d=c.map(e=>`${(0,n.styleText)(`gray`,z)} ${e}${` `.repeat(u-M(e))}${(0,n.styleText)(`gray`,z)}`).join(`
37
+ `),f=o?`${(0,n.styleText)(`gray`,z)}
38
+ `:``,p=o?ze:Ve;a.write(`${f}${(0,n.styleText)(`green`,R)} ${(0,n.styleText)(`reset`,t)} ${(0,n.styleText)(`gray`,Le.repeat(Math.max(u-l-1,1))+Re)}
39
39
  ${d}
40
- ${(0,n.styleText)(`gray`,p+ze.repeat(u+2)+He)}
41
- `)},rt=e=>(0,n.styleText)(`magenta`,e),it=({indicator:e=`dots`,onCancel:t,output:r=process.stdout,cancelMessage:i,errorMessage:a,frames:o=Ne?[`◒`,`◐`,`◓`,`◑`]:[`•`,`o`,`O`,`0`],delay:s=Ne?80:120,signal:c,...l}={})=>{let u=Pe(),d,f,p=!1,m=!1,h=``,g,_=performance.now(),v=R(r),y=l?.styleFrame??rt,b=e=>{let n=e>1?a??F.messages.error:i??F.messages.cancel;m=e===1,p&&(k(n,e),m&&typeof t==`function`&&t())},x=()=>b(2),S=()=>b(1),C=()=>{process.on(`uncaughtExceptionMonitor`,x),process.on(`unhandledRejection`,x),process.on(`SIGINT`,S),process.on(`SIGTERM`,S),process.on(`exit`,b),c&&c.addEventListener(`abort`,S)},w=()=>{process.removeListener(`uncaughtExceptionMonitor`,x),process.removeListener(`unhandledRejection`,x),process.removeListener(`SIGINT`,S),process.removeListener(`SIGTERM`,S),process.removeListener(`exit`,b),c&&c.removeEventListener(`abort`,S)},ee=()=>{if(g===void 0)return;u&&r.write(`
40
+ ${(0,n.styleText)(`gray`,p+Le.repeat(u+2)+Be)}
41
+ `)},tt=e=>(0,n.styleText)(`magenta`,e),nt=({indicator:e=`dots`,onCancel:t,output:r=process.stdout,cancelMessage:i,errorMessage:a,frames:o=je?[`◒`,`◐`,`◓`,`◑`]:[`•`,`o`,`O`,`0`],delay:s=je?80:120,signal:c,...l}={})=>{let u=Me(),d,f,p=!1,m=!1,h=``,g,_=performance.now(),v=Ce(r),y=l?.styleFrame??tt,b=e=>{let n=e>1?a??F.messages.error:i??F.messages.cancel;m=e===1,p&&(O(n,e),m&&typeof t==`function`&&t())},x=()=>b(2),S=()=>b(1),C=()=>{process.on(`uncaughtExceptionMonitor`,x),process.on(`unhandledRejection`,x),process.on(`SIGINT`,S),process.on(`SIGTERM`,S),process.on(`exit`,b),c&&c.addEventListener(`abort`,S)},ee=()=>{process.removeListener(`uncaughtExceptionMonitor`,x),process.removeListener(`unhandledRejection`,x),process.removeListener(`SIGINT`,S),process.removeListener(`SIGTERM`,S),process.removeListener(`exit`,b),c&&c.removeEventListener(`abort`,S)},w=()=>{if(g===void 0)return;u&&r.write(`
42
42
  `);let e=N(g,v,{hard:!0,trim:!1}).split(`
43
- `);e.length>1&&r.write(P.cursor.up(e.length-1)),r.write(P.cursor.to(0)),r.write(P.erase.down())},T=e=>e.replace(/\.+$/,``),E=e=>{let t=(performance.now()-e)/1e3,n=Math.floor(t/60),r=Math.floor(t%60);return n>0?`[${n}m ${r}s]`:`[${r}s]`},D=l.withGuide??F.withGuide,O=(t=``)=>{p=!0,d=Ee({output:r}),h=T(t),_=performance.now(),D&&r.write(`${(0,n.styleText)(`gray`,H)}
44
- `);let i=0,a=0;C(),f=setInterval(()=>{if(u&&h===g)return;ee(),g=h;let t=y(o[i]),n;if(u)n=`${t} ${h}...`;else if(e===`timer`)n=`${t} ${h} ${E(_)}`;else{let e=`.`.repeat(Math.floor(a)).slice(0,3);n=`${t} ${h}${e}`}let s=N(n,v,{hard:!0,trim:!1});r.write(s),i=i+1<o.length?i+1:0,a=a<4?a+.125:0},s)},k=(t=``,i=0,a=!1)=>{if(!p)return;p=!1,clearInterval(f),ee();let o=i===0?(0,n.styleText)(`green`,V):i===1?(0,n.styleText)(`red`,Ie):(0,n.styleText)(`red`,Le);h=t??h,a||(e===`timer`?r.write(`${o} ${h} ${E(_)}
43
+ `);e.length>1&&r.write(P.cursor.up(e.length-1)),r.write(P.cursor.to(0)),r.write(P.erase.down())},T=e=>e.replace(/\.+$/,``),E=e=>{let t=(performance.now()-e)/1e3,n=Math.floor(t/60),r=Math.floor(t%60);return n>0?`[${n}m ${r}s]`:`[${r}s]`},D=l.withGuide??F.withGuide,te=(t=``)=>{p=!0,d=Se({output:r}),h=T(t),_=performance.now(),D&&r.write(`${(0,n.styleText)(`gray`,z)}
44
+ `);let i=0,a=0;C(),f=setInterval(()=>{if(u&&h===g)return;w(),g=h;let t=y(o[i]),n;if(u)n=`${t} ${h}...`;else if(e===`timer`)n=`${t} ${h} ${E(_)}`;else{let e=`.`.repeat(Math.floor(a)).slice(0,3);n=`${t} ${h}${e}`}let s=N(n,v,{hard:!0,trim:!1});r.write(s),i=i+1<o.length?i+1:0,a=a<4?a+.125:0},s)},O=(t=``,i=0,a=!1)=>{if(!p)return;p=!1,clearInterval(f),w();let o=i===0?(0,n.styleText)(`green`,R):i===1?(0,n.styleText)(`red`,Pe):(0,n.styleText)(`red`,Fe);h=t??h,a||(e===`timer`?r.write(`${o} ${h} ${E(_)}
45
45
  `):r.write(`${o} ${h}
46
- `)),w(),d()};return{start:O,stop:(e=``)=>k(e,0),message:(e=``)=>{h=T(e??h)},cancel:(e=``)=>k(e,1),error:(e=``)=>k(e,2),clear:()=>k(``,0,!0),get isCancelled(){return m}}},q=(e,t)=>e.includes(`
46
+ `)),ee(),d()};return{start:te,stop:(e=``)=>O(e,0),message:(e=``)=>{h=T(e??h)},cancel:(e=``)=>O(e,1),error:(e=``)=>O(e,2),clear:()=>O(``,0,!0),get isCancelled(){return m}}},rt=(e,t)=>e.includes(`
47
47
  `)?e.split(`
48
48
  `).map(e=>t(e)).join(`
49
- `):t(e),J=e=>{let t=(e,t)=>{let r=e.label??String(e.value);switch(t){case`disabled`:return`${(0,n.styleText)(`gray`,W)} ${q(r,e=>(0,n.styleText)(`gray`,e))}${e.hint?` ${(0,n.styleText)(`dim`,`(${e.hint??`disabled`})`)}`:``}`;case`selected`:return`${q(r,e=>(0,n.styleText)(`dim`,e))}`;case`active`:return`${(0,n.styleText)(`green`,Re)} ${r}${e.hint?` ${(0,n.styleText)(`dim`,`(${e.hint})`)}`:``}`;case`cancelled`:return`${q(r,e=>(0,n.styleText)([`strikethrough`,`dim`],e))}`;default:return`${(0,n.styleText)(`dim`,W)} ${q(r,e=>(0,n.styleText)(`dim`,e))}`}};return new Ae({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let r=e.withGuide??F.withGuide,i=`${Je(this.state)} `,a=`${Ye(this.state)} `,o=z(e.output,e.message,a,i),s=`${r?`${(0,n.styleText)(`gray`,H)}
49
+ `):t(e),W=e=>{let t=(e,t)=>{let r=e.label??String(e.value);switch(t){case`disabled`:return`${(0,n.styleText)(`gray`,V)} ${rt(r,e=>(0,n.styleText)(`gray`,e))}${e.hint?` ${(0,n.styleText)(`dim`,`(${e.hint??`disabled`})`)}`:``}`;case`selected`:return`${rt(r,e=>(0,n.styleText)(`dim`,e))}`;case`active`:return`${(0,n.styleText)(`green`,Ie)} ${r}${e.hint?` ${(0,n.styleText)(`dim`,`(${e.hint})`)}`:``}`;case`cancelled`:return`${rt(r,e=>(0,n.styleText)([`strikethrough`,`dim`],e))}`;default:return`${(0,n.styleText)(`dim`,V)} ${rt(r,e=>(0,n.styleText)(`dim`,e))}`}};return new Oe({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let r=e.withGuide??F.withGuide,i=`${Ke(this.state)} `,a=`${qe(this.state)} `,o=Te(e.output,e.message,a,i),s=`${r?`${(0,n.styleText)(`gray`,z)}
50
50
  `:``}${o}
51
- `;switch(this.state){case`submit`:{let i=r?`${(0,n.styleText)(`gray`,H)} `:``;return`${s}${z(e.output,t(this.options[this.cursor],`selected`),i)}`}case`cancel`:{let i=r?`${(0,n.styleText)(`gray`,H)} `:``;return`${s}${z(e.output,t(this.options[this.cursor],`cancelled`),i)}${r?`
52
- ${(0,n.styleText)(`gray`,H)}`:``}`}default:{let i=r?`${(0,n.styleText)(`cyan`,H)} `:``,a=r?(0,n.styleText)(`cyan`,U):``,o=s.split(`
53
- `).length,c=r?2:1;return`${s}${i}${Ze({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:i.length,rowPadding:o+c,style:(e,n)=>t(e,e.disabled?`disabled`:n?`active`:`inactive`)}).join(`
51
+ `;switch(this.state){case`submit`:{let i=r?`${(0,n.styleText)(`gray`,z)} `:``;return`${s}${Te(e.output,t(this.options[this.cursor],`selected`),i)}`}case`cancel`:{let i=r?`${(0,n.styleText)(`gray`,z)} `:``;return`${s}${Te(e.output,t(this.options[this.cursor],`cancelled`),i)}${r?`
52
+ ${(0,n.styleText)(`gray`,z)}`:``}`}default:{let i=r?`${(0,n.styleText)(`cyan`,z)} `:``,a=r?(0,n.styleText)(`cyan`,B):``,o=s.split(`
53
+ `).length,c=r?2:1;return`${s}${i}${Ye({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:i.length,rowPadding:o+c,style:(e,n)=>t(e,e.disabled?`disabled`:n?`active`:`inactive`)}).join(`
54
54
  ${i}`)}
55
55
  ${a}
56
- `}}}}).prompt()},at=`${(0,n.styleText)(`gray`,H)} `,Y={message:async(e,{symbol:t=(0,n.styleText)(`gray`,H)}={})=>{process.stdout.write(`${(0,n.styleText)(`gray`,H)}
56
+ `}}}}).prompt()},it=`${(0,n.styleText)(`gray`,z)} `,G={message:async(e,{symbol:t=(0,n.styleText)(`gray`,z)}={})=>{process.stdout.write(`${(0,n.styleText)(`gray`,z)}
57
57
  ${t} `);let r=3;for await(let t of e){t=t.replace(/\n/g,`
58
- ${at}`),t.includes(`
58
+ ${it}`),t.includes(`
59
59
  `)&&(r=3+(0,n.stripVTControlCharacters)(t.slice(t.lastIndexOf(`
60
60
  `))).length);let e=(0,n.stripVTControlCharacters)(t).length;r+e<process.stdout.columns?(r+=e,process.stdout.write(t)):(process.stdout.write(`
61
- ${at}${t.trimStart()}`),r=3+(0,n.stripVTControlCharacters)(t.trimStart()).length)}process.stdout.write(`
62
- `)},info:e=>Y.message(e,{symbol:(0,n.styleText)(`blue`,We)}),success:e=>Y.message(e,{symbol:(0,n.styleText)(`green`,Ge)}),step:e=>Y.message(e,{symbol:(0,n.styleText)(`green`,V)}),warn:e=>Y.message(e,{symbol:(0,n.styleText)(`yellow`,Ke)}),warning:e=>Y.warn(e),error:e=>Y.message(e,{symbol:(0,n.styleText)(`red`,qe)})},ot=e=>new je({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,output:e.output,signal:e.signal,input:e.input,render(){let t=e?.withGuide??F.withGuide,r=`${`${t?`${(0,n.styleText)(`gray`,H)}
63
- `:``}${Je(this.state)} `}${e.message}
64
- `,i=e.placeholder?(0,n.styleText)(`inverse`,e.placeholder[0])+(0,n.styleText)(`dim`,e.placeholder.slice(1)):(0,n.styleText)([`inverse`,`hidden`],`_`),a=this.userInput?this.userInputWithCursor:i,o=this.value??``;switch(this.state){case`error`:{let e=this.error?` ${(0,n.styleText)(`yellow`,this.error)}`:``,i=t?`${(0,n.styleText)(`yellow`,H)} `:``,o=t?(0,n.styleText)(`yellow`,U):``;return`${r.trim()}
61
+ ${it}${t.trimStart()}`),r=3+(0,n.stripVTControlCharacters)(t.trimStart()).length)}process.stdout.write(`
62
+ `)},info:e=>G.message(e,{symbol:(0,n.styleText)(`blue`,He)}),success:e=>G.message(e,{symbol:(0,n.styleText)(`green`,Ue)}),step:e=>G.message(e,{symbol:(0,n.styleText)(`green`,R)}),warn:e=>G.message(e,{symbol:(0,n.styleText)(`yellow`,We)}),warning:e=>G.warn(e),error:e=>G.message(e,{symbol:(0,n.styleText)(`red`,Ge)})},at=e=>new ke({validate:e.validate,placeholder:e.placeholder,defaultValue:e.defaultValue,initialValue:e.initialValue,output:e.output,signal:e.signal,input:e.input,render(){let t=e?.withGuide??F.withGuide,r=`${`${t?`${(0,n.styleText)(`gray`,z)}
63
+ `:``}${Ke(this.state)} `}${e.message}
64
+ `,i=e.placeholder?(0,n.styleText)(`inverse`,e.placeholder[0])+(0,n.styleText)(`dim`,e.placeholder.slice(1)):(0,n.styleText)([`inverse`,`hidden`],`_`),a=this.userInput?this.userInputWithCursor:i,o=this.value??``;switch(this.state){case`error`:{let e=this.error?` ${(0,n.styleText)(`yellow`,this.error)}`:``,i=t?`${(0,n.styleText)(`yellow`,z)} `:``,o=t?(0,n.styleText)(`yellow`,B):``;return`${r.trim()}
65
65
  ${i}${a}
66
66
  ${o}${e}
67
- `}case`submit`:{let e=o?` ${(0,n.styleText)(`dim`,o)}`:``;return`${r}${t?(0,n.styleText)(`gray`,H):``}${e}`}case`cancel`:{let e=o?` ${(0,n.styleText)([`strikethrough`,`dim`],o)}`:``,i=t?(0,n.styleText)(`gray`,H):``;return`${r}${i}${e}${o.trim()?`
68
- ${i}`:``}`}default:return`${r}${t?`${(0,n.styleText)(`cyan`,H)} `:``}${a}
69
- ${t?(0,n.styleText)(`cyan`,U):``}
70
- `}}}).prompt();var st=class{info(e){process.stdout.write(`${D.default.blue(`ℹ ${e}`)}\n`)}warn(e){process.stderr.write(`${D.default.yellow(`⚠ ${e}`)}\n`)}error(e){process.stderr.write(`${D.default.red(`✘ ${e}`)}\n`)}success(e){process.stdout.write(`${D.default.green(`✔ ${e}`)}\n`)}step(e){process.stdout.write(`○ ${e}\n`)}note(e,t){nt(e,t)}log(e){process.stdout.write(`${e}\n`)}spinner(){return it()}json(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}cancel(e){process.stderr.write(`${D.default.red(`✘ ${e}`)}\n`)}fatal(e,t){if(process.stderr.write(`${D.default.red(`✘ ${e}`)}\n`),t){let e=`${D.default.red(t instanceof Error?t.stack??String(t):String(t))}\n`;process.stderr.write(e)}throw t instanceof Error?t:Error(e)}finish(e,t){$e(e)}async flush(){return new Promise(e=>{process.stderr.write(``,()=>e())})}},ct=class{constructor(e){this.options=e,this.originalStdoutWrite=process.stdout.write,e.isJson?this.reporter=new O:e.isQuiet?this.reporter=new k:this.reporter=new st}info(e){this.reporter.info(e)}warn(e){this.reporter.warn(e)}error(e){this.reporter.error(e)}success(e){this.reporter.success(e)}step(e){this.reporter.step(e)}note(e,t){this.reporter.note(e,t)}log(e){this.reporter.log(e)}spinner(){return this.reporter.spinner()}json(e){this.reporter.json(e)}get stdio(){return this.options.isJson?[process.stdin,process.stderr,process.stderr]:`inherit`}interactiveStdout(e){!this.options.isJson||this.options.isYes||(e?process.stdout.write=process.stderr.write.bind(process.stderr):process.stdout.write=this.originalStdoutWrite)}cancel(e){this.reporter.cancel(e)}fatal(e,t){this.reporter.fatal(e,t)}finish(e,t){this.reporter.finish(e,t)}async flush(){await this.reporter.flush()}},lt=e.n({safeAppend:()=>dt});const ut=`// @arkenv-types`;async function dt(e,t,n,r){try{let r=await s.default.readFile(e,`utf-8`),i=n===`vite`?`ImportMetaEnvAugmented`:`ProcessEnvAugmented`;if(r.includes(ut)||r.includes(i))return!1;let a=o.default.dirname(e),c=o.default.relative(a,t).replace(/\.(ts|js|tsx|jsx)$/,``).split(o.default.sep).join(`/`),l=c.startsWith(`.`)?c:`./${c}`,u=n===`vite`?ft(l):pt(l),d=r.endsWith(`
67
+ `}case`submit`:{let e=o?` ${(0,n.styleText)(`dim`,o)}`:``;return`${r}${t?(0,n.styleText)(`gray`,z):``}${e}`}case`cancel`:{let e=o?` ${(0,n.styleText)([`strikethrough`,`dim`],o)}`:``,i=t?(0,n.styleText)(`gray`,z):``;return`${r}${i}${e}${o.trim()?`
68
+ ${i}`:``}`}default:return`${r}${t?`${(0,n.styleText)(`cyan`,z)} `:``}${a}
69
+ ${t?(0,n.styleText)(`cyan`,B):``}
70
+ `}}}).prompt();var ot=class{info(e){process.stdout.write(`${S.default.blue(`ℹ ${e}`)}\n`)}warn(e){process.stderr.write(`${S.default.yellow(`⚠ ${e}`)}\n`)}error(e){process.stderr.write(`${S.default.red(`✘ ${e}`)}\n`)}success(e){process.stdout.write(`${S.default.green(`✔ ${e}`)}\n`)}step(e){process.stdout.write(`○ ${e}\n`)}note(e,t){et(e,t)}log(e){process.stdout.write(`${e}\n`)}spinner(){return nt()}json(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}cancel(e){process.stderr.write(`${S.default.red(`✘ ${e}`)}\n`)}fatal(e,t){if(process.stderr.write(`${S.default.red(`✘ ${e}`)}\n`),t){let e=`${S.default.red(t instanceof Error?t.stack??String(t):String(t))}\n`;process.stderr.write(e)}throw t instanceof Error?t:Error(e)}refuse(e){}finish(e,t){Ze(e)}async flush(){return new Promise(e=>{process.stderr.write(``,()=>e())})}},st=class{constructor(e){this.options=e,this.originalStdoutWrite=process.stdout.write,e.isJson?this.reporter=new ee:e.isQuiet?this.reporter=new w:this.reporter=new ot}debug(e){this.reporter.log(e)}info(e){this.reporter.info(e)}warn(e){this.reporter.warn(e)}error(e){this.reporter.error(e)}success(e){this.reporter.success(e)}step(e){this.reporter.step(e)}note(e,t){this.reporter.note(e,t)}log(e){this.reporter.log(e)}spinner(){return this.reporter.spinner()}json(e){this.reporter.json(e)}get stdio(){return this.options.isJson?[process.stdin,process.stderr,process.stderr]:`inherit`}interactiveStdout(e){!this.options.isJson||this.options.isYes||(e?process.stdout.write=process.stderr.write.bind(process.stderr):process.stdout.write=this.originalStdoutWrite)}cancel(e){this.reporter.cancel(e)}fatal(e,t){this.reporter.fatal(e,t)}refuse(e){this.reporter.refuse(e)}finish(e,t){this.reporter.finish(e,t)}async flush(){await this.reporter.flush()}};function ct(e){return e instanceof Error?e.stack??e.message:String(e)}function lt(e,t,n){e(`${t}: ${n instanceof Error?n.message:String(n)}`),n instanceof Error&&n.stack&&e(n.stack)}const ut={debug:0,info:1,warn:2,error:3},dt=new Set([`debug`,`info`,`warn`,`error`,`silent`]);function ft(e){if(!e)return;let t=e.trim().toLowerCase();if(dt.has(t))return t}function pt(){if(!(typeof process>`u`))return ft(process.env?.ARKENV_LOG_LEVEL)}function mt(e){return e?.level??pt()??`info`}function ht(e,t){return e===`silent`?!1:ut[t]>=ut[e]}function gt(e,t,n){return(r,...i)=>{ht(e,t)&&console[n](r,...i)}}function _t(e){let t=mt(e);return{debug:gt(t,`debug`,`debug`),info:gt(t,`info`,`info`),warn:gt(t,`warn`,`warn`),error:gt(t,`error`,`error`)}}let vt=_t();const yt=`[ArkEnv]`,bt=`[ArkEnv Watcher]`;function xt(e){return{logBuildWarning(t){e.warn(`⚠️ ${yt} ${t}`)},logBuildError(t){e.error(`❌ ${yt} ${t}`)},logBuildErrorDetail(t){e.error(t)},logBuildErrorBlankLine(){e.error(``)},logBuildErrorWithCause(t,n){e.error(`❌ ${yt} ${t}`),e.error(ct(n))},logWatcherError(t){e.error(`${bt} ${t}`)},logWatcherErrorWithCause(t,n){e.error(`${bt} ${t}`),e.error(ct(n))}}}let St=xt(vt);function Ct(e,t){St.logBuildErrorWithCause(e,t)}var wt=e.n({safeAppend:()=>Et});const Tt=`// @arkenv-types`;async function Et(e,t,n,r){try{let r=await s.default.readFile(e,`utf-8`),i=n===`vite`?`ImportMetaEnvAugmented`:`ProcessEnvAugmented`;if(r.includes(Tt)||r.includes(i))return!1;let a=o.default.dirname(e),c=o.default.relative(a,t).replace(/\.(ts|js|tsx|jsx)$/,``).split(o.default.sep).join(`/`),l=c.startsWith(`.`)?c:`./${c}`,u=n===`vite`?Dt(l):Ot(l),d=r.endsWith(`
71
71
  `)?``:`
72
- `;return await s.default.appendFile(e,`${d}\n${ut}\n${u}\n`,`utf-8`),!0}catch(t){let n=`Failed to append to ${e}`;return r?T(r.error.bind(r),n,t):ee(n,t),!1}}function ft(e){return c.default`
72
+ `;return await s.default.appendFile(e,`${d}\n${Tt}\n${u}\n`,`utf-8`),!0}catch(t){let n=`Failed to append to ${e}`;return r?lt(r.error.bind(r),n,t):Ct(n,t),!1}}function Dt(e){return c.default`
73
73
  type ImportMetaEnvAugmented = import("@arkenv/vite-plugin").ImportMetaEnvAugmented<
74
74
  typeof import("${e}").Env
75
75
  >;
@@ -79,7 +79,7 @@ ${t?(0,n.styleText)(`cyan`,U):``}
79
79
  interface ImportMeta {
80
80
  readonly env: ImportMetaEnv;
81
81
  }
82
- `}function pt(e){return c.default`
82
+ `}function Ot(e){return c.default`
83
83
  type ProcessEnvAugmented = import("@arkenv/bun-plugin").ProcessEnvAugmented<
84
84
  typeof import("${e}").Env
85
85
  >;
@@ -87,159 +87,164 @@ ${t?(0,n.styleText)(`cyan`,U):``}
87
87
  declare namespace NodeJS {
88
88
  interface ProcessEnv extends ProcessEnvAugmented {}
89
89
  }
90
- `}async function mt(e,t){for(let n of t)try{return await s.default.access(o.default.join(e,n)),!0}catch{}return!1}async function ht(e=process.cwd(),t){if(t?.compilerOptions?.types){let e=t.compilerOptions.types;if(e.includes(`vite`)||e.includes(`vite/client`))return`vite`}try{let t=o.default.join(e,`package.json`),n=await s.default.readFile(t,`utf-8`),r=JSON.parse(n),i={...r.dependencies,...r.devDependencies};if(i.vite)return`vite`;if(i.next)return`nextjs`;if(i.nuxt)return`nuxt`}catch{}return await mt(e,[`vite.config.ts`,`vite.config.js`])?`vite`:await mt(e,[`next.config.ts`,`next.config.js`,`next.config.mjs`,`next.config.cjs`])?`nextjs`:await mt(e,[`nuxt.config.ts`,`nuxt.config.js`,`nuxt.config.mts`,`nuxt.config.mjs`,`nuxt.config.cjs`])?`nuxt`:(await gt(e,t)).length>0?`bun-fullstack`:`vanilla`}async function gt(e=process.cwd(),t){let n=[];try{let t=o.default.join(e,`bunfig.toml`),r=await s.default.readFile(t,`utf-8`);(r.includes(`[serve]`)||r.includes(`[serve.static]`))&&n.push(`serve`),r.includes(`[build]`)&&n.push(`build`)}catch{}if(n.includes(`serve`)&&n.includes(`build`))return n;let{walk:r}=await Promise.resolve().then(()=>yt),i=await r(e),a=n.includes(`serve`),c=n.includes(`build`);for(let e of i)try{let t=await s.default.readFile(e,`utf-8`);if(!a&&(t.includes(`Bun.serve`)||t.includes(`serve(`))&&(/from\s+['"]bun['"]/.test(t)||t.includes(`Bun.serve`))&&(a=!0,n.push(`serve`)),!c&&(t.includes(`Bun.build`)||t.includes(`build(`))&&(/from\s+['"]bun['"]/.test(t)||t.includes(`Bun.build`))&&(c=!0,n.push(`build`)),a&&c)break}catch{}return n}async function _t(e=process.cwd(),t){let n=process.env.npm_config_user_agent?.toString()||``;if(n.includes(`pnpm`))return`pnpm`;if(n.includes(`yarn`))return`yarn`;if(n.includes(`bun`))return`bun`;if(n.includes(`npm`))return`npm`;let r=t?.path?o.default.dirname(t.path):e;for(;r!==o.default.parse(r).root;){try{let e=o.default.join(r,`package.json`),t=await s.default.readFile(e,`utf-8`),n=JSON.parse(t);if(n.packageManager){if(n.packageManager.startsWith(`pnpm`))return`pnpm`;if(n.packageManager.startsWith(`yarn`))return`yarn`;if(n.packageManager.startsWith(`bun`))return`bun`}}catch{}let e=[];try{e=await s.default.readdir(r)}catch{}if(e.includes(`pnpm-lock.yaml`))return`pnpm`;if(e.includes(`yarn.lock`))return`yarn`;if(e.includes(`bun.lockb`))return`bun`;if(e.includes(`package-lock.json`))return`npm`;r=o.default.dirname(r)}return`npm`}async function vt(e=process.cwd(),t){let n=t;if(!n){let{findTsConfig:t,loadTsConfig:r}=await Promise.resolve().then(()=>Tt),i=await t(e);i&&(n=await r(i))}if(n?.compilerOptions?.rootDir){let t=n.compilerOptions.rootDir,r=o.default.relative(e,t);return r&&r!==`.`&&!r.startsWith(`..`)&&!o.default.isAbsolute(r)?`./${r}/env.ts`:`./env.ts`}try{return await s.default.access(o.default.join(e,`src`)),`./src/env.ts`}catch{return`./env.ts`}}var yt=e.n({getEnvExampleKeys:()=>wt,parseEnvExample:()=>xt,resolveImportPaths:()=>St,scanProjectEnvKeys:()=>Ct,walk:()=>bt});async function bt(e,t=[]){try{let n=await s.default.readdir(e,{withFileTypes:!0});for(let r of n)if(r.isDirectory()){let n=r.name;if(n===`node_modules`||n===`dist`||n===`build`||n===`.git`||n===`.turbo`||n===`scratch`)continue;await bt(o.default.join(e,n),t)}else r.isFile()&&/\.(ts|tsx|js|jsx)$/.test(r.name)&&!r.name.endsWith(`.d.ts`)&&t.push(o.default.join(e,r.name))}catch{}return t}function xt(e){let t=[],n=e.split(/\r?\n/);for(let e of n){let n=e.trim();if(!n||n.startsWith(`#`))continue;let r=n.match(/^([A-Z_][A-Z0-9_]*)\s*=/i);r?.[1]&&t.push(r[1])}return Array.from(new Set(t))}function St(e,t,n){if(e.startsWith(`.`))return[o.default.resolve(o.default.dirname(n),e)];if(o.default.isAbsolute(e))return[e];let r=t.compilerOptions||{},i=r.baseUrl||o.default.dirname(t.path),a=r.paths||{},s=[];for(let[e,t]of Object.entries(a)){let n=e.endsWith(`*`),r=e.replace(/\*$/,``);s.push({cleanPattern:r,targets:Array.isArray(t)?t:[t],hadStar:n})}s.sort((e,t)=>t.cleanPattern.length-e.cleanPattern.length);for(let{cleanPattern:t,targets:n,hadStar:r}of s)if(r&&e.startsWith(t)||!r&&e===t){let r=e.slice(t.length);return n.map(e=>{let t=`${e.replace(/\*$/,``)}${r}`;return o.default.resolve(i,t)})}return r.baseUrl?[o.default.resolve(i,e)]:[]}async function Ct(e,t,n){let r=[],i=await bt(e),a=n?n.replace(/\.(ts|js|tsx|jsx)$/,``):null;for(let e of i)try{let n=await s.default.readFile(e,`utf-8`),i=n.matchAll(/process\.env\.([A-Z_][A-Z0-9_]*)/g);for(let e of i)e[1]&&r.push(e[1]);let c=n.matchAll(/import\.meta\.env\.([A-Z_][A-Z0-9_]*)/g);for(let e of c)e[1]&&r.push(e[1]);if(a){let i=n.matchAll(/import\s+[^;]*from\s+['"]([^'"]+)['"]/g);for(let s of i){let i=s[1],c=[];if(t?c=St(i,t,e):i.startsWith(`.`)&&(c=[o.default.resolve(o.default.dirname(e),i)]),c.some(e=>e.replace(/\.(ts|js|tsx|jsx)$/,``)===a)){let e=n.matchAll(/\benv\.([A-Z_][A-Z0-9_]*)/g);for(let t of e)t[1]&&r.push(t[1])}}}}catch{}return Array.from(new Set(r))}async function wt(e=process.cwd(),t,n){let r=o.default.join(e,`.env.example`);try{let e=xt(await s.default.readFile(r,`utf-8`));if(e.length>0)return{keys:e,source:`.env.example`}}catch{}let i=await Ct(e,t,n);return i.length>0?{keys:i,source:`project`}:null}var Tt=e.n({checkTsConfig:()=>kt,findTsConfig:()=>Dt,loadTsConfig:()=>Ot});const Et=(0,u.createRequire)(require(`url`).pathToFileURL(__filename).href).resolve;async function Dt(e=process.cwd()){let t=[`tsconfig.app.json`,`tsconfig.json`,`tsconfig.base.json`,`tsconfig.node.json`],n=e;for(;n!==o.default.parse(n).root;){for(let e of t){let t=o.default.join(n,e);try{return await s.default.access(t),t}catch{}}n=o.default.dirname(n)}return null}async function Ot(e,t=new Set){let n=o.default.resolve(e);if(t.has(n))throw Error(`Circular extends dependency detected in tsconfig.json: ${n}`);t.add(n);let r=``;try{r=await s.default.readFile(e,`utf-8`)}catch{return{path:e,compilerOptions:{}}}let i=(0,d.parse)(r)||{},a=i.compilerOptions||{},c={};if(i.extends){let n=Array.isArray(i.extends)?i.extends:[i.extends];for(let r of n){let n;if(r.startsWith(`.`)||o.default.isAbsolute(r))n=o.default.resolve(o.default.dirname(e),r);else try{n=Et(r,{paths:[o.default.dirname(e)]})}catch{n=o.default.resolve(o.default.dirname(e),`node_modules`,r)}let i={...(await Ot(n,t)).compilerOptions};i.baseUrl&&=o.default.resolve(o.default.dirname(n),i.baseUrl),i.rootDir&&=o.default.resolve(o.default.dirname(n),i.rootDir),c={...c,...i}}}let l={...a};return l.baseUrl&&=o.default.resolve(o.default.dirname(e),l.baseUrl),l.rootDir&&=o.default.resolve(o.default.dirname(e),l.rootDir),c={...c,...l},{...i,path:e,compilerOptions:c}}async function kt(e=process.cwd()){let t=await Dt(e);if(!t)return{status:`not_found`};let n=o.default.basename(t);try{let e=await Ot(t);return e?.compilerOptions?.strict===!0?{status:`strict`,file:n,parsed:e}:{status:`not_strict`,file:n,parsed:e}}catch{return{status:`not_found`}}}function At(e,t){let n=e.replace(/^v/,``).split(`.`).map(Number),r=t.replace(/^v/,``).split(`.`).map(Number);for(let e=0;e<3;e++){let t=n[e]||0,i=r[e]||0;if(t>i)return 1;if(t<i)return-1}return 0}function jt(e){let t=e.trim().match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?/);return t?[t[1],t[2]??`0`,t[3]??`0`].join(`.`):null}function Mt(e,t){let n=e.trim(),r=n.match(/^[\^~]?\s*(v?\d+(?:\.\d+){0,2})$/);if(r){let e=jt(r[1]);return e!==null&&At(e,t)>=0}let i=n.match(/(?:>=|>|<=|<|=)\s*v?\d+(?:\.\d+){0,2}/g);return!i||i.join(` `)!==n.replace(/\s+/g,` `)?!1:i.some(e=>{let n=e.match(/^(>=|>|<=|<|=)\s*(v?\d+(?:\.\d+){0,2})$/);if(!n)return!1;let[,r,i]=n,a=jt(i);return a&&(r===`>=`||r===`>`||r===`=`)?At(a,t)>=0:!1})}async function Nt(e=process.cwd()){let t=[],n=process.version,r=`22.0.0`;At(n,r)===-1?t.push({status:`fail`,requirement:`Node.js Version`,message:`Node.js version must be >= ${r}.`,current:n,expected:`>= ${r}`}):t.push({status:`pass`,requirement:`Node.js Version`,message:`Node.js version is compatible.`});let i=null;try{let n=o.default.join(e,`package.json`),r=await s.default.readFile(n,`utf-8`);i=JSON.parse(r),t.push({status:`pass`,requirement:`package.json`,message:`package.json found.`})}catch{t.push({status:`warn`,requirement:`package.json`,message:`package.json not found in the current directory.`})}if(i){let e={...i.dependencies,...i.devDependencies}.typescript,n=`5.1.0`;e?Mt(e,n)?t.push({status:`pass`,requirement:`TypeScript Version`,message:`TypeScript version is compatible.`}):t.push({status:`fail`,requirement:`TypeScript Version`,message:`TypeScript version should be >= ${n}.`,current:e,expected:`>= ${n}`}):t.push({status:`warn`,requirement:`TypeScript Version`,message:`TypeScript not found in package.json dependencies.`})}let a=await kt(e);if(a.status===`not_found`)t.push({status:`warn`,requirement:`tsconfig.json`,message:`tsconfig.json not found.`});else{let e=a.parsed.compilerOptions||{};e.strict===!0?t.push({status:`pass`,requirement:`TypeScript Strict Mode`,message:`Strict mode is enabled.`}):t.push({status:`fail`,requirement:`TypeScript Strict Mode`,message:`Strict mode must be enabled.`,current:`false`,expected:`true`});let n=e.moduleResolution?.toLowerCase(),r=e.module?.toLowerCase();[`bundler`,`node16`,`nodenext`].includes(n||``)||!n&&(r===`node16`||r===`nodenext`)?t.push({status:`pass`,requirement:`TypeScript moduleResolution`,message:`moduleResolution is set to ${n||`implicit`}.`}):t.push({status:`fail`,requirement:`TypeScript moduleResolution`,message:`moduleResolution must be set to 'bundler', 'node16', or 'nodenext'.`,current:n||`default`,expected:`bundler, node16, or nodenext`})}return t}var Pt=class{constructor(e){this.logger=e}async isEmptyDirectory(e=process.cwd()){try{return(await s.default.readdir(e)).length===0}catch{return!1}}async hasPackageJson(e=process.cwd()){try{return await s.default.access(o.default.join(e,`package.json`)),!0}catch{return!1}}async findTsConfig(e=process.cwd()){return Dt(e)}async loadTsConfig(e,t=new Set){return Ot(e,t)}async getEnvExampleKeys(e=process.cwd(),t,n){return wt(e,t,n)}async suggestDefaultEnvPath(e=process.cwd(),t){return vt(e,t)}async checkTsConfig(e=process.cwd()){return kt(e)}async checkRequirements(e=process.cwd()){return Nt(e)}async detectFramework(e=process.cwd(),t){return ht(e,t)}async detectBunFeatures(e=process.cwd(),t){return gt(e,t)}async detectPackageManager(e=process.cwd(),t){return _t(e,t)}async hasSkill(e=process.cwd()){try{let t=o.default.join(e,`skills-lock.json`),n=await s.default.readFile(t,`utf-8`),r=JSON.parse(n);if(r&&typeof r==`object`&&r.skills&&typeof r.skills==`object`&&`arkenv`in r.skills)return!0}catch{}for(let t of[`skills/arkenv/SKILL.md`,`.agent/skills/arkenv/SKILL.md`,`.agents/skills/arkenv/SKILL.md`])try{return await s.default.access(o.default.join(e,t)),!0}catch{}return!1}async checkGitStatus(e=process.cwd()){try{return(0,l.execSync)(`git status --porcelain`,{cwd:e,encoding:`utf-8`}).trim().length===0?{status:`clean`}:{status:`dirty`}}catch(e){let t=e;return t.code===`ENOENT`?(this.logger?.log(`Git is not installed on this system. Skipping git status check.`),{status:`not_a_repo`}):typeof t.stderr==`string`&&t.stderr.includes(`not a git repository`)?{status:`not_a_repo`}:{status:`unknown`}}}};const X=e=>D.default.cyan(e),Ft=D.default.blue(`⛯`);function It(e){return e.replace(/import\s*\{([^\n}]*)\}\s*from/g,(e,t)=>`import { ${t.trim()} } from`)}function Lt(e,t){return t.endsWith(`
90
+ `}async function kt(e,t){for(let n of t)try{return await s.default.access(o.default.join(e,n)),!0}catch{}return!1}async function At(e=process.cwd(),t){if(t?.compilerOptions?.types){let e=t.compilerOptions.types;if(e.includes(`vite`)||e.includes(`vite/client`))return`vite`}try{let t=o.default.join(e,`package.json`),n=await s.default.readFile(t,`utf-8`),r=JSON.parse(n),i={...r.dependencies,...r.devDependencies};if(i.vite)return`vite`;if(i.next)return`nextjs`;if(i.nuxt)return`nuxt`}catch{}return await kt(e,[`vite.config.ts`,`vite.config.js`])?`vite`:await kt(e,[`next.config.ts`,`next.config.js`,`next.config.mjs`,`next.config.cjs`])?`nextjs`:await kt(e,[`nuxt.config.ts`,`nuxt.config.js`,`nuxt.config.mts`,`nuxt.config.mjs`,`nuxt.config.cjs`])?`nuxt`:(await jt(e,t)).length>0?`bun-fullstack`:`vanilla`}async function jt(e=process.cwd(),t){let n=[];try{let t=o.default.join(e,`bunfig.toml`),r=await s.default.readFile(t,`utf-8`);(r.includes(`[serve]`)||r.includes(`[serve.static]`))&&n.push(`serve`),r.includes(`[build]`)&&n.push(`build`)}catch{}if(n.includes(`serve`)&&n.includes(`build`))return n;let{walk:r}=await Promise.resolve().then(()=>Pt),i=await r(e),a=n.includes(`serve`),c=n.includes(`build`);for(let e of i)try{let t=await s.default.readFile(e,`utf-8`);if(!a&&(t.includes(`Bun.serve`)||t.includes(`serve(`))&&(/from\s+['"]bun['"]/.test(t)||t.includes(`Bun.serve`))&&(a=!0,n.push(`serve`)),!c&&(t.includes(`Bun.build`)||t.includes(`build(`))&&(/from\s+['"]bun['"]/.test(t)||t.includes(`Bun.build`))&&(c=!0,n.push(`build`)),a&&c)break}catch{}return n}async function Mt(e=process.cwd(),t){let n=process.env.npm_config_user_agent?.toString()||``;if(n.includes(`pnpm`))return`pnpm`;if(n.includes(`yarn`))return`yarn`;if(n.includes(`bun`))return`bun`;if(n.includes(`npm`))return`npm`;let r=t?.path?o.default.dirname(t.path):e;for(;r!==o.default.parse(r).root;){try{let e=o.default.join(r,`package.json`),t=await s.default.readFile(e,`utf-8`),n=JSON.parse(t);if(n.packageManager){if(n.packageManager.startsWith(`pnpm`))return`pnpm`;if(n.packageManager.startsWith(`yarn`))return`yarn`;if(n.packageManager.startsWith(`bun`))return`bun`}}catch{}let e=[];try{e=await s.default.readdir(r)}catch{}if(e.includes(`pnpm-lock.yaml`))return`pnpm`;if(e.includes(`yarn.lock`))return`yarn`;if(e.includes(`bun.lockb`))return`bun`;if(e.includes(`package-lock.json`))return`npm`;r=o.default.dirname(r)}return`npm`}async function Nt(e=process.cwd(),t){let n=t;if(!n){let{findTsConfig:t,loadTsConfig:r}=await Promise.resolve().then(()=>Bt),i=await t(e);i&&(n=await r(i))}if(n?.compilerOptions?.rootDir){let t=n.compilerOptions.rootDir,r=o.default.relative(e,t);return r&&r!==`.`&&!r.startsWith(`..`)&&!o.default.isAbsolute(r)?`./${r}/env.ts`:`./env.ts`}try{return await s.default.access(o.default.join(e,`src`)),`./src/env.ts`}catch{return`./env.ts`}}var Pt=e.n({getEnvExampleKeys:()=>zt,parseEnvExample:()=>It,resolveImportPaths:()=>Lt,scanProjectEnvKeys:()=>Rt,walk:()=>Ft});async function Ft(e,t=[]){try{let n=await s.default.readdir(e,{withFileTypes:!0});for(let r of n)if(r.isDirectory()){let n=r.name;if(n===`node_modules`||n===`dist`||n===`build`||n===`.git`||n===`.turbo`||n===`scratch`)continue;await Ft(o.default.join(e,n),t)}else r.isFile()&&/\.(ts|tsx|js|jsx)$/.test(r.name)&&!r.name.endsWith(`.d.ts`)&&t.push(o.default.join(e,r.name))}catch{}return t}function It(e){let t=[],n=e.split(/\r?\n/);for(let e of n){let n=e.trim();if(!n||n.startsWith(`#`))continue;let r=n.match(/^([A-Z_][A-Z0-9_]*)\s*=/i);r?.[1]&&t.push(r[1])}return Array.from(new Set(t))}function Lt(e,t,n){if(e.startsWith(`.`))return[o.default.resolve(o.default.dirname(n),e)];if(o.default.isAbsolute(e))return[e];let r=t.compilerOptions||{},i=r.baseUrl||o.default.dirname(t.path),a=r.paths||{},s=[];for(let[e,t]of Object.entries(a)){let n=e.endsWith(`*`),r=e.replace(/\*$/,``);s.push({cleanPattern:r,targets:Array.isArray(t)?t:[t],hadStar:n})}s.sort((e,t)=>t.cleanPattern.length-e.cleanPattern.length);for(let{cleanPattern:t,targets:n,hadStar:r}of s)if(r&&e.startsWith(t)||!r&&e===t){let r=e.slice(t.length);return n.map(e=>{let t=`${e.replace(/\*$/,``)}${r}`;return o.default.resolve(i,t)})}return r.baseUrl?[o.default.resolve(i,e)]:[]}async function Rt(e,t,n){let r=[],i=await Ft(e),a=n?n.replace(/\.(ts|js|tsx|jsx)$/,``):null;for(let e of i)try{let n=await s.default.readFile(e,`utf-8`),i=n.matchAll(/process\.env\.([A-Z_][A-Z0-9_]*)/g);for(let e of i)e[1]&&r.push(e[1]);let c=n.matchAll(/import\.meta\.env\.([A-Z_][A-Z0-9_]*)/g);for(let e of c)e[1]&&r.push(e[1]);if(a){let i=n.matchAll(/import\s+[^;]*from\s+['"]([^'"]+)['"]/g);for(let s of i){let i=s[1],c=[];if(t?c=Lt(i,t,e):i.startsWith(`.`)&&(c=[o.default.resolve(o.default.dirname(e),i)]),c.some(e=>e.replace(/\.(ts|js|tsx|jsx)$/,``)===a)){let e=n.matchAll(/\benv\.([A-Z_][A-Z0-9_]*)/g);for(let t of e)t[1]&&r.push(t[1])}}}}catch{}return Array.from(new Set(r))}async function zt(e=process.cwd(),t,n){let r=o.default.join(e,`.env.example`);try{let e=It(await s.default.readFile(r,`utf-8`));if(e.length>0)return{keys:e,source:`.env.example`}}catch{}let i=await Rt(e,t,n);return i.length>0?{keys:i,source:`project`}:null}var Bt=e.n({checkTsConfig:()=>Wt,findTsConfig:()=>Ht,loadTsConfig:()=>Ut});const Vt=(0,u.createRequire)(require(`url`).pathToFileURL(__filename).href).resolve;async function Ht(e=process.cwd()){let t=[`tsconfig.app.json`,`tsconfig.json`,`tsconfig.base.json`,`tsconfig.node.json`],n=e;for(;n!==o.default.parse(n).root;){for(let e of t){let t=o.default.join(n,e);try{return await s.default.access(t),t}catch{}}n=o.default.dirname(n)}return null}async function Ut(e,t=new Set){let n=o.default.resolve(e);if(t.has(n))throw Error(`Circular extends dependency detected in tsconfig.json: ${n}`);t.add(n);let r=``;try{r=await s.default.readFile(e,`utf-8`)}catch{return{path:e,compilerOptions:{}}}let i=(0,d.parse)(r)||{},a=i.compilerOptions||{},c={};if(i.extends){let n=Array.isArray(i.extends)?i.extends:[i.extends];for(let r of n){let n;if(r.startsWith(`.`)||o.default.isAbsolute(r))n=o.default.resolve(o.default.dirname(e),r);else try{n=Vt(r,{paths:[o.default.dirname(e)]})}catch{n=o.default.resolve(o.default.dirname(e),`node_modules`,r)}let i={...(await Ut(n,t)).compilerOptions};i.baseUrl&&=o.default.resolve(o.default.dirname(n),i.baseUrl),i.rootDir&&=o.default.resolve(o.default.dirname(n),i.rootDir),c={...c,...i}}}let l={...a};return l.baseUrl&&=o.default.resolve(o.default.dirname(e),l.baseUrl),l.rootDir&&=o.default.resolve(o.default.dirname(e),l.rootDir),c={...c,...l},{...i,path:e,compilerOptions:c}}async function Wt(e=process.cwd()){let t=await Ht(e);if(!t)return{status:`not_found`};let n=o.default.basename(t);try{let e=await Ut(t);return e?.compilerOptions?.strict===!0?{status:`strict`,file:n,parsed:e}:{status:`not_strict`,file:n,parsed:e}}catch{return{status:`not_found`}}}function Gt(e,t){let n=e.replace(/^v/,``).split(`.`).map(Number),r=t.replace(/^v/,``).split(`.`).map(Number);for(let e=0;e<3;e++){let t=n[e]||0,i=r[e]||0;if(t>i)return 1;if(t<i)return-1}return 0}function Kt(e){let t=e.trim().match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?/);return t?[t[1],t[2]??`0`,t[3]??`0`].join(`.`):null}function qt(e,t){let n=e.trim(),r=n.match(/^[\^~]?\s*(v?\d+(?:\.\d+){0,2})$/);if(r){let e=Kt(r[1]);return e!==null&&Gt(e,t)>=0}let i=n.match(/(?:>=|>|<=|<|=)\s*v?\d+(?:\.\d+){0,2}/g);return!i||i.join(` `)!==n.replace(/\s+/g,` `)?!1:i.some(e=>{let n=e.match(/^(>=|>|<=|<|=)\s*(v?\d+(?:\.\d+){0,2})$/);if(!n)return!1;let[,r,i]=n,a=Kt(i);return a&&(r===`>=`||r===`>`||r===`=`)?Gt(a,t)>=0:!1})}async function Jt(e=process.cwd()){let t=[],n=process.version,r=`22.0.0`;Gt(n,r)===-1?t.push({status:`fail`,requirement:`Node.js Version`,message:`Node.js version must be >= ${r}.`,current:n,expected:`>= ${r}`}):t.push({status:`pass`,requirement:`Node.js Version`,message:`Node.js version is compatible.`});let i=null;try{let n=o.default.join(e,`package.json`),r=await s.default.readFile(n,`utf-8`);i=JSON.parse(r),t.push({status:`pass`,requirement:`package.json`,message:`package.json found.`})}catch{t.push({status:`warn`,requirement:`package.json`,message:`package.json not found in the current directory.`})}if(i){let e={...i.dependencies,...i.devDependencies}.typescript,n=`5.1.0`;e?qt(e,n)?t.push({status:`pass`,requirement:`TypeScript Version`,message:`TypeScript version is compatible.`}):t.push({status:`fail`,requirement:`TypeScript Version`,message:`TypeScript version should be >= ${n}.`,current:e,expected:`>= ${n}`}):t.push({status:`warn`,requirement:`TypeScript Version`,message:`TypeScript not found in package.json dependencies.`})}let a=await Wt(e);if(a.status===`not_found`)t.push({status:`warn`,requirement:`tsconfig.json`,message:`tsconfig.json not found.`});else{let e=a.parsed.compilerOptions||{};e.strict===!0?t.push({status:`pass`,requirement:`TypeScript Strict Mode`,message:`Strict mode is enabled.`}):t.push({status:`fail`,requirement:`TypeScript Strict Mode`,message:`Strict mode must be enabled.`,current:`false`,expected:`true`});let n=e.moduleResolution?.toLowerCase(),r=e.module?.toLowerCase();[`bundler`,`node16`,`nodenext`].includes(n||``)||!n&&(r===`node16`||r===`nodenext`)?t.push({status:`pass`,requirement:`TypeScript moduleResolution`,message:`moduleResolution is set to ${n||`implicit`}.`}):t.push({status:`fail`,requirement:`TypeScript moduleResolution`,message:`moduleResolution must be set to 'bundler', 'node16', or 'nodenext'.`,current:n||`default`,expected:`bundler, node16, or nodenext`})}return t}var Yt=class{constructor(e){this.logger=e}async isEmptyDirectory(e=process.cwd()){try{return(await s.default.readdir(e)).length===0}catch{return!1}}async hasPackageJson(e=process.cwd()){try{return await s.default.access(o.default.join(e,`package.json`)),!0}catch{return!1}}async findTsConfig(e=process.cwd()){return Ht(e)}async loadTsConfig(e,t=new Set){return Ut(e,t)}async getEnvExampleKeys(e=process.cwd(),t,n){return zt(e,t,n)}async suggestDefaultEnvPath(e=process.cwd(),t){return Nt(e,t)}async checkTsConfig(e=process.cwd()){return Wt(e)}async checkRequirements(e=process.cwd()){return Jt(e)}async detectFramework(e=process.cwd(),t){return At(e,t)}async detectBunFeatures(e=process.cwd(),t){return jt(e,t)}async detectPackageManager(e=process.cwd(),t){return Mt(e,t)}async hasSkill(e=process.cwd()){try{let t=o.default.join(e,`skills-lock.json`),n=await s.default.readFile(t,`utf-8`),r=JSON.parse(n);if(r&&typeof r==`object`&&r.skills&&typeof r.skills==`object`&&`arkenv`in r.skills)return!0}catch{}for(let t of[`skills/arkenv/SKILL.md`,`.agent/skills/arkenv/SKILL.md`,`.agents/skills/arkenv/SKILL.md`])try{return await s.default.access(o.default.join(e,t)),!0}catch{}return!1}async checkGitStatus(e=process.cwd()){try{return(0,l.execSync)(`git status --porcelain`,{cwd:e,encoding:`utf-8`}).trim().length===0?{status:`clean`}:{status:`dirty`}}catch(e){let t=e;return t.code===`ENOENT`?(this.logger?.log(`Git is not installed on this system. Skipping git status check.`),{status:`not_a_repo`}):typeof t.stderr==`string`&&t.stderr.includes(`not a git repository`)?{status:`not_a_repo`}:{status:`unknown`}}}};const K=e=>S.default.cyan(e),Xt=S.default.blue(`⛯`);function Zt(e){return e.replace(/import\s*\{([^\n}]*)\}\s*from/g,(e,t)=>`import { ${t.trim()} } from`)}function Qt(e,t){return t.endsWith(`
91
91
  `)&&!e.endsWith(`
92
- `)?`${e}\n`:e}function Rt(e){try{let t=(0,f.parseModule)(e.code),n=e.code,r=t.exports.default;if(r&&typeof r==`object`&&`$type`in r&&r.$type===`function-call`){let e=r;if((e.$callee||JSON.stringify(r))===`defineConfig`&&e.$args){let t=e.$args[0];if(t&&typeof t==`object`&&`$type`in t&&(t.$type===`arrow-function-expression`||t.$type===`function-expression`))return{success:!1,updated:!1,error:`The 'defineConfig' callback form is currently not supported for automatic mutation. Please add the plugin manually.`};r=t}}if(!r||typeof r!=`object`||typeof r==`object`&&`$type`in r)return{success:!1,updated:!1,error:`Could not find default export object in Vite config`};if(r.plugins||=[],Array.isArray(r.plugins))if(!/\barkenv(?:Vite)?Plugin\b/.test(n))t.imports.$add({from:`@arkenv/vite-plugin`,local:`arkenvVitePlugin`,imported:`default`}),e.envImportPath&&t.imports.$add({from:e.envImportPath,imported:`Env`}),r.plugins.push(`__ARK_PLUGIN_PLACEHOLDER__`);else return{success:!0,updated:!1};else return{success:!1,updated:!1,error:`The 'plugins' property in your Vite config is not an array.`};let i=(0,f.generateCode)(t,{format:(0,f.detectCodeFormat)(n)}).code,a=e.envImportPath?`arkenvVitePlugin(Env)`:`arkenvVitePlugin()`;return i=i.replace(/['"]__ARK_PLUGIN_PLACEHOLDER__['"]/g,a),i=It(i),i=Lt(i,n),{success:!0,updated:!0,code:i}}catch(e){return{success:!1,updated:!1,error:`Failed to parse Vite config: ${e instanceof Error?e.message:String(e)}`}}}function zt(e){try{let t=e.code;if(/module\.exports\b/.test(t))return{success:!1,updated:!1,error:"CommonJS is not supported for automatic mutation. Please wrap your config with `withArkEnv` manually."};let n=(0,f.parseModule)(t);if(!n.exports.default)return{success:!1,updated:!1,error:`Could not find default export in Next.js config`};if(typeof n.exports.default==`object`&&`$type`in n.exports.default&&n.exports.default.$type===`function-call`&&n.exports.default.$callee===`withArkEnv`||/\bwithArkEnv\b/.test(t))return{success:!0,updated:!1};n.imports.$add({from:`@arkenv/nextjs/config`,imported:`withArkEnv`}),e.disableCodegen?n.exports.default=f.builders.functionCall(`withArkEnv`,n.exports.default,{codegen:!1}):n.exports.default=f.builders.functionCall(`withArkEnv`,n.exports.default);let r=(0,f.generateCode)(n,{format:(0,f.detectCodeFormat)(t)}).code;return r=It(r),r=Lt(r,t),{success:!0,updated:!0,code:r}}catch(e){return{success:!1,updated:!1,error:`Failed to parse Next.js config: ${e instanceof Error?e.message:String(e)}`}}}function Bt(e){try{let t=e.code,n=(0,f.parseModule)(t),r=n.exports.default;if(r&&typeof r==`object`&&`$type`in r&&r.$type===`function-call`){let e=r;(e.$callee||JSON.stringify(r))===`defineNuxtConfig`&&e.$args&&(r=e.$args[0])}if(!r||typeof r!=`object`||typeof r==`object`&&`$type`in r)return{success:!1,updated:!1,error:`Could not find default export object in Nuxt config`};if(r.modules||=[],Array.isArray(r.modules))if(!r.modules.includes(`@arkenv/nuxt/module`))r.modules.push(`@arkenv/nuxt/module`);else return{success:!0,updated:!1};else return{success:!1,updated:!1,error:`The 'modules' property in your Nuxt config is not an array.`};let i=(0,f.generateCode)(n,{format:(0,f.detectCodeFormat)(t)}).code;return i=It(i),i=Lt(i,t),{success:!0,updated:!0,code:i}}catch(e){return{success:!1,updated:!1,error:`Failed to parse Nuxt config: ${e instanceof Error?e.message:String(e)}`}}}async function Vt(e=process.cwd()){for(let t of[`vite.config.ts`,`vite.config.js`,`vite.config.mts`,`vite.config.mjs`]){let n=o.default.resolve(e,t);try{return await s.default.access(n),n}catch{}}return null}async function Ht(e=process.cwd()){for(let t of[`bunfig.toml`,`bun.setup.ts`,`bun.setup.js`]){let n=o.default.resolve(e,t);try{return await s.default.access(n),n}catch{}}return null}async function Ut(e=process.cwd()){for(let t of[`next.config.ts`,`next.config.js`,`next.config.mts`,`next.config.mjs`]){let n=o.default.resolve(e,t);try{return await s.default.access(n),n}catch{}}return null}async function Wt(e,t,n){try{let r=zt({code:await e.readFile(t),disableCodegen:n});return r.success&&r.updated&&r.code&&await e.writeFile(t,r.code),r.success?r.updated===void 0?{success:!0}:{success:!0,updated:r.updated}:{success:!1,error:r.error}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async function Gt(e=process.cwd()){for(let t of[`nuxt.config.ts`,`nuxt.config.js`,`nuxt.config.mts`,`nuxt.config.mjs`,`nuxt.config.cjs`]){let n=o.default.resolve(e,t);try{return await s.default.access(n),n}catch{}}return null}async function Kt(e,t){try{let n=Bt({code:await e.readFile(t)});return n.success&&n.updated&&n.code&&await e.writeFile(t,n.code),n.success?n.updated===void 0?{success:!0}:{success:!0,updated:n.updated}:{success:!1,error:n.error}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async function qt(e,t,n){try{let r=Rt({code:await e.readFile(t),envImportPath:n});return r.success&&r.updated&&r.code&&await e.writeFile(t,r.code),r.success?r.updated===void 0?{success:!0}:{success:!0,updated:r.updated}:{success:!1,error:r.error}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async function Jt(e,t){if(!t||t.length===0)return{success:!0,instructions:c.default`
93
- ${D.default.green(`✔`)} Use ${D.default.bold(`Vanilla`)} Bun runtime integration.
94
- Access validated variables via your ${X(`env`)} object for typesafety.
95
- Primarily used for ${D.default.cyan(`server-side`)} or runtime-only validation.
92
+ `)?`${e}\n`:e}function $t(e){try{let t=(0,f.parseModule)(e.code),n=e.code,r=t.exports.default;if(r&&typeof r==`object`&&`$type`in r&&r.$type===`function-call`){let e=r;if((e.$callee||JSON.stringify(r))===`defineConfig`&&e.$args){let t=e.$args[0];if(t&&typeof t==`object`&&`$type`in t&&(t.$type===`arrow-function-expression`||t.$type===`function-expression`))return{success:!1,updated:!1,error:`The 'defineConfig' callback form is currently not supported for automatic mutation. Please add the plugin manually.`};r=t}}if(!r||typeof r!=`object`||typeof r==`object`&&`$type`in r)return{success:!1,updated:!1,error:`Could not find default export object in Vite config`};if(r.plugins||=[],Array.isArray(r.plugins))if(!/\barkenv(?:Vite)?Plugin\b/.test(n))t.imports.$add({from:`@arkenv/vite-plugin`,local:`arkenvVitePlugin`,imported:`default`}),e.envImportPath&&t.imports.$add({from:e.envImportPath,imported:`Env`}),r.plugins.push(`__ARK_PLUGIN_PLACEHOLDER__`);else return{success:!0,updated:!1};else return{success:!1,updated:!1,error:`The 'plugins' property in your Vite config is not an array.`};let i=(0,f.generateCode)(t,{format:(0,f.detectCodeFormat)(n)}).code,a=e.envImportPath?`arkenvVitePlugin(Env)`:`arkenvVitePlugin()`;return i=i.replace(/['"]__ARK_PLUGIN_PLACEHOLDER__['"]/g,a),i=Zt(i),i=Qt(i,n),{success:!0,updated:!0,code:i}}catch(e){return{success:!1,updated:!1,error:`Failed to parse Vite config: ${e instanceof Error?e.message:String(e)}`}}}function en(e){try{let t=e.code;if(/module\.exports\b/.test(t))return{success:!1,updated:!1,error:"CommonJS is not supported for automatic mutation. Please wrap your config with `withArkEnv` manually."};let n=(0,f.parseModule)(t);if(!n.exports.default)return{success:!1,updated:!1,error:`Could not find default export in Next.js config`};if(typeof n.exports.default==`object`&&`$type`in n.exports.default&&n.exports.default.$type===`function-call`&&n.exports.default.$callee===`withArkEnv`||/\bwithArkEnv\b/.test(t))return{success:!0,updated:!1};n.imports.$add({from:`@arkenv/nextjs/config`,imported:`withArkEnv`}),e.disableCodegen?n.exports.default=f.builders.functionCall(`withArkEnv`,n.exports.default,{codegen:!1}):n.exports.default=f.builders.functionCall(`withArkEnv`,n.exports.default);let r=(0,f.generateCode)(n,{format:(0,f.detectCodeFormat)(t)}).code;return r=Zt(r),r=Qt(r,t),{success:!0,updated:!0,code:r}}catch(e){return{success:!1,updated:!1,error:`Failed to parse Next.js config: ${e instanceof Error?e.message:String(e)}`}}}function tn(e){try{let t=e.code,n=(0,f.parseModule)(t),r=n.exports.default;if(r&&typeof r==`object`&&`$type`in r&&r.$type===`function-call`){let e=r;(e.$callee||JSON.stringify(r))===`defineNuxtConfig`&&e.$args&&(r=e.$args[0])}if(!r||typeof r!=`object`||typeof r==`object`&&`$type`in r)return{success:!1,updated:!1,error:`Could not find default export object in Nuxt config`};if(r.modules||=[],Array.isArray(r.modules))if(!r.modules.includes(`@arkenv/nuxt/module`))r.modules.push(`@arkenv/nuxt/module`);else return{success:!0,updated:!1};else return{success:!1,updated:!1,error:`The 'modules' property in your Nuxt config is not an array.`};let i=(0,f.generateCode)(n,{format:(0,f.detectCodeFormat)(t)}).code;return i=Zt(i),i=Qt(i,t),{success:!0,updated:!0,code:i}}catch(e){return{success:!1,updated:!1,error:`Failed to parse Nuxt config: ${e instanceof Error?e.message:String(e)}`}}}async function nn(e=process.cwd()){for(let t of[`vite.config.ts`,`vite.config.js`,`vite.config.mts`,`vite.config.mjs`]){let n=o.default.resolve(e,t);try{return await s.default.access(n),n}catch{}}return null}async function rn(e=process.cwd()){for(let t of[`bunfig.toml`,`bun.setup.ts`,`bun.setup.js`]){let n=o.default.resolve(e,t);try{return await s.default.access(n),n}catch{}}return null}async function an(e=process.cwd()){for(let t of[`next.config.ts`,`next.config.js`,`next.config.mts`,`next.config.mjs`]){let n=o.default.resolve(e,t);try{return await s.default.access(n),n}catch{}}return null}async function on(e,t,n){try{let r=en({code:await e.readFile(t),disableCodegen:n});return r.success&&r.updated&&r.code&&await e.writeFile(t,r.code),r.success?r.updated===void 0?{success:!0}:{success:!0,updated:r.updated}:{success:!1,error:r.error}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async function sn(e=process.cwd()){for(let t of[`nuxt.config.ts`,`nuxt.config.js`,`nuxt.config.mts`,`nuxt.config.mjs`,`nuxt.config.cjs`]){let n=o.default.resolve(e,t);try{return await s.default.access(n),n}catch{}}return null}async function cn(e,t){try{let n=tn({code:await e.readFile(t)});return n.success&&n.updated&&n.code&&await e.writeFile(t,n.code),n.success?n.updated===void 0?{success:!0}:{success:!0,updated:n.updated}:{success:!1,error:n.error}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async function ln(e,t,n){try{let r=$t({code:await e.readFile(t),envImportPath:n});return r.success&&r.updated&&r.code&&await e.writeFile(t,r.code),r.success?r.updated===void 0?{success:!0}:{success:!0,updated:r.updated}:{success:!1,error:r.error}}catch(e){return{success:!1,error:e instanceof Error?e.message:String(e)}}}async function un(e,t){if(!t||t.length===0)return{success:!0,instructions:c.default`
93
+ ${S.default.green(`✔`)} Use ${S.default.bold(`Vanilla`)} Bun runtime integration.
94
+ Access validated variables via your ${K(`env`)} object for typesafety.
95
+ Primarily used for ${S.default.cyan(`server-side`)} or runtime-only validation.
96
96
  No plugins are required.
97
97
  `};let n=t.includes(`serve`),r=t.includes(`build`),i=``;return n&&(i+=c.default`
98
- ${D.default.bold(`Bun Fullstack (Bun.serve) Integration:`)}
99
- To inline environment variables (e.g. ${X(`PUBLIC_*`)}) in your ${D.default.cyan(`client-side`)} code, add the plugin to ${X(`bunfig.toml`)}:
98
+ ${S.default.bold(`Bun Fullstack (Bun.serve) Integration:`)}
99
+ To inline environment variables (e.g. ${K(`PUBLIC_*`)}) in your ${S.default.cyan(`client-side`)} code, add the plugin to ${K(`bunfig.toml`)}:
100
100
 
101
101
  [serve.static]
102
102
  plugins = ["@arkenv/bun-plugin"]
103
103
 
104
104
  `),r&&(i&&(i+=`
105
105
  `),i+=c.default`
106
- ${D.default.bold(`Bun Fullstack programmatic bundling (Bun.build):`)}
107
- To inline environment variables (e.g. ${X(`PUBLIC_*`)}) in your custom ${D.default.cyan(`client-side`)} build script, add the plugin to your ${X(`Bun.build`)} call:
106
+ ${S.default.bold(`Bun Fullstack programmatic bundling (Bun.build):`)}
107
+ To inline environment variables (e.g. ${K(`PUBLIC_*`)}) in your custom ${S.default.cyan(`client-side`)} build script, add the plugin to your ${K(`Bun.build`)} call:
108
108
 
109
- ${X(`import arkenv from "@arkenv/bun-plugin";`)}
109
+ ${K(`import arkenv from "@arkenv/bun-plugin";`)}
110
110
 
111
111
  await Bun.build({
112
112
  entrypoints: ["./index.ts"],
113
113
  outdir: "./dist",
114
- ${D.default.green(`plugins: [arkenv]`)}
114
+ ${S.default.green(`plugins: [arkenv]`)}
115
115
  });
116
- `),{success:!0,instructions:i.trim()}}async function Yt(e,t){let n=t||await Dt();if(!n)return{status:`not_found`};let r=o.default.basename(n);try{let t=await e.readFile(n);if((0,d.parse)(t)?.compilerOptions?.strict===!0)return{status:`already_strict`,file:r};let i=(0,d.applyEdits)(t,(0,d.modify)(t,[`compilerOptions`,`strict`],!0,{formattingOptions:{insertSpaces:!0,tabSize:2}}));return await e.writeFile(n,i),{status:`updated`,file:r}}catch{return{status:`error`,file:r}}}var Xt=class{constructor(e,t,n){this.isQuiet=e,this.stdio=t,this.logger=n}async exists(e){try{return await s.default.access(e),!0}catch{return!1}}async readFile(e){return s.default.readFile(e,`utf-8`)}async writeFile(e,t){await s.default.writeFile(e,t,`utf-8`)}async mkdir(e,t){await s.default.mkdir(e,{recursive:t})}async execute(e,t=[],n){return new Promise((r,i)=>{let a=(0,l.spawn)(e,t,{cwd:n,stdio:this.isQuiet?`pipe`:this.stdio,shell:!1}),o=``,s=``,c=1e4;this.isQuiet&&(a.stdout?.on(`data`,e=>{o=(o+e.toString()).slice(-c)}),a.stderr?.on(`data`,e=>{s=(s+e.toString()).slice(-c)})),a.on(`close`,(e,t)=>{if(e===0)r();else{let n=e===null?`Command terminated by signal ${t}`:`Command failed with code ${e}`;this.isQuiet&&(o&&(n+=`\n${D.default.dim(`STDOUT:`)}\n${o}`),s&&(n+=`\n${D.default.red(`STDERR:`)}\n${s}`)),i(Error(n))}}),a.on(`error`,i)})}async updateTsConfigToStrict(e){return Yt(this,e)}async findViteConfig(e){return Vt(e)}async findBunConfig(e){return Ht(e)}async findNextjsConfig(e){return Ut(e)}async findNuxtConfig(e){return Gt(e)}async bootstrapViteConfig(e,t){return qt(this,e,t)}async bootstrapBunConfig(e,t){return Jt(e,t)}async bootstrapNextjsConfig(e,t){return Wt(this,e,t)}async bootstrapNuxtConfig(e){return Kt(this,e)}async safeAppend(e,t,n){let{safeAppend:r}=await Promise.resolve().then(()=>lt);return r(e,t,n,this.logger)}};async function Zt(e){let t=e.defaultPath||`./src/env.ts`;if(e.hasEnvSchemaFile){let e=await G({message:D.default.yellow(`An existing ArkEnv configuration was found at ${X(t)}. Do you want to overwrite it?`),initialValue:!1,active:`Yes (override my configuration)`,inactive:`No (abort)`});return I(e)||!e?null:e}return!0}async function Qt(e){let t=e.detectedKeys,n=e.keysSource||`.env.example`;if(t&&t.length>0){let e=t.length,r=e===1,i=await G({message:n===`.env.example`?`Detected ${X(`.env.example`)} with ${e} ${r?`key`:`keys`}. Use ${r?`it`:`them`} for your schema?`:`Detected ${e} environment variable${r?``:`s`} used in your project. Use ${r?`it`:`them`} for your schema?`,active:`Yes (Recommended)`,initialValue:!0});return I(i)?null:i}return!1}async function $t(e){if(e.framework===`vite`||e.framework===`bun-fullstack`){let t=e.framework===`vite`?`vite-env.d.ts`:`bun-env.d.ts`;if(e.hasTypeFile)return!0;let n=await G({message:`Establish ${X(t)} for typesafe environment variables?`,initialValue:!0,active:`Yes (Recommended)`,inactive:`No`});return I(n)?null:n}return!0}async function en(e){if(!e.installTypeDefinitions||e.framework!==`vite`&&e.framework!==`bun-fullstack`)return`skip`;let t=e.framework===`vite`?`vite-env.d.ts`:`bun-env.d.ts`;if(e.hasTypeFile){let e=await J({message:`Found existing ${X(t)}. How should we handle ArkEnv types?`,options:[{value:`append`,label:`Append types safely (if needed)`,hint:`Recommended`},{value:`overwrite`,label:`Overwrite entirely`,hint:`Destructive`},{value:`skip`,label:`Skip`}]});return I(e)?null:e}return`overwrite`}async function tn(e){let t=await J({message:`Select an example:`,options:e.examples.map(e=>({value:e.id,label:e.name,...e.description?{hint:e.description}:{}}))});return I(t)?null:t}async function nn(e){let t=await J({message:`Select your framework or build tool:`,initialValue:e.framework,options:[{value:`vanilla`,label:`Vanilla${e.framework===`vanilla`?` (Detected)`:``}`,hint:`Node.js, Bun, server-side or runtime-only validation`},{value:`vite`,label:`Vite${e.framework===`vite`?` (Detected)`:``}`,hint:`Client-side and static inlining validation`},{value:`bun-fullstack`,label:`Bun fullstack dev server${e.framework===`bun-fullstack`?` (Detected)`:``}`,hint:`Client-side bundling and Bun.serve integration`},{value:`nextjs`,label:`Next.js${e.framework===`nextjs`?` (Detected)`:``}`,hint:`Next.js App or Pages Router with build and runtime validation`},{value:`nuxt`,label:`Nuxt${e.framework===`nuxt`?` (Detected)`:``}`,hint:`Nuxt with build and runtime validation`}]});return I(t)?null:t}async function rn(e){let t=await G({message:`Optional: Would you also like to bootstrap a custom Bun.build script for programmatic bundling?`,initialValue:e.initialValue??!1});return I(t)?null:t}async function an(){let e=await J({message:`Select your preferred validator library:`,options:[{value:`arktype`,label:`ArkType (Recommended)`,hint:`TypeScript's 1:1 validator, optimized from editor to runtime`},{value:`zod`,label:`Zod`,hint:`TypeScript-first schema validation with static type inference`},{value:`valibot`,label:`Valibot`,hint:`The modular and type safe schema library`}]});return I(e)?null:e}async function on(e){let t=await J({message:`How would you like to structure your environment variables?`,options:(e?.framework,[{value:`flat`,label:`Flat (Recommended)`,hint:`A single flat env.ts file for the best DX`},{value:`strict`,label:`Strict`,hint:`Separate shared, client, and server files for hard bundle boundaries.`}])});return I(t)?null:t}async function sn(e){let t=await G({message:`Enable automated ${e.framework===`nuxt`?`Nuxt`:`Next.js`} code generation for environment variables?`,initialValue:e.initialValue??!0,active:`Yes (Recommended)`,inactive:`No`});return I(t)?null:t}async function cn(e){let t=await G({message:`Use default config path (${X(e.defaultEnvPath||`./src/env.ts`)})?`,initialValue:!0,active:`Yes (Recommended)`,inactive:`No, let me customize it`});return I(t)?null:t}async function ln(e){let t=e.defaultEnvPath||`./src/env.ts`;if(!e.useDefaultPath){let e=await ot({message:`Where should we create the ArkEnv config?`,placeholder:t,initialValue:t,defaultValue:t});if(I(e))return null;let n=typeof e==`string`?e.trim():``;return n===``?t:n}return t}const Z={example:tn,overwriteEnvSchemaFile:Zt,framework:nn,bunBuild:rn,layout:on,nextjsCodegen:sn,useDefaultPath:cn,path:ln,installTypeDefinitions:$t,envDtsHandling:en,validator:an,useEnvExample:Qt};async function un(e,t=!1){return(e?.mode||`existing`)===`new`?dn(e,t):fn(e,t)}async function dn(e,t=!1){let n=e?.examples||[],r=`arkenv-project`;try{let i;if(e?.name){let t=e.name.trim();i=t===`.`||t===`./`||o.default.resolve(process.cwd(),t)===process.cwd()?`.`:t}else if(t)i=r;else{let e=(Q(await ot({message:`Project name:`,placeholder:r,defaultValue:r}))||r).trim();i=e===`.`||e===`./`||o.default.resolve(process.cwd(),e)===process.cwd()?`.`:e}let a=e?.example;!a&&!t?a=Q(await Z.example({examples:n})):!a&&t&&(a=`basic`);let s=n.find(e=>e.id===a);if(!s){let e=n.map(e=>e.id).join(`, `);throw Error(`Unknown example ${a}. Available examples: ${e}`)}return{mode:`new`,example:s.id,name:i,path:`./src/env.ts`,validator:`arktype`,framework:s.framework,language:`ts`,installSkill:!1}}catch(e){if(e instanceof mn)return null;throw e}}async function fn(e,n=!1){let r=e?.defaultEnvPath||`./src/env.ts`,i=e?.envKeys||null,a=e?.envKeysSource||`.env.example`;if(n){let n=e?.framework||`vanilla`,a;(n===`nextjs`||n===`nuxt`)&&(a=e?.isStrict?`strict`:e?.isSimple?`simple`:(e?.isFlat,`flat`));let o=await pn(e,n,r),s;return(n===`vite`||n===`bun-fullstack`)&&(s=o?`append`:`overwrite`),(0,t.shake)({mode:`existing`,path:r,validator:`arktype`,framework:n,layout:a,bunFeatures:n===`bun-fullstack`?e?.bunFeatures??[`serve`]:void 0,language:`ts`,overwriteEnvSchemaFile:!0,installTypeDefinitions:n===`vite`||n===`bun-fullstack`,installSkill:!1,envDtsHandling:s,envKeys:i??void 0,disableCodegen:e?.disableCodegen??!1,wrapNextjsConfig:n===`nextjs`?!0:void 0})}try{let n=Q(await Z.overwriteEnvSchemaFile({hasEnvSchemaFile:e?.hasEnvSchemaFile??!1,defaultPath:r})),o=Q(await Z.framework({framework:e?.framework})),s;(o===`nextjs`||o===`nuxt`)&&(s=e?.isStrict?`strict`:e?.isSimple?`simple`:e?.isFlat?`flat`:Q(await Z.layout({framework:o})));let c;if(o===`bun-fullstack`){let t=!!e?.bunFeatures?.includes(`build`);c=Q(await Z.bunBuild({initialValue:t}))}let l=e?.disableCodegen;o===`nuxt`?l=!0:o===`nextjs`&&l===void 0&&(l=!Q(await Z.nextjsCodegen({initialValue:!0,framework:o})));let u;if(o===`nextjs`&&!l){let e=await G({message:`Would you like to wrap your Next.js config with ${X(`withArkEnv`)}?`,initialValue:!0,active:`Yes (Recommended)`,inactive:`No`});if(I(e))throw Qe(`Operation cancelled`),new mn;u=e}let d=Q(await Z.useDefaultPath({defaultEnvPath:r})),f=Q(await Z.path({useDefaultPath:d,defaultEnvPath:r})),p=await pn(e,o,f),m=Q(await Z.installTypeDefinitions({framework:o,hasTypeFile:p})),h=Q(await Z.envDtsHandling({framework:o,installTypeDefinitions:m,hasTypeFile:p})),g=Q(await Z.validator()),_=Q(await Z.useEnvExample({detectedKeys:i,keysSource:a}));return(0,t.shake)({mode:`existing`,overwriteEnvSchemaFile:n,framework:o,layout:s,path:f,installTypeDefinitions:m,envDtsHandling:h,validator:g,bunFeatures:o===`bun-fullstack`?c?[`serve`,`build`]:[`serve`]:void 0,language:`ts`,installSkill:!1,envKeys:_?i??void 0:void 0,disableCodegen:l,wrapNextjsConfig:u})}catch(e){if(e instanceof mn)return null;throw e}}async function pn(e,t,n){return await e?.hasTypeFileAtPath?.({framework:t,envPath:n})??e?.hasTypeFile??!1}var mn=class extends Error{constructor(){super(`Operation cancelled`)}};function Q(e){if(e===null||I(e))throw Qe(`Operation cancelled`),new mn;return e}var hn=class{async confirm(e,n=!0,r,i){let a=await G((0,t.shake)({message:e,initialValue:n,active:r,inactive:i}));return I(a)?null:a}async runWizard(e,t=!1){return un(e,t)}};const gn={isYes:{long:`--yes`,short:`-y`,kind:`boolean`},isForce:{long:`--force`,short:`-f`,kind:`boolean`},isQuiet:{long:`--quiet`,short:`-q`,kind:`boolean`},isJson:{long:`--json`,short:`-j`,kind:`boolean`},isAgent:{long:`--agent`,short:`-a`,kind:`boolean`},helpRequested:{long:`--help`,short:`-h`,kind:`boolean`},example:{long:`--example`,short:`-e`,kind:`value`},isStrict:{long:`--strict`,short:``,kind:`boolean`},isSimple:{long:`--simple`,short:``,kind:`boolean`},isFlat:{long:`--flat`,short:``,kind:`boolean`},noCodegen:{long:`--no-codegen`,short:`-C`,kind:`boolean`}},_n=new Set(Object.values(gn).flatMap(e=>[e.long,e.short].filter(Boolean))),vn=new Set(Object.values(gn).filter(e=>e.kind===`value`).flatMap(e=>[e.long,e.short].filter(Boolean)));var yn=class{constructor(e,t={}){let n=e.slice(2),r=[],i=!1;for(let e of n){if(i){r.push(e),i=!1;continue}if(vn.has(e)){r.push(e),i=!0;continue}if(/^-[a-zA-Z]{2,}$/.test(e)){let t=e.slice(1).split(``);for(let e of t)r.push(`-${e}`);vn.has(`-${t[t.length-1]}`)&&(i=!0)}else r.push(e)}this.args=r,this.command=this.args[0];let a=1,o=[];for(this.validationError=void 0;a<this.args.length;){let e=this.args[a];if(e.startsWith(`-`)){if(!_n.has(e)){this.validationError=`Unknown argument: ${e}`;break}if(vn.has(e))if(a+1<this.args.length&&!this.args[a+1].startsWith(`-`))a+=2;else{this.validationError=`Missing value for option: ${e}`;break}else a+=1}else o.push(e),a+=1}this.validationError||(o.length>1?this.validationError=`Unknown argument: ${o[1]}`:this.name=o[0]),this.logger=t.logger||new ct({isQuiet:this.isQuiet,isJson:this.isJson,isYes:this.isYes})}get isAgent(){return this.hasFlag(`isAgent`)}get isYes(){return this.isAgent||this.hasFlag(`isYes`)}get isQuiet(){return this.isAgent||this.hasFlag(`isQuiet`)}get isJson(){return this.isAgent||this.hasFlag(`isJson`)}get isForce(){return this.hasFlag(`isForce`)}get helpRequested(){return this.hasFlag(`helpRequested`)}get example(){let e=gn.example;return this.getFlagValue(e.long,e.short)}get isStrict(){return this.hasFlag(`isStrict`)}get isSimple(){return this.hasFlag(`isSimple`)}get isFlat(){return this.hasFlag(`isFlat`)}get noCodegen(){return this.hasFlag(`noCodegen`)}hasFlag(e){let t=gn[e];return this.args.includes(t.long)||!!t.short&&this.args.includes(t.short)}get initInput(){let e={isYes:this.isYes,isForce:this.isForce,isQuiet:this.isQuiet,isAgent:this.isAgent,isStrict:this.isStrict,isSimple:this.isSimple,isFlat:this.isFlat};return this.example!==void 0&&(e.example=this.example),this.name!==void 0&&(e.name=this.name),this.noCodegen&&(e.noCodegen=!0),e}getFlagValue(e,t){let n=this.args.findIndex(n=>n===e||n===t);if(n!==-1&&this.args[n+1]&&!this.args[n+1].startsWith(`-`))return this.args[n+1]}},bn=`1.0.0-alpha.4`;function xn(e,t=2,n=4){let r=Math.max(...e.map(e=>e.left.length),0),i=` `.repeat(t);return e.map(e=>{let t=` `.repeat(r-e.left.length+n);return`${i}${e.left}${t}${e.right}`})}var Sn=class{constructor(e){this.logger=e}async execute(){let e=[{left:`arkenv init [project-name]`,right:`Set up ArkEnv in your project`}],t=[{left:`--yes, -y`,right:`Skip prompts and use defaults (also passed to subprocesses)`},{left:`--force, -f`,right:`Bypass technical requirement checks and dirty git working tree check, then force scaffolding`},{left:`--agent, -a`,right:`Enable non-interactive, machine-readable mode for AI agents. Bypasses all prompts and outputs structured JSON. Macro for --yes --quiet --json`},{left:`--example, -e`,right:`Specify an example name when creating a new project`},{left:`--quiet, -q`,right:`Quiet mode: Suppress output, capture logs on failure`},{left:`--json, -j`,right:`Output structured JSON to stdout`},{left:`--no-codegen, -C`,right:`Disable automatic env.gen.ts code generation for Next.js`},{left:`--help, -h`,right:`Show this help message`}];this.logger.log(`ArkEnv CLI v${bn}`),this.logger.log(`\n${D.default.bold(`Usage:`)}`);for(let t of xn(e))this.logger.log(t);this.logger.log(`\n${D.default.bold(`Options:`)}`);for(let e of xn(t))this.logger.log(e)}};function Cn(e,t,n,r,i,a){let{extraImports:o,serverField:s,clientField:c,sharedField:l,defaultServerFields:u,defaultClientFields:d,defaultSharedFields:f}=t,p=i===`nuxt`?`NUXT_PUBLIC_`:`NEXT_PUBLIC_`,m=i===`nuxt`?`@arkenv/nuxt`:`@arkenv/nextjs`,h=i===`nuxt`?`Nuxt`:`Next.js`,g=[],_=[],v=[];if(e&&e.length>0)for(let t of e)t.startsWith(p)?_.push(c(t)):t===`NODE_ENV`?v.push(l(t)):g.push(s(t));else g.push(...u),_.push(...d),v.push(...f);if((i===`nextjs`||i===`nuxt`)&&a!==`simple`&&a!==`strict`){let t=[...g,..._,...v].map(e=>e.replace(/^\t\t/,` `)),a=[];for(let e of v){let t=e.trim().match(/^([a-zA-Z0-9_]+)\s*:/);if(t){let e=t[1];e!==`NODE_ENV`&&a.push(e)}}let s=[];if(a.length>0&&s.push(`\texposeToClient: [${a.map(e=>`"${e}"`).join(`, `)}]`),r&&i===`nextjs`){let t=[];if(e&&e.length>0)for(let n of e)(n.startsWith(p)||n===`NODE_ENV`||a.includes(n))&&t.push(`\t\t${n}: process.env.${n},`);else{t.push(` NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL,`,` NODE_ENV: process.env.NODE_ENV,`);for(let e of a)t.push(`\t\t${e}: process.env.${e},`)}s.push(`\truntimeEnv: {\n${t.join(`
117
- `)}\n\t}`)}let c=s.length>0?`, {\n${s.join(`,
118
- `)}\n}`:``;return`${[`import arkenv from "${i===`nuxt`?m:r?`@arkenv/nextjs`:n||`./generated/env.gen`}";`,...o?[o]:[]].join(`
116
+ `),{success:!0,instructions:i.trim()}}async function dn(e,t){let n=t||await Ht();if(!n)return{status:`not_found`};let r=o.default.basename(n);try{let t=await e.readFile(n);if((0,d.parse)(t)?.compilerOptions?.strict===!0)return{status:`already_strict`,file:r};let i=(0,d.applyEdits)(t,(0,d.modify)(t,[`compilerOptions`,`strict`],!0,{formattingOptions:{insertSpaces:!0,tabSize:2}}));return await e.writeFile(n,i),{status:`updated`,file:r}}catch{return{status:`error`,file:r}}}var fn=class{constructor(e,t,n){this.isQuiet=e,this.stdio=t,this.logger=n}async exists(e){try{return await s.default.access(e),!0}catch{return!1}}async readFile(e){return s.default.readFile(e,`utf-8`)}async writeFile(e,t){await s.default.writeFile(e,t,`utf-8`)}async mkdir(e,t){await s.default.mkdir(e,{recursive:t})}async execute(e,t=[],n){return new Promise((r,i)=>{let a=(0,l.spawn)(e,t,{cwd:n,stdio:this.isQuiet?`pipe`:this.stdio,shell:!1}),o=``,s=``,c=1e4;this.isQuiet&&(a.stdout?.on(`data`,e=>{o=(o+e.toString()).slice(-c)}),a.stderr?.on(`data`,e=>{s=(s+e.toString()).slice(-c)})),a.on(`close`,(e,t)=>{if(e===0)r();else{let n=e===null?`Command terminated by signal ${t}`:`Command failed with code ${e}`;this.isQuiet&&(o&&(n+=`\n${S.default.dim(`STDOUT:`)}\n${o}`),s&&(n+=`\n${S.default.red(`STDERR:`)}\n${s}`)),i(Error(n))}}),a.on(`error`,i)})}async updateTsConfigToStrict(e){return dn(this,e)}async findViteConfig(e){return nn(e)}async findBunConfig(e){return rn(e)}async findNextjsConfig(e){return an(e)}async findNuxtConfig(e){return sn(e)}async bootstrapViteConfig(e,t){return ln(this,e,t)}async bootstrapBunConfig(e,t){return un(e,t)}async bootstrapNextjsConfig(e,t){return on(this,e,t)}async bootstrapNuxtConfig(e){return cn(this,e)}async safeAppend(e,t,n){let{safeAppend:r}=await Promise.resolve().then(()=>wt);return r(e,t,n,this.logger)}};async function pn(e){let t=e.defaultPath||`./src/env.ts`;if(e.hasEnvSchemaFile){let e=await H({message:S.default.yellow(`An existing ArkEnv configuration was found at ${K(t)}. Do you want to overwrite it?`),initialValue:!1,active:`Yes (override my configuration)`,inactive:`No (abort)`});return I(e)||!e?null:e}return!0}async function mn(e){let t=e.detectedKeys,n=e.keysSource||`.env.example`;if(t&&t.length>0){let e=t.length,r=e===1,i=await H({message:n===`.env.example`?`Detected ${K(`.env.example`)} with ${e} ${r?`key`:`keys`}. Use ${r?`it`:`them`} for your schema?`:`Detected ${e} environment variable${r?``:`s`} used in your project. Use ${r?`it`:`them`} for your schema?`,active:`Yes (Recommended)`,initialValue:!0});return I(i)?null:i}return!1}async function hn(e){if(e.framework===`vite`||e.framework===`bun-fullstack`){let t=e.framework===`vite`?`vite-env.d.ts`:`bun-env.d.ts`;if(e.hasTypeFile)return!0;let n=await H({message:`Establish ${K(t)} for typesafe environment variables?`,initialValue:!0,active:`Yes (Recommended)`,inactive:`No`});return I(n)?null:n}return!0}async function gn(e){if(!e.installTypeDefinitions||e.framework!==`vite`&&e.framework!==`bun-fullstack`)return`skip`;let t=e.framework===`vite`?`vite-env.d.ts`:`bun-env.d.ts`;if(e.hasTypeFile){let e=await W({message:`Found existing ${K(t)}. How should we handle ArkEnv types?`,options:[{value:`append`,label:`Append types safely (if needed)`,hint:`Recommended`},{value:`overwrite`,label:`Overwrite entirely`,hint:`Destructive`},{value:`skip`,label:`Skip`}]});return I(e)?null:e}return`overwrite`}async function _n(e){let t=await W({message:`Select an example:`,options:e.examples.map(e=>({value:e.id,label:e.name,...e.description?{hint:e.description}:{}}))});return I(t)?null:t}async function vn(e){let t=await W({message:`Select your framework or build tool:`,initialValue:e.framework,options:[{value:`vanilla`,label:`Vanilla${e.framework===`vanilla`?` (Detected)`:``}`,hint:`Node.js, Bun, server-side or runtime-only validation`},{value:`vite`,label:`Vite${e.framework===`vite`?` (Detected)`:``}`,hint:`Client-side and static inlining validation`},{value:`bun-fullstack`,label:`Bun fullstack dev server${e.framework===`bun-fullstack`?` (Detected)`:``}`,hint:`Client-side bundling and Bun.serve integration`},{value:`nextjs`,label:`Next.js${e.framework===`nextjs`?` (Detected)`:``}`,hint:`Next.js App or Pages Router with build and runtime validation`},{value:`nuxt`,label:`Nuxt${e.framework===`nuxt`?` (Detected)`:``}`,hint:`Nuxt with build and runtime validation`}]});return I(t)?null:t}async function yn(e){let t=await H({message:`Optional: Would you also like to bootstrap a custom Bun.build script for programmatic bundling?`,initialValue:e.initialValue??!1});return I(t)?null:t}async function bn(){let e=await W({message:`Select your preferred validator library:`,options:[{value:`arktype`,label:`ArkType (Recommended)`,hint:`TypeScript's 1:1 validator, optimized from editor to runtime`},{value:`zod`,label:`Zod`,hint:`TypeScript-first schema validation with static type inference`},{value:`valibot`,label:`Valibot`,hint:`The modular and type safe schema library`}]});return I(e)?null:e}async function xn(e){let t=await W({message:`How would you like to structure your environment variables?`,options:(e?.framework,[{value:`flat`,label:`Flat (Recommended)`,hint:`A single flat env.ts file for the best DX`},{value:`strict`,label:`Strict`,hint:`Separate shared, client, and server files for hard bundle boundaries.`}])});return I(t)?null:t}async function Sn(e){let t=await H({message:`Enable automated ${e.framework===`nuxt`?`Nuxt`:`Next.js`} code generation for environment variables?`,initialValue:e.initialValue??!0,active:`Yes (Recommended)`,inactive:`No`});return I(t)?null:t}const Cn={vercel:{label:`Vercel`,hint:`Add VERCEL, VERCEL_ENV, VERCEL_URL, etc.`,serverOnlyKeys:[`VERCEL`],clientExposedKeys:[`VERCEL_ENV`,`VERCEL_URL`],fields:{VERCEL:{type:`string`},VERCEL_ENV:{type:`enum`,values:[`production`,`preview`,`development`]},VERCEL_URL:{type:`string`}}},netlify:{label:`Netlify`,hint:`Add NETLIFY, CONTEXT, URL, DEPLOY_URL, etc.`,serverOnlyKeys:[`NETLIFY`,`DEPLOY_URL`],clientExposedKeys:[`CONTEXT`,`URL`],fields:{NETLIFY:{type:`string`},DEPLOY_URL:{type:`string`},CONTEXT:{type:`enum`,values:[`production`,`deploy-preview`,`branch-deploy`]},URL:{type:`string`}}}};function wn(e){return e===`none`||Object.keys(Cn).includes(e)}function q(e,t){if(e===`none`)return[];let n=Cn[e],r=[...n.serverOnlyKeys,...n.clientExposedKeys];if(t)for(let e of n.clientExposedKeys)r.push(`${t}${e}`);return r}function Tn(e,t,n){if(!n||n===`none`)return;let r=t&&e.startsWith(t)?e.slice(t.length):e,i=Cn[n].fields;return r in i?i[r]:void 0}function En(e,t,n){let r=q(t??`none`,n);if(!(!e?.length&&r.length===0))return Array.from(new Set([...e??[],...r]))}async function Dn(e){let t=[{value:`none`,label:`None`,hint:`Do not add any hosting-specific environment variables`},...Object.entries(Cn).map(([e,t])=>({value:e,label:t.label,hint:t.hint}))],n=await W({message:`Select a hosting provider preset (optional):`,initialValue:e?.initialValue??`none`,options:t});return I(n)?null:n}async function On(e){let t=await H({message:`Use default config path (${K(e.defaultEnvPath||`./src/env.ts`)})?`,initialValue:!0,active:`Yes (Recommended)`,inactive:`No, let me customize it`});return I(t)?null:t}async function kn(e){let t=e.defaultEnvPath||`./src/env.ts`;if(!e.useDefaultPath){let e=await at({message:`Where should we create the ArkEnv config?`,placeholder:t,initialValue:t,defaultValue:t});if(I(e))return null;let n=typeof e==`string`?e.trim():``;return n===``?t:n}return t}const J={example:_n,overwriteEnvSchemaFile:pn,framework:vn,bunBuild:yn,layout:xn,nextjsCodegen:Sn,useDefaultPath:On,path:kn,installTypeDefinitions:hn,envDtsHandling:gn,validator:bn,hostPreset:Dn,useEnvExample:mn};async function An(e,t=!1){return(e?.mode||`existing`)===`new`?jn(e,t):Mn(e,t)}async function jn(e,t=!1){let n=e?.examples||[],r=`arkenv-project`;try{let i;if(e?.name){let t=e.name.trim();i=t===`.`||t===`./`||o.default.resolve(process.cwd(),t)===process.cwd()?`.`:t}else if(t)i=r;else{let e=(Y(await at({message:`Project name:`,placeholder:r,defaultValue:r}))||r).trim();i=e===`.`||e===`./`||o.default.resolve(process.cwd(),e)===process.cwd()?`.`:e}let a=e?.example;!a&&!t?a=Y(await J.example({examples:n})):!a&&t&&(a=`basic`);let s=n.find(e=>e.id===a);if(!s){let e=n.map(e=>e.id).join(`, `);throw Error(`Unknown example ${a}. Available examples: ${e}`)}return{mode:`new`,example:s.id,name:i,path:`./src/env.ts`,validator:`arktype`,framework:s.framework,language:`ts`,installSkill:!1}}catch(e){if(e instanceof Pn)return null;throw e}}async function Mn(e,n=!1){let r=e?.defaultEnvPath||`./src/env.ts`,i=e?.envKeys||null,a=e?.envKeysSource||`.env.example`;if(n){let n=e?.framework||`vanilla`,a;(n===`nextjs`||n===`nuxt`)&&(a=e?.isStrict?`strict`:e?.isSimple?`simple`:(e?.isFlat,`flat`));let o=await Nn(e,n,r),s;return(n===`vite`||n===`bun-fullstack`)&&(s=o?`append`:`overwrite`),(0,t.shake)({mode:`existing`,path:r,validator:`arktype`,framework:n,layout:a,bunFeatures:n===`bun-fullstack`?e?.bunFeatures??[`serve`]:void 0,language:`ts`,overwriteEnvSchemaFile:!0,installTypeDefinitions:n===`vite`||n===`bun-fullstack`,installSkill:!1,envDtsHandling:s,envKeys:i??void 0,disableCodegen:e?.disableCodegen??!1,wrapNextjsConfig:n===`nextjs`?!0:void 0,hostPreset:e?.hostPreset||`none`})}try{let n=Y(await J.overwriteEnvSchemaFile({hasEnvSchemaFile:e?.hasEnvSchemaFile??!1,defaultPath:r})),o=Y(await J.framework({framework:e?.framework})),s;(o===`nextjs`||o===`nuxt`)&&(s=e?.isStrict?`strict`:e?.isSimple?`simple`:e?.isFlat?`flat`:Y(await J.layout({framework:o})));let c;if(o===`bun-fullstack`){let t=!!e?.bunFeatures?.includes(`build`);c=Y(await J.bunBuild({initialValue:t}))}let l=e?.disableCodegen;o===`nuxt`?l=!0:o===`nextjs`&&l===void 0&&(l=!Y(await J.nextjsCodegen({initialValue:!0,framework:o})));let u;if(o===`nextjs`&&!l){let e=await H({message:`Would you like to wrap your Next.js config with ${K(`withArkEnv`)}?`,initialValue:!0,active:`Yes (Recommended)`,inactive:`No`});if(I(e))throw Xe(`Operation cancelled`),new Pn;u=e}let d=Y(await J.useDefaultPath({defaultEnvPath:r})),f=Y(await J.path({useDefaultPath:d,defaultEnvPath:r})),p=await Nn(e,o,f),m=Y(await J.installTypeDefinitions({framework:o,hasTypeFile:p})),h=Y(await J.envDtsHandling({framework:o,installTypeDefinitions:m,hasTypeFile:p})),g=Y(await J.validator()),_=e?.hostPreset===void 0?Y(await J.hostPreset({initialValue:e?.hostPreset})):e.hostPreset,v=Y(await J.useEnvExample({detectedKeys:i,keysSource:a}));return(0,t.shake)({mode:`existing`,overwriteEnvSchemaFile:n,framework:o,layout:s,path:f,installTypeDefinitions:m,envDtsHandling:h,validator:g,hostPreset:_,bunFeatures:o===`bun-fullstack`?c?[`serve`,`build`]:[`serve`]:void 0,language:`ts`,installSkill:!1,envKeys:v?i??void 0:void 0,disableCodegen:l,wrapNextjsConfig:u})}catch(e){if(e instanceof Pn)return null;throw e}}async function Nn(e,t,n){return await e?.hasTypeFileAtPath?.({framework:t,envPath:n})??e?.hasTypeFile??!1}var Pn=class extends Error{constructor(){super(`Operation cancelled`)}};function Y(e){if(e===null||I(e))throw Xe(`Operation cancelled`),new Pn;return e}var Fn=class{async confirm(e,n=!0,r,i){let a=await H((0,t.shake)({message:e,initialValue:n,active:r,inactive:i}));return I(a)?null:a}async runWizard(e,t=!1){return An(e,t)}};const X={isYes:{long:`--yes`,short:`-y`,kind:`boolean`},isForce:{long:`--force`,short:`-f`,kind:`boolean`},isQuiet:{long:`--quiet`,short:`-q`,kind:`boolean`},isJson:{long:`--json`,short:`-j`,kind:`boolean`},isAgent:{long:`--agent`,short:``,kind:`boolean`},helpRequested:{long:`--help`,short:`-h`,kind:`boolean`},example:{long:`--example`,short:`-e`,kind:`value`},isStrict:{long:`--strict`,short:``,kind:`boolean`},isSimple:{long:`--simple`,short:``,kind:`boolean`},isFlat:{long:`--flat`,short:``,kind:`boolean`},noCodegen:{long:`--no-codegen`,short:``,kind:`boolean`},hostPreset:{long:`--host-preset`,short:`-H`,kind:`value`}},In=new Set(Object.values(X).flatMap(e=>[e.long,e.short].filter(Boolean))),Ln=new Set(Object.values(X).filter(e=>e.kind===`value`).flatMap(e=>[e.long,e.short].filter(Boolean)));var Rn=class{constructor(e,t={}){let n=e.slice(2),r=[],i=!1;for(let e of n){if(i){r.push(e),i=!1;continue}if(Ln.has(e)){r.push(e),i=!0;continue}if(/^-[a-zA-Z]{2,}$/.test(e)){let t=e.slice(1).split(``);for(let e of t)r.push(`-${e}`);Ln.has(`-${t[t.length-1]}`)&&(i=!0)}else r.push(e)}this.args=r,this.command=this.args[0];let a=1,o=[];for(this.validationError=void 0;a<this.args.length;){let e=this.args[a];if(e.startsWith(`-`)){if(!In.has(e)){this.validationError=`Unknown argument: ${e}`;break}if(Ln.has(e))if(a+1<this.args.length&&!this.args[a+1].startsWith(`-`))a+=2;else{this.validationError=`Missing value for option: ${e}`;break}else a+=1}else o.push(e),a+=1}if(!this.validationError){let e=X.hostPreset,t=this.getFlagValue(e.long,e.short);t!==void 0&&!wn(t)&&(this.validationError=`Invalid host preset: ${t}`)}this.validationError||(o.length>1?this.validationError=`Unknown argument: ${o[1]}`:this.name=o[0]),this.logger=t.logger||new st({isQuiet:this.isQuiet,isJson:this.isJson,isYes:this.isYes})}get isAgent(){return this.hasFlag(`isAgent`)}get isYes(){return this.isAgent||this.hasFlag(`isYes`)}get isQuiet(){return this.isAgent||this.hasFlag(`isQuiet`)}get isJson(){return this.isAgent||this.hasFlag(`isJson`)}get isForce(){return this.hasFlag(`isForce`)}get helpRequested(){return this.hasFlag(`helpRequested`)}get example(){let e=X.example;return this.getFlagValue(e.long,e.short)}get isStrict(){return this.hasFlag(`isStrict`)}get isSimple(){return this.hasFlag(`isSimple`)}get isFlat(){return this.hasFlag(`isFlat`)}get noCodegen(){return this.hasFlag(`noCodegen`)}get hostPreset(){let e=X.hostPreset,t=this.getFlagValue(e.long,e.short);if(t!==void 0&&wn(t))return t}hasFlag(e){let t=X[e];return this.args.includes(t.long)||!!t.short&&this.args.includes(t.short)}get initInput(){let e={isYes:this.isYes,isForce:this.isForce,isQuiet:this.isQuiet,isAgent:this.isAgent,isStrict:this.isStrict,isSimple:this.isSimple,isFlat:this.isFlat};return this.example!==void 0&&(e.example=this.example),this.name!==void 0&&(e.name=this.name),this.noCodegen&&(e.noCodegen=!0),this.hostPreset!==void 0&&(e.hostPreset=this.hostPreset),e}getFlagValue(e,t){let n=this.args.findIndex(n=>n===e||n===t);if(n!==-1&&this.args[n+1]&&!this.args[n+1].startsWith(`-`))return this.args[n+1]}},zn=`1.0.0-alpha.6`;function Bn(e,t=2,n=4){let r=Math.max(...e.map(e=>e.left.length),0),i=` `.repeat(t);return e.map(e=>{let t=` `.repeat(r-e.left.length+n);return`${i}${e.left}${t}${e.right}`})}var Vn=class{constructor(e){this.logger=e}async execute(){let e=[{left:`arkenv init [project-name]`,right:`Set up ArkEnv in your project`}],t=[{left:`--yes, -y`,right:`Skip prompts and use defaults (also passed to subprocesses)`},{left:`--force, -f`,right:`Bypass technical requirement checks and dirty git working tree check, then force scaffolding`},{left:`--agent`,right:`Enable non-interactive, machine-readable mode for AI agents. Bypasses all prompts and outputs structured JSON. Macro for --yes --quiet --json`},{left:`--example, -e`,right:`Specify an example name when creating a new project`},{left:`--quiet, -q`,right:`Quiet mode: Suppress output, capture logs on failure`},{left:`--json, -j`,right:`Output structured JSON to stdout`},{left:`--no-codegen`,right:`Disable automatic env.gen.ts code generation for Next.js`},{left:`--host-preset, -H <preset>`,right:`Specify a hosting provider preset (none, vercel, netlify)`},{left:`--help, -h`,right:`Show this help message`}];this.logger.log(`ArkEnv CLI v${zn}`),this.logger.log(`\n${S.default.bold(`Usage:`)}`);for(let t of Bn(e))this.logger.log(t);this.logger.log(`\n${S.default.bold(`Options:`)}`);for(let e of Bn(t))this.logger.log(e)}};async function Hn(e,t){let n=t.targetDir??process.cwd(),r=o.default.join(process.cwd(),`.arkenv-temp`);await e.mkdir(r,!0),t.targetDir&&await e.mkdir(n,!0);try{await e.execute(`git`,[`clone`,`--filter=blob:none`,`--sparse`,t.repository,r]);let i=`examples/${t.example}`;await e.execute(`git`,[`-C`,r,`sparse-checkout`,`set`,i]);let a=o.default.join(r,i),c=await s.default.readdir(a),l=[];for(let t of c){let r=o.default.join(n,t);await e.exists(r)&&l.push(t)}if(l.length>0)throw Error(`Scaffolding into a non-empty directory failed. The following paths already exist: ${l.join(`, `)}`);await Un(a,n);for(let e of[`package-lock.json`,`pnpm-lock.yaml`,`yarn.lock`,`bun.lockb`,`bun.lock`])await s.default.rm(o.default.join(n,e),{force:!0});let u=o.default.join(n,`package.json`);if(await e.exists(u)){let n=await e.readFile(u),r=JSON.parse(n);r.name=t.targetName,delete r.packageManager,await e.writeFile(u,JSON.stringify(r,null,2))}}finally{await s.default.rm(r,{recursive:!0,force:!0})}}async function Un(e,t){let n=await s.default.readdir(e);await Promise.all(n.map(n=>s.default.cp(o.default.join(e,n),o.default.join(t,n),{recursive:!0,force:!1})))}function Wn(e,t){let n=t.length>0;switch(e){case`pnpm`:return[`pnpm`,[n?`add`:`install`,...t]];case`yarn`:return[`yarn`,[n?`add`:`install`,...t]];case`bun`:return[`bun`,[n?`add`:`install`,...t]];default:return[`npm`,[`install`,...t]]}}function Gn(e,t,n){if(t||e.metadata.skillDetected){let t=e.metadata.framework===`nextjs`&&!e.metadata.disableCodegen,r=e.metadata.framework===`nuxt`&&!e.metadata.disableCodegen,i=t&&!n,a=c.default`
117
+ Inside your AI assistant (e.g. Claude Code), use:
118
+ ${K(`/arkenv`)} - automatically refine your schema and configure integrations.
119
+ `;return i?(a+=`
120
+
121
+ `,a+=`Also, wrap your Next.js config with ${K(`withArkEnv`)}:\n`,a+=` ${K(`import { withArkEnv } from "@arkenv/nextjs/config";`)}\n`,e.metadata.layout===`strict`?(a+=` ${K(`export default withArkEnv(nextConfig);`)}\n`,a+=`Import and use: ${K(`import { env } from "${e.metadata.importPath}/client"`)} (client) or ${K(`import { env } from "${e.metadata.importPath}/server"`)} (server)\n`):(a+=` ${K(`export default withArkEnv(nextConfig);`)}\n`,a+=`Import and use: ${K(`import { env } from "${e.metadata.importPath}"`)}\n`)):r&&(a+=`
122
+
123
+ `,e.metadata.layout===`strict`?a+=`Import and use: ${K(`import { env } from "${e.metadata.importPath}/client"`)} (client) or ${K(`import { env } from "${e.metadata.importPath}/server"`)} (server)\n`:a+=`Import and use: ${K(`import { env } from "${e.metadata.importPath}"`)}\n`),{message:a,title:`Next steps`}}let r=e.skill?.dlxCommand.join(` `)||`npx`,i=e.skill?.packageName||`yamcodes/arkenv`,a=``,o=1,s=e.metadata.displayPath;if(e.metadata.layout===`strict`){let e=s.lastIndexOf(`.`),t=e===-1?s:s.slice(0,e);s=`${t}/client.ts, ${t}/server.ts, and ${t}/internal/shared.ts`}a+=`${o++}. Check ${K(s)} and refine your environment schema.\n`;let l=e.metadata.framework===`nextjs`&&!e.metadata.disableCodegen&&!n;return e.metadata.framework===`vite`?a+=`${o++}. Access via ${K(`import.meta.env.YOUR_VAR`)}\n`:e.metadata.framework===`bun-fullstack`?a+=`${o++}. Access via ${K(`process.env.YOUR_VAR`)}\n`:e.metadata.framework===`nextjs`?e.metadata.layout===`strict`?(e.metadata.disableCodegen||l&&(a+=`${o++}. Wrap your Next.js config with ${K(`withArkEnv`)} inside ${K(`next.config.ts`)}:\n`,a+=` ${K(`import { withArkEnv } from "@arkenv/nextjs/config";`)}\n`,a+=` ${K(`export default withArkEnv(nextConfig);`)}\n`),a+=`${o++}. Import and use: ${K(`import { env } from "${e.metadata.importPath}/client"`)} (client) or ${K(`import { env } from "${e.metadata.importPath}/server"`)} (server)\n`):(e.metadata.disableCodegen||l&&(a+=`${o++}. Wrap your Next.js config with ${K(`withArkEnv`)} inside ${K(`next.config.ts`)}:\n`,a+=` ${K(`import { withArkEnv } from "@arkenv/nextjs/config";`)}\n`,a+=` ${K(`export default withArkEnv(nextConfig);`)}\n`),a+=`${o++}. Import and use: ${K(`import { env } from "${e.metadata.importPath}"`)}\n`):e.metadata.framework===`nuxt`&&e.metadata.layout===`strict`?a+=`${o++}. Import and use: ${K(`import { env } from "${e.metadata.importPath}/client"`)} (client) or ${K(`import { env } from "${e.metadata.importPath}/server"`)} (server)\n`:a+=`${o++}. Import and use: ${K(`import { env } from "${e.metadata.importPath}"`)}\n`,a+=`${o++}. (Recommended) Install the AI skill: ${K(`${r} skills add ${i}`)}\n`,a+=` Then run ${K(`/arkenv`)} inside your AI assistant to finish.`,{message:a,title:`Next steps`}}const Kn=[`esbuild`];var qn=class{constructor(e,t){this.workspace=e,this.reporter=t}async execute(e){let t=this.reporter.spinner();t.start(`Scaffolding ArkEnv configuration...`);try{e.clone&&(t.stop(`Starting new project scaffolding...`),this.reporter.step(`Cloning example ${K(e.clone.example)}...`),await Hn(this.workspace,e.clone),t.start(`Scaffolding complete, finalizing...`));for(let t of e.files){if(t.action===`append`){if(!e.bootstrap||e.bootstrap.framework!==`vite`&&e.bootstrap.framework!==`bun-fullstack`){this.reporter.warn(`Skipping safe-append for ${K(o.default.basename(t.path))}: unsupported framework.`);continue}await this.workspace.safeAppend(t.path,t.content,e.bootstrap.framework)?this.reporter.info(`Appended ArkEnv types to ${K(o.default.basename(t.path))}.`):this.reporter.info(`${K(o.default.basename(t.path))} already contains ArkEnv types.`);continue}if(!(t.action===`create`&&await this.workspace.exists(t.path))&&(await this.workspace.mkdir(o.default.dirname(t.path),!0),await this.workspace.writeFile(t.path,t.content),t.label!==`environment schema`&&t.label?.includes(`types`))){let e=t.action===`overwrite`?`Updated`:`Created`;this.reporter.info(`${e} ${K(o.default.basename(t.path))} for typesafe environment variables.`)}}if(t.stop(`Configuration scaffolded!`),e.install&&process.env.SKIP_INSTALL!==`true`){e.install.packageManager===`pnpm`&&await this.configurePnpmBuilds(e.install.cwd??e.cwd),this.reporter.step(`Installing dependencies with ${K(e.install.packageManager)}...`);let[t,n]=Wn(e.install.packageManager,e.install.dependencies);await this.workspace.execute(t,n,e.install.cwd??e.cwd)}let n=!1;if(e.tsConfig){let t=await this.workspace.updateTsConfigToStrict(e.tsConfig.path);t.status===`updated`?(this.reporter.info(`Enforced strict: true in your ${K(t.file)}`),n=!0):t.status===`error`&&this.reporter.warn(`Could not automatically update ${K(t.file||`tsconfig.json`)}. Please ensure 'strict: true' is set manually.`)}let r=!1;if(e.bootstrap){if(e.bootstrap.framework===`vite`){let t=await this.workspace.findViteConfig(e.cwd);if(t){this.reporter.step(`Bootstrapping Vite plugin...`);let n=await this.workspace.bootstrapViteConfig(t,e.bootstrap.importPath||`./src/env`);n.success?n.updated&&this.reporter.info(`Updated ${K(o.default.basename(t))}`):(this.reporter.warn(`Could not automatically update ${K(o.default.basename(t))}: ${n.error}`),this.reporter.info(`Please add ${K(`@arkenv/vite-plugin`)} manually.`))}else this.reporter.info(`No Vite config found - please add ${K(`@arkenv/vite-plugin`)} to your Vite config manually.`)}else if(e.bootstrap.framework===`bun-fullstack`){let t=await this.workspace.findBunConfig(e.cwd),n=await this.workspace.bootstrapBunConfig(t,e.bootstrap.bunFeatures);n.success&&n.instructions?this.reporter.info(n.instructions):n.success||this.reporter.error(n.error||`Bun bootstrap failed`)}else if(e.bootstrap.framework===`nextjs`){if(!e.bootstrap.disableCodegen){this.reporter.step(`Generating Next.js environment bindings...`);let t=`import('@arkenv/nextjs/config').then(({ runCodegen }) => { const path = require('path'); const schemaPath = path.resolve(process.cwd(), '${e.metadata.displayPath}'); const outputPath = path.join(path.dirname(schemaPath), 'generated', 'env.gen.ts'); runCodegen(schemaPath, outputPath); }).catch(err => { console.error(err); process.exit(1); });`;try{await this.workspace.execute(`node`,[`-e`,t],e.cwd),this.reporter.info(`Generated ${K(`env.gen.ts`)} for Next.js`)}catch{this.reporter.warn(`Failed to automatically generate ${K(`env.gen.ts`)}. It will be generated when you start your dev server.`)}}if(e.bootstrap.wrapNextjsConfig!==!1){this.reporter.step(`Bootstrapping Next.js config...`);let t=await this.workspace.findNextjsConfig(e.cwd);if(t){let n=await this.workspace.bootstrapNextjsConfig(t,e.bootstrap.disableCodegen);n.success?n.updated?(this.reporter.info(`Updated ${K(o.default.basename(t))}`),r=!0):(this.reporter.info(`${K(o.default.basename(t))} already uses withArkEnv`),r=!0):this.reporter.warn(`Could not automatically update ${K(o.default.basename(t))}: ${n.error}`)}else this.reporter.info(`No Next.js config found. Please wrap your config with ${K(`withArkEnv`)} manually.`)}}else if(e.bootstrap.framework===`nuxt`){this.reporter.step(`Bootstrapping Nuxt config...`);let t=await this.workspace.findNuxtConfig(e.cwd);if(t){let e=await this.workspace.bootstrapNuxtConfig(t);e.success?(e.updated?this.reporter.info(`Updated ${K(o.default.basename(t))}`):this.reporter.info(`${K(o.default.basename(t))} already registers @arkenv/nuxt/module`),r=!0):this.reporter.warn(`Could not automatically update ${K(o.default.basename(t))}: ${e.error}`)}else this.reporter.info(`No Nuxt config found. Please register ${K(`@arkenv/nuxt/module`)} manually.`)}}let i=!1;if(e.skill&&process.env.SKIP_INSTALL!==`true`){this.reporter.step(`Installing ArkEnv agent skill...`);try{let[t,...n]=e.skill.dlxCommand,r=[...n,`skills`,`add`,e.skill.packageName];e.skill.isYes&&r.push(`--yes`),await this.workspace.execute(t,r,e.cwd),i=!0}catch(e){let t=e instanceof Error?e.message:String(e);this.reporter.warn(`Failed to install ArkEnv AI skill: ${t}`)}}let a=Gn(e,i,r);if(this.reporter.note(a.message,a.title),e.metadata.layout===`strict`){let t=o.default.resolve(e.cwd,e.metadata.displayPath);if(await this.workspace.exists(t)){let t=e.metadata.displayPath,n=o.default.basename(t,o.default.extname(t));this.reporter.warn(`Found existing single-file schema at ${K(t)}. You can delete it after updating your imports to point to your new ${K(`${n}/client`)} and ${K(`${n}/server`)}.`)}}this.reporter.finish(`${Xt} ArkEnv scaffolding complete. Happy coding!`,{path:e.metadata.displayPath,framework:e.metadata.framework,validator:e.metadata.validator,packageManager:e.metadata.packageManager,tsConfigUpdated:n,skillInstalled:i})}catch(e){throw t.stop(`Scaffolding failed.`),e}}async configurePnpmBuilds(e){let t=o.default.join(e,`package.json`);if(await this.workspace.exists(t))try{let e=await this.workspace.readFile(t),n=JSON.parse(e);n.pnpm=n.pnpm||{},n.pnpm.onlyBuiltDependencies=n.pnpm.onlyBuiltDependencies||[];for(let e of Kn)n.pnpm.onlyBuiltDependencies.includes(e)||n.pnpm.onlyBuiltDependencies.push(e);await this.workspace.writeFile(t,JSON.stringify(n,null,2)+`
124
+ `)}catch(e){this.reporter.warn(`Could not update package.json with pnpm whitelisting: ${e}`)}let n=o.default.join(e,`pnpm-workspace.yaml`),r=``;if(await this.workspace.exists(n))try{r=await this.workspace.readFile(n)}catch{}let i=this.updatePnpmWorkspaceYaml(r);try{await this.workspace.writeFile(n,i)}catch(e){this.reporter.warn(`Could not write pnpm-workspace.yaml: ${e}`)}}updatePnpmWorkspaceYaml(e){let t=(0,p.parseDocument)(e||``);t.has(`allowBuilds`)||t.set(`allowBuilds`,t.createNode({}));let n=t.get(`allowBuilds`);if((0,p.isMap)(n)||(t.set(`allowBuilds`,t.createNode({})),n=t.get(`allowBuilds`)),(0,p.isMap)(n))for(let e of Kn)n.get(e)!==!0&&n.set(e,!0);return String(t)}};const Jn=e=>c.default`
125
+ /// <reference types="vite/client" />
126
+
127
+ type ImportMetaEnvAugmented =
128
+ import("@arkenv/vite-plugin").ImportMetaEnvAugmented<
129
+ typeof import("./${o.default.basename(e).replace(/\.(ts|js|tsx|jsx)$/,``)}").Env
130
+ >;
131
+
132
+ interface ImportMetaEnv extends ImportMetaEnvAugmented {}
133
+
134
+ interface ImportMeta {
135
+ readonly env: ImportMetaEnv;
136
+ }
137
+ `,Yn=e=>c.default`
138
+ /// <reference types="bun-types" />
139
+
140
+ type ProcessEnvAugmented = import("@arkenv/bun-plugin").ProcessEnvAugmented<
141
+ typeof import("./${o.default.basename(e).replace(/\.(ts|js|tsx|jsx)$/,``)}").Env
142
+ >;
143
+
144
+ declare namespace NodeJS {
145
+ interface ProcessEnv extends ProcessEnvAugmented {}
146
+ }
147
+ `,Z={nextjs:{id:`nextjs`,packageName:`@arkenv/nextjs`,clientPrefix:`NEXT_PUBLIC_`,displayName:`Next.js`,supportsWrapNextjsConfig:!0},nuxt:{id:`nuxt`,packageName:`@arkenv/nuxt`,clientPrefix:`NUXT_PUBLIC_`,displayName:`Nuxt`,supportsWrapNextjsConfig:!1}};function Xn(e){if(e===`nextjs`||e===`nuxt`)return Z[e]}function Zn(e){return e===`nextjs`||e===`nuxt`}const Qn={nextjs:Z.nextjs.clientPrefix,nuxt:Z.nuxt.clientPrefix,vite:`VITE_`,"bun-fullstack":`BUN_PUBLIC_`,vanilla:``};function $n(e){let{typeFilePath:t,typeFileExists:n,envDtsHandling:r,templateContent:i,appendContent:a,overwriteLabel:o,appendLabel:s}=e;return r===`skip`?[]:r===`append`||!r&&n?[{path:t,content:a,action:`append`,label:s}]:[{path:t,content:i,action:n?`overwrite`:`create`,label:o}]}function er(e,t){let n=Xn(e.framework);return{framework:e.framework,clientPrefix:Qn[e.framework],...n?.packageName!==void 0&&{packageName:n.packageName},disableCodegen:e.disableCodegen===!0,...e.layout!==void 0&&{layout:e.layout},...t!==void 0&&{nextjsImportPath:t},...e.hostPreset!==void 0&&{hostPreset:e.hostPreset}}}const tr={NODE_ENV:`development`,PORT:`3000`,DATABASE_URL:`postgres://localhost:5432/mydb`},nr=`generated`;function rr(e){let t={};for(let n of e)t[n]=tr[n]??``;return t}function ir(e,t,n){if(!n)return;let r=((n.compilerOptions||{}).paths||{})[`@/*`];if(!r)return;let i=n.path?o.default.dirname(n.path):e,a=o.default.relative(i,t).replace(/\\/g,`/`);for(let e of r){let t=e.replace(/^\.\//,``).replace(/\*$/,``);if(t===``||a.startsWith(t)){let e=a;return t!==``&&a.startsWith(t)&&(e=a.substring(t.length)),e=e.replace(/^\/+/,``).replace(/\/+$/,``),`@/${e}/env.gen`.replace(/\/+/g,`/`)}}}function ar(e,t,n){if(!(!Zn(n.framework)||n.disableCodegen||!e.tsConfig?.parsed))return ir(e.cwd,t,e.tsConfig.parsed)}function or(e,t){return ar(e,o.default.join(e.targetDir,nr),t)}function sr(e,t,n){return ar(e,o.default.join(t,nr),n)}function Q(e,t,n,r){let i=er(t,r),a=e.getSimpleTemplate(t.envKeys??[],i),o=n.existingFiles.includes(n.targetPath);return!o||t.overwriteEnvSchemaFile!==!1?[{path:n.targetPath,content:a,action:o?`overwrite`:`create`,label:`environment schema`}]:[]}function cr(e,t,n,r){let i=o.default.extname(n.targetPath),a=n.targetPath.slice(0,-i.length),s=o.default.join(a,`internal`,`shared${i}`),c=o.default.join(a,`client${i}`),l=o.default.join(a,`server${i}`),u=er(t,r),d=e.getStrictTemplates(t.envKeys??[],u),f=n.existingFiles.includes(s),p=n.existingFiles.includes(c),m=n.existingFiles.includes(l),h=[];return(!f||t.overwriteEnvSchemaFile!==!1)&&h.push({path:s,content:d.shared,action:f?`overwrite`:`create`,label:`shared environment schema`}),(!p||t.overwriteEnvSchemaFile!==!1)&&h.push({path:c,content:d.client,action:p?`overwrite`:`create`,label:`client environment schema`}),(!m||t.overwriteEnvSchemaFile!==!1)&&h.push({path:l,content:d.server,action:m?`overwrite`:`create`,label:`server environment schema`}),h}const lr={clientPrefix:Qn[`bun-fullstack`],getEnvDefaults(e){return e&&e.length>0?rr(e):{BUN_PUBLIC_API_URL:`https://api.example.com`,NODE_ENV:`development`}},getDependencies(e){return e.bunFeatures?.length?[`@arkenv/bun-plugin`]:[]},requiresArktypePeer(e){return!!e.bunFeatures?.length},bootstrap(e){return(0,t.shake)({framework:`bun-fullstack`,bunFeatures:e.bunFeatures})},getSchemaFiles(e,t,n){return Q(e,t,n)},getTypeDefinitionFiles(e,t){if(!e.bunFeatures?.length||e.installTypeDefinitions===!1)return[];let n=o.default.join(t.targetDir,`bun-env.d.ts`);return $n({typeFilePath:n,typeFileExists:t.existingFiles.includes(n),envDtsHandling:e.envDtsHandling,templateContent:Yn(e.path),appendContent:t.targetPath,overwriteLabel:`bun-fullstack types`,appendLabel:`${e.framework} types`})}};function ur(e){let{id:n,packageName:r,clientPrefix:i,supportsWrapNextjsConfig:a}=e,s=`${i}API_URL`;return{clientPrefix:i,getEnvDefaults(e){return e&&e.length>0?rr(e):{DATABASE_URL:`postgres://localhost:5432/mydb`,[s]:`https://api.example.com`,NODE_ENV:`development`}},getDependencies(){return[r]},requiresArktypePeer(){return!0},bootstrap(e){return(0,t.shake)({framework:n,...a&&{wrapNextjsConfig:e.wrapNextjsConfig!==!1},disableCodegen:e.disableCodegen})},getSchemaFiles(e,t,n){if(t.layout===`strict`){let r=o.default.extname(n.targetPath);return cr(e,t,n,sr(n,n.targetPath.slice(0,-r.length),t))}return Q(e,t,n,or(n,t))},getTypeDefinitionFiles(){return[]}}}const dr=ur(Z.nextjs),fr=ur(Z.nuxt),pr={clientPrefix:Qn.vanilla,getEnvDefaults(e){return e&&e.length>0?rr(e):{PORT:`3000`,NODE_ENV:`development`}},getDependencies(){return[]},requiresArktypePeer(){return!1},bootstrap(){},getSchemaFiles(e,t,n){return Q(e,t,n)},getTypeDefinitionFiles(){return[]}},mr={vite:{clientPrefix:Qn.vite,getEnvDefaults(e){return e&&e.length>0?rr(e):{PORT:`3000`,VITE_API_URL:`https://api.example.com`}},getDependencies(){return[`@arkenv/vite-plugin`]},requiresArktypePeer(){return!0},bootstrap(e){return(0,t.shake)({framework:`vite`})},getSchemaFiles(e,t,n){return Q(e,t,n)},getTypeDefinitionFiles(e,t){return e.installTypeDefinitions===!1?[]:$n({typeFilePath:o.default.join(t.targetDir,`vite-env.d.ts`),typeFileExists:t.existingFiles.includes(o.default.join(t.targetDir,`vite-env.d.ts`)),envDtsHandling:e.envDtsHandling,templateContent:Jn(e.path),appendContent:t.targetPath,overwriteLabel:`vite types`,appendLabel:`${e.framework} types`})}},"bun-fullstack":lr,nextjs:dr,nuxt:fr,vanilla:pr},hr={basic:{HOST:`localhost`,PORT:`3000`,NODE_ENV:`development`},"basic-js":{HOST:`localhost`,PORT:`3000`,NODE_ENV:`development`},"with-bun":{HOST:`localhost`,PORT:`3000`,NODE_ENV:`development`},"with-nextjs":{DATABASE_URL:`postgres://localhost:5432/mydb`,NEXT_PUBLIC_API_URL:`https://api.example.com`,NODE_ENV:`development`},"with-nextjs-strict":{DATABASE_URL:`postgres://localhost:5432/mydb`,NEXT_PUBLIC_API_URL:`https://api.example.com`,NODE_ENV:`development`},"with-nuxt":{DATABASE_URL:`postgres://localhost:5432/mydb`,NUXT_PUBLIC_API_URL:`https://api.example.com`,NODE_ENV:`development`},"with-vite-react":{PORT:`3000`,VITE_MY_VAR:`hello`,VITE_MY_NUMBER:`42`,VITE_MY_BOOLEAN:`true`},"with-bun-react":{BUN_PUBLIC_API_URL:`https://api.example.com`,BUN_PUBLIC_DEBUG:`true`,NODE_ENV:`development`},"with-zod":{HOST:`localhost`,PORT:`3000`,NODE_ENV:`development`},"with-standard-schema":{HOST:`localhost`,PORT:`3000`,NODE_ENV:`development`}};function gr(e,t){return hr[e]??t()}function _r(e){switch(e){case`pnpm`:return[`pnpm`,`dlx`];case`yarn`:return[`yarn`,`dlx`];case`bun`:return[`bunx`];default:return[`npx`]}}function vr(e,t,n,r){let i=q(r??`none`,n);for(let a of i)n&&a.startsWith(n)?e.clientFields.push(`\t\t${t.formatCodegenField(a,`client`,n,r)}`):e.serverFields.push(`\t\t${t.formatCodegenField(a,`server`,n,r)}`)}function yr(e){let t=[];for(let n of e){let e=n.trim().match(/^([a-zA-Z0-9_]+)\s*:/);e&&t.push(e[1])}return t}function br(e,t,n,r=[]){let i=[],a=new Set,o=e=>{a.has(e)||(a.add(e),i.push(`\t\t${e}: process.env.${e},`))};if(e&&e.length>0){for(let n of e)(n.startsWith(t)||n===`NODE_ENV`||r.includes(n))&&o(n);return i}o(`${t}API_URL`),o(`NODE_ENV`);for(let e of yr(n))o(e);for(let e of r)o(e);return i}function xr(e){let{envKeys:t,dialect:n,config:r,importPath:i,disableCodegen:a,layout:o,hostPreset:s}=e,{clientPrefix:c}=r,l=[],u=[],d=[];if(t&&t.length>0)for(let e of t)e.startsWith(c)?u.push(`\t\t${n.formatCodegenField(e,`client`,c,s)}`):e===`NODE_ENV`?d.push(`\t\t${n.formatCodegenField(e,`shared`,c,s)}`):l.push(`\t\t${n.formatCodegenField(e,`server`,c,s)}`);else{let e=n.getDefaultCodegenFields(c);l.push(...e.serverFields),u.push(...e.clientFields),d.push(...e.sharedFields),vr({serverFields:l,clientFields:u},n,c,s)}return o!==`simple`&&o!==`strict`?Sr({serverFields:l,clientFields:u,sharedFields:d,envKeys:t,dialect:n,config:r,nextjsImportPath:i,disableCodegen:a}):Cr({serverFields:l,clientFields:u,sharedFields:d,envKeys:t,dialect:n,config:r,nextjsImportPath:i,disableCodegen:a,layout:o})}function Sr(e){let{serverFields:t,clientFields:n,sharedFields:r,envKeys:i,dialect:a,config:o,nextjsImportPath:s,disableCodegen:c}=e,{clientPrefix:l,packageName:u,displayName:d}=o,f=o.id,p=a.extraImport,m=[...t,...n,...r].map(e=>e.replace(/^\t\t/,` `)),h=[];for(let e of r){let t=e.trim().match(/^([a-zA-Z0-9_]+)\s*:/);if(t){let e=t[1];e!==`NODE_ENV`&&h.push(e)}}let g=[];if(h.length>0&&g.push(`\texposeToClient: [${h.map(e=>`"${e}"`).join(`, `)}]`),c&&f===`nextjs`){let e=br(i,l,n,h);g.push(`\truntimeEnv: {\n${e.join(`
148
+ `)}\n\t}`)}let _=g.length>0?`, {\n${g.join(`,
149
+ `)}\n}`:``;return`${[`import arkenv from "${f===`nuxt`||c?u:s||`./generated/env.gen`}";`,...p?[p]:[]].join(`
119
150
  `)}
120
151
 
121
152
  /**
122
153
  * Environment variable schema.
123
- * ${i===`nuxt`?`In ${h}, use \`${m}\` to validate variables at build-time and runtime.`:`In ${h}, use the generated \`arkenv\` from \`env.gen.ts\` to validate variables.`}
154
+ * ${f===`nuxt`?`In ${d}, use \`${u}\` to validate variables at build-time and runtime.`:`In ${d}, use the generated \`arkenv\` from \`env.gen.ts\` to validate variables.`}
124
155
  * Enforces client/server separation and prevents secret leaks.
125
156
  */
126
157
  export const env = arkenv({
127
- ${t.join(`
158
+ ${m.join(`
128
159
  `)}
129
- }${c});
130
- `}let y=[];if(g.length>0&&y.push(`\tserver: {\n${g.join(`
131
- `)}\n\t}`),_.length>0&&y.push(`\tclient: {\n${_.join(`
132
- `)}\n\t}`),v.length>0&&y.push(`\tshared: {\n${v.join(`
133
- `)}\n\t}`),r||i===`nuxt`&&a===`simple`){let t=[];if(e&&e.length>0)for(let n of e)(n.startsWith(p)||n===`NODE_ENV`)&&t.push(`\t\t${n}: process.env.${n},`);else t.push(`\t\t${p}API_URL: process.env.${p}API_URL,`,` NODE_ENV: process.env.NODE_ENV,`);return i!==`nuxt`&&y.push(`\truntimeEnv: {\n${t.join(`
134
- `)}\n\t}`),`${[`import arkenv from "${m}";`,...o?[o]:[]].join(`
160
+ }${_});
161
+ `}function Cr(e){let{serverFields:t,clientFields:n,sharedFields:r,envKeys:i,dialect:a,config:o,nextjsImportPath:s,disableCodegen:c,layout:l}=e,{clientPrefix:u,packageName:d,displayName:f}=o,p=o.id,m=a.extraImport,h=[];if(t.length>0&&h.push(`\tserver: {\n${t.join(`
162
+ `)}\n\t}`),n.length>0&&h.push(`\tclient: {\n${n.join(`
163
+ `)}\n\t}`),r.length>0&&h.push(`\tshared: {\n${r.join(`
164
+ `)}\n\t}`),c||p===`nuxt`&&l===`simple`){let e=br(i,u,n);return p!==`nuxt`&&h.push(`\truntimeEnv: {\n${e.join(`
165
+ `)}\n\t}`),`${[`import arkenv from "${d}";`,...m?[m]:[]].join(`
135
166
  `)}
136
167
 
137
168
  /**
138
169
  * Environment variable schema.
139
- * In ${h}, use \`${m}\` to validate variables at build-time and runtime.
170
+ * In ${f}, use \`${d}\` to validate variables at build-time and runtime.
140
171
  * Enforces client/server separation and prevents secret leaks.
141
172
  */
142
173
  export const env = arkenv({
143
- ${y.join(`,
174
+ ${h.join(`,
144
175
  `)},
145
176
  });
146
- `}return`${[`import arkenv from "${n||`./generated/env.gen`}";`,...o?[o]:[]].join(`
177
+ `}return`${[`import arkenv from "${s||`./generated/env.gen`}";`,...m?[m]:[]].join(`
147
178
  `)}
148
179
 
149
180
  /**
150
181
  * Environment variable schema.
151
- * In ${h}, use the generated \`arkenv\` from \`env.gen.ts\` to validate variables.
182
+ * In ${f}, use the generated \`arkenv\` from \`env.gen.ts\` to validate variables.
152
183
  * Enforces client/server separation and prevents secret leaks.
153
184
  */
154
185
  export const env = arkenv({
155
- ${y.join(`,
186
+ ${h.join(`,
156
187
  `)},
157
188
  });
158
- `}const wn=(e,t,n,r,i)=>{let a=e?.length?e.map(e=>`\t\t${e}: "string?",`).join(`
159
- `):` NODE_ENV: "'development' | 'production' | 'test' = 'development'",
160
- PORT: "number.port = 3000",`;return t===`vite`?c.default`
161
- import { type } from "@arkenv/core";
162
-
163
- /**
164
- * Environment variable schema.
165
- * In Vite, use \`@arkenv/vite-plugin\` to validate these at build-time
166
- * and provide typesafety for \`import.meta.env\` on the client-side.
167
- */
168
- export const Env = type({
169
- ${a}
170
- });
171
- `:t===`bun-fullstack`?c.default`
172
- import { type } from "@arkenv/core";
173
-
174
- /**
175
- * Environment variable schema.
176
- * In Bun Fullstack, use \`@arkenv/bun-plugin\` to validate these at build-time
177
- * and provide typesafety for \`process.env\` on the client-side.
178
- */
179
- export const Env = type({
180
- ${a}
181
- });
182
- `:t===`nextjs`||t===`nuxt`?Cn(e,{serverField:e=>`\t\t${e}: "string?",`,clientField:e=>`\t\t${e}: "string?",`,sharedField:e=>`\t\t${e}: "'development' | 'production' | 'test' = 'development'",`,defaultServerFields:[` DATABASE_URL: "string = 'postgres://localhost:5432/mydb'",`],defaultClientFields:[`\t\t${t===`nuxt`?`NUXT_PUBLIC_`:`NEXT_PUBLIC_`}API_URL: "string = 'https://api.example.com'",`],defaultSharedFields:[` NODE_ENV: "'development' | 'production' | 'test' = 'development'",`]},n,r,t,i):c.default`
183
- import arkenv, { type } from "@arkenv/core";
189
+ `}function wr(e,t,n){return c.default`
190
+ ${e.pluginEnvImports.split(`
191
+ `).map(e=>`\t${e}`).join(`
192
+ `)}
184
193
 
185
194
  /**
186
- * Environment variable schema for server-side or runtime-only validation.
195
+ * ${t===`vite`?"Environment variable schema.\n * In Vite, use `@arkenv/vite-plugin` to validate these at build-time\n * and provide typesafety for `import.meta.env` on the client-side.":"Environment variable schema.\n * In Bun Fullstack, use `@arkenv/bun-plugin` to validate these at build-time\n * and provide typesafety for `process.env` on the client-side."}
187
196
  */
188
197
  export const Env = type({
189
- ${a}
198
+ ${n}
190
199
  });
200
+ `}function Tr(e,t,n){let r=q(n.hostPreset??`none`,n.clientPrefix),i=Xn(n.framework);if(i){let a=t.length>0?Array.from(new Set([...t,...r])):void 0;return`${xr({...a===void 0?{}:{envKeys:a},dialect:e,config:i,...n.nextjsImportPath!==void 0&&{importPath:n.nextjsImportPath},disableCodegen:n.disableCodegen,...n.layout!==void 0&&{layout:n.layout},...n.hostPreset!==void 0&&{hostPreset:n.hostPreset}})}\n`}let a;if(t.length>0){let i=Array.from(new Set([...t,...r]));a=e.formatSimpleSchemaFields(i,n.clientPrefix,n.hostPreset)}else a=r.length>0?`${e.defaultSimpleSchemaFields}\n${e.formatSimpleSchemaFields(r,n.clientPrefix,n.hostPreset)}`:e.defaultSimpleSchemaFields;return n.framework===`vite`||n.framework===`bun-fullstack`?`${wr(e,n.framework,a)}\n`:`${e.assembleVanilla(a)}\n`}function Er(e,t=` `){return e.length===0?`{}`:`{\n${t}${e.map(e=>e.trim()).join(`\n${t}`)}\n${t.slice(1)}}`}function Dr(e,t,n){let r=[],i=[],a=[],o=[];for(let s of e)s.startsWith(t.clientPrefix)?(i.push(n(s,`client`,t)),o.push(`${s}: process.env.${s},`)):s===`NODE_ENV`?(a.push(n(s,`shared`,t)),o.push(`${s}: process.env.${s},`)):r.push(n(s,`server`,t));return{serverFields:r,clientFields:i,sharedFields:a,runtimeEnvFields:o}}function Or(e,t){return{shared:`${e.shared}\n`,client:`${jr(t)?e.clientNoCodegen:e.clientCodegen}\n`,server:`${e.server}\n`}}function kr(e){return e.packageName??Xn(e.framework)?.packageName??`@arkenv/nextjs`}function Ar(e,t){return t.framework===`nuxt`?``:`,\n\t\truntimeEnv: {\n\t\t\t${e.map(e=>e.trim()).join(`
201
+ `)}\n\t\t}`}function jr(e){return e.disableCodegen||e.framework===`nuxt`}function Mr(e){return jr(e)?`${kr(e)}/client`:e.nextjsImportPath||`./generated/env.gen`}function Nr(e,t,n){let r=q(n.hostPreset??`none`,n.clientPrefix);for(let i of r)n.clientPrefix&&i.startsWith(n.clientPrefix)?(e.clientFields.push(t.formatStrictField(i,`client`,n.clientPrefix,n.hostPreset)),e.runtimeEnvFields.push(`${i}: process.env.${i},`)):e.serverFields.push(t.formatStrictField(i,`server`,n.clientPrefix,n.hostPreset))}function Pr(e,t,n){let r=kr(n),i=Mr(n),a=q(n.hostPreset??`none`,n.clientPrefix),{serverFields:o,clientFields:s,sharedFields:c,runtimeEnvFields:l}=t.length>0?Dr(Array.from(new Set([...t,...a])),n,(t,r)=>e.formatStrictField(t,r,n.clientPrefix,n.hostPreset)):(()=>{let t=e.getDefaultStrictFields(n.clientPrefix);return Nr(t,e,n),t})(),u=Ar(l,n),d=Er(c,` `),f=Er(s,` `),p=Er(o,` `),m=e.strictExtraImports;return Or({shared:`${e.sharedImports}
191
202
 
192
- export const env = arkenv(Env);
193
- `},Tn=e=>c.default`
194
- /// <reference types="vite/client" />
195
-
196
- type ImportMetaEnvAugmented =
197
- import("@arkenv/vite-plugin").ImportMetaEnvAugmented<
198
- typeof import("./${o.default.basename(e).replace(/\.(ts|js|tsx|jsx)$/,``)}").Env
199
- >;
200
-
201
- interface ImportMetaEnv extends ImportMetaEnvAugmented {}
203
+ /**
204
+ * @internal 🛑 INTERNAL SCHEMA ONLY.
205
+ * Do not import this directly. Import \`env\` from \`./client\` or \`./server\` instead.
206
+ */
207
+ export const SharedSchema = ${e.wrapSharedSchema(d)};`,clientCodegen:`import arkenv from "${i}";
208
+ ${m}import { SharedSchema } from "./internal/shared";
202
209
 
203
- interface ImportMeta {
204
- readonly env: ImportMetaEnv;
205
- }
206
- `,En=e=>c.default`
207
- /// <reference types="bun-types" />
210
+ export const env = arkenv(
211
+ ${f},
212
+ {
213
+ extends: [SharedSchema],
214
+ },
215
+ );`,clientNoCodegen:`import arkenv from "${i}";
216
+ ${m}import { SharedSchema } from "./internal/shared";
208
217
 
209
- type ProcessEnvAugmented = import("@arkenv/bun-plugin").ProcessEnvAugmented<
210
- typeof import("./${o.default.basename(e).replace(/\.(ts|js|tsx|jsx)$/,``)}").Env
211
- >;
218
+ export const env = arkenv(
219
+ ${f},
220
+ {
221
+ extends: [SharedSchema]${u}
222
+ },
223
+ );`,server:`import arkenv from "${r}/server";
224
+ ${m}import { env as clientEnv } from "./client";
212
225
 
213
- declare namespace NodeJS {
214
- interface ProcessEnv extends ProcessEnvAugmented {}
215
- }
216
- `,Dn=(e,t,n,r,i)=>{let a=e?.length?e.map(e=>`\t\t${e}: v.optional(v.string()),`).join(`
217
- `):` NODE_ENV: v.optional(v.picklist(["development", "production", "test"]), "development"),
218
- PORT: v.optional(v.pipe(v.string(), v.transform(Number), v.number(), v.integer(), v.minValue(1), v.maxValue(65535)), 3000),`;return t===`vite`?c.default`
219
- import { type } from "@arkenv/core";
220
- import * as v from "valibot";
226
+ export const env = arkenv(
227
+ ${p},
228
+ {
229
+ extends: [clientEnv],
230
+ },
231
+ );`},n)}function Fr(e,t){return t.type===`string`?e.formatOptionalString():e.formatOptionalEnum(t.values)}function $(e,t,n,r){let i=Tn(t,n,r);if(i)return Fr(e,i)}const Ir={formatOptionalString(){return`"string?"`},formatOptionalEnum(e){return`"'${e.join(`' | '`)}'?"`},formatStrictField(e,t,n=``,r=void 0){if(t===`shared`)return`${e}: "'development' | 'production' | 'test' = 'development'",`;if(t===`server`&&e===`PORT`)return`PORT: "number.port = 3000",`;let i=$(Ir,e,n,r);return i?`${e}: ${i},`:`${e}: "string?",`},formatCodegenField(e,t,n=``,r=void 0){if(t===`shared`)return`${e}: "'development' | 'production' | 'test' = 'development'",`;let i=$(Ir,e,n,r);return i?`${e}: ${i},`:`${e}: "string?",`},defaultSimpleSchemaFields:` NODE_ENV: "'development' | 'production' | 'test' = 'development'",
232
+ PORT: "number.port = 3000",`,formatSimpleSchemaFields(e,t=``,n=void 0){return e.map(e=>`\t\t${e}: ${$(Ir,e,t,n)??`"string?"`},`).join(`
233
+ `)},getDefaultStrictFields(e){let t=`${e}API_URL`;return{serverFields:[`DATABASE_URL: "string = 'postgres://localhost:5432/mydb'",`],clientFields:[`${t}: "string = 'https://api.example.com'",`],sharedFields:[`NODE_ENV: "'development' | 'production' | 'test' = 'development'",`],runtimeEnvFields:[`${t}: process.env.${t},`,`NODE_ENV: process.env.NODE_ENV,`]}},getDefaultCodegenFields(e){return{serverFields:[` DATABASE_URL: "string = 'postgres://localhost:5432/mydb'",`],clientFields:[`\t\t${e}API_URL: "string = 'https://api.example.com'",`],sharedFields:[` NODE_ENV: "'development' | 'production' | 'test' = 'development'",`]}},sharedImports:`import { type } from "@arkenv/core";`,wrapSharedSchema(e){return`type(${e})`},strictExtraImports:``,assembleVanilla(e){return c.default`
234
+ import arkenv, { type } from "@arkenv/core";
221
235
 
222
236
  /**
223
- * Environment variable schema.
224
- * In Vite, use \`@arkenv/vite-plugin\` to validate these at build-time
225
- * and provide typesafety for \`import.meta.env\` on the client-side.
237
+ * Environment variable schema for server-side or runtime-only validation.
226
238
  */
227
239
  export const Env = type({
228
- ${a}
240
+ ${e}
229
241
  });
230
- `:t===`bun-fullstack`?c.default`
231
- import { type } from "@arkenv/core";
232
- import * as v from "valibot";
233
242
 
234
- /**
235
- * Environment variable schema.
236
- * In Bun Fullstack, use \`@arkenv/bun-plugin\` to validate these at build-time
237
- * and provide typesafety for \`process.env\` on the client-side.
238
- */
239
- export const Env = type({
240
- ${a}
241
- });
242
- `:t===`nextjs`||t===`nuxt`?Cn(e,{extraImports:`import * as v from "valibot";`,serverField:e=>`\t\t${e}: v.optional(v.string()),`,clientField:e=>`\t\t${e}: v.optional(v.string()),`,sharedField:e=>`\t\t${e}: v.optional(v.picklist(["development", "production", "test"]), "development"),`,defaultServerFields:[` DATABASE_URL: v.optional(v.pipe(v.string(), v.url()), "postgres://localhost:5432/mydb"),`],defaultClientFields:[`\t\t${t===`nuxt`?`NUXT_PUBLIC_`:`NEXT_PUBLIC_`}API_URL: v.optional(v.pipe(v.string(), v.url()), "https://api.example.com"),`],defaultSharedFields:[` NODE_ENV: v.optional(v.picklist(["development", "production", "test"]), "development"),`]},n,r,t,i):c.default`
243
+ export const env = arkenv(Env);
244
+ `},pluginEnvImports:`import { type } from "@arkenv/core";`},Lr={extraImport:`import * as v from "valibot";`,formatOptionalString(){return`v.optional(v.string())`},formatOptionalEnum(e){return`v.optional(v.picklist([${e.map(e=>`"${e}"`).join(`, `)}]))`},formatStrictField(e,t,n=``,r=void 0){if(t===`shared`)return`${e}: v.optional(v.picklist(["development", "production", "test"]), "development"),`;if(t===`server`&&e===`PORT`)return`PORT: v.optional(v.pipe(v.string(), v.transform(Number), v.number(), v.integer(), v.minValue(1), v.maxValue(65535)), 3000),`;let i=$(Lr,e,n,r);return i?`${e}: ${i},`:`${e}: v.optional(v.string()),`},formatCodegenField(e,t,n=``,r=void 0){if(t===`shared`)return`${e}: v.optional(v.picklist(["development", "production", "test"]), "development"),`;let i=$(Lr,e,n,r);return i?`${e}: ${i},`:`${e}: v.optional(v.string()),`},defaultSimpleSchemaFields:` NODE_ENV: v.optional(v.picklist(["development", "production", "test"]), "development"),
245
+ PORT: v.optional(v.pipe(v.string(), v.transform(Number), v.number(), v.integer(), v.minValue(1), v.maxValue(65535)), 3000),`,formatSimpleSchemaFields(e,t=``,n=void 0){return e.map(e=>`\t\t${e}: ${$(Lr,e,t,n)??`v.optional(v.string())`},`).join(`
246
+ `)},getDefaultStrictFields(e){let t=`${e}API_URL`;return{serverFields:[`DATABASE_URL: v.optional(v.pipe(v.string(), v.url()), "postgres://localhost:5432/mydb"),`],clientFields:[`${t}: v.optional(v.pipe(v.string(), v.url()), "https://api.example.com"),`],sharedFields:[`NODE_ENV: v.optional(v.picklist(["development", "production", "test"]), "development"),`],runtimeEnvFields:[`${t}: process.env.${t},`,`NODE_ENV: process.env.NODE_ENV,`]}},getDefaultCodegenFields(e){return{serverFields:[` DATABASE_URL: v.optional(v.pipe(v.string(), v.url()), "postgres://localhost:5432/mydb"),`],clientFields:[`\t\t${e}API_URL: v.optional(v.pipe(v.string(), v.url()), "https://api.example.com"),`],sharedFields:[` NODE_ENV: v.optional(v.picklist(["development", "production", "test"]), "development"),`]}},sharedImports:`import * as v from "valibot";`,wrapSharedSchema(e){return`v.object(${e})`},strictExtraImports:`import * as v from "valibot";
247
+ `,assembleVanilla(e){return c.default`
243
248
  import arkenv from "@arkenv/standard";
244
249
  import * as v from "valibot";
245
250
 
@@ -247,35 +252,13 @@ ${a}
247
252
  * Environment variable schema for server-side or runtime-only validation.
248
253
  */
249
254
  export const env = arkenv({
250
- ${a}
251
- });
252
- `},On=(e,t,n,r,i)=>{let a=e?.length?e.map(e=>`\t\t${e}: z.string().optional(),`).join(`
253
- `):` NODE_ENV: z.enum(["development", "production", "test"]).default("development"),
254
- PORT: z.coerce.number().int().min(1).max(65535).default(3000),`;return t===`vite`?c.default`
255
- import { type } from "@arkenv/core";
256
- import { z } from "zod";
257
-
258
- /**
259
- * Environment variable schema.
260
- * In Vite, use \`@arkenv/vite-plugin\` to validate these at build-time
261
- * and provide typesafety for \`import.meta.env\` on the client-side.
262
- */
263
- export const Env = type({
264
- ${a}
255
+ ${e}
265
256
  });
266
- `:t===`bun-fullstack`?c.default`
267
- import { type } from "@arkenv/core";
268
- import { z } from "zod";
269
-
270
- /**
271
- * Environment variable schema.
272
- * In Bun Fullstack, use \`@arkenv/bun-plugin\` to validate these at build-time
273
- * and provide typesafety for \`process.env\` on the client-side.
274
- */
275
- export const Env = type({
276
- ${a}
277
- });
278
- `:t===`nextjs`||t===`nuxt`?Cn(e,{extraImports:`import { z } from "zod";`,serverField:e=>`\t\t${e}: z.string().optional(),`,clientField:e=>`\t\t${e}: z.string().optional(),`,sharedField:e=>`\t\t${e}: z.enum(["development", "production", "test"]).default("development"),`,defaultServerFields:[` DATABASE_URL: z.string().url().default("postgres://localhost:5432/mydb"),`],defaultClientFields:[`\t\t${t===`nuxt`?`NUXT_PUBLIC_`:`NEXT_PUBLIC_`}API_URL: z.string().url().default("https://api.example.com"),`],defaultSharedFields:[` NODE_ENV: z.enum(["development", "production", "test"]).default("development"),`]},n,r,t,i):c.default`
257
+ `},pluginEnvImports:`import { type } from "@arkenv/core";
258
+ import * as v from "valibot";`},Rr={extraImport:`import { z } from "zod";`,formatOptionalString(){return`z.string().optional()`},formatOptionalEnum(e){return`z.enum([${e.map(e=>`"${e}"`).join(`, `)}]).optional()`},formatStrictField(e,t,n=``,r=void 0){if(t===`shared`)return`${e}: z.enum(["development", "production", "test"]).default("development"),`;if(t===`server`&&e===`PORT`)return`PORT: z.coerce.number().int().min(1).max(65535).default(3000),`;let i=$(Rr,e,n,r);return i?`${e}: ${i},`:`${e}: z.string().optional(),`},formatCodegenField(e,t,n=``,r=void 0){if(t===`shared`)return`${e}: z.enum(["development", "production", "test"]).default("development"),`;let i=$(Rr,e,n,r);return i?`${e}: ${i},`:`${e}: z.string().optional(),`},defaultSimpleSchemaFields:` NODE_ENV: z.enum(["development", "production", "test"]).default("development"),
259
+ PORT: z.coerce.number().int().min(1).max(65535).default(3000),`,formatSimpleSchemaFields(e,t=``,n=void 0){return e.map(e=>`\t\t${e}: ${$(Rr,e,t,n)??`z.string().optional()`},`).join(`
260
+ `)},getDefaultStrictFields(e){let t=`${e}API_URL`;return{serverFields:[`DATABASE_URL: z.string().url().default("postgres://localhost:5432/mydb"),`],clientFields:[`${t}: z.string().url().default("https://api.example.com"),`],sharedFields:[`NODE_ENV: z.enum(["development", "production", "test"]).default("development"),`],runtimeEnvFields:[`${t}: process.env.${t},`,`NODE_ENV: process.env.NODE_ENV,`]}},getDefaultCodegenFields(e){return{serverFields:[` DATABASE_URL: z.string().url().default("postgres://localhost:5432/mydb"),`],clientFields:[`\t\t${e}API_URL: z.string().url().default("https://api.example.com"),`],sharedFields:[` NODE_ENV: z.enum(["development", "production", "test"]).default("development"),`]}},sharedImports:`import { z } from "zod";`,wrapSharedSchema(e){return`z.object(${e})`},strictExtraImports:`import { z } from "zod";
261
+ `,assembleVanilla(e){return c.default`
279
262
  import arkenv from "@arkenv/standard";
280
263
  import { z } from "zod";
281
264
 
@@ -283,123 +266,18 @@ ${a}
283
266
  * Environment variable schema for server-side or runtime-only validation.
284
267
  */
285
268
  export const env = arkenv({
286
- ${a}
269
+ ${e}
287
270
  });
288
- `};function kn(e,t){let{validator:n,envKeys:r,framework:i,disableCodegen:a,layout:o}=e;switch(n){case`arktype`:return`${wn(r,i,t,a,o)}\n`;case`zod`:return`${On(r,i,t,a,o)}\n`;case`valibot`:return`${Dn(r,i,t,a,o)}\n`;default:throw Error(`Unsupported validator: ${n}`)}}function $(e,t=` `){return e.length===0?`{}`:`{\n${t}${e.map(e=>e.trim()).join(`\n${t}`)}\n${t.slice(1)}}`}function An(e,t){let{validator:n,envKeys:r}=e,i=e.disableCodegen||e.framework===`nuxt`,a=[],o=[],s=[],c=[],l=e.framework===`nuxt`?`NUXT_PUBLIC_`:`NEXT_PUBLIC_`,u=e.framework===`nuxt`?`@arkenv/nuxt`:`@arkenv/nextjs`;if(r&&r.length>0)for(let e of r)e.startsWith(l)?(n===`arktype`?o.push(`${e}: "string?",`):n===`zod`?o.push(`${e}: z.string().optional(),`):n===`valibot`&&o.push(`${e}: v.optional(v.string()),`),c.push(`${e}: process.env.${e},`)):e===`NODE_ENV`?(n===`arktype`?s.push(`${e}: "'development' | 'production' | 'test' = 'development'",`):n===`zod`?s.push(`${e}: z.enum(["development", "production", "test"]).default("development"),`):n===`valibot`&&s.push(`${e}: v.optional(v.picklist(["development", "production", "test"]), "development"),`),c.push(`${e}: process.env.${e},`)):e===`PORT`?n===`arktype`?a.push(`PORT: "number.port = 3000",`):n===`zod`?a.push(`PORT: z.coerce.number().int().min(1).max(65535).default(3000),`):n===`valibot`&&a.push(`PORT: v.optional(v.pipe(v.string(), v.transform(Number), v.number(), v.integer(), v.minValue(1), v.maxValue(65535)), 3000),`):n===`arktype`?a.push(`${e}: "string?",`):n===`zod`?a.push(`${e}: z.string().optional(),`):n===`valibot`&&a.push(`${e}: v.optional(v.string()),`);else{let t=e.framework===`nuxt`?`NUXT_PUBLIC_API_URL`:`NEXT_PUBLIC_API_URL`;n===`arktype`?(a.push(`DATABASE_URL: "string = 'postgres://localhost:5432/mydb'",`),o.push(`${t}: "string = 'https://api.example.com'",`),s.push(`NODE_ENV: "'development' | 'production' | 'test' = 'development'",`)):n===`zod`?(a.push(`DATABASE_URL: z.string().url().default("postgres://localhost:5432/mydb"),`),o.push(`${t}: z.string().url().default("https://api.example.com"),`),s.push(`NODE_ENV: z.enum(["development", "production", "test"]).default("development"),`)):n===`valibot`&&(a.push(`DATABASE_URL: v.optional(v.pipe(v.string(), v.url()), "postgres://localhost:5432/mydb"),`),o.push(`${t}: v.optional(v.pipe(v.string(), v.url()), "https://api.example.com"),`),s.push(`NODE_ENV: v.optional(v.picklist(["development", "production", "test"]), "development"),`)),c.push(`${t}: process.env.${t},`,`NODE_ENV: process.env.NODE_ENV,`)}let d=e.framework===`nuxt`?``:`,\n\t\truntimeEnv: {\n\t\t\t${c.map(e=>e.trim()).join(`
289
- `)}\n\t\t}`,f=``,p=``,m=``;return n===`arktype`?(f=`import { type } from "@arkenv/core";
290
-
291
- /**
292
- * @internal 🛑 INTERNAL SCHEMA ONLY.
293
- * Do not import this directly. Import \`env\` from \`./client\` or \`./server\` instead.
294
- */
295
- export const SharedSchema = type(${$(s,` `)});`,p=i?`import arkenv from "${u}/client";
296
- import { SharedSchema } from "./internal/shared";
297
-
298
- export const env = arkenv(
299
- ${$(o,` `)},
300
- {
301
- extends: [SharedSchema]${d}
302
- },
303
- );`:`import arkenv from "${t||`./generated/env.gen`}";
304
- import { SharedSchema } from "./internal/shared";
305
-
306
- export const env = arkenv(
307
- ${$(o,` `)},
308
- {
309
- extends: [SharedSchema],
310
- },
311
- );`,m=`import arkenv from "${u}/server";
312
- import { env as clientEnv } from "./client";
313
-
314
- export const env = arkenv(
315
- ${$(a,` `)},
316
- {
317
- extends: [clientEnv],
318
- },
319
- );`):n===`zod`?(f=`import { z } from "zod";
320
-
321
- /**
322
- * @internal 🛑 INTERNAL SCHEMA ONLY.
323
- * Do not import this directly. Import \`env\` from \`./client\` or \`./server\` instead.
324
- */
325
- export const SharedSchema = z.object(${$(s,` `)});`,p=i?`import arkenv from "${u}/client";
326
- import { z } from "zod";
327
- import { SharedSchema } from "./internal/shared";
328
-
329
- export const env = arkenv(
330
- ${$(o,` `)},
331
- {
332
- extends: [SharedSchema]${d}
333
- },
334
- );`:`import arkenv from "${t||`./generated/env.gen`}";
335
- import { z } from "zod";
336
- import { SharedSchema } from "./internal/shared";
337
-
338
- export const env = arkenv(
339
- ${$(o,` `)},
340
- {
341
- extends: [SharedSchema],
342
- },
343
- );`,m=`import arkenv from "${u}/server";
344
- import { z } from "zod";
345
- import { env as clientEnv } from "./client";
346
-
347
- export const env = arkenv(
348
- ${$(a,` `)},
349
- {
350
- extends: [clientEnv],
351
- },
352
- );`):n===`valibot`&&(f=`import * as v from "valibot";
353
-
354
- /**
355
- * @internal 🛑 INTERNAL SCHEMA ONLY.
356
- * Do not import this directly. Import \`env\` from \`./client\` or \`./server\` instead.
357
- */
358
- export const SharedSchema = v.object(${$(s,` `)});`,p=i?`import arkenv from "${u}/client";
359
- import * as v from "valibot";
360
- import { SharedSchema } from "./internal/shared";
361
-
362
- export const env = arkenv(
363
- ${$(o,` `)},
364
- {
365
- extends: [SharedSchema]${d}
366
- },
367
- );`:`import arkenv from "${t||`./generated/env.gen`}";
368
- import * as v from "valibot";
369
- import { SharedSchema } from "./internal/shared";
370
-
371
- export const env = arkenv(
372
- ${$(o,` `)},
373
- {
374
- extends: [SharedSchema],
375
- },
376
- );`,m=`import arkenv from "${u}/server";
377
- import * as v from "valibot";
378
- import { env as clientEnv } from "./client";
379
-
380
- export const env = arkenv(
381
- ${$(a,` `)},
382
- {
383
- extends: [clientEnv],
384
- },
385
- );`),{shared:`${f}\n`,client:`${p}\n`,server:`${m}\n`}}async function jn(e,t){let n=t.targetDir??process.cwd(),r=o.default.join(process.cwd(),`.arkenv-temp`);await e.mkdir(r,!0),t.targetDir&&await e.mkdir(n,!0);try{await e.execute(`git`,[`clone`,`--filter=blob:none`,`--sparse`,t.repository,r]);let i=`examples/${t.example}`;await e.execute(`git`,[`-C`,r,`sparse-checkout`,`set`,i]);let a=o.default.join(r,i),c=await s.default.readdir(a),l=[];for(let t of c){let r=o.default.join(n,t);await e.exists(r)&&l.push(t)}if(l.length>0)throw Error(`Scaffolding into a non-empty directory failed. The following paths already exist: ${l.join(`, `)}`);await Mn(a,n);for(let e of[`package-lock.json`,`pnpm-lock.yaml`,`yarn.lock`,`bun.lockb`,`bun.lock`])await s.default.rm(o.default.join(n,e),{force:!0});let u=o.default.join(n,`package.json`);if(await e.exists(u)){let n=await e.readFile(u),r=JSON.parse(n);r.name=t.targetName,delete r.packageManager,await e.writeFile(u,JSON.stringify(r,null,2))}}finally{await s.default.rm(r,{recursive:!0,force:!0})}}async function Mn(e,t){let n=await s.default.readdir(e);await Promise.all(n.map(n=>s.default.cp(o.default.join(e,n),o.default.join(t,n),{recursive:!0,force:!1})))}function Nn(e,t){let n=t.length>0;switch(e){case`pnpm`:return[`pnpm`,[n?`add`:`install`,...t]];case`yarn`:return[`yarn`,[n?`add`:`install`,...t]];case`bun`:return[`bun`,[n?`add`:`install`,...t]];default:return[`npm`,[`install`,...t]]}}function Pn(e,t,n){if(t||e.metadata.skillDetected){let t=e.metadata.framework===`nextjs`&&!e.metadata.disableCodegen,r=e.metadata.framework===`nuxt`&&!e.metadata.disableCodegen,i=t&&!n,a=c.default`
386
- Inside your AI assistant (e.g. Claude Code), use:
387
- ${X(`/arkenv`)} - automatically refine your schema and configure integrations.
388
- `;return i?(a+=`
389
-
390
- `,a+=`Also, wrap your Next.js config with ${X(`withArkEnv`)}:\n`,a+=` ${X(`import { withArkEnv } from "@arkenv/nextjs/config";`)}\n`,e.metadata.layout===`strict`?(a+=` ${X(`export default withArkEnv(nextConfig);`)}\n`,a+=`Import and use: ${X(`import { env } from "${e.metadata.importPath}/client"`)} (client) or ${X(`import { env } from "${e.metadata.importPath}/server"`)} (server)\n`):(a+=` ${X(`export default withArkEnv(nextConfig);`)}\n`,a+=`Import and use: ${X(`import { env } from "${e.metadata.importPath}"`)}\n`)):r&&(a+=`
391
-
392
- `,e.metadata.layout===`strict`?a+=`Import and use: ${X(`import { env } from "${e.metadata.importPath}/client"`)} (client) or ${X(`import { env } from "${e.metadata.importPath}/server"`)} (server)\n`:a+=`Import and use: ${X(`import { env } from "${e.metadata.importPath}"`)}\n`),{message:a,title:`Next steps`}}let r=e.skill?.dlxCommand.join(` `)||`npx`,i=e.skill?.packageName||`yamcodes/arkenv`,a=``,o=1,s=e.metadata.displayPath;if(e.metadata.layout===`strict`){let e=s.lastIndexOf(`.`),t=e===-1?s:s.slice(0,e);s=`${t}/client.ts, ${t}/server.ts, and ${t}/internal/shared.ts`}a+=`${o++}. Check ${X(s)} and refine your environment schema.\n`;let l=e.metadata.framework===`nextjs`&&!e.metadata.disableCodegen&&!n;return e.metadata.framework===`vite`?a+=`${o++}. Access via ${X(`import.meta.env.YOUR_VAR`)}\n`:e.metadata.framework===`bun-fullstack`?a+=`${o++}. Access via ${X(`process.env.YOUR_VAR`)}\n`:e.metadata.framework===`nextjs`?e.metadata.layout===`strict`?(e.metadata.disableCodegen||l&&(a+=`${o++}. Wrap your Next.js config with ${X(`withArkEnv`)} inside ${X(`next.config.ts`)}:\n`,a+=` ${X(`import { withArkEnv } from "@arkenv/nextjs/config";`)}\n`,a+=` ${X(`export default withArkEnv(nextConfig);`)}\n`),a+=`${o++}. Import and use: ${X(`import { env } from "${e.metadata.importPath}/client"`)} (client) or ${X(`import { env } from "${e.metadata.importPath}/server"`)} (server)\n`):(e.metadata.disableCodegen||l&&(a+=`${o++}. Wrap your Next.js config with ${X(`withArkEnv`)} inside ${X(`next.config.ts`)}:\n`,a+=` ${X(`import { withArkEnv } from "@arkenv/nextjs/config";`)}\n`,a+=` ${X(`export default withArkEnv(nextConfig);`)}\n`),a+=`${o++}. Import and use: ${X(`import { env } from "${e.metadata.importPath}"`)}\n`):e.metadata.framework===`nuxt`&&e.metadata.layout===`strict`?a+=`${o++}. Import and use: ${X(`import { env } from "${e.metadata.importPath}/client"`)} (client) or ${X(`import { env } from "${e.metadata.importPath}/server"`)} (server)\n`:a+=`${o++}. Import and use: ${X(`import { env } from "${e.metadata.importPath}"`)}\n`,a+=`${o++}. (Recommended) Install the AI skill: ${X(`${r} skills add ${i}`)}\n`,a+=` Then run ${X(`/arkenv`)} inside your AI assistant to finish.`,{message:a,title:`Next steps`}}const Fn=[`esbuild`];var In=class{constructor(e,t){this.workspace=e,this.reporter=t}async execute(e){let t=this.reporter.spinner();t.start(`Scaffolding ArkEnv configuration...`);try{e.clone&&(t.stop(`Starting new project scaffolding...`),this.reporter.step(`Cloning example ${X(e.clone.example)}...`),await jn(this.workspace,e.clone),t.start(`Scaffolding complete, finalizing...`));for(let t of e.files){if(t.action===`append`){if(!e.bootstrap||e.bootstrap.framework!==`vite`&&e.bootstrap.framework!==`bun-fullstack`){this.reporter.warn(`Skipping safe-append for ${X(o.default.basename(t.path))}: unsupported framework.`);continue}await this.workspace.safeAppend(t.path,t.content,e.bootstrap.framework)?this.reporter.info(`Appended ArkEnv types to ${X(o.default.basename(t.path))}.`):this.reporter.info(`${X(o.default.basename(t.path))} already contains ArkEnv types.`);continue}if(!(t.action===`create`&&await this.workspace.exists(t.path))&&(await this.workspace.mkdir(o.default.dirname(t.path),!0),await this.workspace.writeFile(t.path,t.content),t.label!==`environment schema`&&t.label?.includes(`types`))){let e=t.action===`overwrite`?`Updated`:`Created`;this.reporter.info(`${e} ${X(o.default.basename(t.path))} for typesafe environment variables.`)}}if(t.stop(`Configuration scaffolded!`),e.install&&process.env.SKIP_INSTALL!==`true`){e.install.packageManager===`pnpm`&&await this.configurePnpmBuilds(e.install.cwd??e.cwd),this.reporter.step(`Installing dependencies with ${X(e.install.packageManager)}...`);let[t,n]=Nn(e.install.packageManager,e.install.dependencies);await this.workspace.execute(t,n,e.install.cwd??e.cwd)}let n=!1;if(e.tsConfig){let t=await this.workspace.updateTsConfigToStrict(e.tsConfig.path);t.status===`updated`?(this.reporter.info(`Enforced strict: true in your ${X(t.file)}`),n=!0):t.status===`error`&&this.reporter.warn(`Could not automatically update ${X(t.file||`tsconfig.json`)}. Please ensure 'strict: true' is set manually.`)}let r=!1;if(e.bootstrap){if(e.bootstrap.framework===`vite`){let t=await this.workspace.findViteConfig(e.cwd);if(t){this.reporter.step(`Bootstrapping Vite plugin...`);let n=await this.workspace.bootstrapViteConfig(t,e.bootstrap.importPath||`./src/env`);n.success?n.updated&&this.reporter.info(`Updated ${X(o.default.basename(t))}`):(this.reporter.warn(`Could not automatically update ${X(o.default.basename(t))}: ${n.error}`),this.reporter.info(`Please add ${X(`@arkenv/vite-plugin`)} manually.`))}else this.reporter.info(`No Vite config found - please add ${X(`@arkenv/vite-plugin`)} to your Vite config manually.`)}else if(e.bootstrap.framework===`bun-fullstack`){let t=await this.workspace.findBunConfig(e.cwd),n=await this.workspace.bootstrapBunConfig(t,e.bootstrap.bunFeatures);n.success&&n.instructions?this.reporter.info(n.instructions):n.success||this.reporter.error(n.error||`Bun bootstrap failed`)}else if(e.bootstrap.framework===`nextjs`){if(!e.bootstrap.disableCodegen){this.reporter.step(`Generating Next.js environment bindings...`);let t=`import('@arkenv/nextjs/config').then(({ runCodegen }) => { const path = require('path'); const schemaPath = path.resolve(process.cwd(), '${e.metadata.displayPath}'); const outputPath = path.join(path.dirname(schemaPath), 'generated', 'env.gen.ts'); runCodegen(schemaPath, outputPath); }).catch(err => { console.error(err); process.exit(1); });`;try{await this.workspace.execute(`node`,[`-e`,t],e.cwd),this.reporter.info(`Generated ${X(`env.gen.ts`)} for Next.js`)}catch{this.reporter.warn(`Failed to automatically generate ${X(`env.gen.ts`)}. It will be generated when you start your dev server.`)}}if(e.bootstrap.wrapNextjsConfig!==!1){this.reporter.step(`Bootstrapping Next.js config...`);let t=await this.workspace.findNextjsConfig(e.cwd);if(t){let n=await this.workspace.bootstrapNextjsConfig(t,e.bootstrap.disableCodegen);n.success?n.updated?(this.reporter.info(`Updated ${X(o.default.basename(t))}`),r=!0):(this.reporter.info(`${X(o.default.basename(t))} already uses withArkEnv`),r=!0):this.reporter.warn(`Could not automatically update ${X(o.default.basename(t))}: ${n.error}`)}else this.reporter.info(`No Next.js config found. Please wrap your config with ${X(`withArkEnv`)} manually.`)}}else if(e.bootstrap.framework===`nuxt`){this.reporter.step(`Bootstrapping Nuxt config...`);let t=await this.workspace.findNuxtConfig(e.cwd);if(t){let e=await this.workspace.bootstrapNuxtConfig(t);e.success?(e.updated?this.reporter.info(`Updated ${X(o.default.basename(t))}`):this.reporter.info(`${X(o.default.basename(t))} already registers @arkenv/nuxt/module`),r=!0):this.reporter.warn(`Could not automatically update ${X(o.default.basename(t))}: ${e.error}`)}else this.reporter.info(`No Nuxt config found. Please register ${X(`@arkenv/nuxt/module`)} manually.`)}}let i=!1;if(e.skill&&process.env.SKIP_INSTALL!==`true`){this.reporter.step(`Installing ArkEnv agent skill...`);try{let[t,...n]=e.skill.dlxCommand,r=[...n,`skills`,`add`,e.skill.packageName];e.skill.isYes&&r.push(`--yes`),await this.workspace.execute(t,r,e.cwd),i=!0}catch(e){let t=e instanceof Error?e.message:String(e);this.reporter.warn(`Failed to install ArkEnv AI skill: ${t}`)}}let a=Pn(e,i,r);if(this.reporter.note(a.message,a.title),e.metadata.layout===`strict`){let t=o.default.resolve(e.cwd,e.metadata.displayPath);if(await this.workspace.exists(t)){let t=e.metadata.displayPath,n=o.default.basename(t,o.default.extname(t));this.reporter.warn(`Found existing single-file schema at ${X(t)}. You can delete it after updating your imports to point to your new ${X(`${n}/client`)} and ${X(`${n}/server`)}.`)}}this.reporter.finish(`${Ft} ArkEnv scaffolding complete. Happy coding!`,{path:e.metadata.displayPath,framework:e.metadata.framework,validator:e.metadata.validator,packageManager:e.metadata.packageManager,tsConfigUpdated:n,skillInstalled:i})}catch(e){throw t.stop(`Scaffolding failed.`),e}}async configurePnpmBuilds(e){let t=o.default.join(e,`package.json`);if(await this.workspace.exists(t))try{let e=await this.workspace.readFile(t),n=JSON.parse(e);n.pnpm=n.pnpm||{},n.pnpm.onlyBuiltDependencies=n.pnpm.onlyBuiltDependencies||[];for(let e of Fn)n.pnpm.onlyBuiltDependencies.includes(e)||n.pnpm.onlyBuiltDependencies.push(e);await this.workspace.writeFile(t,JSON.stringify(n,null,2)+`
393
- `)}catch(e){this.reporter.warn(`Could not update package.json with pnpm whitelisting: ${e}`)}let n=o.default.join(e,`pnpm-workspace.yaml`),r=``;if(await this.workspace.exists(n))try{r=await this.workspace.readFile(n)}catch{}let i=this.updatePnpmWorkspaceYaml(r);try{await this.workspace.writeFile(n,i)}catch(e){this.reporter.warn(`Could not write pnpm-workspace.yaml: ${e}`)}}updatePnpmWorkspaceYaml(e){let t=(0,p.parseDocument)(e||``);t.has(`allowBuilds`)||t.set(`allowBuilds`,t.createNode({}));let n=t.get(`allowBuilds`);if((0,p.isMap)(n)||(t.set(`allowBuilds`,t.createNode({})),n=t.get(`allowBuilds`)),(0,p.isMap)(n))for(let e of Fn)n.get(e)!==!0&&n.set(e,!0);return String(t)}};function Ln(e){switch(e){case`pnpm`:return[`pnpm`,`dlx`];case`yarn`:return[`yarn`,`dlx`];case`bun`:return[`bunx`];default:return[`npx`]}}const Rn={basic:{HOST:`localhost`,PORT:`3000`,NODE_ENV:`development`},"basic-js":{HOST:`localhost`,PORT:`3000`,NODE_ENV:`development`},"with-bun":{HOST:`localhost`,PORT:`3000`,NODE_ENV:`development`},"with-nextjs":{DATABASE_URL:`postgres://localhost:5432/mydb`,NEXT_PUBLIC_API_URL:`https://api.example.com`,NODE_ENV:`development`},"with-nextjs-strict":{DATABASE_URL:`postgres://localhost:5432/mydb`,NEXT_PUBLIC_API_URL:`https://api.example.com`,NODE_ENV:`development`},"with-nuxt":{DATABASE_URL:`postgres://localhost:5432/mydb`,NUXT_PUBLIC_API_URL:`https://api.example.com`,NODE_ENV:`development`},"with-vite-react":{PORT:`3000`,VITE_MY_VAR:`hello`,VITE_MY_NUMBER:`42`,VITE_MY_BOOLEAN:`true`},"with-bun-react":{BUN_PUBLIC_API_URL:`https://api.example.com`,BUN_PUBLIC_DEBUG:`true`,NODE_ENV:`development`},"with-zod":{HOST:`localhost`,PORT:`3000`,NODE_ENV:`development`},"with-standard-schema":{HOST:`localhost`,PORT:`3000`,NODE_ENV:`development`}};function zn(e,t){let n={};if(e&&e.length>0){for(let t of e)t===`NODE_ENV`?n[t]=`development`:t===`PORT`?n[t]=`3000`:t===`DATABASE_URL`?n[t]=`postgres://localhost:5432/mydb`:n[t]=``;return n}return t===`nextjs`?{DATABASE_URL:`postgres://localhost:5432/mydb`,NEXT_PUBLIC_API_URL:`https://api.example.com`,NODE_ENV:`development`}:t===`nuxt`?{DATABASE_URL:`postgres://localhost:5432/mydb`,NUXT_PUBLIC_API_URL:`https://api.example.com`,NODE_ENV:`development`}:t===`vite`?{PORT:`3000`,VITE_API_URL:`https://api.example.com`}:t===`bun-fullstack`?{BUN_PUBLIC_API_URL:`https://api.example.com`,NODE_ENV:`development`}:{PORT:`3000`,NODE_ENV:`development`}}function Bn(e,t){return Rn[e]?Rn[e]:zn(void 0,t)}function Vn(e){let t=e.split(/\r?\n/),n=[],r=null;for(let e of t){let t=e.replace(/\\"/g,``).replace(/\\'/g,``);if(r){(t.match(new RegExp(r,`g`))||[]).length%2!=0&&(r=null);continue}let i=e.trim();if(!i||i.startsWith(`#`)){n.push(e);continue}let a=e.match(/^(\s*(?:export\s+)?)([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/i);if(a){let e=a[1],t=a[2],i=a[3].trim();n.push(`${e}${t}=`);let o=i.replace(/\\"/g,``).replace(/\\'/g,``);i.startsWith(`"`)?(o.match(/"/g)||[]).length%2!=0&&(r=`"`):i.startsWith(`'`)&&(o.match(/'/g)||[]).length%2!=0&&(r=`'`)}else n.push(e)}return n.join(`
394
- `)}function Hn(e,t){return e.some(e=>{let n=e.indexOf(`#`),r=(n===-1?e:e.slice(0,n)).trim();if(!r)return!1;if(r===t||r===`/${t}`)return!0;if(r.includes(`*`)){let e=`^${r.replace(/\./g,`\\.`).replace(/\*/g,`.*`).replace(/^\//,`/?`)}$`;try{let n=new RegExp(e);return n.test(t)||n.test(`/${t}`)}catch{return!1}}return!1})}function Un(e){let{mode:n,options:r,packageManager:i,tsConfig:a,shouldUpdateTsConfig:s,cwd:c,existingFiles:l}=e,u=r.name&&r.name!==`.`?o.default.basename(r.name):void 0,d={files:[],cwd:c,metadata:(0,t.shake)({displayPath:``,framework:r.framework,validator:r.validator,packageManager:i,importPath:``,mode:n,example:r.example,name:u,layout:r.layout,skillDetected:r.skillDetected,disableCodegen:r.disableCodegen})};if(n===`new`){if(!r.example)throw Error(`New project scaffolding requires an example.`);let t=r.name&&r.name!==`.`?o.default.join(c,r.name):void 0,n=r.name&&r.name!==`.`?o.default.basename(r.name):o.default.basename(c);d.clone={repository:`https://github.com/yamcodes/arkenv.git`,example:r.example,targetName:n,...t!==void 0&&{targetDir:t}},d.install={packageManager:i,dependencies:[],...t!==void 0&&{cwd:t}},r.installSkill&&(d.skill={dlxCommand:Ln(i),packageName:`yamcodes/arkenv`,isYes:e.isYes});let a=t??c,s=o.default.join(a,`.env`),l=o.default.join(a,`.env.example`),u=Bn(r.example,r.framework),f=`${Object.entries(u).map(([e,t])=>`${e}=${t}`).join(`
395
- `)}\n`;return d.files.push({path:s,content:f,action:`create`,label:`local environment variables`}),d.files.push({path:l,content:f,action:`create`,label:`environment variables template`}),d.metadata.displayPath=`./src/env.ts`,d.metadata.importPath=`./src/env`,d}let f=o.default.resolve(c,r.path),p=o.default.dirname(f);if((r.framework===`nextjs`||r.framework===`nuxt`)&&r.layout===`strict`){let e=o.default.extname(f),t=f.slice(0,-e.length),n=o.default.join(t,`internal`,`shared${e}`),i=o.default.join(t,`client${e}`),s=o.default.join(t,`server${e}`),u;if((r.framework===`nextjs`||r.framework===`nuxt`)&&!r.disableCodegen&&a?.parsed){let e=a.parsed,n=(e.compilerOptions||{}).paths||{};if(n[`@/*`]){let r=e.path?o.default.dirname(e.path):c,i=o.default.join(t,`generated`),a=o.default.relative(r,i).replace(/\\/g,`/`);for(let e of n[`@/*`]){let t=e.replace(/^\.\//,``).replace(/\*$/,``);if(t===``||a.startsWith(t)){let e=a;t!==``&&a.startsWith(t)&&(e=a.substring(t.length)),e=e.replace(/^\/+/,``).replace(/\/+$/,``),u=`@/${e}/env.gen`.replace(/\/+/g,`/`);break}}}}let p=An(r,u),m=l.includes(n),h=l.includes(i),g=l.includes(s);(!m||r.overwriteEnvSchemaFile!==!1)&&d.files.push({path:n,content:p.shared,action:m?`overwrite`:`create`,label:`shared environment schema`}),(!h||r.overwriteEnvSchemaFile!==!1)&&d.files.push({path:i,content:p.client,action:h?`overwrite`:`create`,label:`client environment schema`}),(!g||r.overwriteEnvSchemaFile!==!1)&&d.files.push({path:s,content:p.server,action:g?`overwrite`:`create`,label:`server environment schema`})}else{let e;if((r.framework===`nextjs`||r.framework===`nuxt`)&&!r.disableCodegen&&a?.parsed){let t=a.parsed,n=(t.compilerOptions||{}).paths||{};if(n[`@/*`]){let r=t.path?o.default.dirname(t.path):c,i=o.default.join(p,`generated`),a=o.default.relative(r,i).replace(/\\/g,`/`);for(let t of n[`@/*`]){let n=t.replace(/^\.\//,``).replace(/\*$/,``);if(n===``||a.startsWith(n)){let t=a;n!==``&&a.startsWith(n)&&(t=a.substring(n.length)),t=t.replace(/^\/+/,``).replace(/\/+$/,``),e=`@/${t}/env.gen`.replace(/\/+/g,`/`);break}}}}let t=kn(r,e),n=l.includes(f);(!n||r.overwriteEnvSchemaFile!==!1)&&d.files.push({path:f,content:t,action:n?`overwrite`:`create`,label:`environment schema`})}let m=o.default.join(c,`.env`),h=o.default.join(c,`.env.example`),g=l.includes(m),_=l.includes(h);if(!g){let e=r.envExampleContent===void 0?(()=>{let e=zn(r.envKeys,r.framework);return`${Object.entries(e).map(([e,t])=>`${e}=${t}`).join(`
396
- `)}\n`})():r.envExampleContent;d.files.push({path:m,content:e,action:`create`,label:`local environment variables`})}if(!_){let e=r.envContent===void 0?(()=>{let e=zn(r.envKeys,r.framework);return`${Object.entries(e).map(([e,t])=>`${e}=${t}`).join(`
397
- `)}\n`})():Vn(r.envContent);d.files.push({path:h,content:e,action:`create`,label:`environment variables template`})}if(n===`existing`){let e=o.default.join(c,`.gitignore`),t=l.includes(e);if(t&&r.gitignoreContent!==void 0){let t=r.gitignoreContent.split(/\r?\n/),n=Hn(t,`.env`),i=Hn(t,`.env.local`);if(!n||!i){let t=`
271
+ `},pluginEnvImports:`import { type } from "@arkenv/core";
272
+ import { z } from "zod";`},zr={arktype:Ir,zod:Rr,valibot:Lr};function Br(e){return{formatField(t,n,r){return e.formatStrictField(t,n,r.clientPrefix,r.hostPreset)},getSimpleTemplate(t,n){return Tr(e,t,n)},getStrictTemplates(t,n){return Pr(e,t,n)}}}const Vr={arktype:Br(zr.arktype),zod:Br(zr.zod),valibot:Br(zr.valibot)};function Hr(e){return e.mode===`new`?Xr(e):Zr(e)}function Ur(e){let t=e.split(/\r?\n/),n=[],r=null;for(let e of t){let t=e.replace(/\\"/g,``).replace(/\\'/g,``);if(r){(t.match(new RegExp(r,`g`))||[]).length%2!=0&&(r=null);continue}let i=e.trim();if(!i||i.startsWith(`#`)){n.push(e);continue}let a=e.match(/^(\s*(?:export\s+)?)([A-Z_][A-Z0-9_]*)\s*=\s*(.*)$/i);if(a){let e=a[1],t=a[2],i=a[3].trim();n.push(`${e}${t}=`);let o=i.replace(/\\"/g,``).replace(/\\'/g,``);i.startsWith(`"`)?(o.match(/"/g)||[]).length%2!=0&&(r=`"`):i.startsWith(`'`)&&(o.match(/'/g)||[]).length%2!=0&&(r=`'`)}else n.push(e)}return n.join(`
273
+ `)}function Wr(e,t){return e.some(e=>{let n=e.indexOf(`#`),r=(n===-1?e:e.slice(0,n)).trim();if(!r)return!1;if(r===t||r===`/${t}`)return!0;if(r.includes(`*`)){let e=`^${r.replace(/\./g,`\\.`).replace(/\*/g,`.*`).replace(/^\//,`/?`)}$`;try{let n=new RegExp(e);return n.test(t)||n.test(`/${t}`)}catch{return!1}}return!1})}function Gr(e){return Object.entries(e).map(([e,t])=>`${e}=${t}`).join(`
274
+ `)+`
275
+ `}function Kr(e,t){let{cwd:n,options:r,existingFiles:i}=e,a=mr[r.framework],s=o.default.join(n,`.env`),c=o.default.join(n,`.env.example`),l=i.includes(s),u=i.includes(c),d=En(r.envKeys,r.hostPreset,a.clientPrefix);if(!l){let e=r.envExampleContent===void 0?Gr(a.getEnvDefaults(d)):r.envExampleContent;t.files.push({path:s,content:e,action:`create`,label:`local environment variables`})}if(!u){let e=r.envContent===void 0?Gr(a.getEnvDefaults(d)):Ur(r.envContent);t.files.push({path:c,content:e,action:`create`,label:`environment variables template`})}}function qr(e,t){let{cwd:n,options:r,existingFiles:i}=e,a=o.default.join(n,`.gitignore`),s=i.includes(a);if(s&&r.gitignoreContent!==void 0){let e=r.gitignoreContent.split(/\r?\n/),n=Wr(e,`.env`),i=Wr(e,`.env.local`);if(!n||!i){let e=`
398
276
  # Environment variables
399
- `;n||(t+=`.env
400
- `),i||(t+=`.env.local
401
- `);let a=r.gitignoreContent.endsWith(`
402
- `)?`${r.gitignoreContent}${t.trim()}\n`:`${r.gitignoreContent}\n${t.trim()}\n`;d.files.push({path:e,content:a,action:`overwrite`,label:`.gitignore update`})}}else t||d.files.push({path:e,content:`# Environment variables
277
+ `;n||(e+=`.env
278
+ `),i||(e+=`.env.local
279
+ `);let o=r.gitignoreContent.endsWith(`
280
+ `)?`${r.gitignoreContent}${e.trim()}\n`:`${r.gitignoreContent}\n${e.trim()}\n`;t.files.push({path:a,content:o,action:`overwrite`,label:`.gitignore update`})}}else s||t.files.push({path:a,content:`# Environment variables
403
281
  .env
404
282
  .env.local
405
- `,action:`create`,label:`.gitignore file`})}let v=[`arkenv`,r.validator];if(r.framework===`vite`&&v.push(`@arkenv/vite-plugin`),r.framework===`bun-fullstack`&&r.bunFeatures?.length&&v.push(`@arkenv/bun-plugin`),r.framework===`nextjs`&&v.push(`@arkenv/nextjs`),r.framework===`nuxt`&&v.push(`@arkenv/nuxt`),(r.framework===`vite`||r.framework===`nextjs`||r.framework===`nuxt`||r.framework===`bun-fullstack`&&r.bunFeatures?.length)&&!v.includes(`arktype`)&&v.push(`arktype`),d.install={packageManager:i,dependencies:v},s&&a.file&&(d.tsConfig={path:o.default.resolve(c,a.file),action:`strict`}),(r.framework===`vite`||r.framework===`bun-fullstack`&&r.bunFeatures?.length)&&r.installTypeDefinitions!==!1){let e=r.framework===`vite`?`vite-env.d.ts`:`bun-env.d.ts`,t=o.default.join(p,e),n=l.includes(t);if(r.envDtsHandling!==`skip`)if(r.envDtsHandling===`append`||!r.envDtsHandling&&n)d.files.push({path:t,content:f,action:`append`,label:`${r.framework} types`});else{let e=r.framework===`vite`?Tn(r.path):En(r.path);d.files.push({path:t,content:e,action:n?`overwrite`:`create`,label:`${r.framework} types`})}}(r.framework===`vite`||r.framework===`bun-fullstack`||r.framework===`nextjs`||r.framework===`nuxt`)&&(d.bootstrap=(0,t.shake)({framework:r.framework,bunFeatures:r.framework===`bun-fullstack`?r.bunFeatures:void 0,wrapNextjsConfig:r.framework===`nextjs`?r.wrapNextjsConfig!==!1:void 0,disableCodegen:r.disableCodegen})),r.installSkill&&(d.skill={dlxCommand:Ln(i),packageName:`yamcodes/arkenv`,isYes:e.isYes});let y=o.default.relative(c,f).replace(/\\/g,`/`),b=y.startsWith(`.`)?y:`./${y}`,x=b.replace(/\.(ts|js|tsx|jsx)$/,``);return d.metadata.displayPath=b,d.metadata.importPath=x,d.bootstrap&&(d.bootstrap.importPath=x),d}var Wn=class{async fetchRegistry(){try{let e=await fetch(`https://raw.githubusercontent.com/yamcodes/arkenv/main/examples/registry.json`);if(!e.ok)throw Error(`Failed to fetch registry: ${e.statusText}`);return await e.json()}catch{return{examples:[{id:`basic`,name:`Basic`,description:`A minimal ArkEnv setup in Node.js`,framework:`vanilla`},{id:`with-nextjs`,name:`Next.js`,description:`Minimal Next.js project with ArkType`,framework:`nextjs`},{id:`with-vite-react`,name:`React + Vite`,framework:`vite`},{id:`with-bun`,name:`Bun (Vanilla)`,description:`Minimal Bun project with ArkType`,framework:`vanilla`},{id:`with-bun-react`,name:`React + Bun fullstack dev server`,framework:`bun-fullstack`},{id:`with-zod`,name:`Zod`,description:`ArkEnv with Zod in Node.js`,framework:`vanilla`}]}}}},Gn=class{constructor(e,t,n,r,i=new Wn){this.logger=e,this.workspace=t,this.prompt=n,this.scanner=r,this.registry=i}async execute(e){let t=await this.collect(e);if(!t)return!1;let n=Un(t),r=new In(this.workspace,this.logger);try{await r.execute(n)}catch(e){this.logger.fatal(`Scaffolding failed.`,e)}return!0}async collect(e){this.logger.interactiveStdout(!0);try{let t=e.name;t&&o.default.resolve(process.cwd(),t)===process.cwd()&&(t=`.`);let n={...e,...t!==void 0&&{name:t}},r=t&&t!==`.`?o.default.resolve(process.cwd(),t):process.cwd(),i=await this.workspace.exists(r),a=i?await this.scanner.hasPackageJson(r):!1,s=i?await this.scanner.isEmptyDirectory(r):!0;return n.example===void 0?a?await this.collectExistingProject(n,r):s||n.isForce?await this.collectNewProject(n,s):(this.logger.error(`Directory is not empty and no ${X(`package.json`)} was found.`),this.logger.info(`To scaffold a new project, run ${X(`arkenv init`)} in an empty directory or use ${X(`--force`)} to proceed anyway.`),null):await this.collectNewProject(n,s)}finally{this.logger.interactiveStdout(!1)}}async collectExistingProject(e,n){let{isYes:r,isForce:i,isQuiet:a,isAgent:s}=e,c=await this.scanner.checkRequirements(n),l=c.filter(e=>e.status===`fail`),u=c.filter(e=>e.status===`warn`);for(let e of u)this.logger.warn(`${e.requirement}: ${e.message}`);if(l.length>0)if(i){this.logger.warn(`Technical requirements not met, but continuing due to --force flag.`);for(let e of l)this.logger.warn(`${e.requirement}: ${e.message}`)}else{this.logger.error(`Technical requirements not met:`);for(let e of l)this.logger.error(`- ${e.requirement}: ${e.message}${e.current?` (Current: ${e.current}, Expected: ${e.expected})`:``}`);return this.logger.info(`Use --force to bypass these checks.`),null}let d=await this.scanner.checkGitStatus(n);if(d.status===`dirty`)if(i)this.logger.warn(`Git working tree is not clean, but continuing due to --force flag.`);else return this.logger.error(`Git working tree is not clean. Commit or stash your changes (use 'git stash -u' for untracked files) before running arkenv init.`),this.logger.info(`Use --force to bypass this check.`),null;d.status===`unknown`&&this.logger.warn(`Git working tree status could not be determined. Proceeding with caution.`);let f=!1,p=await this.scanner.checkTsConfig(n);if(p.status===`not_strict`)if(r)f=!0;else{this.logger.warn(`TypeScript strict mode is not enabled in your ${X(p.file)}.`);let e=await this.prompt.confirm(`ArkEnv requires ${X(`strict`)} mode in your ${X(p.file)}. Would you like to enable it now?`,!0,`Yes (Recommended)`);if(e===null)return null;if(!e)return this.logger.cancel(`Operation cancelled.`),null;f=!0}let m=await this.scanner.detectFramework(n,p.parsed);if(e.isSimple&&m===`nextjs`)return this.logger.error(`❌ Error: The --simple layout is deprecated and no longer supported by the CLI. Arkenv now exclusively uses the Flat Layout. Run npx arkenv init without this flag.`),null;let h=m===`bun-fullstack`?await this.scanner.detectBunFeatures(n,p.parsed):void 0,g=await this.scanner.suggestDefaultEnvPath(n,p.parsed),_=o.default.resolve(n,g),v=await this.scanner.getEnvExampleKeys(n,p.parsed,_),y=await(async()=>{if(e.isStrict){let e=o.default.extname(_),t=_.slice(0,-e.length),n=[o.default.join(t,`internal`,`shared${e}`),o.default.join(t,`client${e}`),o.default.join(t,`server${e}`)];if((await Promise.all(n.map(e=>this.workspace.exists(e)))).some(Boolean))return!0}return this.workspace.exists(_)})(),b=async({framework:e,envPath:t})=>{if(e!==`vite`&&e!==`bun-fullstack`)return!1;let r=e===`vite`?`vite-env.d.ts`:`bun-env.d.ts`,i=o.default.resolve(n,t),a=o.default.dirname(i),s=o.default.join(a,r);return this.workspace.exists(s)},x=await b({framework:m,envPath:g}),S=await this.prompt.runWizard((0,t.shake)({mode:`existing`,framework:m,bunFeatures:h,defaultEnvPath:g,tsConfig:p.parsed??null,envKeys:v?.keys,envKeysSource:v?.source,hasTypeFileAtPath:b,hasTypeFile:x,hasEnvSchemaFile:y,isStrict:e.isStrict,isSimple:e.isSimple,isFlat:e.isFlat,disableCodegen:e.noCodegen}),r);if(S===null)return null;let C=await this.scanner.hasSkill(n);if(C&&(S.skillDetected=!0,!a&&!s&&this.logger.info(`ArkEnv agent skill detected.`)),C)S.installSkill=!1;else if(s)S.installSkill=!1;else if(r)S.installSkill=!0;else{let e=await this.prompt.confirm(`Would you like to install the ArkEnv agent skill?`,!0,`Yes (Recommended)`);if(e===null)return null;S.installSkill=e}let w=o.default.resolve(n,S.path);if(S.overwriteEnvSchemaFile===void 0&&(S.layout===`strict`?await(async()=>{let e=o.default.extname(w),t=w.slice(0,-e.length);return(await Promise.all([this.workspace.exists(o.default.join(t,`internal`,`shared${e}`)),this.workspace.exists(o.default.join(t,`client${e}`)),this.workspace.exists(o.default.join(t,`server${e}`))])).some(Boolean)})():await this.workspace.exists(w))){let e=S.layout===`strict`?`Strict layout files (client, server, internal/shared)`:o.default.basename(w),t=await this.prompt.confirm(`${e} already exist. Overwrite?`,!1);if(t===null)return null;if(!t)return this.logger.cancel(`Operation cancelled.`),null;S.overwriteEnvSchemaFile=t}let ee=await this.scanner.detectPackageManager(n,p.parsed),T=o.default.extname(w),E=w.slice(0,-T.length),D=S.layout===`strict`?[o.default.join(E,`internal`,`shared${T}`),o.default.join(E,`client${T}`),o.default.join(E,`server${T}`)]:[w],O=[];for(let e of D)await this.workspace.exists(e)&&O.push(e);let k;if(S.framework===`vite`?k=`vite-env.d.ts`:S.framework===`bun-fullstack`&&(k=`bun-env.d.ts`),k){let e=o.default.dirname(w),t=o.default.join(e,k);await this.workspace.exists(t)&&O.push(t)}let A=o.default.join(n,`.env`),j=o.default.join(n,`.env.example`);await this.workspace.exists(A)&&(O.push(A),S.envContent=await this.workspace.readFile(A)),await this.workspace.exists(j)&&(O.push(j),S.envExampleContent=await this.workspace.readFile(j));let te=o.default.join(n,`.gitignore`);return await this.workspace.exists(te)&&(O.push(te),S.gitignoreContent=await this.workspace.readFile(te)),(0,t.shake)({mode:`existing`,cwd:n,options:S,detectedFramework:m,detectedBunFeatures:h,packageManager:ee,tsConfig:p,shouldUpdateTsConfig:f,existingFiles:O,isYes:r})}async collectNewProject(e,n=!0){let{isYes:r,example:i,name:a,isForce:o}=e,s=await this.registry.fetchRegistry(),c=await this.prompt.runWizard((0,t.shake)({mode:`new`,examples:s.examples,example:i,name:a}),r);if(c===null)return null;if(c.name===`.`&&!n&&!o)return this.logger.error(`Cannot scaffold into ${X(`.`)} because the current directory is not empty.`),this.logger.info(`Run ${X(`arkenv init`)} in an empty directory or choose a sub-directory name instead.`),null;let l=this.detectPackageManager();return(0,t.shake)({mode:`new`,cwd:process.cwd(),options:c,detectedFramework:c.framework,packageManager:l,tsConfig:{status:`not_found`},shouldUpdateTsConfig:!1,existingFiles:[],isYes:r})}detectPackageManager(){let e=process.env.npm_config_user_agent||``;return e.includes(`pnpm`)?`pnpm`:e.includes(`yarn`)?`yarn`:e.includes(`bun`)?`bun`:`npm`}};function Kn(e){let t=new yn(e),n=t.logger,r=new Xt(t.isQuiet,n.stdio,n),i=new hn;return{cli:t,logger:n,workspace:r,prompt:i,initUseCase:new Gn(n,r,i,new Pt(n)),helpUseCase:new Sn(n)}}if(typeof require<`u`&&require.main!==module)throw Error(`🚨 ${x(`You imported the 'arkenv' package as a library. Starting with v1.0.0, the 'arkenv' package is exclusively the interactive CLI. If you want to validate environment variables in your code, please install and import '@arkenv/core' instead.`)}`);const qn=new ct({isQuiet:!1,isJson:!1});let Jn,Yn=!1;async function Xn(){if(process.env.INIT_CWD)try{process.chdir(process.env.INIT_CWD)}catch{}let{cli:e,logger:n,initUseCase:r,helpUseCase:i}=Kn(process.argv);Jn=n,Zn(n),e.validationError&&(n.error(e.validationError),await i.execute(),await n.flush(),process.exit(1)),e.helpRequested&&(await i.execute(),await n.flush(),process.exit(0)),e.command!==`init`&&(e.command?n.error(`Unknown command: ${e.command}`):n.error(`Missing command.`),await i.execute(),await n.flush(),process.exit(1));try{await r.execute((0,t.shake)(e.initInput))||(await n.flush(),process.exit(1))}catch(e){try{n.fatal(`An unexpected error occurred`,e)}catch{}await n.flush(),process.exit(1)}}function Zn(e){let t=async t=>{Yn&&process.exit(t),Yn=!0,setTimeout(()=>{process.exit(t)},2e3).unref(),e.interactiveStdout&&e.interactiveStdout(!1);try{e.cancel(`Operation cancelled.`),await e.flush()}catch(t){e.error&&e.error(`Logger failed during shutdown`,t)}finally{process.exit(t)}};process.on(`SIGINT`,()=>t(130)),process.on(`SIGTERM`,()=>t(143))}Xn(),process.on(`unhandledRejection`,async e=>{let t=Jn??qn;try{t.fatal(`Unhandled rejection`,e)}catch{}await t.flush(),process.exit(1)}),process.on(`uncaughtException`,async e=>{let t=Jn??qn;try{t.fatal(`Uncaught exception`,e)}catch{}await t.flush(),process.exit(1)});
283
+ `,action:`create`,label:`.gitignore file`})}function Jr(e){let{mode:n,options:r,packageManager:i}=e,a=r.name&&r.name!==`.`?o.default.basename(r.name):void 0;return(0,t.shake)({displayPath:``,framework:r.framework,validator:r.validator,packageManager:i,importPath:``,mode:n,example:r.example,name:a,layout:r.layout,skillDetected:r.skillDetected,disableCodegen:r.disableCodegen})}function Yr(e,t){e.options.installSkill&&(t.skill={dlxCommand:_r(e.packageManager),packageName:`yamcodes/arkenv`,isYes:e.isYes})}function Xr(e){let{options:t,packageManager:n,cwd:r}=e;if(!t.example)throw Error(`New project scaffolding requires an example.`);let i=t.name&&t.name!==`.`?o.default.join(r,t.name):void 0,a=t.name&&t.name!==`.`?o.default.basename(t.name):o.default.basename(r),s={files:[],cwd:r,metadata:Jr(e),clone:{repository:`https://github.com/yamcodes/arkenv.git`,example:t.example,targetName:a,...i!==void 0&&{targetDir:i}},install:{packageManager:n,dependencies:[],...i!==void 0&&{cwd:i}}};Yr(e,s);let c=Gr(gr(t.example,()=>mr[t.framework].getEnvDefaults())),l=i??r;return s.files.push({path:o.default.join(l,`.env`),content:c,action:`create`,label:`local environment variables`},{path:o.default.join(l,`.env.example`),content:c,action:`create`,label:`environment variables template`}),s.metadata.displayPath=`./src/env.ts`,s.metadata.importPath=`./src/env`,s}function Zr(e){let{options:t,packageManager:n,tsConfig:r,shouldUpdateTsConfig:i,cwd:a,existingFiles:s}=e,c=mr[t.framework],l=Vr[t.validator],u=o.default.resolve(a,t.path),d=o.default.dirname(u),f={files:[],cwd:a,metadata:Jr(e)},p={targetPath:u,targetDir:d,cwd:a,existingFiles:s,overwriteEnvSchemaFile:t.overwriteEnvSchemaFile,installTypeDefinitions:t.installTypeDefinitions,envDtsHandling:t.envDtsHandling,path:t.path,tsConfig:r};f.files.push(...c.getSchemaFiles(l,t,p)),Kr(e,f),qr(e,f);let m=[`arkenv`,t.validator,...c.getDependencies(t)];c.requiresArktypePeer(t)&&!m.includes(`arktype`)&&m.push(`arktype`),f.install={packageManager:n,dependencies:m},i&&r.file&&(f.tsConfig={path:o.default.resolve(a,r.file),action:`strict`}),f.files.push(...c.getTypeDefinitionFiles(t,p));let h=c.bootstrap(t);h&&(f.bootstrap=h),Yr(e,f);let g=o.default.relative(a,u).replace(/\\/g,`/`),_=g.startsWith(`.`)?g:`./${g}`,v=_.replace(/\.(ts|js|tsx|jsx)$/,``);return f.metadata.displayPath=_,f.metadata.importPath=v,f.bootstrap&&(f.bootstrap.importPath=v),f}var Qr=class{async fetchRegistry(){try{let e=await fetch(`https://raw.githubusercontent.com/yamcodes/arkenv/main/examples/registry.json`);if(!e.ok)throw Error(`Failed to fetch registry: ${e.statusText}`);return await e.json()}catch{return{examples:[{id:`basic`,name:`Basic`,description:`A minimal ArkEnv setup in Node.js`,framework:`vanilla`},{id:`with-nextjs`,name:`Next.js`,description:`Minimal Next.js project with ArkType`,framework:`nextjs`},{id:`with-vite-react`,name:`React + Vite`,framework:`vite`},{id:`with-bun`,name:`Bun (Vanilla)`,description:`Minimal Bun project with ArkType`,framework:`vanilla`},{id:`with-bun-react`,name:`React + Bun fullstack dev server`,framework:`bun-fullstack`},{id:`with-zod`,name:`Zod`,description:`ArkEnv with Zod in Node.js`,framework:`vanilla`}]}}}},$r=class{constructor(e,t,n,r,i=new Qr){this.logger=e,this.workspace=t,this.prompt=n,this.scanner=r,this.registry=i}async execute(e){let t=await this.collect(e);if(!t)return!1;let n=Hr(t),r=new qn(this.workspace,this.logger);try{await r.execute(n)}catch(e){this.logger.fatal(`Scaffolding failed.`,e)}return!0}async collect(e){this.logger.interactiveStdout(!0);try{let t=e.name;t&&o.default.resolve(process.cwd(),t)===process.cwd()&&(t=`.`);let n={...e,...t!==void 0&&{name:t}},r=t&&t!==`.`?o.default.resolve(process.cwd(),t):process.cwd(),i=await this.workspace.exists(r),a=i?await this.scanner.hasPackageJson(r):!1,s=i?await this.scanner.isEmptyDirectory(r):!0;return n.example===void 0?a?await this.collectExistingProject(n,r):s||n.isForce?await this.collectNewProject(n,s):(this.logger.error(`Directory is not empty and no ${K(`package.json`)} was found.`),this.logger.info(`To scaffold a new project, run ${K(`arkenv init`)} in an empty directory or use ${K(`--force`)} to proceed anyway.`),this.logger.refuse({code:C.NON_EMPTY_DIR,message:`Directory is not empty and no package.json was found.`,retryWith:[`--force`]}),null):await this.collectNewProject(n,s)}finally{this.logger.interactiveStdout(!1)}}async collectExistingProject(e,n){let{isYes:r,isForce:i,isQuiet:a,isAgent:s}=e,c=await this.scanner.checkRequirements(n),l=c.filter(e=>e.status===`fail`),u=c.filter(e=>e.status===`warn`);for(let e of u)this.logger.warn(`${e.requirement}: ${e.message}`);if(l.length>0)if(i){this.logger.warn(`Technical requirements not met, but continuing due to --force flag.`);for(let e of l)this.logger.warn(`${e.requirement}: ${e.message}`)}else{this.logger.error(`Technical requirements not met:`);for(let e of l)this.logger.error(`- ${e.requirement}: ${e.message}${e.current?` (Current: ${e.current}, Expected: ${e.expected})`:``}`);return this.logger.info(`Use --force to bypass these checks.`),this.logger.refuse({code:C.REQUIREMENTS_NOT_MET,message:`Technical requirements not met.`,retryWith:[`--force`],details:{requirements:l.map(e=>(0,t.shake)({requirement:e.requirement,message:e.message,current:e.current,expected:e.expected}))}}),null}let d=await this.scanner.checkGitStatus(n);if(d.status===`dirty`)if(i)this.logger.warn(`Git working tree is not clean, but continuing due to --force flag.`);else return this.logger.error(`Git working tree is not clean. Commit or stash your changes (use 'git stash -u' for untracked files) before running arkenv init.`),this.logger.info(`Use --force to bypass this check.`),this.logger.refuse({code:C.GIT_TREE_DIRTY,message:`Git working tree is not clean.`,retryWith:[`--force`]}),null;d.status===`unknown`&&this.logger.warn(`Git working tree status could not be determined. Proceeding with caution.`);let f=!1,p=await this.scanner.checkTsConfig(n);if(p.status===`not_strict`)if(r)f=!0;else{this.logger.warn(`TypeScript strict mode is not enabled in your ${K(p.file)}.`);let e=await this.prompt.confirm(`ArkEnv requires ${K(`strict`)} mode in your ${K(p.file)}. Would you like to enable it now?`,!0,`Yes (Recommended)`);if(e===null)return null;if(!e)return this.logger.cancel(`Operation cancelled.`),null;f=!0}let m=await this.scanner.detectFramework(n,p.parsed);if(e.isSimple&&m===`nextjs`)return this.logger.error(`❌ Error: The --simple layout is deprecated and no longer supported by the CLI. Arkenv now exclusively uses the Flat Layout. Run npx arkenv init without this flag.`),null;let h=m===`bun-fullstack`?await this.scanner.detectBunFeatures(n,p.parsed):void 0,g=await this.scanner.suggestDefaultEnvPath(n,p.parsed),_=o.default.resolve(n,g),v=await this.scanner.getEnvExampleKeys(n,p.parsed,_),y=await(async()=>{if(e.isStrict){let e=o.default.extname(_),t=_.slice(0,-e.length),n=[o.default.join(t,`internal`,`shared${e}`),o.default.join(t,`client${e}`),o.default.join(t,`server${e}`)];if((await Promise.all(n.map(e=>this.workspace.exists(e)))).some(Boolean))return!0}return this.workspace.exists(_)})(),b=async({framework:e,envPath:t})=>{if(e!==`vite`&&e!==`bun-fullstack`)return!1;let r=e===`vite`?`vite-env.d.ts`:`bun-env.d.ts`,i=o.default.resolve(n,t),a=o.default.dirname(i),s=o.default.join(a,r);return this.workspace.exists(s)},x=await b({framework:m,envPath:g}),S=await this.prompt.runWizard((0,t.shake)({mode:`existing`,framework:m,bunFeatures:h,defaultEnvPath:g,tsConfig:p.parsed??null,envKeys:v?.keys,envKeysSource:v?.source,hasTypeFileAtPath:b,hasTypeFile:x,hasEnvSchemaFile:y,isStrict:e.isStrict,isSimple:e.isSimple,isFlat:e.isFlat,disableCodegen:e.noCodegen,hostPreset:e.hostPreset}),r);if(S===null)return null;let ee=await this.scanner.hasSkill(n);if(ee&&(S.skillDetected=!0,!a&&!s&&this.logger.info(`ArkEnv agent skill detected.`)),ee)S.installSkill=!1;else if(s)S.installSkill=!1;else if(r)S.installSkill=!0;else{let e=await this.prompt.confirm(`Would you like to install the ArkEnv agent skill?`,!0,`Yes (Recommended)`);if(e===null)return null;S.installSkill=e}let w=o.default.resolve(n,S.path);if(S.overwriteEnvSchemaFile===void 0&&(S.layout===`strict`?await(async()=>{let e=o.default.extname(w),t=w.slice(0,-e.length);return(await Promise.all([this.workspace.exists(o.default.join(t,`internal`,`shared${e}`)),this.workspace.exists(o.default.join(t,`client${e}`)),this.workspace.exists(o.default.join(t,`server${e}`))])).some(Boolean)})():await this.workspace.exists(w))){let e=S.layout===`strict`?`Strict layout files (client, server, internal/shared)`:o.default.basename(w),t=await this.prompt.confirm(`${e} already exist. Overwrite?`,!1);if(t===null)return null;if(!t)return this.logger.cancel(`Operation cancelled.`),null;S.overwriteEnvSchemaFile=t}let T=await this.scanner.detectPackageManager(n,p.parsed),E=o.default.extname(w),D=w.slice(0,-E.length),te=S.layout===`strict`?[o.default.join(D,`internal`,`shared${E}`),o.default.join(D,`client${E}`),o.default.join(D,`server${E}`)]:[w],O=[];for(let e of te)await this.workspace.exists(e)&&O.push(e);let k;if(S.framework===`vite`?k=`vite-env.d.ts`:S.framework===`bun-fullstack`&&(k=`bun-env.d.ts`),k){let e=o.default.dirname(w),t=o.default.join(e,k);await this.workspace.exists(t)&&O.push(t)}let A=o.default.join(n,`.env`),j=o.default.join(n,`.env.example`);await this.workspace.exists(A)&&(O.push(A),S.envContent=await this.workspace.readFile(A)),await this.workspace.exists(j)&&(O.push(j),S.envExampleContent=await this.workspace.readFile(j));let ne=o.default.join(n,`.gitignore`);return await this.workspace.exists(ne)&&(O.push(ne),S.gitignoreContent=await this.workspace.readFile(ne)),(0,t.shake)({mode:`existing`,cwd:n,options:S,detectedFramework:m,detectedBunFeatures:h,packageManager:T,tsConfig:p,shouldUpdateTsConfig:f,existingFiles:O,isYes:r})}async collectNewProject(e,n=!0){let{isYes:r,example:i,name:a,isForce:o}=e,s=await this.registry.fetchRegistry(),c=await this.prompt.runWizard((0,t.shake)({mode:`new`,examples:s.examples,example:i,name:a}),r);if(c===null)return null;if(c.name===`.`&&!n&&!o)return this.logger.error(`Cannot scaffold into ${K(`.`)} because the current directory is not empty.`),this.logger.info(`Run ${K(`arkenv init`)} in an empty directory or choose a sub-directory name instead.`),this.logger.refuse({code:C.NON_EMPTY_DIR,message:`Cannot scaffold into the current directory because it is not empty.`,retryWith:[`--force`]}),null;let l=this.detectPackageManager();return(0,t.shake)({mode:`new`,cwd:process.cwd(),options:c,detectedFramework:c.framework,packageManager:l,tsConfig:{status:`not_found`},shouldUpdateTsConfig:!1,existingFiles:[],isYes:r})}detectPackageManager(){let e=process.env.npm_config_user_agent||``;return e.includes(`pnpm`)?`pnpm`:e.includes(`yarn`)?`yarn`:e.includes(`bun`)?`bun`:`npm`}};function ei(e){let t=new Rn(e),n=t.logger,r=new fn(t.isQuiet,n.stdio,n),i=new Fn;return{cli:t,logger:n,workspace:r,prompt:i,initUseCase:new $r(n,r,i,new Yt(n)),helpUseCase:new Vn(n)}}if(typeof require<`u`&&require.main!==module)throw Error(`🚨 ${b(`You imported the 'arkenv' package as a library. Starting with v1.0.0, the 'arkenv' package is exclusively the interactive CLI. If you want to validate environment variables in your code, please install and import '@arkenv/core' instead.`)}`);const ti=new st({isQuiet:!1,isJson:!1});let ni,ri=!1;async function ii(){if(process.env.INIT_CWD)try{process.chdir(process.env.INIT_CWD)}catch{}let{cli:e,logger:n,initUseCase:r,helpUseCase:i}=ei(process.argv);ni=n,ai(n),e.validationError&&(n.error(e.validationError),await i.execute(),await n.flush(),process.exit(1)),e.helpRequested&&(await i.execute(),await n.flush(),process.exit(0)),e.command!==`init`&&(e.command?n.error(`Unknown command: ${e.command}`):n.error(`Missing command.`),await i.execute(),await n.flush(),process.exit(1));try{await r.execute((0,t.shake)(e.initInput))||(await n.flush(),process.exit(1))}catch(e){try{n.fatal(`An unexpected error occurred`,e)}catch{}await n.flush(),process.exit(1)}}function ai(e){let t=async t=>{ri&&process.exit(t),ri=!0,setTimeout(()=>{process.exit(t)},2e3).unref(),e.interactiveStdout&&e.interactiveStdout(!1);try{e.cancel(`Operation cancelled.`),await e.flush()}catch(t){e.error&&e.error(`Logger failed during shutdown`,t)}finally{process.exit(t)}};process.on(`SIGINT`,()=>t(130)),process.on(`SIGTERM`,()=>t(143))}ii(),process.on(`unhandledRejection`,async e=>{let t=ni??ti;try{t.fatal(`Unhandled rejection`,e)}catch{}await t.flush(),process.exit(1)}),process.on(`uncaughtException`,async e=>{let t=ni??ti;try{t.fatal(`Uncaught exception`,e)}catch{}await t.flush(),process.exit(1)});
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "arkenv",
3
3
  "type": "module",
4
- "version": "1.0.0-alpha.4",
4
+ "version": "1.0.0-alpha.6",
5
5
  "description": "Interactive CLI for scaffolding ArkEnv projects",
6
6
  "bin": {
7
7
  "arkenv": "./dist/index.cjs"
@@ -47,6 +47,7 @@
47
47
  "tsdown": "0.21.10",
48
48
  "typescript": "6.0.3",
49
49
  "vitest": "4.1.5",
50
+ "@repo/log": "0.0.1",
50
51
  "@repo/utils": "0.1.3"
51
52
  },
52
53
  "scripts": {