@arkenv/cli 0.2.10 → 0.3.0
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.
- package/dist/index.cjs +105 -100
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -19,74 +19,74 @@ const e=require(`./chunk-i8uDWG73.cjs`);let t=require(`radashi`),n=require(`node
|
|
|
19
19
|
declare namespace NodeJS {
|
|
20
20
|
interface ProcessEnv extends ProcessEnvAugmented {}
|
|
21
21
|
}
|
|
22
|
-
`}var v=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})),y=e.r(v(),1),b=class{info(e){process.stderr.write(`${y.default.blue(`ℹ ${e}`)}\n`)}warn(e){process.stderr.write(`${y.default.yellow(`⚠ ${e}`)}\n`)}error(e){process.stderr.write(`${y.default.red(`✘ ${e}`)}\n`)}success(e){process.stderr.write(`${y.default.green(`✔ ${e}`)}\n`)}step(e){process.stderr.write(`○ ${e}\n`)}note(e,t){process.stderr.write(`${y.default.dim(`○ ${t?`${t}: `:``}${e}`)}\n`)}log(e){process.stderr.write(`${e}\n`)}spinner(){return{start:e=>process.stderr.write(`${y.default.dim(`○ ${e}...`)}\n`),stop:e=>process.stderr.write(`${y.default.green(`✔ ${e}`)}\n`),message:e=>process.stderr.write(`${y.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())})}},x=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 S=(()=>{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}})(),
|
|
23
|
-
`),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===``){
|
|
24
|
-
`){a&&(r+=
|
|
25
|
-
`&&(i&&
|
|
26
|
-
`)}var
|
|
22
|
+
`}var v=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})),y=e.r(v(),1),b=class{info(e){process.stderr.write(`${y.default.blue(`ℹ ${e}`)}\n`)}warn(e){process.stderr.write(`${y.default.yellow(`⚠ ${e}`)}\n`)}error(e){process.stderr.write(`${y.default.red(`✘ ${e}`)}\n`)}success(e){process.stderr.write(`${y.default.green(`✔ ${e}`)}\n`)}step(e){process.stderr.write(`○ ${e}\n`)}note(e,t){process.stderr.write(`${y.default.dim(`○ ${t?`${t}: `:``}${e}`)}\n`)}log(e){process.stderr.write(`${e}\n`)}spinner(){return{start:e=>process.stderr.write(`${y.default.dim(`○ ${e}...`)}\n`),stop:e=>process.stderr.write(`${y.default.green(`✔ ${e}`)}\n`),message:e=>process.stderr.write(`${y.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())})}},x=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 S=(()=>{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}})(),ee=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,C=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,w=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,T=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,E=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,te=/\t{1,1000}/y,D=/[\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,O=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,ne=/\p{M}+/gu,re={limit:1/0,ellipsis:``},ie=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?ie(i,re,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[O,l],[w,0],[T,o],[te,s],[D,c],[E,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,k=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(ne,``)){let t=e.codePointAt(0)||0;if(k=ee(t)?2:C(t)?u:l,x+k>v&&(_=Math.min(_,Math.max(y,f)+h)),x+k>r){g=!0;break outer}h+=e.length,x+=k}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===E?S(e.slice(p,n.lastIndex)):n===D?1:n.lastIndex-p,k=h*i,x+k>v&&(_=Math.min(_,p+Math.floor((v-x)/i))),x+k>r){g=!0;break outer}x+=k,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}},k={limit:1/0,ellipsis:``,ellipsisWidth:0},A=(e,t={})=>ie(e,k,t).width,ae=`]8;;`,oe=RegExp(`(?:\\[(?<code>\\d+)m|\\${ae}(?<uri>.*))`,`y`),se=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},ce=e=>`[${e}m`,le=e=>`${ae}${e}`,ue=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:A(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=A(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===``)&&(i=!0,a=t.startsWith(ae,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())},de=e=>{let t=e.split(` `),n=t.length;for(;n&&!A(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},fe=(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=A(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=A(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(``),ue(s,r,t),c=A(s.at(-1)??``);continue}if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){ue(s,r,t),c=A(s.at(-1)??``);continue}s.push(``),c=0}if(c+i>t&&n.wordWrap===!1){ue(s,r,t),c=A(s.at(-1)??``);continue}s[s.length-1]+=r,c+=i}n.trim!==!1&&(s=s.map(e=>de(e)));let l=s.join(`
|
|
23
|
+
`),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===``){oe.lastIndex=e+1;let t=oe.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]===`
|
|
24
|
+
`){a&&(r+=le(``));let e=i?se(i):void 0;i&&e&&(r+=ce(e))}else t===`
|
|
25
|
+
`&&(i&&se(i)&&(r+=ce(i)),a&&(r+=le(a)))}return r},pe=/\r?\n/;function j(e,t,n){return String(e).normalize().split(pe).map(e=>fe(e,t,n)).join(`
|
|
26
|
+
`)}var M=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 me(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?me(a,t<0?-1:1,n):a}const N={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 he(e,t){if(typeof e==`string`)return N.aliases.get(e)===t;for(let n of e)if(n!==void 0&&he(n,t))return!0;return!1}function ge(e,t){if(e===t)return;let n=e.split(`
|
|
27
27
|
`),r=t.split(`
|
|
28
|
-
`),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
|
|
28
|
+
`),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 _e=globalThis.process.platform.startsWith(`win`),ve=Symbol(`clack:cancel`);function P(e){return e===ve}function F(e,t){let n=e;n.isTTY&&n.setRawMode(t)}function ye({input:e=o.stdin,output:t=o.stdout,overwrite:n=!0,hideCursor:r=!0}={}){let i=s.createInterface({input:e,output:t,prompt:``,tabSize:1});s.emitKeypressEvents(e,i),e instanceof c.ReadStream&&e.isTTY&&e.setRawMode(!0);let a=(i,{name:o,sequence:c})=>{if(he([String(i),o,c],`cancel`)){r&&t.write(M.cursor.show),process.exit(0);return}if(!n)return;let l=o===`return`?0:-1,u=o===`return`?-1:0;s.moveCursor(t,l,u,()=>{s.clearLine(t,1,()=>{e.once(`keypress`,a)})})};return r&&t.write(M.cursor.hide),e.once(`keypress`,a),()=>{e.off(`keypress`,a),r&&t.write(M.cursor.show),e instanceof c.ReadStream&&e.isTTY&&!_e&&e.setRawMode(!1),i.terminal=!1,i.close()}}const I=e=>`columns`in e&&typeof e.columns==`number`?e.columns:80,be=e=>`rows`in e&&typeof e.rows==`number`?e.rows:20;function L(e,t,n,r=n,i){return j(t,I(e??o.stdout)-n.length,{hard:!0,trim:!1}).split(`
|
|
29
29
|
`).map((e,t)=>{let a=i?i(e,t):e;return`${t===0?r:n}${a}`}).join(`
|
|
30
|
-
`)}let
|
|
31
|
-
`),
|
|
32
|
-
`).length-1;this.output.write(
|
|
33
|
-
`);this.output.write(t[a]),this._prevFrame=e,this.output.write(
|
|
30
|
+
`)}let xe=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=o.stdin,output:r=o.stdout,render:i,signal:a,...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=i.bind(this),this._track=t,this._abortSignal=a,this.input=n,this.output=r}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(ve);this._abortSignal.addEventListener(`abort`,()=>{this.state=`cancel`,this.close()},{once:!0})}this.rl=s.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),F(this.input,!0),this.output.on(`resize`,this.render),this.render(),this.once(`submit`,()=>{this.output.write(M.cursor.show),this.output.off(`resize`,this.render),F(this.input,!1),e(this.value)}),this.once(`cancel`,()=>{this.output.write(M.cursor.show),this.output.off(`resize`,this.render),F(this.input,!1),e(ve)})})}_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&&N.aliases.has(t.name)&&this.emit(`cursor`,N.aliases.get(t.name)),N.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`)}he([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(`
|
|
31
|
+
`),F(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=j(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
32
|
+
`).length-1;this.output.write(M.cursor.move(-999,e*-1))}render(){let e=j(this._render(this)??``,process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state===`initial`)this.output.write(M.cursor.hide);else{let t=ge(this._prevFrame,e),n=be(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(M.cursor.move(0,a-i)),this.output.write(M.erase.lines(1));let t=e.split(`
|
|
33
|
+
`);this.output.write(t[a]),this._prevFrame=e,this.output.write(M.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(M.cursor.move(0,e))}this.output.write(M.erase.down());let t=e.split(`
|
|
34
34
|
`).slice(a);this.output.write(t.join(`
|
|
35
|
-
`)),this._prevFrame=e;return}}this.output.write(
|
|
36
|
-
`);_.push(i),v+=i.length}if(v>d){let t=0,n=0,r=v,i=e-y,a=(e,t)=>
|
|
35
|
+
`)),this._prevFrame=e;return}}this.output.write(M.erase.down())}this.output.write(e),this.state===`initial`&&(this.state=`active`),this._prevFrame=e}}};var Se=class extends xe{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(M.cursor.move(0,-1)),this.value=e,this.state=`submit`,this.close()}),this.on(`cursor`,()=>{this.value=!this.value})}},Ce=class extends xe{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?me(n,1,this.options):n,this.changeValue(),this.on(`cursor`,e=>{switch(e){case`left`:case`up`:this.cursor=me(this.cursor,-1,this.options);break;case`down`:case`right`:this.cursor=me(this.cursor,1,this.options);break}this.changeValue()})}},we=class extends xe{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),[n,...r]=e.slice(this.cursor);return`${t}${(0,a.styleText)(`inverse`,n)}${r.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 Te(){return o.default.platform===`win32`?!!o.default.env.CI||!!o.default.env.WT_SESSION||!!o.default.env.TERMINUS_SUBLIME||o.default.env.ConEmuTask===`{cmd::Cmder}`||o.default.env.TERM_PROGRAM===`Terminus-Sublime`||o.default.env.TERM_PROGRAM===`vscode`||o.default.env.TERM===`xterm-256color`||o.default.env.TERM===`alacritty`||o.default.env.TERMINAL_EMULATOR===`JetBrains-JediTerm`:o.default.env.TERM!==`linux`}const Ee=Te(),De=()=>process.env.CI===`true`,R=(e,t)=>Ee?e:t,Oe=R(`◆`,`*`),ke=R(`■`,`x`),Ae=R(`▲`,`x`),z=R(`◇`,`o`),B=R(`│`,`|`),V=R(`└`,`—`),je=R(`●`,`>`),H=R(`○`,` `),Me=R(`─`,`-`),Ne=R(`╮`,`+`),Pe=R(`├`,`+`),Fe=R(`╯`,`+`),Ie=R(`╰`,`+`),Le=R(`●`,`•`),Re=R(`◆`,`*`),ze=R(`▲`,`!`),Be=R(`■`,`x`),Ve=e=>{switch(e){case`initial`:case`active`:return(0,a.styleText)(`cyan`,Oe);case`cancel`:return(0,a.styleText)(`red`,ke);case`error`:return(0,a.styleText)(`yellow`,Ae);case`submit`:return(0,a.styleText)(`green`,z)}},He=e=>{switch(e){case`initial`:case`active`:return(0,a.styleText)(`cyan`,B);case`cancel`:return(0,a.styleText)(`red`,B);case`error`:return(0,a.styleText)(`yellow`,B);case`submit`:return(0,a.styleText)(`green`,B)}},Ue=(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}},We=({cursor:e,options:t,style:n,output:r=process.stdout,maxItems:i=1/0,columnPadding:o=0,rowPadding:s=4})=>{let c=I(r)-o,l=be(r),u=(0,a.styleText)(`dim`,`...`),d=Math.max(l-s,0),f=Math.max(Math.min(i,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 r=y;r<b;r++){let i=j(n(t[r],r===e),c,{hard:!0,trim:!1}).split(`
|
|
36
|
+
`);_.push(i),v+=i.length}if(v>d){let t=0,n=0,r=v,i=e-y,a=(e,t)=>Ue(_,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},U=e=>{let t=e.active??`Yes`,n=e.inactive??`No`;return new Se({active:t,inactive:n,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let r=e.withGuide??N.withGuide,i=`${Ve(this.state)} `,o=r?`${(0,a.styleText)(`gray`,B)} `:``,s=L(e.output,e.message,o,i),c=`${r?`${(0,a.styleText)(`gray`,B)}
|
|
37
37
|
`:``}${s}
|
|
38
|
-
`,l=this.value?t:n;switch(this.state){case`submit`:return`${c}${r?`${(0,a.styleText)(`gray`,
|
|
39
|
-
${(0,a.styleText)(`gray`,
|
|
40
|
-
${(0,a.styleText)(`cyan`,
|
|
41
|
-
`:` ${(0,a.styleText)(`dim`,`/`)} `}${this.value?`${(0,a.styleText)(`dim`,
|
|
38
|
+
`,l=this.value?t:n;switch(this.state){case`submit`:return`${c}${r?`${(0,a.styleText)(`gray`,B)} `:``}${(0,a.styleText)(`dim`,l)}`;case`cancel`:return`${c}${r?`${(0,a.styleText)(`gray`,B)} `:``}${(0,a.styleText)([`strikethrough`,`dim`],l)}${r?`
|
|
39
|
+
${(0,a.styleText)(`gray`,B)}`:``}`;default:{let i=r?`${(0,a.styleText)(`cyan`,B)} `:``,o=r?(0,a.styleText)(`cyan`,V):``;return`${c}${i}${this.value?`${(0,a.styleText)(`green`,je)} ${t}`:`${(0,a.styleText)(`dim`,H)} ${(0,a.styleText)(`dim`,t)}`}${e.vertical?r?`
|
|
40
|
+
${(0,a.styleText)(`cyan`,B)} `:`
|
|
41
|
+
`:` ${(0,a.styleText)(`dim`,`/`)} `}${this.value?`${(0,a.styleText)(`dim`,H)} ${(0,a.styleText)(`dim`,n)}`:`${(0,a.styleText)(`green`,je)} ${n}`}
|
|
42
42
|
${o}
|
|
43
|
-
`}}}}).prompt()},
|
|
43
|
+
`}}}}).prompt()},W={message:(e=[],{symbol:t=(0,a.styleText)(`gray`,B),secondarySymbol:n=(0,a.styleText)(`gray`,B),output:r=process.stdout,spacing:i=1,withGuide:o}={})=>{let s=[],c=o??N.withGuide,l=c?n:``,u=c?`${t} `:``,d=c?`${n} `:``;for(let e=0;e<i;e++)s.push(l);let f=Array.isArray(e)?e:e.split(`
|
|
44
44
|
`);if(f.length>0){let[e,...r]=f;e.length>0?s.push(`${u}${e}`):s.push(c?t:``);for(let e of r)e.length>0?s.push(`${d}${e}`):s.push(c?n:``)}r.write(`${s.join(`
|
|
45
45
|
`)}
|
|
46
|
-
`)},info:(e,t)=>{
|
|
46
|
+
`)},info:(e,t)=>{W.message(e,{...t,symbol:(0,a.styleText)(`blue`,Le)})},success:(e,t)=>{W.message(e,{...t,symbol:(0,a.styleText)(`green`,Re)})},step:(e,t)=>{W.message(e,{...t,symbol:(0,a.styleText)(`green`,z)})},warn:(e,t)=>{W.message(e,{...t,symbol:(0,a.styleText)(`yellow`,ze)})},warning:(e,t)=>{W.warn(e,t)},error:(e,t)=>{W.message(e,{...t,symbol:(0,a.styleText)(`red`,Be)})}},Ge=(e=``,t)=>{let n=t?.output??process.stdout,r=t?.withGuide??N.withGuide?`${(0,a.styleText)(`gray`,V)} `:``;n.write(`${r}${(0,a.styleText)(`red`,e)}
|
|
47
47
|
|
|
48
|
-
`)},
|
|
49
|
-
${(0,a.styleText)(`gray`,
|
|
48
|
+
`)},Ke=(e=``,t)=>{let n=t?.output??process.stdout,r=t?.withGuide??N.withGuide?`${(0,a.styleText)(`gray`,B)}
|
|
49
|
+
${(0,a.styleText)(`gray`,V)} `:``;n.write(`${r}${e}
|
|
50
50
|
|
|
51
|
-
`)},
|
|
52
|
-
`),a=i.reduce((e,t)=>Math.max(
|
|
53
|
-
`).map(s),``],l=
|
|
54
|
-
`),f=i?`${(0,a.styleText)(`gray`,
|
|
55
|
-
`:``,p=i?
|
|
51
|
+
`)},qe=e=>(0,a.styleText)(`dim`,e),Je=(e,t,n)=>{let r={hard:!0,trim:!1},i=j(e,t,r).split(`
|
|
52
|
+
`),a=i.reduce((e,t)=>Math.max(A(t),e),0);return j(e,t-(i.map(n).reduce((e,t)=>Math.max(A(t),e),0)-a),r)},Ye=(e=``,t=``,n)=>{let r=n?.output??o.default.stdout,i=n?.withGuide??N.withGuide,s=n?.format??qe,c=[``,...Je(e,I(r)-6,s).split(`
|
|
53
|
+
`).map(s),``],l=A(t),u=Math.max(c.reduce((e,t)=>{let n=A(t);return n>e?n:e},0),l)+2,d=c.map(e=>`${(0,a.styleText)(`gray`,B)} ${e}${` `.repeat(u-A(e))}${(0,a.styleText)(`gray`,B)}`).join(`
|
|
54
|
+
`),f=i?`${(0,a.styleText)(`gray`,B)}
|
|
55
|
+
`:``,p=i?Pe:Ie;r.write(`${f}${(0,a.styleText)(`green`,z)} ${(0,a.styleText)(`reset`,t)} ${(0,a.styleText)(`gray`,Me.repeat(Math.max(u-l-1,1))+Ne)}
|
|
56
56
|
${d}
|
|
57
|
-
${(0,a.styleText)(`gray`,p+
|
|
58
|
-
`)},
|
|
59
|
-
`);let e=
|
|
60
|
-
`);e.length>1&&n.write(
|
|
61
|
-
`);let r=0,i=0;
|
|
57
|
+
${(0,a.styleText)(`gray`,p+Me.repeat(u+2)+Fe)}
|
|
58
|
+
`)},Xe=e=>(0,a.styleText)(`magenta`,e),Ze=({indicator:e=`dots`,onCancel:t,output:n=process.stdout,cancelMessage:r,errorMessage:i,frames:o=Ee?[`◒`,`◐`,`◓`,`◑`]:[`•`,`o`,`O`,`0`],delay:s=Ee?80:120,signal:c,...l}={})=>{let u=De(),d,f,p=!1,m=!1,h=``,g,_=performance.now(),v=I(n),y=l?.styleFrame??Xe,b=e=>{let n=e>1?i??N.messages.error:r??N.messages.cancel;m=e===1,p&&(O(n,e),m&&typeof t==`function`&&t())},x=()=>b(2),S=()=>b(1),ee=()=>{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)},C=()=>{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&&n.write(`
|
|
59
|
+
`);let e=j(g,v,{hard:!0,trim:!1}).split(`
|
|
60
|
+
`);e.length>1&&n.write(M.cursor.up(e.length-1)),n.write(M.cursor.to(0)),n.write(M.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]`},te=l.withGuide??N.withGuide,D=(t=``)=>{p=!0,d=ye({output:n}),h=T(t),_=performance.now(),te&&n.write(`${(0,a.styleText)(`gray`,B)}
|
|
61
|
+
`);let r=0,i=0;ee(),f=setInterval(()=>{if(u&&h===g)return;w(),g=h;let t=y(o[r]),a;if(u)a=`${t} ${h}...`;else if(e===`timer`)a=`${t} ${h} ${E(_)}`;else{let e=`.`.repeat(Math.floor(i)).slice(0,3);a=`${t} ${h}${e}`}let s=j(a,v,{hard:!0,trim:!1});n.write(s),r=r+1<o.length?r+1:0,i=i<4?i+.125:0},s)},O=(t=``,r=0,i=!1)=>{if(!p)return;p=!1,clearInterval(f),w();let o=r===0?(0,a.styleText)(`green`,z):r===1?(0,a.styleText)(`red`,ke):(0,a.styleText)(`red`,Ae);h=t??h,i||(e===`timer`?n.write(`${o} ${h} ${E(_)}
|
|
62
62
|
`):n.write(`${o} ${h}
|
|
63
|
-
`)),
|
|
63
|
+
`)),C(),d()};return{start:D,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}}},G=(e,t)=>e.includes(`
|
|
64
64
|
`)?e.split(`
|
|
65
65
|
`).map(e=>t(e)).join(`
|
|
66
|
-
`):t(e),
|
|
66
|
+
`):t(e),K=e=>{let t=(e,t)=>{let n=e.label??String(e.value);switch(t){case`disabled`:return`${(0,a.styleText)(`gray`,H)} ${G(n,e=>(0,a.styleText)(`gray`,e))}${e.hint?` ${(0,a.styleText)(`dim`,`(${e.hint??`disabled`})`)}`:``}`;case`selected`:return`${G(n,e=>(0,a.styleText)(`dim`,e))}`;case`active`:return`${(0,a.styleText)(`green`,je)} ${n}${e.hint?` ${(0,a.styleText)(`dim`,`(${e.hint})`)}`:``}`;case`cancelled`:return`${G(n,e=>(0,a.styleText)([`strikethrough`,`dim`],e))}`;default:return`${(0,a.styleText)(`dim`,H)} ${G(n,e=>(0,a.styleText)(`dim`,e))}`}};return new Ce({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let n=e.withGuide??N.withGuide,r=`${Ve(this.state)} `,i=`${He(this.state)} `,o=L(e.output,e.message,i,r),s=`${n?`${(0,a.styleText)(`gray`,B)}
|
|
67
67
|
`:``}${o}
|
|
68
|
-
`;switch(this.state){case`submit`:{let r=n?`${(0,a.styleText)(`gray`,
|
|
69
|
-
${(0,a.styleText)(`gray`,
|
|
70
|
-
`).length,c=n?2:1;return`${s}${r}${
|
|
68
|
+
`;switch(this.state){case`submit`:{let r=n?`${(0,a.styleText)(`gray`,B)} `:``;return`${s}${L(e.output,t(this.options[this.cursor],`selected`),r)}`}case`cancel`:{let r=n?`${(0,a.styleText)(`gray`,B)} `:``;return`${s}${L(e.output,t(this.options[this.cursor],`cancelled`),r)}${n?`
|
|
69
|
+
${(0,a.styleText)(`gray`,B)}`:``}`}default:{let r=n?`${(0,a.styleText)(`cyan`,B)} `:``,i=n?(0,a.styleText)(`cyan`,V):``,o=s.split(`
|
|
70
|
+
`).length,c=n?2:1;return`${s}${r}${We({output:e.output,cursor:this.cursor,options:this.options,maxItems:e.maxItems,columnPadding:r.length,rowPadding:o+c,style:(e,n)=>t(e,e.disabled?`disabled`:n?`active`:`inactive`)}).join(`
|
|
71
71
|
${r}`)}
|
|
72
72
|
${i}
|
|
73
|
-
`}}}}).prompt()},
|
|
73
|
+
`}}}}).prompt()},Qe=`${(0,a.styleText)(`gray`,B)} `,q={message:async(e,{symbol:t=(0,a.styleText)(`gray`,B)}={})=>{process.stdout.write(`${(0,a.styleText)(`gray`,B)}
|
|
74
74
|
${t} `);let n=3;for await(let t of e){t=t.replace(/\n/g,`
|
|
75
|
-
${
|
|
75
|
+
${Qe}`),t.includes(`
|
|
76
76
|
`)&&(n=3+(0,a.stripVTControlCharacters)(t.slice(t.lastIndexOf(`
|
|
77
77
|
`))).length);let e=(0,a.stripVTControlCharacters)(t).length;n+e<process.stdout.columns?(n+=e,process.stdout.write(t)):(process.stdout.write(`
|
|
78
|
-
${
|
|
79
|
-
`)},info:e=>
|
|
80
|
-
`:``}${
|
|
81
|
-
`,r=e.placeholder?(0,a.styleText)(`inverse`,e.placeholder[0])+(0,a.styleText)(`dim`,e.placeholder.slice(1)):(0,a.styleText)([`inverse`,`hidden`],`_`),i=this.userInput?this.userInputWithCursor:r,o=this.value??``;switch(this.state){case`error`:{let e=this.error?` ${(0,a.styleText)(`yellow`,this.error)}`:``,r=t?`${(0,a.styleText)(`yellow`,
|
|
78
|
+
${Qe}${t.trimStart()}`),n=3+(0,a.stripVTControlCharacters)(t.trimStart()).length)}process.stdout.write(`
|
|
79
|
+
`)},info:e=>q.message(e,{symbol:(0,a.styleText)(`blue`,Le)}),success:e=>q.message(e,{symbol:(0,a.styleText)(`green`,Re)}),step:e=>q.message(e,{symbol:(0,a.styleText)(`green`,z)}),warn:e=>q.message(e,{symbol:(0,a.styleText)(`yellow`,ze)}),warning:e=>q.warn(e),error:e=>q.message(e,{symbol:(0,a.styleText)(`red`,Be)})},$e=e=>new we({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??N.withGuide,n=`${`${t?`${(0,a.styleText)(`gray`,B)}
|
|
80
|
+
`:``}${Ve(this.state)} `}${e.message}
|
|
81
|
+
`,r=e.placeholder?(0,a.styleText)(`inverse`,e.placeholder[0])+(0,a.styleText)(`dim`,e.placeholder.slice(1)):(0,a.styleText)([`inverse`,`hidden`],`_`),i=this.userInput?this.userInputWithCursor:r,o=this.value??``;switch(this.state){case`error`:{let e=this.error?` ${(0,a.styleText)(`yellow`,this.error)}`:``,r=t?`${(0,a.styleText)(`yellow`,B)} `:``,o=t?(0,a.styleText)(`yellow`,V):``;return`${n.trim()}
|
|
82
82
|
${r}${i}
|
|
83
83
|
${o}${e}
|
|
84
|
-
`}case`submit`:{let e=o?` ${(0,a.styleText)(`dim`,o)}`:``;return`${n}${t?(0,a.styleText)(`gray`,
|
|
85
|
-
${r}`:``}`}default:return`${n}${t?`${(0,a.styleText)(`cyan`,
|
|
86
|
-
${t?(0,a.styleText)(`cyan`,
|
|
87
|
-
`}}}).prompt();var $e=class{info(e){process.stdout.write(`${y.default.blue(`ℹ ${e}`)}\n`)}warn(e){process.stderr.write(`${y.default.yellow(`⚠ ${e}`)}\n`)}error(e){process.stderr.write(`${y.default.red(`✘ ${e}`)}\n`)}success(e){process.stdout.write(`${y.default.green(`✔ ${e}`)}\n`)}step(e){process.stdout.write(`○ ${e}\n`)}note(e,t){qe(e,t)}log(e){process.stdout.write(`${e}\n`)}spinner(){return Ye()}json(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}cancel(e){process.stderr.write(`${y.default.red(`✘ ${e}`)}\n`)}fatal(e,t){if(process.stderr.write(`${y.default.red(`✘ ${e}`)}\n`),t){let e=`${y.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){We(e)}async flush(){return new Promise(e=>{process.stderr.write(``,()=>e())})}},et=class{constructor(e){this.options=e,this.originalStdoutWrite=process.stdout.write,e.isJson?this.reporter=new b:e.isQuiet?this.reporter=new x:this.reporter=new $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)}finish(e,t){this.reporter.finish(e,t)}async flush(){await this.reporter.flush()}};async function tt(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=r.default.join(e,`package.json`),i=await n.default.readFile(t,`utf-8`),a=JSON.parse(i),o={...a.dependencies,...a.devDependencies};if(o.vite)return`vite`;if(o.next)return`nextjs`}catch{}try{return await n.default.access(r.default.join(e,`vite.config.ts`)),`vite`}catch{}try{return await n.default.access(r.default.join(e,`vite.config.js`)),`vite`}catch{}try{return await n.default.access(r.default.join(e,`next.config.ts`)),`nextjs`}catch{}try{return await n.default.access(r.default.join(e,`next.config.js`)),`nextjs`}catch{}try{return await n.default.access(r.default.join(e,`next.config.mjs`)),`nextjs`}catch{}try{return await n.default.access(r.default.join(e,`next.config.cjs`)),`nextjs`}catch{}return(await nt(e,t)).length>0?`bun-fullstack`:`vanilla`}async function nt(e=process.cwd(),t){let i=[];try{let t=r.default.join(e,`bunfig.toml`),a=await n.default.readFile(t,`utf-8`);(a.includes(`[serve]`)||a.includes(`[serve.static]`))&&i.push(`serve`),a.includes(`[build]`)&&i.push(`build`)}catch{}if(i.includes(`serve`)&&i.includes(`build`))return i;let{walk:a}=await Promise.resolve().then(()=>at),o=await a(e),s=i.includes(`serve`),c=i.includes(`build`);for(let e of o)try{let t=await n.default.readFile(e,`utf-8`);if(!s&&(t.includes(`Bun.serve`)||t.includes(`serve(`))&&(/from\s+['"]bun['"]/.test(t)||t.includes(`Bun.serve`))&&(s=!0,i.push(`serve`)),!c&&(t.includes(`Bun.build`)||t.includes(`build(`))&&(/from\s+['"]bun['"]/.test(t)||t.includes(`Bun.build`))&&(c=!0,i.push(`build`)),s&&c)break}catch{}return i}async function rt(e=process.cwd(),t){let i=process.env.npm_config_user_agent?.toString()||``;if(i.includes(`pnpm`))return`pnpm`;if(i.includes(`yarn`))return`yarn`;if(i.includes(`bun`))return`bun`;if(i.includes(`npm`))return`npm`;let a=t?.path?r.default.dirname(t.path):e;for(;a!==r.default.parse(a).root;){try{let e=r.default.join(a,`package.json`),t=await n.default.readFile(e,`utf-8`),i=JSON.parse(t);if(i.packageManager){if(i.packageManager.startsWith(`pnpm`))return`pnpm`;if(i.packageManager.startsWith(`yarn`))return`yarn`;if(i.packageManager.startsWith(`bun`))return`bun`}}catch{}let e=[];try{e=await n.default.readdir(a)}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`;a=r.default.dirname(a)}return`npm`}async function it(e=process.cwd(),t){let i=t;if(!i){let{findTsConfig:t,loadTsConfig:n}=await Promise.resolve().then(()=>dt),r=await t(e);r&&(i=await n(r))}if(i?.compilerOptions?.rootDir){let t=i.compilerOptions.rootDir,n=r.default.relative(e,t);return n&&n!==`.`&&!n.startsWith(`..`)&&!r.default.isAbsolute(n)?`./${n}/env.ts`:`./env.ts`}try{return await n.default.access(r.default.join(e,`src`)),`./src/env.ts`}catch{return`./env.ts`}}var at=e.n({getEnvExampleKeys:()=>ut,parseEnvExample:()=>st,resolveImportPaths:()=>ct,scanProjectEnvKeys:()=>lt,walk:()=>ot});async function ot(e,t=[]){try{let i=await n.default.readdir(e,{withFileTypes:!0});for(let n of i)if(n.isDirectory()){let i=n.name;if(i===`node_modules`||i===`dist`||i===`build`||i===`.git`||i===`.turbo`||i===`scratch`)continue;await ot(r.default.join(e,i),t)}else n.isFile()&&/\.(ts|tsx|js|jsx)$/.test(n.name)&&!n.name.endsWith(`.d.ts`)&&t.push(r.default.join(e,n.name))}catch{}return t}function st(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 ct(e,t,n){if(e.startsWith(`.`))return[r.default.resolve(r.default.dirname(n),e)];if(r.default.isAbsolute(e))return[e];let i=t.compilerOptions||{},a=i.baseUrl||r.default.dirname(t.path),o=i.paths||{},s=[];for(let[e,t]of Object.entries(o)){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:i}of s)if(i&&e.startsWith(t)||!i&&e===t){let i=e.slice(t.length);return n.map(e=>{let t=`${e.replace(/\*$/,``)}${i}`;return r.default.resolve(a,t)})}return i.baseUrl?[r.default.resolve(a,e)]:[]}async function lt(e,t,i){let a=[],o=await ot(e),s=i?i.replace(/\.(ts|js|tsx|jsx)$/,``):null;for(let e of o)try{let i=await n.default.readFile(e,`utf-8`),o=i.matchAll(/process\.env\.([A-Z_][A-Z0-9_]*)/g);for(let e of o)e[1]&&a.push(e[1]);let c=i.matchAll(/import\.meta\.env\.([A-Z_][A-Z0-9_]*)/g);for(let e of c)e[1]&&a.push(e[1]);if(s){let n=i.matchAll(/import\s+[^;]*from\s+['"]([^'"]+)['"]/g);for(let o of n){let n=o[1],c=[];if(t?c=ct(n,t,e):n.startsWith(`.`)&&(c=[r.default.resolve(r.default.dirname(e),n)]),c.some(e=>e.replace(/\.(ts|js|tsx|jsx)$/,``)===s)){let e=i.matchAll(/\benv\.([A-Z_][A-Z0-9_]*)/g);for(let t of e)t[1]&&a.push(t[1])}}}}catch{}return Array.from(new Set(a))}async function ut(e=process.cwd(),t,i){let a=r.default.join(e,`.env.example`);try{let e=st(await n.default.readFile(a,`utf-8`));if(e.length>0)return{keys:e,source:`.env.example`}}catch{}let o=await lt(e,t,i);return o.length>0?{keys:o,source:`project`}:null}var dt=e.n({checkTsConfig:()=>ht,findTsConfig:()=>pt,loadTsConfig:()=>mt});const ft=(0,u.createRequire)(require(`url`).pathToFileURL(__filename).href).resolve;async function pt(e=process.cwd()){let t=[`tsconfig.app.json`,`tsconfig.json`,`tsconfig.base.json`,`tsconfig.node.json`],i=e;for(;i!==r.default.parse(i).root;){for(let e of t){let t=r.default.join(i,e);try{return await n.default.access(t),t}catch{}}i=r.default.dirname(i)}return null}async function mt(e,t=new Set){let i=r.default.resolve(e);if(t.has(i))throw Error(`Circular extends dependency detected in tsconfig.json: ${i}`);t.add(i);let a=``;try{a=await n.default.readFile(e,`utf-8`)}catch{return{path:e,compilerOptions:{}}}let o=(0,d.parse)(a)||{},s=o.compilerOptions||{},c={};if(o.extends){let n=Array.isArray(o.extends)?o.extends:[o.extends];for(let i of n){let n;if(i.startsWith(`.`)||r.default.isAbsolute(i))n=r.default.resolve(r.default.dirname(e),i);else try{n=ft(i,{paths:[r.default.dirname(e)]})}catch{n=r.default.resolve(r.default.dirname(e),`node_modules`,i)}let a={...(await mt(n,t)).compilerOptions};a.baseUrl&&=r.default.resolve(r.default.dirname(n),a.baseUrl),a.rootDir&&=r.default.resolve(r.default.dirname(n),a.rootDir),c={...c,...a}}}let l={...s};return l.baseUrl&&=r.default.resolve(r.default.dirname(e),l.baseUrl),l.rootDir&&=r.default.resolve(r.default.dirname(e),l.rootDir),c={...c,...l},{...o,path:e,compilerOptions:c}}async function ht(e=process.cwd()){let t=await pt(e);if(!t)return{status:`not_found`};let n=r.default.basename(t);try{let e=await mt(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 _t(e){let t=e.trim().match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?/);return t?[t[1],t[2]??`0`,t[3]??`0`].join(`.`):null}function vt(e,t){let n=e.trim(),r=n.match(/^[\^~]?\s*(v?\d+(?:\.\d+){0,2})$/);if(r){let e=_t(r[1]);return e!==null&>(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=_t(i);return a&&(r===`>=`||r===`>`||r===`=`)?gt(a,t)>=0:!1})}async function yt(e=process.cwd()){let t=[],i=process.version,a=`22.0.0`;gt(i,a)===-1?t.push({status:`fail`,requirement:`Node.js Version`,message:`Node.js version must be >= ${a}.`,current:i,expected:`>= ${a}`}):t.push({status:`pass`,requirement:`Node.js Version`,message:`Node.js version is compatible.`});let o=null;try{let i=r.default.join(e,`package.json`),a=await n.default.readFile(i,`utf-8`);o=JSON.parse(a),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(o){let e={...o.dependencies,...o.devDependencies}.typescript,n=`5.1.0`;e?vt(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 s=await ht(e);if(s.status===`not_found`)t.push({status:`warn`,requirement:`tsconfig.json`,message:`tsconfig.json not found.`});else{let e=s.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 bt=class{async isEmptyDirectory(e=process.cwd()){try{return(await n.default.readdir(e)).length===0}catch{return!1}}async hasPackageJson(e=process.cwd()){try{return await n.default.access(r.default.join(e,`package.json`)),!0}catch{return!1}}async findTsConfig(e=process.cwd()){return pt(e)}async loadTsConfig(e,t=new Set){return mt(e,t)}async getEnvExampleKeys(e=process.cwd(),t,n){return ut(e,t,n)}async suggestDefaultEnvPath(e=process.cwd(),t){return it(e,t)}async checkTsConfig(e=process.cwd()){return ht(e)}async checkRequirements(e=process.cwd()){return yt(e)}async detectFramework(e=process.cwd(),t){return tt(e,t)}async detectBunFeatures(e=process.cwd(),t){return nt(e,t)}async detectPackageManager(e=process.cwd(),t){return rt(e,t)}async hasSkill(e=process.cwd()){try{let t=r.default.join(e,`skills-lock.json`),i=await n.default.readFile(t,`utf-8`),a=JSON.parse(i);if(a&&typeof a==`object`&&a.skills&&typeof a.skills==`object`&&`arkenv`in a.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 n.default.access(r.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`?(console.debug(`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 Y=e=>y.default.cyan(e),xt=y.default.blue(`⛯`);function St(e){return e.replace(/import\s*\{([^\n}]*)\}\s*from/g,(e,t)=>`import { ${t.trim()} } from`)}function Ct(e,t){return t.endsWith(`
|
|
84
|
+
`}case`submit`:{let e=o?` ${(0,a.styleText)(`dim`,o)}`:``;return`${n}${t?(0,a.styleText)(`gray`,B):``}${e}`}case`cancel`:{let e=o?` ${(0,a.styleText)([`strikethrough`,`dim`],o)}`:``,r=t?(0,a.styleText)(`gray`,B):``;return`${n}${r}${e}${o.trim()?`
|
|
85
|
+
${r}`:``}`}default:return`${n}${t?`${(0,a.styleText)(`cyan`,B)} `:``}${i}
|
|
86
|
+
${t?(0,a.styleText)(`cyan`,V):``}
|
|
87
|
+
`}}}).prompt();var et=class{info(e){process.stdout.write(`${y.default.blue(`ℹ ${e}`)}\n`)}warn(e){process.stderr.write(`${y.default.yellow(`⚠ ${e}`)}\n`)}error(e){process.stderr.write(`${y.default.red(`✘ ${e}`)}\n`)}success(e){process.stdout.write(`${y.default.green(`✔ ${e}`)}\n`)}step(e){process.stdout.write(`○ ${e}\n`)}note(e,t){Ye(e,t)}log(e){process.stdout.write(`${e}\n`)}spinner(){return Ze()}json(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}cancel(e){process.stderr.write(`${y.default.red(`✘ ${e}`)}\n`)}fatal(e,t){if(process.stderr.write(`${y.default.red(`✘ ${e}`)}\n`),t){let e=`${y.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){Ke(e)}async flush(){return new Promise(e=>{process.stderr.write(``,()=>e())})}},tt=class{constructor(e){this.options=e,this.originalStdoutWrite=process.stdout.write,e.isJson?this.reporter=new b:e.isQuiet?this.reporter=new x:this.reporter=new et}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()}};async function nt(e,t){for(let i of t)try{return await n.default.access(r.default.join(e,i)),!0}catch{}return!1}async function rt(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=r.default.join(e,`package.json`),i=await n.default.readFile(t,`utf-8`),a=JSON.parse(i),o={...a.dependencies,...a.devDependencies};if(o.vite)return`vite`;if(o.next)return`nextjs`;if(o.nuxt)return`nuxt`}catch{}return await nt(e,[`vite.config.ts`,`vite.config.js`])?`vite`:await nt(e,[`next.config.ts`,`next.config.js`,`next.config.mjs`,`next.config.cjs`])?`nextjs`:await nt(e,[`nuxt.config.ts`,`nuxt.config.js`,`nuxt.config.mts`,`nuxt.config.mjs`,`nuxt.config.cjs`])?`nuxt`:(await it(e,t)).length>0?`bun-fullstack`:`vanilla`}async function it(e=process.cwd(),t){let i=[];try{let t=r.default.join(e,`bunfig.toml`),a=await n.default.readFile(t,`utf-8`);(a.includes(`[serve]`)||a.includes(`[serve.static]`))&&i.push(`serve`),a.includes(`[build]`)&&i.push(`build`)}catch{}if(i.includes(`serve`)&&i.includes(`build`))return i;let{walk:a}=await Promise.resolve().then(()=>st),o=await a(e),s=i.includes(`serve`),c=i.includes(`build`);for(let e of o)try{let t=await n.default.readFile(e,`utf-8`);if(!s&&(t.includes(`Bun.serve`)||t.includes(`serve(`))&&(/from\s+['"]bun['"]/.test(t)||t.includes(`Bun.serve`))&&(s=!0,i.push(`serve`)),!c&&(t.includes(`Bun.build`)||t.includes(`build(`))&&(/from\s+['"]bun['"]/.test(t)||t.includes(`Bun.build`))&&(c=!0,i.push(`build`)),s&&c)break}catch{}return i}async function at(e=process.cwd(),t){let i=process.env.npm_config_user_agent?.toString()||``;if(i.includes(`pnpm`))return`pnpm`;if(i.includes(`yarn`))return`yarn`;if(i.includes(`bun`))return`bun`;if(i.includes(`npm`))return`npm`;let a=t?.path?r.default.dirname(t.path):e;for(;a!==r.default.parse(a).root;){try{let e=r.default.join(a,`package.json`),t=await n.default.readFile(e,`utf-8`),i=JSON.parse(t);if(i.packageManager){if(i.packageManager.startsWith(`pnpm`))return`pnpm`;if(i.packageManager.startsWith(`yarn`))return`yarn`;if(i.packageManager.startsWith(`bun`))return`bun`}}catch{}let e=[];try{e=await n.default.readdir(a)}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`;a=r.default.dirname(a)}return`npm`}async function ot(e=process.cwd(),t){let i=t;if(!i){let{findTsConfig:t,loadTsConfig:n}=await Promise.resolve().then(()=>pt),r=await t(e);r&&(i=await n(r))}if(i?.compilerOptions?.rootDir){let t=i.compilerOptions.rootDir,n=r.default.relative(e,t);return n&&n!==`.`&&!n.startsWith(`..`)&&!r.default.isAbsolute(n)?`./${n}/env.ts`:`./env.ts`}try{return await n.default.access(r.default.join(e,`src`)),`./src/env.ts`}catch{return`./env.ts`}}var st=e.n({getEnvExampleKeys:()=>ft,parseEnvExample:()=>lt,resolveImportPaths:()=>ut,scanProjectEnvKeys:()=>dt,walk:()=>ct});async function ct(e,t=[]){try{let i=await n.default.readdir(e,{withFileTypes:!0});for(let n of i)if(n.isDirectory()){let i=n.name;if(i===`node_modules`||i===`dist`||i===`build`||i===`.git`||i===`.turbo`||i===`scratch`)continue;await ct(r.default.join(e,i),t)}else n.isFile()&&/\.(ts|tsx|js|jsx)$/.test(n.name)&&!n.name.endsWith(`.d.ts`)&&t.push(r.default.join(e,n.name))}catch{}return t}function lt(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 ut(e,t,n){if(e.startsWith(`.`))return[r.default.resolve(r.default.dirname(n),e)];if(r.default.isAbsolute(e))return[e];let i=t.compilerOptions||{},a=i.baseUrl||r.default.dirname(t.path),o=i.paths||{},s=[];for(let[e,t]of Object.entries(o)){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:i}of s)if(i&&e.startsWith(t)||!i&&e===t){let i=e.slice(t.length);return n.map(e=>{let t=`${e.replace(/\*$/,``)}${i}`;return r.default.resolve(a,t)})}return i.baseUrl?[r.default.resolve(a,e)]:[]}async function dt(e,t,i){let a=[],o=await ct(e),s=i?i.replace(/\.(ts|js|tsx|jsx)$/,``):null;for(let e of o)try{let i=await n.default.readFile(e,`utf-8`),o=i.matchAll(/process\.env\.([A-Z_][A-Z0-9_]*)/g);for(let e of o)e[1]&&a.push(e[1]);let c=i.matchAll(/import\.meta\.env\.([A-Z_][A-Z0-9_]*)/g);for(let e of c)e[1]&&a.push(e[1]);if(s){let n=i.matchAll(/import\s+[^;]*from\s+['"]([^'"]+)['"]/g);for(let o of n){let n=o[1],c=[];if(t?c=ut(n,t,e):n.startsWith(`.`)&&(c=[r.default.resolve(r.default.dirname(e),n)]),c.some(e=>e.replace(/\.(ts|js|tsx|jsx)$/,``)===s)){let e=i.matchAll(/\benv\.([A-Z_][A-Z0-9_]*)/g);for(let t of e)t[1]&&a.push(t[1])}}}}catch{}return Array.from(new Set(a))}async function ft(e=process.cwd(),t,i){let a=r.default.join(e,`.env.example`);try{let e=lt(await n.default.readFile(a,`utf-8`));if(e.length>0)return{keys:e,source:`.env.example`}}catch{}let o=await dt(e,t,i);return o.length>0?{keys:o,source:`project`}:null}var pt=e.n({checkTsConfig:()=>gt,findTsConfig:()=>J,loadTsConfig:()=>ht});const mt=(0,u.createRequire)(require(`url`).pathToFileURL(__filename).href).resolve;async function J(e=process.cwd()){let t=[`tsconfig.app.json`,`tsconfig.json`,`tsconfig.base.json`,`tsconfig.node.json`],i=e;for(;i!==r.default.parse(i).root;){for(let e of t){let t=r.default.join(i,e);try{return await n.default.access(t),t}catch{}}i=r.default.dirname(i)}return null}async function ht(e,t=new Set){let i=r.default.resolve(e);if(t.has(i))throw Error(`Circular extends dependency detected in tsconfig.json: ${i}`);t.add(i);let a=``;try{a=await n.default.readFile(e,`utf-8`)}catch{return{path:e,compilerOptions:{}}}let o=(0,d.parse)(a)||{},s=o.compilerOptions||{},c={};if(o.extends){let n=Array.isArray(o.extends)?o.extends:[o.extends];for(let i of n){let n;if(i.startsWith(`.`)||r.default.isAbsolute(i))n=r.default.resolve(r.default.dirname(e),i);else try{n=mt(i,{paths:[r.default.dirname(e)]})}catch{n=r.default.resolve(r.default.dirname(e),`node_modules`,i)}let a={...(await ht(n,t)).compilerOptions};a.baseUrl&&=r.default.resolve(r.default.dirname(n),a.baseUrl),a.rootDir&&=r.default.resolve(r.default.dirname(n),a.rootDir),c={...c,...a}}}let l={...s};return l.baseUrl&&=r.default.resolve(r.default.dirname(e),l.baseUrl),l.rootDir&&=r.default.resolve(r.default.dirname(e),l.rootDir),c={...c,...l},{...o,path:e,compilerOptions:c}}async function gt(e=process.cwd()){let t=await J(e);if(!t)return{status:`not_found`};let n=r.default.basename(t);try{let e=await ht(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 _t(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 vt(e){let t=e.trim().match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?/);return t?[t[1],t[2]??`0`,t[3]??`0`].join(`.`):null}function yt(e,t){let n=e.trim(),r=n.match(/^[\^~]?\s*(v?\d+(?:\.\d+){0,2})$/);if(r){let e=vt(r[1]);return e!==null&&_t(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=vt(i);return a&&(r===`>=`||r===`>`||r===`=`)?_t(a,t)>=0:!1})}async function bt(e=process.cwd()){let t=[],i=process.version,a=`22.0.0`;_t(i,a)===-1?t.push({status:`fail`,requirement:`Node.js Version`,message:`Node.js version must be >= ${a}.`,current:i,expected:`>= ${a}`}):t.push({status:`pass`,requirement:`Node.js Version`,message:`Node.js version is compatible.`});let o=null;try{let i=r.default.join(e,`package.json`),a=await n.default.readFile(i,`utf-8`);o=JSON.parse(a),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(o){let e={...o.dependencies,...o.devDependencies}.typescript,n=`5.1.0`;e?yt(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 s=await gt(e);if(s.status===`not_found`)t.push({status:`warn`,requirement:`tsconfig.json`,message:`tsconfig.json not found.`});else{let e=s.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 xt=class{async isEmptyDirectory(e=process.cwd()){try{return(await n.default.readdir(e)).length===0}catch{return!1}}async hasPackageJson(e=process.cwd()){try{return await n.default.access(r.default.join(e,`package.json`)),!0}catch{return!1}}async findTsConfig(e=process.cwd()){return J(e)}async loadTsConfig(e,t=new Set){return ht(e,t)}async getEnvExampleKeys(e=process.cwd(),t,n){return ft(e,t,n)}async suggestDefaultEnvPath(e=process.cwd(),t){return ot(e,t)}async checkTsConfig(e=process.cwd()){return gt(e)}async checkRequirements(e=process.cwd()){return bt(e)}async detectFramework(e=process.cwd(),t){return rt(e,t)}async detectBunFeatures(e=process.cwd(),t){return it(e,t)}async detectPackageManager(e=process.cwd(),t){return at(e,t)}async hasSkill(e=process.cwd()){try{let t=r.default.join(e,`skills-lock.json`),i=await n.default.readFile(t,`utf-8`),a=JSON.parse(i);if(a&&typeof a==`object`&&a.skills&&typeof a.skills==`object`&&`arkenv`in a.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 n.default.access(r.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`?(console.debug(`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 Y=e=>y.default.cyan(e),St=y.default.blue(`⛯`);function Ct(e){return e.replace(/import\s*\{([^\n}]*)\}\s*from/g,(e,t)=>`import { ${t.trim()} } from`)}function wt(e,t){return t.endsWith(`
|
|
88
88
|
`)&&!e.endsWith(`
|
|
89
|
-
`)?`${e}\n`:e}function
|
|
89
|
+
`)?`${e}\n`:e}function Tt(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=Ct(i),i=wt(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 Et(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`}),n.exports.default=f.builders.functionCall(`withArkEnv`,n.exports.default);let r=(0,f.generateCode)(n,{format:(0,f.detectCodeFormat)(t)}).code;return r=Ct(r),r=wt(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 Dt(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=Ct(i),i=wt(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 Ot(e=process.cwd()){for(let t of[`vite.config.ts`,`vite.config.js`,`vite.config.mts`,`vite.config.mjs`]){let i=r.default.resolve(e,t);try{return await n.default.access(i),i}catch{}}return null}async function kt(e=process.cwd()){for(let t of[`bunfig.toml`,`bun.setup.ts`,`bun.setup.js`]){let i=r.default.resolve(e,t);try{return await n.default.access(i),i}catch{}}return null}async function At(e=process.cwd()){for(let t of[`next.config.ts`,`next.config.js`,`next.config.mts`,`next.config.mjs`]){let i=r.default.resolve(e,t);try{return await n.default.access(i),i}catch{}}return null}async function jt(e,t){try{let n=Et({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 Mt(e=process.cwd()){for(let t of[`nuxt.config.ts`,`nuxt.config.js`,`nuxt.config.mts`,`nuxt.config.mjs`,`nuxt.config.cjs`]){let i=r.default.resolve(e,t);try{return await n.default.access(i),i}catch{}}return null}async function Nt(e,t){try{let n=Dt({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 Pt(e,t,n){try{let r=Tt({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 Ft(e,t){if(!t||t.length===0)return{success:!0,instructions:i.default`
|
|
90
90
|
${y.default.green(`✔`)} Use ${y.default.bold(`Vanilla`)} Bun runtime integration.
|
|
91
91
|
Access validated variables via your ${Y(`env`)} object for typesafety.
|
|
92
92
|
Primarily used for ${y.default.cyan(`server-side`)} or runtime-only validation.
|
|
@@ -110,35 +110,49 @@ ${t?(0,a.styleText)(`cyan`,U):``}
|
|
|
110
110
|
outdir: "./dist",
|
|
111
111
|
${y.default.green(`plugins: [arkenv]`)}
|
|
112
112
|
});
|
|
113
|
-
`),{success:!0,instructions:a.trim()}}async function Mt(e,t){let n=t||await pt();if(!n)return{status:`not_found`};let i=r.default.basename(n);try{let t=await e.readFile(n);if((0,d.parse)(t)?.compilerOptions?.strict===!0)return{status:`already_strict`,file:i};let r=(0,d.applyEdits)(t,(0,d.modify)(t,[`compilerOptions`,`strict`],!0,{formattingOptions:{insertSpaces:!0,tabSize:2}}));return await e.writeFile(n,r),{status:`updated`,file:i}}catch{return{status:`error`,file:i}}}var Nt=class{constructor(e,t){this.isQuiet=e,this.stdio=t}async exists(e){try{return await n.default.access(e),!0}catch{return!1}}async readFile(e){return n.default.readFile(e,`utf-8`)}async writeFile(e,t){await n.default.writeFile(e,t,`utf-8`)}async mkdir(e,t){await n.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${y.default.dim(`STDOUT:`)}\n${o}`),s&&(n+=`\n${y.default.red(`STDERR:`)}\n${s}`)),i(Error(n))}}),a.on(`error`,i)})}async updateTsConfigToStrict(e){return Mt(this,e)}async findViteConfig(e){return Et(e)}async findBunConfig(e){return Dt(e)}async findNextjsConfig(e){return Ot(e)}async bootstrapViteConfig(e,t){return At(this,e,t)}async bootstrapBunConfig(e,t){return jt(e,t)}async bootstrapNextjsConfig(e){return kt(this,e)}async safeAppend(e,t,n){let{safeAppend:r}=await Promise.resolve().then(()=>p);return r(e,t,n)}};async function Pt(e){let t=e.defaultPath||`./src/env.ts`;if(e.hasEnvSchemaFile){let e=await G({message:y.default.yellow(`An existing ArkEnv configuration was found at ${Y(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 Ft(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 ${Y(`.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 It(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 ${Y(t)} for typesafe environment variables?`,initialValue:!0,active:`Yes (Recommended)`,inactive:`No`});return I(n)?null:n}return!0}async function Lt(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 q({message:`Found existing ${Y(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 Rt(e){let t=await q({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 zt(e){let t=await q({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`}]});return I(t)?null:t}async function Bt(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 Vt(){let e=await q({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 Ht(){let e=await q({message:`How would you like to structure your environment variables?`,options:[{value:`simple`,label:`Simple (Recommended)`,hint:`A single env.ts file for the best DX`},{value:`strict`,label:`Strict`,hint:`Separate shared, client, and server files for hard bundle boundaries.`}]});return I(e)?null:e}async function Ut(e){let t=await G({message:`Enable automated Next.js code generation for environment variables?`,initialValue:e.initialValue??!0,active:`Yes (Recommended)`,inactive:`No`});return I(t)?null:t}async function Wt(e){let t=await G({message:`Use default config path (${Y(e.defaultEnvPath||`./src/env.ts`)})?`,initialValue:!0,active:`Yes (Recommended)`,inactive:`No, let me customize it`});return I(t)?null:t}async function Gt(e){let t=e.defaultEnvPath||`./src/env.ts`;if(!e.useDefaultPath){let e=await Qe({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 X={example:Rt,overwriteEnvSchemaFile:Pt,framework:zt,bunBuild:Bt,layout:Ht,nextjsCodegen:Ut,useDefaultPath:Wt,path:Gt,installTypeDefinitions:It,envDtsHandling:Lt,validator:Vt,useEnvExample:Ft};async function Kt(e,t=!1){return(e?.mode||`existing`)===`new`?qt(e,t):Jt(e,t)}async function qt(e,t=!1){let n=e?.examples||[],i=`arkenv-project`;try{let a;if(e?.name){let t=e.name.trim();a=t===`.`||t===`./`||r.default.resolve(process.cwd(),t)===process.cwd()?`.`:t}else if(t)a=i;else{let e=(Z(await Qe({message:`Project name:`,placeholder:i,defaultValue:i}))||i).trim();a=e===`.`||e===`./`||r.default.resolve(process.cwd(),e)===process.cwd()?`.`:e}let o=e?.example;!o&&!t?o=Z(await X.example({examples:n})):!o&&t&&(o=`basic`);let s=n.find(e=>e.id===o);if(!s){let e=n.map(e=>e.id).join(`, `);throw Error(`Unknown example ${o}. Available examples: ${e}`)}return{mode:`new`,example:s.id,name:a,path:`./src/env.ts`,validator:`arktype`,framework:s.framework,language:`ts`,installSkill:!1}}catch(e){if(e instanceof Xt)return null;throw e}}async function Jt(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`&&(a=e?.isStrict?`strict`:(e?.isSimple,`simple`));let o=await Yt(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=Z(await X.overwriteEnvSchemaFile({hasEnvSchemaFile:e?.hasEnvSchemaFile??!1,defaultPath:r})),o=Z(await X.framework({framework:e?.framework})),s;o===`nextjs`&&(s=e?.isStrict?`strict`:e?.isSimple?`simple`:Z(await X.layout()));let c;if(o===`bun-fullstack`){let t=!!e?.bunFeatures?.includes(`build`);c=Z(await X.bunBuild({initialValue:t}))}let l=e?.disableCodegen;o===`nextjs`&&l===void 0&&(l=!Z(await X.nextjsCodegen({initialValue:!0})));let u;if(o===`nextjs`&&!l){let e=await G({message:`Would you like to wrap your Next.js config with ${Y(`withArkEnv`)}?`,initialValue:!0,active:`Yes (Recommended)`,inactive:`No`});if(I(e))throw Ue(`Operation cancelled`),new Xt;u=e}let d=Z(await X.useDefaultPath({defaultEnvPath:r})),f=Z(await X.path({useDefaultPath:d,defaultEnvPath:r})),p=await Yt(e,o,f),m=Z(await X.installTypeDefinitions({framework:o,hasTypeFile:p})),h=Z(await X.envDtsHandling({framework:o,installTypeDefinitions:m,hasTypeFile:p})),g=Z(await X.validator()),_=Z(await X.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 Xt)return null;throw e}}async function Yt(e,t,n){return await e?.hasTypeFileAtPath?.({framework:t,envPath:n})??e?.hasTypeFile??!1}var Xt=class extends Error{constructor(){super(`Operation cancelled`)}};function Z(e){if(e===null||I(e))throw Ue(`Operation cancelled`),new Xt;return e}var Zt=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 Kt(e,t)}};const Qt={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`},noCodegen:{long:`--no-codegen`,short:`-C`,kind:`boolean`}},$t=new Set(Object.values(Qt).flatMap(e=>[e.long,e.short].filter(Boolean))),en=new Set(Object.values(Qt).filter(e=>e.kind===`value`).flatMap(e=>[e.long,e.short].filter(Boolean)));var tn=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(en.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}`);en.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(!$t.has(e)){this.validationError=`Unknown argument: ${e}`;break}if(en.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 et({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=Qt.example;return this.getFlagValue(e.long,e.short)}get isStrict(){return this.hasFlag(`isStrict`)}get isSimple(){return this.hasFlag(`isSimple`)}get noCodegen(){return this.hasFlag(`noCodegen`)}hasFlag(e){let t=Qt[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};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]}},nn=`0.2.10`;function rn(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 an=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${nn}`),this.logger.log(`\n${y.default.bold(`Usage:`)}`);for(let t of rn(e))this.logger.log(t);this.logger.log(`\n${y.default.bold(`Options:`)}`);for(let e of rn(t))this.logger.log(e)}};function on(e,t,n,r){let{extraImports:i,serverField:a,clientField:o,sharedField:s,defaultServerFields:c,defaultClientFields:l,defaultSharedFields:u}=t,d=[],f=[],p=[];if(e&&e.length>0)for(let t of e)t.startsWith(`NEXT_PUBLIC_`)?f.push(o(t)):t===`NODE_ENV`?p.push(s(t)):d.push(a(t));else d.push(...c),f.push(...l),p.push(...u);let m=[];if(d.length>0&&m.push(`\tserver: {\n${d.join(`
|
|
114
|
-
`)}\n\t}`)
|
|
115
|
-
`)}\n
|
|
116
|
-
`)}\n\t}`),r){let t=[];if(e&&e.length>0)for(let n of e)(n.startsWith(`NEXT_PUBLIC_`)||n===`NODE_ENV`)&&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,`);return m.push(`\truntimeEnv: {\n${t.join(`
|
|
117
|
-
`)}\n\t}`),`${[`import arkenv from "@arkenv/nextjs";`,...i?[i]:[]].join(`
|
|
113
|
+
`),{success:!0,instructions:a.trim()}}async function It(e,t){let n=t||await J();if(!n)return{status:`not_found`};let i=r.default.basename(n);try{let t=await e.readFile(n);if((0,d.parse)(t)?.compilerOptions?.strict===!0)return{status:`already_strict`,file:i};let r=(0,d.applyEdits)(t,(0,d.modify)(t,[`compilerOptions`,`strict`],!0,{formattingOptions:{insertSpaces:!0,tabSize:2}}));return await e.writeFile(n,r),{status:`updated`,file:i}}catch{return{status:`error`,file:i}}}var Lt=class{constructor(e,t){this.isQuiet=e,this.stdio=t}async exists(e){try{return await n.default.access(e),!0}catch{return!1}}async readFile(e){return n.default.readFile(e,`utf-8`)}async writeFile(e,t){await n.default.writeFile(e,t,`utf-8`)}async mkdir(e,t){await n.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${y.default.dim(`STDOUT:`)}\n${o}`),s&&(n+=`\n${y.default.red(`STDERR:`)}\n${s}`)),i(Error(n))}}),a.on(`error`,i)})}async updateTsConfigToStrict(e){return It(this,e)}async findViteConfig(e){return Ot(e)}async findBunConfig(e){return kt(e)}async findNextjsConfig(e){return At(e)}async findNuxtConfig(e){return Mt(e)}async bootstrapViteConfig(e,t){return Pt(this,e,t)}async bootstrapBunConfig(e,t){return Ft(e,t)}async bootstrapNextjsConfig(e){return jt(this,e)}async bootstrapNuxtConfig(e){return Nt(this,e)}async safeAppend(e,t,n){let{safeAppend:r}=await Promise.resolve().then(()=>p);return r(e,t,n)}};async function Rt(e){let t=e.defaultPath||`./src/env.ts`;if(e.hasEnvSchemaFile){let e=await U({message:y.default.yellow(`An existing ArkEnv configuration was found at ${Y(t)}. Do you want to overwrite it?`),initialValue:!1,active:`Yes (override my configuration)`,inactive:`No (abort)`});return P(e)||!e?null:e}return!0}async function zt(e){let t=e.detectedKeys,n=e.keysSource||`.env.example`;if(t&&t.length>0){let e=t.length,r=e===1,i=await U({message:n===`.env.example`?`Detected ${Y(`.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 P(i)?null:i}return!1}async function Bt(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 U({message:`Establish ${Y(t)} for typesafe environment variables?`,initialValue:!0,active:`Yes (Recommended)`,inactive:`No`});return P(n)?null:n}return!0}async function Vt(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 K({message:`Found existing ${Y(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 P(e)?null:e}return`overwrite`}async function Ht(e){let t=await K({message:`Select an example:`,options:e.examples.map(e=>({value:e.id,label:e.name,...e.description?{hint:e.description}:{}}))});return P(t)?null:t}async function Ut(e){let t=await K({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 P(t)?null:t}async function Wt(e){let t=await U({message:`Optional: Would you also like to bootstrap a custom Bun.build script for programmatic bundling?`,initialValue:e.initialValue??!1});return P(t)?null:t}async function Gt(){let e=await K({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 P(e)?null:e}async function Kt(e){let t=await K({message:`How would you like to structure your environment variables?`,options:e?.framework===`nextjs`?[{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.`}]:[{value:`simple`,label:`Simple (Recommended)`,hint:`A single env.ts file for the best DX`},{value:`strict`,label:`Strict`,hint:`Separate shared, client, and server files for hard bundle boundaries.`}]});return P(t)?null:t}async function qt(e){let t=await U({message:`Enable automated ${e.framework===`nuxt`?`Nuxt`:`Next.js`} code generation for environment variables?`,initialValue:e.initialValue??!0,active:`Yes (Recommended)`,inactive:`No`});return P(t)?null:t}async function Jt(e){let t=await U({message:`Use default config path (${Y(e.defaultEnvPath||`./src/env.ts`)})?`,initialValue:!0,active:`Yes (Recommended)`,inactive:`No, let me customize it`});return P(t)?null:t}async function Yt(e){let t=e.defaultEnvPath||`./src/env.ts`;if(!e.useDefaultPath){let e=await $e({message:`Where should we create the ArkEnv config?`,placeholder:t,initialValue:t,defaultValue:t});if(P(e))return null;let n=typeof e==`string`?e.trim():``;return n===``?t:n}return t}const X={example:Ht,overwriteEnvSchemaFile:Rt,framework:Ut,bunBuild:Wt,layout:Kt,nextjsCodegen:qt,useDefaultPath:Jt,path:Yt,installTypeDefinitions:Bt,envDtsHandling:Vt,validator:Gt,useEnvExample:zt};async function Xt(e,t=!1){return(e?.mode||`existing`)===`new`?Zt(e,t):Qt(e,t)}async function Zt(e,t=!1){let n=e?.examples||[],i=`arkenv-project`;try{let a;if(e?.name){let t=e.name.trim();a=t===`.`||t===`./`||r.default.resolve(process.cwd(),t)===process.cwd()?`.`:t}else if(t)a=i;else{let e=(Z(await $e({message:`Project name:`,placeholder:i,defaultValue:i}))||i).trim();a=e===`.`||e===`./`||r.default.resolve(process.cwd(),e)===process.cwd()?`.`:e}let o=e?.example;!o&&!t?o=Z(await X.example({examples:n})):!o&&t&&(o=`basic`);let s=n.find(e=>e.id===o);if(!s){let e=n.map(e=>e.id).join(`, `);throw Error(`Unknown example ${o}. Available examples: ${e}`)}return{mode:`new`,example:s.id,name:a,path:`./src/env.ts`,validator:`arktype`,framework:s.framework,language:`ts`,installSkill:!1}}catch(e){if(e instanceof en)return null;throw e}}async function Qt(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||n===`nextjs`?`flat`:`simple`);let o=await $t(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=Z(await X.overwriteEnvSchemaFile({hasEnvSchemaFile:e?.hasEnvSchemaFile??!1,defaultPath:r})),o=Z(await X.framework({framework:e?.framework})),s;(o===`nextjs`||o===`nuxt`)&&(s=e?.isStrict?`strict`:e?.isSimple?`simple`:e?.isFlat?`flat`:Z(await X.layout({framework:o})));let c;if(o===`bun-fullstack`){let t=!!e?.bunFeatures?.includes(`build`);c=Z(await X.bunBuild({initialValue:t}))}let l=e?.disableCodegen;o===`nuxt`?l=!0:o===`nextjs`&&l===void 0&&(l=!Z(await X.nextjsCodegen({initialValue:!0,framework:o})));let u;if(o===`nextjs`&&!l){let e=await U({message:`Would you like to wrap your Next.js config with ${Y(`withArkEnv`)}?`,initialValue:!0,active:`Yes (Recommended)`,inactive:`No`});if(P(e))throw Ge(`Operation cancelled`),new en;u=e}let d=Z(await X.useDefaultPath({defaultEnvPath:r})),f=Z(await X.path({useDefaultPath:d,defaultEnvPath:r})),p=await $t(e,o,f),m=Z(await X.installTypeDefinitions({framework:o,hasTypeFile:p})),h=Z(await X.envDtsHandling({framework:o,installTypeDefinitions:m,hasTypeFile:p})),g=Z(await X.validator()),_=Z(await X.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 en)return null;throw e}}async function $t(e,t,n){return await e?.hasTypeFileAtPath?.({framework:t,envPath:n})??e?.hasTypeFile??!1}var en=class extends Error{constructor(){super(`Operation cancelled`)}};function Z(e){if(e===null||P(e))throw Ge(`Operation cancelled`),new en;return e}var tn=class{async confirm(e,n=!0,r,i){let a=await U((0,t.shake)({message:e,initialValue:n,active:r,inactive:i}));return P(a)?null:a}async runWizard(e,t=!1){return Xt(e,t)}};const nn={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`}},rn=new Set(Object.values(nn).flatMap(e=>[e.long,e.short].filter(Boolean))),an=new Set(Object.values(nn).filter(e=>e.kind===`value`).flatMap(e=>[e.long,e.short].filter(Boolean)));var on=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(an.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}`);an.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(!rn.has(e)){this.validationError=`Unknown argument: ${e}`;break}if(an.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 tt({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=nn.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=nn[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]}},sn=`0.3.0`;function cn(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 ln=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${sn}`),this.logger.log(`\n${y.default.bold(`Usage:`)}`);for(let t of cn(e))this.logger.log(t);this.logger.log(`\n${y.default.bold(`Options:`)}`);for(let e of cn(t))this.logger.log(e)}};function un(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`&&a!==`simple`){let t=[...g,..._,...v].map(e=>e.replace(/^\t\t/,` `)),i=[];for(let e of v){let t=e.trim().match(/^([a-zA-Z0-9_]+)\s*:/);if(t){let e=t[1];e!==`NODE_ENV`&&i.push(e)}}let a=[];if(i.length>0&&a.push(`\texposeToClient: [${i.map(e=>`"${e}"`).join(`, `)}]`),r){let t=[];if(e&&e.length>0)for(let n of e)(n.startsWith(p)||n===`NODE_ENV`||i.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 i)t.push(`\t\t${e}: process.env.${e},`)}a.push(`\truntimeEnv: {\n${t.join(`
|
|
114
|
+
`)}\n\t}`)}let s=a.length>0?`, {\n${a.join(`,
|
|
115
|
+
`)}\n}`:``;return`${[`import arkenv from "${r?`@arkenv/nextjs`:n||`./generated/env.gen`}";`,...o?[o]:[]].join(`
|
|
118
116
|
`)}
|
|
119
117
|
|
|
120
118
|
/**
|
|
121
119
|
* Environment variable schema.
|
|
122
|
-
* In
|
|
120
|
+
* In ${h}, use the generated \`arkenv\` from \`env.gen.ts\` to validate variables.
|
|
123
121
|
* Enforces client/server separation and prevents secret leaks.
|
|
124
122
|
*/
|
|
125
123
|
export const env = arkenv({
|
|
126
|
-
${
|
|
124
|
+
${t.join(`
|
|
125
|
+
`)}
|
|
126
|
+
}${s});
|
|
127
|
+
`}let y=[];if(g.length>0&&y.push(`\tserver: {\n${g.join(`
|
|
128
|
+
`)}\n\t}`),_.length>0&&y.push(`\tclient: {\n${_.join(`
|
|
129
|
+
`)}\n\t}`),v.length>0&&y.push(`\tshared: {\n${v.join(`
|
|
130
|
+
`)}\n\t}`),r||i===`nuxt`){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(`
|
|
131
|
+
`)}\n\t}`),`${[`import arkenv from "${m}";`,...o?[o]:[]].join(`
|
|
132
|
+
`)}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Environment variable schema.
|
|
136
|
+
* In ${h}, use \`${m}\` to validate variables at build-time and runtime.
|
|
137
|
+
* Enforces client/server separation and prevents secret leaks.
|
|
138
|
+
*/
|
|
139
|
+
export const env = arkenv({
|
|
140
|
+
${y.join(`,
|
|
127
141
|
`)},
|
|
128
142
|
});
|
|
129
|
-
`}return`${[`import arkenv from "${n||`./generated/env.gen`}";`,...
|
|
143
|
+
`}return`${[`import arkenv from "${n||`./generated/env.gen`}";`,...o?[o]:[]].join(`
|
|
130
144
|
`)}
|
|
131
145
|
|
|
132
146
|
/**
|
|
133
147
|
* Environment variable schema.
|
|
134
|
-
* In
|
|
148
|
+
* In ${h}, use the generated \`arkenv\` from \`env.gen.ts\` to validate variables.
|
|
135
149
|
* Enforces client/server separation and prevents secret leaks.
|
|
136
150
|
*/
|
|
137
151
|
export const env = arkenv({
|
|
138
|
-
${
|
|
152
|
+
${y.join(`,
|
|
139
153
|
`)},
|
|
140
154
|
});
|
|
141
|
-
`}const
|
|
155
|
+
`}const dn=(e,t,n,r,a)=>{let o=e?.length?e.map(e=>`\t\t${e}: "string?",`).join(`
|
|
142
156
|
`):` NODE_ENV: "'development' | 'production' | 'test' = 'development'",
|
|
143
157
|
PORT: "number.port = 3000",`;return t===`vite`?i.default`
|
|
144
158
|
import { type } from "arkenv";
|
|
@@ -149,7 +163,7 @@ ${m.join(`,
|
|
|
149
163
|
* and provide typesafety for \`import.meta.env\` on the client-side.
|
|
150
164
|
*/
|
|
151
165
|
export const Env = type({
|
|
152
|
-
${
|
|
166
|
+
${o}
|
|
153
167
|
});
|
|
154
168
|
`:t===`bun-fullstack`?i.default`
|
|
155
169
|
import { type } from "arkenv";
|
|
@@ -160,20 +174,20 @@ ${m.join(`,
|
|
|
160
174
|
* and provide typesafety for \`process.env\` on the client-side.
|
|
161
175
|
*/
|
|
162
176
|
export const Env = type({
|
|
163
|
-
${
|
|
177
|
+
${o}
|
|
164
178
|
});
|
|
165
|
-
`:t===`nextjs`?
|
|
179
|
+
`:t===`nextjs`||t===`nuxt`?un(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,a):i.default`
|
|
166
180
|
import arkenv, { type } from "arkenv";
|
|
167
181
|
|
|
168
182
|
/**
|
|
169
183
|
* Environment variable schema for server-side or runtime-only validation.
|
|
170
184
|
*/
|
|
171
185
|
export const Env = type({
|
|
172
|
-
${
|
|
186
|
+
${o}
|
|
173
187
|
});
|
|
174
188
|
|
|
175
189
|
export const env = arkenv(Env);
|
|
176
|
-
`},
|
|
190
|
+
`},fn=e=>i.default`
|
|
177
191
|
/// <reference types="vite/client" />
|
|
178
192
|
|
|
179
193
|
type ImportMetaEnvAugmented =
|
|
@@ -186,7 +200,7 @@ ${a}
|
|
|
186
200
|
interface ImportMeta {
|
|
187
201
|
readonly env: ImportMetaEnv;
|
|
188
202
|
}
|
|
189
|
-
`,
|
|
203
|
+
`,pn=e=>i.default`
|
|
190
204
|
/// <reference types="bun-types" />
|
|
191
205
|
|
|
192
206
|
type ProcessEnvAugmented = import("@arkenv/bun-plugin").ProcessEnvAugmented<
|
|
@@ -196,7 +210,7 @@ ${a}
|
|
|
196
210
|
declare namespace NodeJS {
|
|
197
211
|
interface ProcessEnv extends ProcessEnvAugmented {}
|
|
198
212
|
}
|
|
199
|
-
`,
|
|
213
|
+
`,mn=(e,t,n,r,a)=>{let o=e?.length?e.map(e=>`\t\t${e}: v.optional(v.string()),`).join(`
|
|
200
214
|
`):` NODE_ENV: v.optional(v.picklist(["development", "production", "test"]), "development"),
|
|
201
215
|
PORT: v.optional(v.pipe(v.string(), v.transform(Number), v.number(), v.integer(), v.minValue(1), v.maxValue(65535)), 3000),`;return t===`vite`?i.default`
|
|
202
216
|
import { type } from "arkenv";
|
|
@@ -208,7 +222,7 @@ ${a}
|
|
|
208
222
|
* and provide typesafety for \`import.meta.env\` on the client-side.
|
|
209
223
|
*/
|
|
210
224
|
export const Env = type({
|
|
211
|
-
${
|
|
225
|
+
${o}
|
|
212
226
|
});
|
|
213
227
|
`:t===`bun-fullstack`?i.default`
|
|
214
228
|
import { type } from "arkenv";
|
|
@@ -220,9 +234,9 @@ ${a}
|
|
|
220
234
|
* and provide typesafety for \`process.env\` on the client-side.
|
|
221
235
|
*/
|
|
222
236
|
export const Env = type({
|
|
223
|
-
${
|
|
237
|
+
${o}
|
|
224
238
|
});
|
|
225
|
-
`:t===`nextjs`?
|
|
239
|
+
`:t===`nextjs`||t===`nuxt`?un(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,a):i.default`
|
|
226
240
|
import arkenv from "arkenv/standard";
|
|
227
241
|
import * as v from "valibot";
|
|
228
242
|
|
|
@@ -230,9 +244,9 @@ ${a}
|
|
|
230
244
|
* Environment variable schema for server-side or runtime-only validation.
|
|
231
245
|
*/
|
|
232
246
|
export const env = arkenv({
|
|
233
|
-
${
|
|
247
|
+
${o}
|
|
234
248
|
});
|
|
235
|
-
`},
|
|
249
|
+
`},hn=(e,t,n,r,a)=>{let o=e?.length?e.map(e=>`\t\t${e}: z.string().optional(),`).join(`
|
|
236
250
|
`):` NODE_ENV: z.enum(["development", "production", "test"]).default("development"),
|
|
237
251
|
PORT: z.coerce.number().int().min(1).max(65535).default(3000),`;return t===`vite`?i.default`
|
|
238
252
|
import { type } from "arkenv";
|
|
@@ -244,7 +258,7 @@ ${a}
|
|
|
244
258
|
* and provide typesafety for \`import.meta.env\` on the client-side.
|
|
245
259
|
*/
|
|
246
260
|
export const Env = type({
|
|
247
|
-
${
|
|
261
|
+
${o}
|
|
248
262
|
});
|
|
249
263
|
`:t===`bun-fullstack`?i.default`
|
|
250
264
|
import { type } from "arkenv";
|
|
@@ -256,9 +270,9 @@ ${a}
|
|
|
256
270
|
* and provide typesafety for \`process.env\` on the client-side.
|
|
257
271
|
*/
|
|
258
272
|
export const Env = type({
|
|
259
|
-
${
|
|
273
|
+
${o}
|
|
260
274
|
});
|
|
261
|
-
`:t===`nextjs`?
|
|
275
|
+
`:t===`nextjs`||t===`nuxt`?un(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,a):i.default`
|
|
262
276
|
import arkenv from "arkenv/standard";
|
|
263
277
|
import { z } from "zod";
|
|
264
278
|
|
|
@@ -266,25 +280,22 @@ ${a}
|
|
|
266
280
|
* Environment variable schema for server-side or runtime-only validation.
|
|
267
281
|
*/
|
|
268
282
|
export const env = arkenv({
|
|
269
|
-
${
|
|
283
|
+
${o}
|
|
270
284
|
});
|
|
271
|
-
`};function
|
|
285
|
+
`};function gn(e,t){let{validator:n,envKeys:r,framework:i,disableCodegen:a,layout:o}=e;switch(n){case`arktype`:return`${dn(r,i,t,a,o)}\n`;case`zod`:return`${hn(r,i,t,a,o)}\n`;case`valibot`:return`${mn(r,i,t,a,o)}\n`;default:throw Error(`Unsupported validator: ${n}`)}}function Q(e,t=` `){return e.length===0?`{}`:`{\n${t}${e.map(e=>e.trim()).join(`\n${t}`)}\n${t.slice(1)}}`}function _n(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(`
|
|
286
|
+
`)}\n\t\t}`,f=``,p=``,m=``;return n===`arktype`?(f=`import { type } from "${u}/shared";
|
|
272
287
|
|
|
273
288
|
/**
|
|
274
289
|
* @internal 🛑 INTERNAL SCHEMA ONLY.
|
|
275
290
|
* Do not import this directly. Import \`env\` from \`./client\` or \`./server\` instead.
|
|
276
291
|
*/
|
|
277
|
-
export const SharedSchema = type(${Q(s,` `)});`,
|
|
292
|
+
export const SharedSchema = type(${Q(s,` `)});`,p=i?`import arkenv from "${u}/client";
|
|
278
293
|
import { SharedSchema } from "./internal/shared";
|
|
279
294
|
|
|
280
295
|
export const env = arkenv(
|
|
281
296
|
${Q(o,` `)},
|
|
282
297
|
{
|
|
283
|
-
extends: [SharedSchema]
|
|
284
|
-
runtimeEnv: {
|
|
285
|
-
${c.map(e=>e.trim()).join(`
|
|
286
|
-
`)}
|
|
287
|
-
},
|
|
298
|
+
extends: [SharedSchema]${d}
|
|
288
299
|
},
|
|
289
300
|
);`:`import arkenv from "${t||`./generated/env.gen`}";
|
|
290
301
|
import { SharedSchema } from "./internal/shared";
|
|
@@ -294,7 +305,7 @@ export const env = arkenv(
|
|
|
294
305
|
{
|
|
295
306
|
extends: [SharedSchema],
|
|
296
307
|
},
|
|
297
|
-
);`,
|
|
308
|
+
);`,m=`import arkenv from "${u}/server";
|
|
298
309
|
import { env as clientEnv } from "./client";
|
|
299
310
|
|
|
300
311
|
export const env = arkenv(
|
|
@@ -302,24 +313,20 @@ export const env = arkenv(
|
|
|
302
313
|
{
|
|
303
314
|
extends: [clientEnv],
|
|
304
315
|
},
|
|
305
|
-
);`):n===`zod`?(
|
|
316
|
+
);`):n===`zod`?(f=`import { z } from "zod";
|
|
306
317
|
|
|
307
318
|
/**
|
|
308
319
|
* @internal 🛑 INTERNAL SCHEMA ONLY.
|
|
309
320
|
* Do not import this directly. Import \`env\` from \`./client\` or \`./server\` instead.
|
|
310
321
|
*/
|
|
311
|
-
export const SharedSchema = z.object(${Q(s,` `)});`,
|
|
322
|
+
export const SharedSchema = z.object(${Q(s,` `)});`,p=i?`import arkenv from "${u}/client";
|
|
312
323
|
import { z } from "zod";
|
|
313
324
|
import { SharedSchema } from "./internal/shared";
|
|
314
325
|
|
|
315
326
|
export const env = arkenv(
|
|
316
327
|
${Q(o,` `)},
|
|
317
328
|
{
|
|
318
|
-
extends: [SharedSchema]
|
|
319
|
-
runtimeEnv: {
|
|
320
|
-
${c.map(e=>e.trim()).join(`
|
|
321
|
-
`)}
|
|
322
|
-
},
|
|
329
|
+
extends: [SharedSchema]${d}
|
|
323
330
|
},
|
|
324
331
|
);`:`import arkenv from "${t||`./generated/env.gen`}";
|
|
325
332
|
import { z } from "zod";
|
|
@@ -330,7 +337,7 @@ export const env = arkenv(
|
|
|
330
337
|
{
|
|
331
338
|
extends: [SharedSchema],
|
|
332
339
|
},
|
|
333
|
-
);`,
|
|
340
|
+
);`,m=`import arkenv from "${u}/server";
|
|
334
341
|
import { z } from "zod";
|
|
335
342
|
import { env as clientEnv } from "./client";
|
|
336
343
|
|
|
@@ -339,24 +346,20 @@ export const env = arkenv(
|
|
|
339
346
|
{
|
|
340
347
|
extends: [clientEnv],
|
|
341
348
|
},
|
|
342
|
-
);`):n===`valibot`&&(
|
|
349
|
+
);`):n===`valibot`&&(f=`import * as v from "valibot";
|
|
343
350
|
|
|
344
351
|
/**
|
|
345
352
|
* @internal 🛑 INTERNAL SCHEMA ONLY.
|
|
346
353
|
* Do not import this directly. Import \`env\` from \`./client\` or \`./server\` instead.
|
|
347
354
|
*/
|
|
348
|
-
export const SharedSchema = v.object(${Q(s,` `)});`,
|
|
355
|
+
export const SharedSchema = v.object(${Q(s,` `)});`,p=i?`import arkenv from "${u}/client";
|
|
349
356
|
import * as v from "valibot";
|
|
350
357
|
import { SharedSchema } from "./internal/shared";
|
|
351
358
|
|
|
352
359
|
export const env = arkenv(
|
|
353
360
|
${Q(o,` `)},
|
|
354
361
|
{
|
|
355
|
-
extends: [SharedSchema]
|
|
356
|
-
runtimeEnv: {
|
|
357
|
-
${c.map(e=>e.trim()).join(`
|
|
358
|
-
`)}
|
|
359
|
-
},
|
|
362
|
+
extends: [SharedSchema]${d}
|
|
360
363
|
},
|
|
361
364
|
);`:`import arkenv from "${t||`./generated/env.gen`}";
|
|
362
365
|
import * as v from "valibot";
|
|
@@ -367,7 +370,7 @@ export const env = arkenv(
|
|
|
367
370
|
{
|
|
368
371
|
extends: [SharedSchema],
|
|
369
372
|
},
|
|
370
|
-
);`,
|
|
373
|
+
);`,m=`import arkenv from "${u}/server";
|
|
371
374
|
import * as v from "valibot";
|
|
372
375
|
import { env as clientEnv } from "./client";
|
|
373
376
|
|
|
@@ -376,9 +379,11 @@ export const env = arkenv(
|
|
|
376
379
|
{
|
|
377
380
|
extends: [clientEnv],
|
|
378
381
|
},
|
|
379
|
-
);`),{shared:`${
|
|
382
|
+
);`),{shared:`${f}\n`,client:`${p}\n`,server:`${m}\n`}}async function vn(e,t){let i=t.targetDir??process.cwd(),a=r.default.join(process.cwd(),`.arkenv-temp`);await e.mkdir(a,!0),t.targetDir&&await e.mkdir(i,!0);try{await e.execute(`git`,[`clone`,`--filter=blob:none`,`--sparse`,t.repository,a]);let o=`examples/${t.example}`;await e.execute(`git`,[`-C`,a,`sparse-checkout`,`set`,o]);let s=r.default.join(a,o),c=await n.default.readdir(s),l=[];for(let t of c){let n=r.default.join(i,t);await e.exists(n)&&l.push(t)}if(l.length>0)throw Error(`Scaffolding into a non-empty directory failed. The following paths already exist: ${l.join(`, `)}`);await yn(s,i);for(let e of[`package-lock.json`,`pnpm-lock.yaml`,`yarn.lock`,`bun.lockb`,`bun.lock`])await n.default.rm(r.default.join(i,e),{force:!0});let u=r.default.join(i,`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 n.default.rm(a,{recursive:!0,force:!0})}}async function yn(e,t){let i=await n.default.readdir(e);await Promise.all(i.map(i=>n.default.cp(r.default.join(e,i),r.default.join(t,i),{recursive:!0,force:!1})))}function bn(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 xn(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,a=t&&!n,o=i.default`
|
|
380
383
|
Inside your AI assistant (e.g. Claude Code), use:
|
|
381
384
|
${Y(`/arkenv`)} - automatically refine your schema and configure integrations.
|
|
382
|
-
`;return
|
|
385
|
+
`;return a?(o+=`
|
|
386
|
+
|
|
387
|
+
`,o+=`Also, wrap your Next.js config with ${Y(`withArkEnv`)}:\n`,o+=` ${Y(`import { withArkEnv } from "@arkenv/nextjs/config";`)}\n`,e.metadata.layout===`strict`?(o+=` ${Y(`export default withArkEnv(nextConfig);`)}\n`,o+=`Import and use: ${Y(`import { env } from "${e.metadata.importPath}/client"`)} (client) or ${Y(`import { env } from "${e.metadata.importPath}/server"`)} (server)\n`):(o+=` ${Y(`export default withArkEnv(nextConfig);`)}\n`,o+=`Import and use: ${Y(`import { env } from "${e.metadata.importPath}"`)}\n`)):r&&(o+=`
|
|
383
388
|
|
|
384
|
-
`,r+=`Also, wrap your Next.js config with ${Y(`withArkEnv`)}:\n`,r+=` ${Y(`import { withArkEnv } from "@arkenv/nextjs/config";`)}\n`,e.metadata.layout===`strict`?(r+=` ${Y(`export default withArkEnv(nextConfig);`)}\n`,r+=`Import and use: ${Y(`import { env } from "${e.metadata.importPath}/client"`)} (client) or ${Y(`import { env } from "${e.metadata.importPath}/server"`)} (server)\n`):(r+=` ${Y(`export default withArkEnv(nextConfig);`)}\n`,r+=`Import and use: ${Y(`import { env } from "${e.metadata.importPath}"`)}\n`)),{message:r,title:`Next steps`}}let r=e.skill?.dlxCommand.join(` `)||`npx`,a=e.skill?.packageName||`yamcodes/arkenv`,o=``,s=1,c=e.metadata.displayPath;if(e.metadata.layout===`strict`){let e=c.lastIndexOf(`.`),t=e===-1?c:c.slice(0,e);c=`${t}/client.ts, ${t}/server.ts, and ${t}/internal/shared.ts`}o+=`${s++}. Check ${Y(c)} and refine your environment schema.\n`;let l=e.metadata.framework===`nextjs`&&!e.metadata.disableCodegen&&!n;return e.metadata.framework===`vite`?o+=`${s++}. Access via ${Y(`import.meta.env.YOUR_VAR`)}\n`:e.metadata.framework===`bun-fullstack`?o+=`${s++}. Access via ${Y(`process.env.YOUR_VAR`)}\n`:e.metadata.framework===`nextjs`?e.metadata.layout===`strict`?(e.metadata.disableCodegen||l&&(o+=`${s++}. Wrap your Next.js config with ${Y(`withArkEnv`)} inside ${Y(`next.config.ts`)}:\n`,o+=` ${Y(`import { withArkEnv } from "@arkenv/nextjs/config";`)}\n`,o+=` ${Y(`export default withArkEnv(nextConfig);`)}\n`),o+=`${s++}. Import and use: ${Y(`import { env } from "${e.metadata.importPath}/client"`)} (client) or ${Y(`import { env } from "${e.metadata.importPath}/server"`)} (server)\n`):(e.metadata.disableCodegen||l&&(o+=`${s++}. Wrap your Next.js config with ${Y(`withArkEnv`)} inside ${Y(`next.config.ts`)}:\n`,o+=` ${Y(`import { withArkEnv } from "@arkenv/nextjs/config";`)}\n`,o+=` ${Y(`export default withArkEnv(nextConfig);`)}\n`),o+=`${s++}. Import and use: ${Y(`import { env } from "${e.metadata.importPath}"`)}\n`):o+=`${s++}. Import and use: ${Y(`import { env } from "${e.metadata.importPath}"`)}\n`,o+=`${s++}. (Recommended) Install the AI skill: ${Y(`${r} skills add ${a}`)}\n`,o+=` Then run ${Y(`/arkenv`)} inside your AI assistant to finish.`,{message:o,title:`Next steps`}}var vn=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 ${Y(e.clone.example)}...`),await mn(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 ${Y(r.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 ${Y(r.default.basename(t.path))}.`):this.reporter.info(`${Y(r.default.basename(t.path))} already contains ArkEnv types.`);continue}if(await this.workspace.mkdir(r.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} ${Y(r.default.basename(t.path))} for typesafe environment variables.`)}}if(t.stop(`Configuration scaffolded!`),e.install&&process.env.SKIP_INSTALL!==`true`){this.reporter.step(`Installing dependencies with ${Y(e.install.packageManager)}...`);let[t,n]=gn(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 ${Y(t.file)}`),n=!0):t.status===`error`&&this.reporter.warn(`Could not automatically update ${Y(t.file||`tsconfig.json`)}. Please ensure 'strict: true' is set manually.`)}let i=!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 ${Y(r.default.basename(t))}`):(this.reporter.warn(`Could not automatically update ${Y(r.default.basename(t))}: ${n.error}`),this.reporter.info(`Please add ${Y(`@arkenv/vite-plugin`)} manually.`))}else this.reporter.info(`No Vite config found — please add ${Y(`@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`){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 ${Y(`env.gen.ts`)} for Next.js`)}catch{this.reporter.warn(`Failed to automatically generate ${Y(`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 e=await this.workspace.bootstrapNextjsConfig(t);e.success?e.updated?(this.reporter.info(`Updated ${Y(r.default.basename(t))}`),i=!0):(this.reporter.info(`${Y(r.default.basename(t))} already uses withArkEnv`),i=!0):this.reporter.warn(`Could not automatically update ${Y(r.default.basename(t))}: ${e.error}`)}else this.reporter.info(`No Next.js config found. Please wrap your config with ${Y(`withArkEnv`)} manually.`)}}}let a=!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),a=!0}catch(e){let t=e instanceof Error?e.message:String(e);this.reporter.warn(`Failed to install ArkEnv AI skill: ${t}`)}}let o=_n(e,a,i);if(this.reporter.note(o.message,o.title),e.metadata.layout===`strict`){let t=r.default.resolve(e.cwd,e.metadata.displayPath);if(await this.workspace.exists(t)){let t=e.metadata.displayPath,n=r.default.basename(t,r.default.extname(t));this.reporter.warn(`Found existing single-file schema at ${Y(t)}. You can delete it after updating your imports to point to your new ${Y(`${n}/client`)} and ${Y(`${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:a})}catch(e){throw t.stop(`Scaffolding failed.`),e}}};function yn(e){switch(e){case`pnpm`:return[`pnpm`,`dlx`];case`yarn`:return[`yarn`,`dlx`];case`bun`:return[`bunx`];default:return[`npx`]}}function bn(e){let{mode:n,options:i,packageManager:a,tsConfig:o,shouldUpdateTsConfig:s,cwd:c,existingFiles:l}=e,u=i.name&&i.name!==`.`?r.default.basename(i.name):void 0,d={files:[],cwd:c,metadata:(0,t.shake)({displayPath:``,framework:i.framework,validator:i.validator,packageManager:a,importPath:``,mode:n,example:i.example,name:u,layout:i.layout,skillDetected:i.skillDetected,disableCodegen:i.disableCodegen})};if(n===`new`){if(!i.example)throw Error(`New project scaffolding requires an example.`);let t=i.name&&i.name!==`.`?r.default.join(c,i.name):void 0,n=i.name&&i.name!==`.`?r.default.basename(i.name):r.default.basename(c);return d.clone={repository:`https://github.com/yamcodes/arkenv.git`,example:i.example,targetName:n,...t!==void 0&&{targetDir:t}},d.install={packageManager:a,dependencies:[],...t!==void 0&&{cwd:t}},i.installSkill&&(d.skill={dlxCommand:yn(a),packageName:`yamcodes/arkenv`,isYes:e.isYes}),d.metadata.displayPath=`./src/env.ts`,d.metadata.importPath=`./src/env`,d}let f=r.default.resolve(c,i.path),p=r.default.dirname(f);if(i.framework===`nextjs`&&i.layout===`strict`){let e=r.default.extname(f),t=f.slice(0,-e.length),n=r.default.join(t,`internal`,`shared${e}`),a=r.default.join(t,`client${e}`),s=r.default.join(t,`server${e}`),u;if(i.framework===`nextjs`&&!i.disableCodegen&&o?.parsed){let e=o.parsed,n=(e.compilerOptions||{}).paths||{};if(n[`@/*`]){let i=e.path?r.default.dirname(e.path):c,a=r.default.join(t,`generated`),o=r.default.relative(i,a).replace(/\\/g,`/`);for(let e of n[`@/*`]){let t=e.replace(/^\.\//,``).replace(/\*$/,``);if(t===``||o.startsWith(t)){let e=o;t!==``&&o.startsWith(t)&&(e=o.substring(t.length)),e=e.replace(/^\/+/,``).replace(/\/+$/,``),u=`@/${e}/env.gen`.replace(/\/+/g,`/`);break}}}}let p=pn(i,u),m=l.includes(n),h=l.includes(a),g=l.includes(s);(!m||i.overwriteEnvSchemaFile!==!1)&&d.files.push({path:n,content:p.shared,action:m?`overwrite`:`create`,label:`shared environment schema`}),(!h||i.overwriteEnvSchemaFile!==!1)&&d.files.push({path:a,content:p.client,action:h?`overwrite`:`create`,label:`client environment schema`}),(!g||i.overwriteEnvSchemaFile!==!1)&&d.files.push({path:s,content:p.server,action:g?`overwrite`:`create`,label:`server environment schema`})}else{let e;if(i.framework===`nextjs`&&!i.disableCodegen&&o?.parsed){let t=o.parsed,n=(t.compilerOptions||{}).paths||{};if(n[`@/*`]){let i=t.path?r.default.dirname(t.path):c,a=r.default.join(p,`generated`),o=r.default.relative(i,a).replace(/\\/g,`/`);for(let t of n[`@/*`]){let n=t.replace(/^\.\//,``).replace(/\*$/,``);if(n===``||o.startsWith(n)){let t=o;n!==``&&o.startsWith(n)&&(t=o.substring(n.length)),t=t.replace(/^\/+/,``).replace(/\/+$/,``),e=`@/${t}/env.gen`.replace(/\/+/g,`/`);break}}}}let t=fn(i,e),n=l.includes(f);(!n||i.overwriteEnvSchemaFile!==!1)&&d.files.push({path:f,content:t,action:n?`overwrite`:`create`,label:`environment schema`})}let m=[`arkenv`,i.validator];if(i.framework===`vite`&&m.push(`@arkenv/vite-plugin`),i.framework===`bun-fullstack`&&i.bunFeatures?.length&&m.push(`@arkenv/bun-plugin`),i.framework===`nextjs`&&m.push(`@arkenv/nextjs`),(i.framework===`vite`||i.framework===`nextjs`||i.framework===`bun-fullstack`&&i.bunFeatures?.length)&&!m.includes(`arktype`)&&m.push(`arktype`),d.install={packageManager:a,dependencies:m},s&&o.file&&(d.tsConfig={path:r.default.resolve(c,o.file),action:`strict`}),(i.framework===`vite`||i.framework===`bun-fullstack`&&i.bunFeatures?.length)&&i.installTypeDefinitions!==!1){let e=i.framework===`vite`?`vite-env.d.ts`:`bun-env.d.ts`,t=r.default.join(p,e),n=l.includes(t);if(i.envDtsHandling!==`skip`)if(i.envDtsHandling===`append`||!i.envDtsHandling&&n)d.files.push({path:t,content:f,action:`append`,label:`${i.framework} types`});else{let e=i.framework===`vite`?cn(i.path):ln(i.path);d.files.push({path:t,content:e,action:n?`overwrite`:`create`,label:`${i.framework} types`})}}(i.framework===`vite`||i.framework===`bun-fullstack`||i.framework===`nextjs`&&!i.disableCodegen)&&(d.bootstrap=(0,t.shake)({framework:i.framework,bunFeatures:i.framework===`bun-fullstack`?i.bunFeatures:void 0,wrapNextjsConfig:i.framework===`nextjs`?i.wrapNextjsConfig!==!1:void 0})),i.installSkill&&(d.skill={dlxCommand:yn(a),packageName:`yamcodes/arkenv`,isYes:e.isYes});let h=r.default.relative(c,f).replace(/\\/g,`/`),g=h.startsWith(`.`)?h:`./${h}`,_=g.replace(/\.(ts|js|tsx|jsx)$/,``);return d.metadata.displayPath=g,d.metadata.importPath=_,d.bootstrap&&(d.bootstrap.importPath=_),d}var xn=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`}]}}}},Sn=class{constructor(e,t,n,r,i=new xn){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=bn(t),r=new vn(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&&r.default.resolve(process.cwd(),t)===process.cwd()&&(t=`.`);let n={...e,...t!==void 0&&{name:t}},i=t&&t!==`.`?r.default.resolve(process.cwd(),t):process.cwd(),a=await this.workspace.exists(i),o=a?await this.scanner.hasPackageJson(i):!1,s=a?await this.scanner.isEmptyDirectory(i):!0;return n.example===void 0?o?await this.collectExistingProject(n,i):s||n.isForce?await this.collectNewProject(n,s):(this.logger.error(`Directory is not empty and no ${Y(`package.json`)} was found.`),this.logger.info(`To scaffold a new project, run ${Y(`arkenv init`)} in an empty directory or use ${Y(`--force`)} to proceed anyway.`),null):await this.collectNewProject(n,s)}finally{this.logger.interactiveStdout(!1)}}async collectExistingProject(e,n){let{isYes:i,isForce:a,isQuiet:o,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(a){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(a)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(i)f=!0;else{this.logger.warn(`TypeScript strict mode is not enabled in your ${Y(p.file)}.`);let e=await this.prompt.confirm(`ArkEnv requires ${Y(`strict`)} mode in your ${Y(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),h=m===`bun-fullstack`?await this.scanner.detectBunFeatures(n,p.parsed):void 0,g=await this.scanner.suggestDefaultEnvPath(n,p.parsed),_=r.default.resolve(n,g),v=await this.scanner.getEnvExampleKeys(n,p.parsed,_),y=await(async()=>{if(e.isStrict){let e=r.default.extname(_),t=_.slice(0,-e.length),n=[r.default.join(t,`internal`,`shared${e}`),r.default.join(t,`client${e}`),r.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 i=e===`vite`?`vite-env.d.ts`:`bun-env.d.ts`,a=r.default.resolve(n,t),o=r.default.dirname(a),s=r.default.join(o,i);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,disableCodegen:e.noCodegen}),i);if(S===null)return null;let C=await this.scanner.hasSkill(n);if(C&&(S.skillDetected=!0,!o&&!s&&this.logger.info(`ArkEnv agent skill detected.`)),C)S.installSkill=!1;else if(s)S.installSkill=!1;else if(i)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=r.default.resolve(n,S.path);if(S.overwriteEnvSchemaFile===void 0&&(S.layout===`strict`?await(async()=>{let e=r.default.extname(w),t=w.slice(0,-e.length);return(await Promise.all([this.workspace.exists(r.default.join(t,`internal`,`shared${e}`)),this.workspace.exists(r.default.join(t,`client${e}`)),this.workspace.exists(r.default.join(t,`server${e}`))])).some(Boolean)})():await this.workspace.exists(w))){let e=S.layout===`strict`?`Strict layout files (client, server, internal/shared)`:r.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=r.default.extname(w),D=w.slice(0,-E.length),ee=S.layout===`strict`?[r.default.join(D,`internal`,`shared${E}`),r.default.join(D,`client${E}`),r.default.join(D,`server${E}`)]:[w],O=[];for(let e of ee)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=r.default.dirname(w),t=r.default.join(e,k);await this.workspace.exists(t)&&O.push(t)}return(0,t.shake)({mode:`existing`,cwd:n,options:S,detectedFramework:m,detectedBunFeatures:h,packageManager:T,tsConfig:p,shouldUpdateTsConfig:f,existingFiles:O,isYes:i})}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 ${Y(`.`)} because the current directory is not empty.`),this.logger.info(`Run ${Y(`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 Cn(e){let t=new tn(e),n=t.logger,r=new Nt(t.isQuiet,n.stdio),i=new Zt;return{cli:t,logger:n,workspace:r,prompt:i,initUseCase:new Sn(n,r,i,new bt),helpUseCase:new an(n)}}let $,wn=!1;async function Tn(){if(process.env.INIT_CWD)try{process.chdir(process.env.INIT_CWD)}catch{}let{cli:e,logger:n,initUseCase:r,helpUseCase:i}=Cn(process.argv);$=n,En(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 En(e){let t=async t=>{wn&&process.exit(t),wn=!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))}Tn(),process.on(`unhandledRejection`,async e=>{if($){try{$.fatal(`Unhandled rejection`,e)}catch{}await $.flush()}else console.error(`Unhandled rejection`,e);process.exit(1)}),process.on(`uncaughtException`,async e=>{if($){try{$.fatal(`Uncaught exception`,e)}catch{}await $.flush()}else console.error(`Uncaught exception`,e);process.exit(1)});
|
|
389
|
+
`,e.metadata.layout===`strict`?o+=`Import and use: ${Y(`import { env } from "${e.metadata.importPath}/client"`)} (client) or ${Y(`import { env } from "${e.metadata.importPath}/server"`)} (server)\n`:o+=`Import and use: ${Y(`import { env } from "${e.metadata.importPath}"`)}\n`),{message:o,title:`Next steps`}}let r=e.skill?.dlxCommand.join(` `)||`npx`,a=e.skill?.packageName||`yamcodes/arkenv`,o=``,s=1,c=e.metadata.displayPath;if(e.metadata.layout===`strict`){let e=c.lastIndexOf(`.`),t=e===-1?c:c.slice(0,e);c=`${t}/client.ts, ${t}/server.ts, and ${t}/internal/shared.ts`}o+=`${s++}. Check ${Y(c)} and refine your environment schema.\n`;let l=e.metadata.framework===`nextjs`&&!e.metadata.disableCodegen&&!n;return e.metadata.framework===`vite`?o+=`${s++}. Access via ${Y(`import.meta.env.YOUR_VAR`)}\n`:e.metadata.framework===`bun-fullstack`?o+=`${s++}. Access via ${Y(`process.env.YOUR_VAR`)}\n`:e.metadata.framework===`nextjs`?e.metadata.layout===`strict`?(e.metadata.disableCodegen||l&&(o+=`${s++}. Wrap your Next.js config with ${Y(`withArkEnv`)} inside ${Y(`next.config.ts`)}:\n`,o+=` ${Y(`import { withArkEnv } from "@arkenv/nextjs/config";`)}\n`,o+=` ${Y(`export default withArkEnv(nextConfig);`)}\n`),o+=`${s++}. Import and use: ${Y(`import { env } from "${e.metadata.importPath}/client"`)} (client) or ${Y(`import { env } from "${e.metadata.importPath}/server"`)} (server)\n`):(e.metadata.disableCodegen||l&&(o+=`${s++}. Wrap your Next.js config with ${Y(`withArkEnv`)} inside ${Y(`next.config.ts`)}:\n`,o+=` ${Y(`import { withArkEnv } from "@arkenv/nextjs/config";`)}\n`,o+=` ${Y(`export default withArkEnv(nextConfig);`)}\n`),o+=`${s++}. Import and use: ${Y(`import { env } from "${e.metadata.importPath}"`)}\n`):e.metadata.framework===`nuxt`&&e.metadata.layout===`strict`?o+=`${s++}. Import and use: ${Y(`import { env } from "${e.metadata.importPath}/client"`)} (client) or ${Y(`import { env } from "${e.metadata.importPath}/server"`)} (server)\n`:o+=`${s++}. Import and use: ${Y(`import { env } from "${e.metadata.importPath}"`)}\n`,o+=`${s++}. (Recommended) Install the AI skill: ${Y(`${r} skills add ${a}`)}\n`,o+=` Then run ${Y(`/arkenv`)} inside your AI assistant to finish.`,{message:o,title:`Next steps`}}var Sn=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 ${Y(e.clone.example)}...`),await vn(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 ${Y(r.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 ${Y(r.default.basename(t.path))}.`):this.reporter.info(`${Y(r.default.basename(t.path))} already contains ArkEnv types.`);continue}if(await this.workspace.mkdir(r.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} ${Y(r.default.basename(t.path))} for typesafe environment variables.`)}}if(t.stop(`Configuration scaffolded!`),e.install&&process.env.SKIP_INSTALL!==`true`){this.reporter.step(`Installing dependencies with ${Y(e.install.packageManager)}...`);let[t,n]=bn(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 ${Y(t.file)}`),n=!0):t.status===`error`&&this.reporter.warn(`Could not automatically update ${Y(t.file||`tsconfig.json`)}. Please ensure 'strict: true' is set manually.`)}let i=!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 ${Y(r.default.basename(t))}`):(this.reporter.warn(`Could not automatically update ${Y(r.default.basename(t))}: ${n.error}`),this.reporter.info(`Please add ${Y(`@arkenv/vite-plugin`)} manually.`))}else this.reporter.info(`No Vite config found - please add ${Y(`@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`){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 ${Y(`env.gen.ts`)} for Next.js`)}catch{this.reporter.warn(`Failed to automatically generate ${Y(`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 e=await this.workspace.bootstrapNextjsConfig(t);e.success?e.updated?(this.reporter.info(`Updated ${Y(r.default.basename(t))}`),i=!0):(this.reporter.info(`${Y(r.default.basename(t))} already uses withArkEnv`),i=!0):this.reporter.warn(`Could not automatically update ${Y(r.default.basename(t))}: ${e.error}`)}else this.reporter.info(`No Next.js config found. Please wrap your config with ${Y(`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 ${Y(r.default.basename(t))}`):this.reporter.info(`${Y(r.default.basename(t))} already registers @arkenv/nuxt/module`),i=!0):this.reporter.warn(`Could not automatically update ${Y(r.default.basename(t))}: ${e.error}`)}else this.reporter.info(`No Nuxt config found. Please register ${Y(`@arkenv/nuxt/module`)} manually.`)}}let a=!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),a=!0}catch(e){let t=e instanceof Error?e.message:String(e);this.reporter.warn(`Failed to install ArkEnv AI skill: ${t}`)}}let o=xn(e,a,i);if(this.reporter.note(o.message,o.title),e.metadata.layout===`strict`){let t=r.default.resolve(e.cwd,e.metadata.displayPath);if(await this.workspace.exists(t)){let t=e.metadata.displayPath,n=r.default.basename(t,r.default.extname(t));this.reporter.warn(`Found existing single-file schema at ${Y(t)}. You can delete it after updating your imports to point to your new ${Y(`${n}/client`)} and ${Y(`${n}/server`)}.`)}}this.reporter.finish(`${St} ArkEnv scaffolding complete. Happy coding!`,{path:e.metadata.displayPath,framework:e.metadata.framework,validator:e.metadata.validator,packageManager:e.metadata.packageManager,tsConfigUpdated:n,skillInstalled:a})}catch(e){throw t.stop(`Scaffolding failed.`),e}}};function Cn(e){switch(e){case`pnpm`:return[`pnpm`,`dlx`];case`yarn`:return[`yarn`,`dlx`];case`bun`:return[`bunx`];default:return[`npx`]}}function wn(e){let{mode:n,options:i,packageManager:a,tsConfig:o,shouldUpdateTsConfig:s,cwd:c,existingFiles:l}=e,u=i.name&&i.name!==`.`?r.default.basename(i.name):void 0,d={files:[],cwd:c,metadata:(0,t.shake)({displayPath:``,framework:i.framework,validator:i.validator,packageManager:a,importPath:``,mode:n,example:i.example,name:u,layout:i.layout,skillDetected:i.skillDetected,disableCodegen:i.disableCodegen})};if(n===`new`){if(!i.example)throw Error(`New project scaffolding requires an example.`);let t=i.name&&i.name!==`.`?r.default.join(c,i.name):void 0,n=i.name&&i.name!==`.`?r.default.basename(i.name):r.default.basename(c);return d.clone={repository:`https://github.com/yamcodes/arkenv.git`,example:i.example,targetName:n,...t!==void 0&&{targetDir:t}},d.install={packageManager:a,dependencies:[],...t!==void 0&&{cwd:t}},i.installSkill&&(d.skill={dlxCommand:Cn(a),packageName:`yamcodes/arkenv`,isYes:e.isYes}),d.metadata.displayPath=`./src/env.ts`,d.metadata.importPath=`./src/env`,d}let f=r.default.resolve(c,i.path),p=r.default.dirname(f);if((i.framework===`nextjs`||i.framework===`nuxt`)&&i.layout===`strict`){let e=r.default.extname(f),t=f.slice(0,-e.length),n=r.default.join(t,`internal`,`shared${e}`),a=r.default.join(t,`client${e}`),s=r.default.join(t,`server${e}`),u;if((i.framework===`nextjs`||i.framework===`nuxt`)&&!i.disableCodegen&&o?.parsed){let e=o.parsed,n=(e.compilerOptions||{}).paths||{};if(n[`@/*`]){let i=e.path?r.default.dirname(e.path):c,a=r.default.join(t,`generated`),o=r.default.relative(i,a).replace(/\\/g,`/`);for(let e of n[`@/*`]){let t=e.replace(/^\.\//,``).replace(/\*$/,``);if(t===``||o.startsWith(t)){let e=o;t!==``&&o.startsWith(t)&&(e=o.substring(t.length)),e=e.replace(/^\/+/,``).replace(/\/+$/,``),u=`@/${e}/env.gen`.replace(/\/+/g,`/`);break}}}}let p=_n(i,u),m=l.includes(n),h=l.includes(a),g=l.includes(s);(!m||i.overwriteEnvSchemaFile!==!1)&&d.files.push({path:n,content:p.shared,action:m?`overwrite`:`create`,label:`shared environment schema`}),(!h||i.overwriteEnvSchemaFile!==!1)&&d.files.push({path:a,content:p.client,action:h?`overwrite`:`create`,label:`client environment schema`}),(!g||i.overwriteEnvSchemaFile!==!1)&&d.files.push({path:s,content:p.server,action:g?`overwrite`:`create`,label:`server environment schema`})}else{let e;if((i.framework===`nextjs`||i.framework===`nuxt`)&&!i.disableCodegen&&o?.parsed){let t=o.parsed,n=(t.compilerOptions||{}).paths||{};if(n[`@/*`]){let i=t.path?r.default.dirname(t.path):c,a=r.default.join(p,`generated`),o=r.default.relative(i,a).replace(/\\/g,`/`);for(let t of n[`@/*`]){let n=t.replace(/^\.\//,``).replace(/\*$/,``);if(n===``||o.startsWith(n)){let t=o;n!==``&&o.startsWith(n)&&(t=o.substring(n.length)),t=t.replace(/^\/+/,``).replace(/\/+$/,``),e=`@/${t}/env.gen`.replace(/\/+/g,`/`);break}}}}let t=gn(i,e),n=l.includes(f);(!n||i.overwriteEnvSchemaFile!==!1)&&d.files.push({path:f,content:t,action:n?`overwrite`:`create`,label:`environment schema`})}let m=[`arkenv`,i.validator];if(i.framework===`vite`&&m.push(`@arkenv/vite-plugin`),i.framework===`bun-fullstack`&&i.bunFeatures?.length&&m.push(`@arkenv/bun-plugin`),i.framework===`nextjs`&&m.push(`@arkenv/nextjs`),i.framework===`nuxt`&&m.push(`@arkenv/nuxt`),(i.framework===`vite`||i.framework===`nextjs`||i.framework===`nuxt`||i.framework===`bun-fullstack`&&i.bunFeatures?.length)&&!m.includes(`arktype`)&&m.push(`arktype`),d.install={packageManager:a,dependencies:m},s&&o.file&&(d.tsConfig={path:r.default.resolve(c,o.file),action:`strict`}),(i.framework===`vite`||i.framework===`bun-fullstack`&&i.bunFeatures?.length)&&i.installTypeDefinitions!==!1){let e=i.framework===`vite`?`vite-env.d.ts`:`bun-env.d.ts`,t=r.default.join(p,e),n=l.includes(t);if(i.envDtsHandling!==`skip`)if(i.envDtsHandling===`append`||!i.envDtsHandling&&n)d.files.push({path:t,content:f,action:`append`,label:`${i.framework} types`});else{let e=i.framework===`vite`?fn(i.path):pn(i.path);d.files.push({path:t,content:e,action:n?`overwrite`:`create`,label:`${i.framework} types`})}}(i.framework===`vite`||i.framework===`bun-fullstack`||i.framework===`nextjs`&&!i.disableCodegen||i.framework===`nuxt`)&&(d.bootstrap=(0,t.shake)({framework:i.framework,bunFeatures:i.framework===`bun-fullstack`?i.bunFeatures:void 0,wrapNextjsConfig:i.framework===`nextjs`?i.wrapNextjsConfig!==!1:void 0})),i.installSkill&&(d.skill={dlxCommand:Cn(a),packageName:`yamcodes/arkenv`,isYes:e.isYes});let h=r.default.relative(c,f).replace(/\\/g,`/`),g=h.startsWith(`.`)?h:`./${h}`,_=g.replace(/\.(ts|js|tsx|jsx)$/,``);return d.metadata.displayPath=g,d.metadata.importPath=_,d.bootstrap&&(d.bootstrap.importPath=_),d}var Tn=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`}]}}}},En=class{constructor(e,t,n,r,i=new Tn){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=wn(t),r=new Sn(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&&r.default.resolve(process.cwd(),t)===process.cwd()&&(t=`.`);let n={...e,...t!==void 0&&{name:t}},i=t&&t!==`.`?r.default.resolve(process.cwd(),t):process.cwd(),a=await this.workspace.exists(i),o=a?await this.scanner.hasPackageJson(i):!1,s=a?await this.scanner.isEmptyDirectory(i):!0;return n.example===void 0?o?await this.collectExistingProject(n,i):s||n.isForce?await this.collectNewProject(n,s):(this.logger.error(`Directory is not empty and no ${Y(`package.json`)} was found.`),this.logger.info(`To scaffold a new project, run ${Y(`arkenv init`)} in an empty directory or use ${Y(`--force`)} to proceed anyway.`),null):await this.collectNewProject(n,s)}finally{this.logger.interactiveStdout(!1)}}async collectExistingProject(e,n){let{isYes:i,isForce:a,isQuiet:o,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(a){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(a)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(i)f=!0;else{this.logger.warn(`TypeScript strict mode is not enabled in your ${Y(p.file)}.`);let e=await this.prompt.confirm(`ArkEnv requires ${Y(`strict`)} mode in your ${Y(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),_=r.default.resolve(n,g),v=await this.scanner.getEnvExampleKeys(n,p.parsed,_),y=await(async()=>{if(e.isStrict){let e=r.default.extname(_),t=_.slice(0,-e.length),n=[r.default.join(t,`internal`,`shared${e}`),r.default.join(t,`client${e}`),r.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 i=e===`vite`?`vite-env.d.ts`:`bun-env.d.ts`,a=r.default.resolve(n,t),o=r.default.dirname(a),s=r.default.join(o,i);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}),i);if(S===null)return null;let ee=await this.scanner.hasSkill(n);if(ee&&(S.skillDetected=!0,!o&&!s&&this.logger.info(`ArkEnv agent skill detected.`)),ee)S.installSkill=!1;else if(s)S.installSkill=!1;else if(i)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 C=r.default.resolve(n,S.path);if(S.overwriteEnvSchemaFile===void 0&&(S.layout===`strict`?await(async()=>{let e=r.default.extname(C),t=C.slice(0,-e.length);return(await Promise.all([this.workspace.exists(r.default.join(t,`internal`,`shared${e}`)),this.workspace.exists(r.default.join(t,`client${e}`)),this.workspace.exists(r.default.join(t,`server${e}`))])).some(Boolean)})():await this.workspace.exists(C))){let e=S.layout===`strict`?`Strict layout files (client, server, internal/shared)`:r.default.basename(C),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 w=await this.scanner.detectPackageManager(n,p.parsed),T=r.default.extname(C),E=C.slice(0,-T.length),te=S.layout===`strict`?[r.default.join(E,`internal`,`shared${T}`),r.default.join(E,`client${T}`),r.default.join(E,`server${T}`)]:[C],D=[];for(let e of te)await this.workspace.exists(e)&&D.push(e);let O;if(S.framework===`vite`?O=`vite-env.d.ts`:S.framework===`bun-fullstack`&&(O=`bun-env.d.ts`),O){let e=r.default.dirname(C),t=r.default.join(e,O);await this.workspace.exists(t)&&D.push(t)}return(0,t.shake)({mode:`existing`,cwd:n,options:S,detectedFramework:m,detectedBunFeatures:h,packageManager:w,tsConfig:p,shouldUpdateTsConfig:f,existingFiles:D,isYes:i})}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 ${Y(`.`)} because the current directory is not empty.`),this.logger.info(`Run ${Y(`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 Dn(e){let t=new on(e),n=t.logger,r=new Lt(t.isQuiet,n.stdio),i=new tn;return{cli:t,logger:n,workspace:r,prompt:i,initUseCase:new En(n,r,i,new xt),helpUseCase:new ln(n)}}let $,On=!1;async function kn(){if(process.env.INIT_CWD)try{process.chdir(process.env.INIT_CWD)}catch{}let{cli:e,logger:n,initUseCase:r,helpUseCase:i}=Dn(process.argv);$=n,An(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 An(e){let t=async t=>{On&&process.exit(t),On=!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))}kn(),process.on(`unhandledRejection`,async e=>{if($){try{$.fatal(`Unhandled rejection`,e)}catch{}await $.flush()}else console.error(`Unhandled rejection`,e);process.exit(1)}),process.on(`uncaughtException`,async e=>{if($){try{$.fatal(`Uncaught exception`,e)}catch{}await $.flush()}else console.error(`Uncaught exception`,e);process.exit(1)});
|