@arkenv/cli 0.1.0 → 0.2.1
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/README.md +10 -0
- package/dist/index.cjs +69 -69
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -25,6 +25,16 @@ npx @arkenv/cli@latest init
|
|
|
25
25
|
|
|
26
26
|
This CLI is built with a port-and-adapter architecture to remain flexible and testable. See [ARCHITECTURE.md](./ARCHITECTURE.md) for details on the codebase design, architecture rules, and how to use the interactive testing scripts.
|
|
27
27
|
|
|
28
|
+
### Running the local CLI
|
|
29
|
+
|
|
30
|
+
To run your local changes to the CLI from anywhere inside this repository:
|
|
31
|
+
|
|
32
|
+
```sh
|
|
33
|
+
pnpm arkenv [command]
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
This root workspace script will automatically rebuild `@arkenv/cli` and execute the built bundle via Node.
|
|
37
|
+
|
|
28
38
|
### Local Environment Adapters (`Node*`)
|
|
29
39
|
|
|
30
40
|
Implementations prefixed with `Node` (e.g., `NodeWorkspace`, `NodeProjectScanner`) represent the standard local development environment. They utilize standard `node:*` APIs (like `node:fs` and `node:child_process`) which are universally supported across modern runtimes including Node.js, Bun, and Deno. This naming reflects the API standard used rather than a runtime restriction.
|
package/dist/index.cjs
CHANGED
|
@@ -19,79 +19,79 @@ 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 y=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})),b=e.r(y(),1),x=class{info(e){process.stderr.write(`${b.default.blue(`ℹ ${e}`)}\n`)}warn(e){process.stderr.write(`${b.default.yellow(`⚠ ${e}`)}\n`)}error(e){process.stderr.write(`${b.default.red(`✘ ${e}`)}\n`)}success(e){process.stderr.write(`${b.default.green(`✔ ${e}`)}\n`)}step(e){process.stderr.write(`○ ${e}\n`)}note(e,t){process.stderr.write(`${b.default.dim(`○ ${t?`${t}: `:``}${e}`)}\n`)}log(e){process.stderr.write(`${e}\n`)}spinner(){return{start:e=>process.stderr.write(`${b.default.dim(`○ ${e}...`)}\n`),stop:e=>process.stderr.write(`${b.default.green(`✔ ${e}`)}\n`),message:e=>process.stderr.write(`${b.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())})}},S=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 ee=(()=>{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}})(),te=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,
|
|
22
|
+
`}var y=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})),b=e.r(y(),1),x=class{info(e){process.stderr.write(`${b.default.blue(`ℹ ${e}`)}\n`)}warn(e){process.stderr.write(`${b.default.yellow(`⚠ ${e}`)}\n`)}error(e){process.stderr.write(`${b.default.red(`✘ ${e}`)}\n`)}success(e){process.stderr.write(`${b.default.green(`✔ ${e}`)}\n`)}step(e){process.stderr.write(`○ ${e}\n`)}note(e,t){process.stderr.write(`${b.default.dim(`○ ${t?`${t}: `:``}${e}`)}\n`)}log(e){process.stderr.write(`${e}\n`)}spinner(){return{start:e=>process.stderr.write(`${b.default.dim(`○ ${e}...`)}\n`),stop:e=>process.stderr.write(`${b.default.green(`✔ ${e}`)}\n`),message:e=>process.stderr.write(`${b.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())})}},S=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 ee=(()=>{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}})(),te=e=>e===12288||e>=65281&&e<=65376||e>=65504&&e<=65510,ne=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,re=/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]|\u001b\]8;[^;]*;.*?(?:\u0007|\u001b\u005c)/y,C=/[\x00-\x08\x0A-\x1F\x7F-\x9F]{1,1000}/y,ie=/(?:(?![\uFF61-\uFF9F\uFF00-\uFFEF])[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}\p{Script=Tangut}]){1,1000}/uy,ae=/\t{1,1000}/y,w=/[\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,oe=/(?:[\x20-\x7E\xA0-\xFF](?!\uFE0F)){1,1000}/y,se=/\p{M}+/gu,ce={limit:1/0,ellipsis:``},le=(e,t={},n={})=>{let r=t.limit??1/0,i=t.ellipsis??``,a=t?.ellipsisWidth??(i?le(i,ce,n).width:0),o=n.controlWidth??0,s=n.tabWidth??8,c=n.emojiWidth??2,l=n.regularWidth??1,u=n.wideWidth??2,d=[[oe,l],[re,0],[C,o],[ae,s],[w,c],[ie,u]],f=0,p=0,m=e.length,h=0,g=!1,_=m,v=Math.max(0,r-a),y=0,b=0,x=0,S=0;outer:for(;;){if(b>y||p>=m&&p>f){let t=e.slice(y,b)||e.slice(f,p);h=0;for(let e of t.replaceAll(se,``)){let t=e.codePointAt(0)||0;if(S=te(t)?2:ne(t)?u:l,x+S>v&&(_=Math.min(_,Math.max(y,f)+h)),x+S>r){g=!0;break outer}h+=e.length,x+=S}y=b=0}if(p>=m)break outer;for(let t=0,n=d.length;t<n;t++){let[n,i]=d[t];if(n.lastIndex=p,n.test(e)){if(h=n===ie?ee(e.slice(p,n.lastIndex)):n===w?1:n.lastIndex-p,S=h*i,x+S>v&&(_=Math.min(_,p+Math.floor((v-x)/i))),x+S>r){g=!0;break outer}x+=S,y=f,b=p,p=f=n.lastIndex;continue outer}}p+=1}return{width:g?v:x,index:g?_:m,truncated:g,ellipsed:g&&r>=a}},ue={limit:1/0,ellipsis:``,ellipsisWidth:0},T=(e,t={})=>le(e,ue,t).width,E=`]8;;`,de=RegExp(`(?:\\[(?<code>\\d+)m|\\${E}(?<uri>.*))`,`y`),fe=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},pe=e=>`[${e}m`,me=e=>`${E}${e}`,D=(e,t,n)=>{let r=t[Symbol.iterator](),i=!1,a=!1,o=e.at(-1),s=o===void 0?0:T(o),c=r.next(),l=r.next(),u=0;for(;!c.done;){let o=c.value,d=T(o);s+d<=n?e[e.length-1]+=o:(e.push(o),s=0),(o===`\x1B`||o===``)&&(i=!0,a=t.startsWith(E,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())},he=e=>{let t=e.split(` `),n=t.length;for(;n&&!T(t[n-1]);)n--;return n===t.length?e:t.slice(0,n).join(` `)+t.slice(n).join(``)},ge=(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=T(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=T(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(``),D(s,r,t),c=T(s.at(-1)??``);continue}if(c+i>t&&c&&i){if(n.wordWrap===!1&&c<t){D(s,r,t),c=T(s.at(-1)??``);continue}s.push(``),c=0}if(c+i>t&&n.wordWrap===!1){D(s,r,t),c=T(s.at(-1)??``);continue}s[s.length-1]+=r,c+=i}n.trim!==!1&&(s=s.map(e=>he(e)));let l=s.join(`
|
|
23
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===``){de.lastIndex=e+1;let t=de.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
24
|
`){a&&(r+=me(``));let e=i?fe(i):void 0;i&&e&&(r+=pe(e))}else t===`
|
|
25
|
-
`&&(i&&fe(i)&&(r+=pe(i)),a&&(r+=me(a)))}return r},
|
|
26
|
-
`)}var
|
|
25
|
+
`&&(i&&fe(i)&&(r+=pe(i)),a&&(r+=me(a)))}return r},_e=/\r?\n/;function O(e,t,n){return String(e).normalize().split(_e).map(e=>ge(e,t,n)).join(`
|
|
26
|
+
`)}var k=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 A(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?A(a,t<0?-1:1,n):a}const j={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 ve(e,t){if(typeof e==`string`)return j.aliases.get(e)===t;for(let n of e)if(n!==void 0&&ve(n,t))return!0;return!1}function ye(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 be=globalThis.process.platform.startsWith(`win`),
|
|
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 be=globalThis.process.platform.startsWith(`win`),xe=Symbol(`clack:cancel`);function M(e){return e===xe}function N(e,t){let n=e;n.isTTY&&n.setRawMode(t)}function Se({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(ve([String(i),o,c],`cancel`)){r&&t.write(k.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(k.cursor.hide),e.once(`keypress`,a),()=>{e.off(`keypress`,a),r&&t.write(k.cursor.show),e instanceof c.ReadStream&&e.isTTY&&!be&&e.setRawMode(!1),i.terminal=!1,i.close()}}const P=e=>`columns`in e&&typeof e.columns==`number`?e.columns:80,Ce=e=>`rows`in e&&typeof e.rows==`number`?e.rows:20;function F(e,t,n,r=n,i){return O(t,P(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 I=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(xe);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),N(this.input,!0),this.output.on(`resize`,this.render),this.render(),this.once(`submit`,()=>{this.output.write(k.cursor.show),this.output.off(`resize`,this.render),N(this.input,!1),e(this.value)}),this.once(`cancel`,()=>{this.output.write(k.cursor.show),this.output.off(`resize`,this.render),N(this.input,!1),e(xe)})})}_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&&j.aliases.has(t.name)&&this.emit(`cursor`,j.aliases.get(t.name)),j.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`)}ve([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
|
+
`),N(this.input,!1),this.rl?.close(),this.rl=void 0,this.emit(`${this.state}`,this.value),this.unsubscribe()}restoreCursor(){let e=O(this._prevFrame,process.stdout.columns,{hard:!0,trim:!1}).split(`
|
|
32
|
+
`).length-1;this.output.write(k.cursor.move(-999,e*-1))}render(){let e=O(this._render(this)??``,process.stdout.columns,{hard:!0,trim:!1});if(e!==this._prevFrame){if(this.state===`initial`)this.output.write(k.cursor.hide);else{let t=ye(this._prevFrame,e),n=Ce(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(k.cursor.move(0,a-i)),this.output.write(k.erase.lines(1));let t=e.split(`
|
|
33
|
+
`);this.output.write(t[a]),this._prevFrame=e,this.output.write(k.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(k.cursor.move(0,e))}this.output.write(k.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(k.erase.down())}this.output.write(e),this.state===`initial`&&(this.state=`active`),this._prevFrame=e}}};var we=class extends I{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(k.cursor.move(0,-1)),this.value=e,this.state=`submit`,this.close()}),this.on(`cursor`,()=>{this.value=!this.value})}},Te=class extends I{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?A(n,1,this.options):n,this.changeValue(),this.on(`cursor`,e=>{switch(e){case`left`:case`up`:this.cursor=A(this.cursor,-1,this.options);break;case`down`:case`right`:this.cursor=A(this.cursor,1,this.options);break}this.changeValue()})}},Ee=class extends I{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 De(){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 L=De(),Oe=()=>process.env.CI===`true`,R=(e,t)=>L?e:t,ke=R(`◆`,`*`),Ae=R(`■`,`x`),je=R(`▲`,`x`),z=R(`◇`,`o`),B=R(`│`,`|`),V=R(`└`,`—`),Me=R(`●`,`>`),H=R(`○`,` `),Ne=R(`─`,`-`),Pe=R(`╮`,`+`),Fe=R(`├`,`+`),Ie=R(`╯`,`+`),Le=R(`╰`,`+`),Re=R(`●`,`•`),ze=R(`◆`,`*`),Be=R(`▲`,`!`),Ve=R(`■`,`x`),He=e=>{switch(e){case`initial`:case`active`:return(0,a.styleText)(`cyan`,ke);case`cancel`:return(0,a.styleText)(`red`,Ae);case`error`:return(0,a.styleText)(`yellow`,je);case`submit`:return(0,a.styleText)(`green`,z)}},Ue=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)}},We=(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}},Ge=({cursor:e,options:t,style:n,output:r=process.stdout,maxItems:i=1/0,columnPadding:o=0,rowPadding:s=4})=>{let c=P(r)-o,l=Ce(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=O(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)=>We(_,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 we({active:t,inactive:n,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue??!0,render(){let r=e.withGuide??j.withGuide,i=`${He(this.state)} `,o=r?`${(0,a.styleText)(`gray`,B)} `:``,s=F(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`,Me)} ${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`,Me)} ${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??j.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`,Re)})},success:(e,t)=>{W.message(e,{...t,symbol:(0,a.styleText)(`green`,ze)})},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`,Be)})},warning:(e,t)=>{W.warn(e,t)},error:(e,t)=>{W.message(e,{...t,symbol:(0,a.styleText)(`red`,Ve)})}},Ke=(e=``,t)=>{let n=t?.output??process.stdout,r=t?.withGuide??j.withGuide?`${(0,a.styleText)(`gray`,V)} `:``;n.write(`${r}${(0,a.styleText)(`red`,e)}
|
|
47
47
|
|
|
48
|
-
`)},
|
|
49
|
-
${(0,a.styleText)(`gray`,
|
|
48
|
+
`)},qe=(e=``,t)=>{let n=t?.output??process.stdout,r=t?.withGuide??j.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
|
+
`)},Je=e=>(0,a.styleText)(`dim`,e),Ye=(e,t,n)=>{let r={hard:!0,trim:!1},i=O(e,t,r).split(`
|
|
52
|
+
`),a=i.reduce((e,t)=>Math.max(T(t),e),0);return O(e,t-(i.map(n).reduce((e,t)=>Math.max(T(t),e),0)-a),r)},Xe=(e=``,t=``,n)=>{let r=n?.output??o.default.stdout,i=n?.withGuide??j.withGuide,s=n?.format??Je,c=[``,...Ye(e,P(r)-6,s).split(`
|
|
53
|
+
`).map(s),``],l=T(t),u=Math.max(c.reduce((e,t)=>{let n=T(t);return n>e?n:e},0),l)+2,d=c.map(e=>`${(0,a.styleText)(`gray`,B)} ${e}${` `.repeat(u-T(e))}${(0,a.styleText)(`gray`,B)}`).join(`
|
|
54
|
+
`),f=i?`${(0,a.styleText)(`gray`,B)}
|
|
55
|
+
`:``,p=i?Fe:Le;r.write(`${f}${(0,a.styleText)(`green`,z)} ${(0,a.styleText)(`reset`,t)} ${(0,a.styleText)(`gray`,Ne.repeat(Math.max(u-l-1,1))+Pe)}
|
|
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;ee(),f=setInterval(()=>{if(u&&h===g)return;
|
|
57
|
+
${(0,a.styleText)(`gray`,p+Ne.repeat(u+2)+Ie)}
|
|
58
|
+
`)},Ze=e=>(0,a.styleText)(`magenta`,e),Qe=({indicator:e=`dots`,onCancel:t,output:n=process.stdout,cancelMessage:r,errorMessage:i,frames:o=L?[`◒`,`◐`,`◓`,`◑`]:[`•`,`o`,`O`,`0`],delay:s=L?80:120,signal:c,...l}={})=>{let u=Oe(),d,f,p=!1,m=!1,h=``,g,_=performance.now(),v=P(n),y=l?.styleFrame??Ze,b=e=>{let n=e>1?i??j.messages.error:r??j.messages.cancel;m=e===1,p&&(w(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)},te=()=>{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)},ne=()=>{if(g===void 0)return;u&&n.write(`
|
|
59
|
+
`);let e=O(g,v,{hard:!0,trim:!1}).split(`
|
|
60
|
+
`);e.length>1&&n.write(k.cursor.up(e.length-1)),n.write(k.cursor.to(0)),n.write(k.erase.down())},re=e=>e.replace(/\.+$/,``),C=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]`},ie=l.withGuide??j.withGuide,ae=(t=``)=>{p=!0,d=Se({output:n}),h=re(t),_=performance.now(),ie&&n.write(`${(0,a.styleText)(`gray`,B)}
|
|
61
|
+
`);let r=0,i=0;ee(),f=setInterval(()=>{if(u&&h===g)return;ne(),g=h;let t=y(o[r]),a;if(u)a=`${t} ${h}...`;else if(e===`timer`)a=`${t} ${h} ${C(_)}`;else{let e=`.`.repeat(Math.floor(i)).slice(0,3);a=`${t} ${h}${e}`}let s=O(a,v,{hard:!0,trim:!1});n.write(s),r=r+1<o.length?r+1:0,i=i<4?i+.125:0},s)},w=(t=``,r=0,i=!1)=>{if(!p)return;p=!1,clearInterval(f),ne();let o=r===0?(0,a.styleText)(`green`,z):r===1?(0,a.styleText)(`red`,Ae):(0,a.styleText)(`red`,je);h=t??h,i||(e===`timer`?n.write(`${o} ${h} ${C(_)}
|
|
62
62
|
`):n.write(`${o} ${h}
|
|
63
|
-
`)),te(),d()};return{start:
|
|
63
|
+
`)),te(),d()};return{start:ae,stop:(e=``)=>w(e,0),message:(e=``)=>{h=re(e??h)},cancel:(e=``)=>w(e,1),error:(e=``)=>w(e,2),clear:()=>w(``,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`,Me)} ${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 Te({options:e.options,signal:e.signal,input:e.input,output:e.output,initialValue:e.initialValue,render(){let n=e.withGuide??j.withGuide,r=`${He(this.state)} `,i=`${Ue(this.state)} `,o=F(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}${F(e.output,t(this.options[this.cursor],`selected`),r)}`}case`cancel`:{let r=n?`${(0,a.styleText)(`gray`,B)} `:``;return`${s}${F(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}${Ge({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()},$e=`${(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
|
+
${$e}`),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
|
+
${$e}${t.trimStart()}`),n=3+(0,a.stripVTControlCharacters)(t.trimStart()).length)}process.stdout.write(`
|
|
79
|
+
`)},info:e=>q.message(e,{symbol:(0,a.styleText)(`blue`,Re)}),success:e=>q.message(e,{symbol:(0,a.styleText)(`green`,ze)}),step:e=>q.message(e,{symbol:(0,a.styleText)(`green`,z)}),warn:e=>q.message(e,{symbol:(0,a.styleText)(`yellow`,Be)}),warning:e=>q.warn(e),error:e=>q.message(e,{symbol:(0,a.styleText)(`red`,Ve)})},et=e=>new Ee({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??j.withGuide,n=`${`${t?`${(0,a.styleText)(`gray`,B)}
|
|
80
|
+
`:``}${He(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 et=class{info(e){process.stdout.write(`${b.default.blue(`ℹ ${e}`)}\n`)}warn(e){process.stderr.write(`${b.default.yellow(`⚠ ${e}`)}\n`)}error(e){process.stderr.write(`${b.default.red(`✘ ${e}`)}\n`)}success(e){process.stdout.write(`${b.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(`${b.default.red(`✘ ${e}`)}\n`)}fatal(e,t){if(process.stderr.write(`${b.default.red(`✘ ${e}`)}\n`),t){let e=`${b.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 x:e.isQuiet?this.reporter=new S: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=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);if({...a.dependencies,...a.devDependencies}.vite)return`vite`}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{}return(await rt(e,t)).length>0?`bun-fullstack`:`vanilla`}async function rt(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(()=>ot),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 it(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 at(e=process.cwd(),t){let i=t;if(!i){let{findTsConfig:t,loadTsConfig:n}=await Promise.resolve().then(()=>ft),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 ot=e.n({getEnvExampleKeys:()=>dt,parseEnvExample:()=>ct,resolveImportPaths:()=>lt,scanProjectEnvKeys:()=>ut,walk:()=>st});async function st(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 st(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 ct(e){let t=[],n=e.split(/\r?\n/);for(let e of n){let n=e.trim();if(!n||n.startsWith(`#`))continue;let r=n.match(/^([A-Z_][A-Z0-9_]*)\s*=/i);r?.[1]&&t.push(r[1])}return Array.from(new Set(t))}function lt(e,t,n){if(e.startsWith(`.`))return[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 ut(e,t,i){let a=[],o=await st(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=lt(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 dt(e=process.cwd(),t,i){let a=r.default.join(e,`.env.example`);try{let e=ct(await n.default.readFile(a,`utf-8`));if(e.length>0)return{keys:e,source:`.env.example`}}catch{}let o=await ut(e,t,i);return o.length>0?{keys:o,source:`project`}:null}var ft=e.n({checkTsConfig:()=>mt,findTsConfig:()=>Y,loadTsConfig:()=>X});const pt=(0,u.createRequire)(require(`url`).pathToFileURL(__filename).href).resolve;async function Y(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 X(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=pt(i,{paths:[r.default.dirname(e)]})}catch{n=r.default.resolve(r.default.dirname(e),`node_modules`,i)}let a={...(await X(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 mt(e=process.cwd()){let t=await Y(e);if(!t)return{status:`not_found`};let n=r.default.basename(t);try{let e=await X(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 ht(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 gt(e){let t=e.trim().match(/^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?/);return t?[t[1],t[2]??`0`,t[3]??`0`].join(`.`):null}function _t(e,t){let n=e.trim(),r=n.match(/^[\^~]?\s*(v?\d+(?:\.\d+){0,2})$/);if(r){let e=gt(r[1]);return e!==null&&ht(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=gt(i);return a&&(r===`>=`||r===`>`||r===`=`)?ht(a,t)>=0:!1})}async function vt(e=process.cwd()){let t=[],i=process.version,a=`22.0.0`;ht(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?_t(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 mt(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 yt=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 Y(e)}async loadTsConfig(e,t=new Set){return X(e,t)}async getEnvExampleKeys(e=process.cwd(),t,n){return dt(e,t,n)}async suggestDefaultEnvPath(e=process.cwd(),t){return at(e,t)}async checkTsConfig(e=process.cwd()){return mt(e)}async checkRequirements(e=process.cwd()){return vt(e)}async detectFramework(e=process.cwd(),t){return nt(e,t)}async detectBunFeatures(e=process.cwd(),t){return rt(e,t)}async detectPackageManager(e=process.cwd(),t){return it(e,t)}};const Z=e=>b.default.cyan(e),bt=b.default.blue(`⛯`);function xt(e){try{let t=(0,p.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,p.generateCode)(t,{format:(0,p.detectCodeFormat)(n)}).code,a=e.envImportPath?`arkenvVitePlugin(Env)`:`arkenvVitePlugin()`;return i=i.replace(/['"]__ARK_PLUGIN_PLACEHOLDER__['"]/g,a),{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)}`}}}async function St(){for(let e of[`vite.config.ts`,`vite.config.js`,`vite.config.mts`,`vite.config.mjs`]){let t=r.default.resolve(process.cwd(),e);try{return await n.default.access(t),t}catch{}}return null}async function Ct(){for(let e of[`bunfig.toml`,`bun.setup.ts`,`bun.setup.js`]){let t=r.default.resolve(process.cwd(),e);try{return await n.default.access(t),t}catch{}}return null}async function wt(e,t,n){try{let r=xt({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 Tt(e,t){if(!t||t.length===0)return{success:!0,instructions:i.default`
|
|
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 tt=class{info(e){process.stdout.write(`${b.default.blue(`ℹ ${e}`)}\n`)}warn(e){process.stderr.write(`${b.default.yellow(`⚠ ${e}`)}\n`)}error(e){process.stderr.write(`${b.default.red(`✘ ${e}`)}\n`)}success(e){process.stdout.write(`${b.default.green(`✔ ${e}`)}\n`)}step(e){process.stdout.write(`○ ${e}\n`)}note(e,t){Xe(e,t)}log(e){process.stdout.write(`${e}\n`)}spinner(){return Qe()}json(e){process.stdout.write(`${JSON.stringify(e,null,2)}\n`)}cancel(e){process.stderr.write(`${b.default.red(`✘ ${e}`)}\n`)}fatal(e,t){if(process.stderr.write(`${b.default.red(`✘ ${e}`)}\n`),t){let e=`${b.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){qe(e)}async flush(){return new Promise(e=>{process.stderr.write(``,()=>e())})}},nt=class{constructor(e){this.options=e,this.originalStdoutWrite=process.stdout.write,e.isJson?this.reporter=new x:e.isQuiet?this.reporter=new S:this.reporter=new tt}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 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);if({...a.dependencies,...a.devDependencies}.vite)return`vite`}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{}return(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:()=>ht,findTsConfig:()=>J,loadTsConfig:()=>Y});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 Y(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 Y(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 J(e);if(!t)return{status:`not_found`};let n=r.default.basename(t);try{let e=await Y(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 J(e)}async loadTsConfig(e,t=new Set){return Y(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 ht(e)}async checkRequirements(e=process.cwd()){return yt(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)}};const X=e=>b.default.cyan(e),xt=b.default.blue(`⛯`);function St(e){try{let t=(0,p.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,p.generateCode)(t,{format:(0,p.detectCodeFormat)(n)}).code,a=e.envImportPath?`arkenvVitePlugin(Env)`:`arkenvVitePlugin()`;return i=i.replace(/['"]__ARK_PLUGIN_PLACEHOLDER__['"]/g,a),{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)}`}}}async function Ct(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 wt(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 Tt(e,t,n){try{let r=St({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 Et(e,t){if(!t||t.length===0)return{success:!0,instructions:i.default`
|
|
88
88
|
${b.default.green(`✔`)} Use ${b.default.bold(`Vanilla`)} Bun runtime integration.
|
|
89
|
-
Access validated variables via your ${
|
|
89
|
+
Access validated variables via your ${X(`env`)} object for typesafety.
|
|
90
90
|
Primarily used for ${b.default.cyan(`server-side`)} or runtime-only validation.
|
|
91
91
|
No plugins are required.
|
|
92
92
|
`};let n=t.includes(`serve`),r=t.includes(`build`),a=``;return n&&(a+=i.default`
|
|
93
93
|
${b.default.bold(`Bun Fullstack (Bun.serve) Integration:`)}
|
|
94
|
-
To inline environment variables (e.g. ${
|
|
94
|
+
To inline environment variables (e.g. ${X(`PUBLIC_*`)}) in your ${b.default.cyan(`client-side`)} code, add the plugin to ${X(`bunfig.toml`)}:
|
|
95
95
|
|
|
96
96
|
[serve.static]
|
|
97
97
|
plugins = ["@arkenv/bun-plugin"]
|
|
@@ -99,16 +99,16 @@ ${t?(0,a.styleText)(`cyan`,H):``}
|
|
|
99
99
|
`),r&&(a&&(a+=`
|
|
100
100
|
`),a+=i.default`
|
|
101
101
|
${b.default.bold(`Bun Fullstack programmatic bundling (Bun.build):`)}
|
|
102
|
-
To inline environment variables (e.g. ${
|
|
102
|
+
To inline environment variables (e.g. ${X(`PUBLIC_*`)}) in your custom ${b.default.cyan(`client-side`)} build script, add the plugin to your ${X(`Bun.build`)} call:
|
|
103
103
|
|
|
104
|
-
${
|
|
104
|
+
${X(`import arkenv from "@arkenv/bun-plugin";`)}
|
|
105
105
|
|
|
106
106
|
await Bun.build({
|
|
107
107
|
entrypoints: ["./index.ts"],
|
|
108
108
|
outdir: "./dist",
|
|
109
109
|
${b.default.green(`plugins: [arkenv]`)}
|
|
110
110
|
});
|
|
111
|
-
`),{success:!0,instructions:a.trim()}}async function Et(e,t){let n=t||await Y();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 Dt=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=[]){return new Promise((n,r)=>{let i=(0,f.spawn)(e,t,{stdio:this.isQuiet?`pipe`:this.stdio,shell:!1}),a=``,o=``,s=1e4;this.isQuiet&&(i.stdout?.on(`data`,e=>{a=(a+e.toString()).slice(-s)}),i.stderr?.on(`data`,e=>{o=(o+e.toString()).slice(-s)})),i.on(`close`,(e,t)=>{if(e===0)n();else{let n=e===null?`Command terminated by signal ${t}`:`Command failed with code ${e}`;this.isQuiet&&(a&&(n+=`\n${b.default.dim(`STDOUT:`)}\n${a}`),o&&(n+=`\n${b.default.red(`STDERR:`)}\n${o}`)),r(Error(n))}}),i.on(`error`,r)})}async updateTsConfigToStrict(e){return Et(this,e)}async findViteConfig(){return St()}async findBunConfig(){return Ct()}async bootstrapViteConfig(e,t){return wt(this,e,t)}async bootstrapBunConfig(e,t){return Tt(e,t)}async safeAppend(e,t,n){let{safeAppend:r}=await Promise.resolve().then(()=>m);return r(e,t,n)}};const Q={example:e=>async()=>q({message:`Select an example:`,options:e.map(e=>({value:e.id,label:e.name,...e.description?{hint:e.description}:{}}))}),overwriteEnvSchemaFile:(e=`./src/env.ts`)=>async()=>{if((0,l.existsSync)(r.default.resolve(process.cwd(),e))){let t=await W({message:b.default.yellow(`An existing ArkEnv configuration was found at ${Z(e)}. Do you want to overwrite it?`),initialValue:!1,active:`Yes (override my configuration)`,inactive:`No (abort)`});return N(t)||!t?null:t}return!0},framework:e=>async()=>{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`}]});return N(t)?null:t},bunBuild:(e=!1)=>async()=>{let t=await W({message:`Optional: Would you also like to bootstrap a custom Bun.build script for programmatic bundling?`,initialValue:e});return N(t)?null:t},useDefaultPath:(e=`./src/env.ts`)=>async()=>{let t=await W({message:`Use default config path (${Z(e)})?`,initialValue:!0,active:`Yes (Recommended)`,inactive:`No, let me customize it`});return N(t)?null:t},path:(e=`./src/env.ts`)=>async({results:t})=>{if(t.useDefaultPath===null)return null;if(!t.useDefaultPath){let t=await $e({message:`Where should we create the ArkEnv config?`,placeholder:e,initialValue:e});if(N(t))return null;let n=typeof t==`string`?t.trim():``;return n===``?e:n}return e},installTypeDefinitions:async({results:e})=>{if(e.framework===null)return null;if(e.framework===`vite`||e.framework===`bun-fullstack`){let t=e.framework===`vite`?`vite-env.d.ts`:`bun-env.d.ts`,n=r.default.dirname(r.default.resolve(process.cwd(),e.path||`./src/env.ts`)),i=r.default.join(n,t);if(l.default.existsSync(i))return!0;let a=await W({message:`Establish ${Z(t)} for typesafe environment variables?`,initialValue:!0,active:`Yes (Recommended)`,inactive:`No`});return N(a)?null:a}return!0},envDtsHandling:async({results:e})=>{if(e.installTypeDefinitions===null)return null;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`,n=r.default.dirname(r.default.resolve(process.cwd(),e.path||`./src/env.ts`)),i=r.default.join(n,t);if(l.default.existsSync(i)){let e=await q({message:`Found existing ${Z(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 N(e)?null:e}return`overwrite`},validator:async()=>{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 N(e)?null:e},useEnvExample:(e,t=`.env.example`)=>async()=>{if(e&&e.length>0){let n=e.length,r=n===1,i=await W({message:t===`.env.example`?`Detected ${Z(`.env.example`)} with ${n} ${r?`key`:`keys`}. Use ${r?`it`:`them`} for your schema?`:`Detected ${n} environment variable${r?``:`s`} used in your project. Use ${r?`it`:`them`} for your schema?`,active:`Yes (Recommended)`,initialValue:!0});return N(i)?null:i}return!1}};async function Ot(e,t=!1){return(e?.mode||`existing`)===`new`?kt(e,t):At(e,t)}async function kt(e,t=!1){let n=e?.examples||[],i=r.default.basename(process.cwd()),a;if(e?.name)a=e.name;else if(t)a=i;else{let e=jt(await $e({message:`Project name:`,placeholder:i,initialValue:``}));if(e===null)return null;a=e||i}a===`.`&&(a=i);let o=e?.example;if(!o&&!t){let e=jt(await Q.example(n)());if(e===null)return null;o=e}else !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}}async function At(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;return(n===`vite`||n===`bun-fullstack`)&&(a=e?.hasTypeFile?`append`:`overwrite`),(0,t.shake)({mode:`existing`,path:r,validator:`arktype`,framework:n,bunFeatures:n===`bun-fullstack`?e?.bunFeatures??[`serve`]:void 0,language:`ts`,overwriteEnvSchemaFile:!0,installTypeDefinitions:n!==`vanilla`,installSkill:!1,envDtsHandling:a,envKeys:i??void 0})}let o={mode:`existing`},s=[{key:`overwriteEnvSchemaFile`,fn:()=>Q.overwriteEnvSchemaFile(r)()},{key:`framework`,fn:()=>Q.framework(e)()},{key:`bunBuild`,fn:({results:t})=>t.framework===`bun-fullstack`?Q.bunBuild(e?.bunFeatures?.includes(`build`)||t.framework===`bun-fullstack`&&e?.framework===`bun-fullstack`&&e?.bunFeatures?.includes(`build`))():Promise.resolve(void 0)},{key:`useDefaultPath`,fn:()=>Q.useDefaultPath(r)()},{key:`path`,fn:e=>Q.path(r)(e)},{key:`installTypeDefinitions`,fn:e=>Q.installTypeDefinitions(e)},{key:`envDtsHandling`,fn:e=>Q.envDtsHandling(e)},{key:`validator`,fn:()=>Q.validator()},{key:`useEnvExample`,fn:()=>Q.useEnvExample(i,a)()}];for(let{key:e,fn:t}of s){let n=jt(await t({results:o}));if(n===null)return null;o[e]=n}let c=o.framework===`bun-fullstack`?o.bunBuild?[`serve`,`build`]:[`serve`]:void 0;return(0,t.shake)({...o,bunFeatures:c,language:`ts`,installSkill:!1,envKeys:o.useEnvExample?i??void 0:void 0})}function jt(e){return e===null||N(e)?(Ge(`Operation cancelled`),null):e}var Mt=class{async confirm(e,n=!0,r,i){let a=await W((0,t.shake)({message:e,initialValue:n,active:r,inactive:i}));return N(a)?null:a}async runWizard(e,t=!1){return Ot(e,t)}},Nt=class{constructor(e,t={}){this.args=e.slice(2),this.command=this.args[0],this.isYes=this.args.includes(`--yes`)||this.args.includes(`-y`),this.isForce=this.args.includes(`--force`)||this.args.includes(`-f`),this.isQuiet=this.args.includes(`--quiet`)||this.args.includes(`-q`),this.isJson=this.args.includes(`--json`)||this.args.includes(`-j`),this.isAgent=this.args.includes(`--agent`)||this.args.includes(`-a`),this.helpRequested=this.args.includes(`--help`)||this.args.includes(`-h`),this.example=this.getFlagValue(`--example`,`-e`),this.name=this.getFlagValue(`--name`,`-n`),this.isAgent&&(this.isYes=!0,this.isQuiet=!0,this.isJson=!0),this.logger=t.logger||new tt({isQuiet:this.isQuiet,isJson:this.isJson,isYes:this.isYes})}get initInput(){let e={isYes:this.isYes,isForce:this.isForce,isQuiet:this.isQuiet,isAgent:this.isAgent};return this.example!==void 0&&(e.example=this.example),this.name!==void 0&&(e.name=this.name),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]}},Pt=`0.1.0`,Ft=class{constructor(e){this.logger=e}async execute(){this.logger.log(`ArkEnv CLI v${Pt}`),this.logger.log(`\n${b.default.bold(`Usage:`)}`),this.logger.log(` arkenv init Set up ArkEnv in your project`),this.logger.log(`\n${b.default.bold(`Options:`)}`),this.logger.log(` --yes, -y Skip prompts and use defaults (also passed to skill processes)`),this.logger.log(` --force, -f Bypass technical requirement checks and force scaffolding`),this.logger.log(` --agent, -a Agent mode: --yes --quiet --json`),this.logger.log(` --example, -e Specify an example ID to scaffold from (when creating a new project)`),this.logger.log(` --name, -n Specify the project name (when creating a new project)`),this.logger.log(` --quiet, -q Quiet mode: Suppress output, capture logs on failure`),this.logger.log(` --json, -j Output structured JSON to stdout`),this.logger.log(` --help, -h Show this help message`)}};const It=(e,t)=>{let n=e?.length?e.map(e=>`\t\t${e}: "string = ''",`).join(`
|
|
111
|
+
`),{success:!0,instructions:a.trim()}}async function Dt(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 Ot=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,f.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${b.default.dim(`STDOUT:`)}\n${o}`),s&&(n+=`\n${b.default.red(`STDERR:`)}\n${s}`)),i(Error(n))}}),a.on(`error`,i)})}async updateTsConfigToStrict(e){return Dt(this,e)}async findViteConfig(e){return Ct(e)}async findBunConfig(e){return wt(e)}async bootstrapViteConfig(e,t){return Tt(this,e,t)}async bootstrapBunConfig(e,t){return Et(e,t)}async safeAppend(e,t,n){let{safeAppend:r}=await Promise.resolve().then(()=>m);return r(e,t,n)}};const Z={example:e=>async()=>K({message:`Select an example:`,options:e.map(e=>({value:e.id,label:e.name,...e.description?{hint:e.description}:{}}))}),overwriteEnvSchemaFile:(e=`./src/env.ts`)=>async()=>{if((0,l.existsSync)(r.default.resolve(process.cwd(),e))){let t=await U({message:b.default.yellow(`An existing ArkEnv configuration was found at ${X(e)}. Do you want to overwrite it?`),initialValue:!1,active:`Yes (override my configuration)`,inactive:`No (abort)`});return M(t)||!t?null:t}return!0},framework:e=>async()=>{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`}]});return M(t)?null:t},bunBuild:(e=!1)=>async()=>{let t=await U({message:`Optional: Would you also like to bootstrap a custom Bun.build script for programmatic bundling?`,initialValue:e});return M(t)?null:t},useDefaultPath:(e=`./src/env.ts`)=>async()=>{let t=await U({message:`Use default config path (${X(e)})?`,initialValue:!0,active:`Yes (Recommended)`,inactive:`No, let me customize it`});return M(t)?null:t},path:(e=`./src/env.ts`)=>async({results:t})=>{if(t.useDefaultPath===null)return null;if(!t.useDefaultPath){let t=await et({message:`Where should we create the ArkEnv config?`,placeholder:e,initialValue:e,defaultValue:e});if(M(t))return null;let n=typeof t==`string`?t.trim():``;return n===``?e:n}return e},installTypeDefinitions:async({results:e})=>{if(e.framework===null)return null;if(e.framework===`vite`||e.framework===`bun-fullstack`){let t=e.framework===`vite`?`vite-env.d.ts`:`bun-env.d.ts`,n=r.default.dirname(r.default.resolve(process.cwd(),e.path||`./src/env.ts`)),i=r.default.join(n,t);if(l.default.existsSync(i))return!0;let a=await U({message:`Establish ${X(t)} for typesafe environment variables?`,initialValue:!0,active:`Yes (Recommended)`,inactive:`No`});return M(a)?null:a}return!0},envDtsHandling:async({results:e})=>{if(e.installTypeDefinitions===null)return null;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`,n=r.default.dirname(r.default.resolve(process.cwd(),e.path||`./src/env.ts`)),i=r.default.join(n,t);if(l.default.existsSync(i)){let e=await K({message:`Found existing ${X(t)}. How should we handle ArkEnv types?`,options:[{value:`append`,label:`Append types safely (if needed)`,hint:`Recommended`},{value:`overwrite`,label:`Overwrite entirely`,hint:`Destructive`},{value:`skip`,label:`Skip`}]});return M(e)?null:e}return`overwrite`},validator:async()=>{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 M(e)?null:e},useEnvExample:(e,t=`.env.example`)=>async()=>{if(e&&e.length>0){let n=e.length,r=n===1,i=await U({message:t===`.env.example`?`Detected ${X(`.env.example`)} with ${n} ${r?`key`:`keys`}. Use ${r?`it`:`them`} for your schema?`:`Detected ${n} environment variable${r?``:`s`} used in your project. Use ${r?`it`:`them`} for your schema?`,active:`Yes (Recommended)`,initialValue:!0});return M(i)?null:i}return!1}};async function kt(e,t=!1){return(e?.mode||`existing`)===`new`?At(e,t):jt(e,t)}async function At(e,t=!1){let n=e?.examples||[],i=`arkenv-project`,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=Mt(await et({message:`Project name:`,placeholder:i,defaultValue:i}));if(e===null)return null;let t=(e||i).trim();a=t===`.`||t===`./`||r.default.resolve(process.cwd(),t)===process.cwd()?`.`:t}let o=e?.example;if(!o&&!t){let e=Mt(await Z.example(n)());if(e===null)return null;o=e}else !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}}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;return(n===`vite`||n===`bun-fullstack`)&&(a=e?.hasTypeFile?`append`:`overwrite`),(0,t.shake)({mode:`existing`,path:r,validator:`arktype`,framework:n,bunFeatures:n===`bun-fullstack`?e?.bunFeatures??[`serve`]:void 0,language:`ts`,overwriteEnvSchemaFile:!0,installTypeDefinitions:n!==`vanilla`,installSkill:!1,envDtsHandling:a,envKeys:i??void 0})}let o={mode:`existing`},s=[{key:`overwriteEnvSchemaFile`,fn:()=>Z.overwriteEnvSchemaFile(r)()},{key:`framework`,fn:()=>Z.framework(e)()},{key:`bunBuild`,fn:({results:t})=>t.framework===`bun-fullstack`?Z.bunBuild(e?.bunFeatures?.includes(`build`)||t.framework===`bun-fullstack`&&e?.framework===`bun-fullstack`&&e?.bunFeatures?.includes(`build`))():Promise.resolve(void 0)},{key:`useDefaultPath`,fn:()=>Z.useDefaultPath(r)()},{key:`path`,fn:e=>Z.path(r)(e)},{key:`installTypeDefinitions`,fn:e=>Z.installTypeDefinitions(e)},{key:`envDtsHandling`,fn:e=>Z.envDtsHandling(e)},{key:`validator`,fn:()=>Z.validator()},{key:`useEnvExample`,fn:()=>Z.useEnvExample(i,a)()}];for(let{key:e,fn:t}of s){let n=Mt(await t({results:o}));if(n===null)return null;o[e]=n}let c=o.framework===`bun-fullstack`?o.bunBuild?[`serve`,`build`]:[`serve`]:void 0;return(0,t.shake)({...o,bunFeatures:c,language:`ts`,installSkill:!1,envKeys:o.useEnvExample?i??void 0:void 0})}function Mt(e){return e===null||M(e)?(Ke(`Operation cancelled`),null):e}var Nt=class{async confirm(e,n=!0,r,i){let a=await U((0,t.shake)({message:e,initialValue:n,active:r,inactive:i}));return M(a)?null:a}async runWizard(e,t=!1){return kt(e,t)}};const Q={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`}},Pt=new Set(Object.values(Q).flatMap(e=>[e.long,e.short])),Ft=new Set(Object.values(Q).filter(e=>e.kind===`value`).flatMap(e=>[e.long,e.short]));var It=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(Ft.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}`);Ft.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(!Pt.has(e)){this.validationError=`Unknown argument: ${e}`;break}if(Ft.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 nt({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=Q.example;return this.getFlagValue(e.long,e.short)}hasFlag(e){let t=Q[e];return this.args.includes(t.long)||this.args.includes(t.short)}get initInput(){let e={isYes:this.isYes,isForce:this.isForce,isQuiet:this.isQuiet,isAgent:this.isAgent};return this.example!==void 0&&(e.example=this.example),this.name!==void 0&&(e.name=this.name),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]}},Lt=`0.2.1`;function Rt(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 zt=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 force scaffolding`},{left:`--agent, -a`,right:`Agent mode: --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:`--help, -h`,right:`Show this help message`}];this.logger.log(`ArkEnv CLI v${Lt}`),this.logger.log(`\n${b.default.bold(`Usage:`)}`);for(let t of Rt(e))this.logger.log(t);this.logger.log(`\n${b.default.bold(`Options:`)}`);for(let e of Rt(t))this.logger.log(e)}};const Bt=(e,t)=>{let n=e?.length?e.map(e=>`\t\t${e}: "string = ''",`).join(`
|
|
112
112
|
`):` NODE_ENV: "'development' | 'production' | 'test' = 'development'",
|
|
113
113
|
PORT: "number.port = 3000",`;return t===`vite`?i.default`
|
|
114
114
|
import { type } from "arkenv";
|
|
@@ -143,7 +143,7 @@ ${n}
|
|
|
143
143
|
});
|
|
144
144
|
|
|
145
145
|
export const env = arkenv(Env);
|
|
146
|
-
`},
|
|
146
|
+
`},Vt=e=>i.default`
|
|
147
147
|
/// <reference types="vite/client" />
|
|
148
148
|
|
|
149
149
|
type ImportMetaEnvAugmented =
|
|
@@ -156,7 +156,7 @@ ${n}
|
|
|
156
156
|
interface ImportMeta {
|
|
157
157
|
readonly env: ImportMetaEnv;
|
|
158
158
|
}
|
|
159
|
-
`,
|
|
159
|
+
`,Ht=e=>i.default`
|
|
160
160
|
/// <reference types="bun-types" />
|
|
161
161
|
|
|
162
162
|
type ProcessEnvAugmented = import("@arkenv/bun-plugin").ProcessEnvAugmented<
|
|
@@ -166,9 +166,10 @@ ${n}
|
|
|
166
166
|
declare namespace NodeJS {
|
|
167
167
|
interface ProcessEnv extends ProcessEnvAugmented {}
|
|
168
168
|
}
|
|
169
|
-
`,
|
|
169
|
+
`,Ut=(e,t)=>{let n=e?.length?e.map(e=>`\t\t${e}: v.optional(v.string(), ""),`).join(`
|
|
170
170
|
`):` NODE_ENV: v.optional(v.picklist(["development", "production", "test"]), "development"),
|
|
171
171
|
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`
|
|
172
|
+
import { type } from "arkenv";
|
|
172
173
|
import * as v from "valibot";
|
|
173
174
|
|
|
174
175
|
/**
|
|
@@ -176,10 +177,11 @@ ${n}
|
|
|
176
177
|
* In Vite, use \`@arkenv/vite-plugin\` to validate these at build-time
|
|
177
178
|
* and provide typesafety for \`import.meta.env\` on the client-side.
|
|
178
179
|
*/
|
|
179
|
-
export const Env =
|
|
180
|
+
export const Env = type({
|
|
180
181
|
${n}
|
|
181
182
|
});
|
|
182
183
|
`:t===`bun-fullstack`?i.default`
|
|
184
|
+
import { type } from "arkenv";
|
|
183
185
|
import * as v from "valibot";
|
|
184
186
|
|
|
185
187
|
/**
|
|
@@ -187,7 +189,7 @@ ${n}
|
|
|
187
189
|
* In Bun Fullstack, use \`@arkenv/bun-plugin\` to validate these at build-time
|
|
188
190
|
* and provide typesafety for \`process.env\` on the client-side.
|
|
189
191
|
*/
|
|
190
|
-
export const Env =
|
|
192
|
+
export const Env = type({
|
|
191
193
|
${n}
|
|
192
194
|
});
|
|
193
195
|
`:i.default`
|
|
@@ -197,14 +199,13 @@ ${n}
|
|
|
197
199
|
/**
|
|
198
200
|
* Environment variable schema for server-side or runtime-only validation.
|
|
199
201
|
*/
|
|
200
|
-
export const
|
|
202
|
+
export const env = arkenv({
|
|
201
203
|
${n}
|
|
202
204
|
});
|
|
203
|
-
|
|
204
|
-
export const env = arkenv(Env);
|
|
205
|
-
`},Bt=(e,t)=>{let n=e?.length?e.map(e=>`\t\t${e}: z.string().default(""),`).join(`
|
|
205
|
+
`},Wt=(e,t)=>{let n=e?.length?e.map(e=>`\t\t${e}: z.string().default(""),`).join(`
|
|
206
206
|
`):` NODE_ENV: z.enum(["development", "production", "test"]).default("development"),
|
|
207
207
|
PORT: z.coerce.number().int().min(1).max(65535).default(3000),`;return t===`vite`?i.default`
|
|
208
|
+
import { type } from "arkenv";
|
|
208
209
|
import { z } from "zod";
|
|
209
210
|
|
|
210
211
|
/**
|
|
@@ -212,10 +213,11 @@ ${n}
|
|
|
212
213
|
* In Vite, use \`@arkenv/vite-plugin\` to validate these at build-time
|
|
213
214
|
* and provide typesafety for \`import.meta.env\` on the client-side.
|
|
214
215
|
*/
|
|
215
|
-
export const Env =
|
|
216
|
+
export const Env = type({
|
|
216
217
|
${n}
|
|
217
218
|
});
|
|
218
219
|
`:t===`bun-fullstack`?i.default`
|
|
220
|
+
import { type } from "arkenv";
|
|
219
221
|
import { z } from "zod";
|
|
220
222
|
|
|
221
223
|
/**
|
|
@@ -223,7 +225,7 @@ ${n}
|
|
|
223
225
|
* In Bun Fullstack, use \`@arkenv/bun-plugin\` to validate these at build-time
|
|
224
226
|
* and provide typesafety for \`process.env\` on the client-side.
|
|
225
227
|
*/
|
|
226
|
-
export const Env =
|
|
228
|
+
export const Env = type({
|
|
227
229
|
${n}
|
|
228
230
|
});
|
|
229
231
|
`:i.default`
|
|
@@ -233,17 +235,15 @@ ${n}
|
|
|
233
235
|
/**
|
|
234
236
|
* Environment variable schema for server-side or runtime-only validation.
|
|
235
237
|
*/
|
|
236
|
-
export const
|
|
238
|
+
export const env = arkenv({
|
|
237
239
|
${n}
|
|
238
240
|
});
|
|
239
|
-
|
|
240
|
-
export const env = arkenv(Env);
|
|
241
|
-
`};function Vt(e){let{validator:t,envKeys:n,framework:r}=e;switch(t){case`arktype`:return`${It(n,r)}\n`;case`zod`:return`${Bt(n,r)}\n`;case`valibot`:return`${zt(n,r)}\n`;default:throw Error(`Unsupported validator: ${t}`)}}async function Ht(e,t){let i=r.default.join(process.cwd(),`.arkenv-temp`);await e.mkdir(i,!0);try{await e.execute(`git`,[`clone`,`--filter=blob:none`,`--sparse`,t.repository,i]);let a=`examples/${t.example}`;await e.execute(`git`,[`-C`,i,`sparse-checkout`,`set`,a]),await Ut(r.default.join(i,a),process.cwd());for(let e of[`package-lock.json`,`pnpm-lock.yaml`,`yarn.lock`,`bun.lockb`,`bun.lock`])await n.default.rm(r.default.join(process.cwd(),e),{force:!0});let o=r.default.join(process.cwd(),`package.json`);if(await e.exists(o)){let n=await e.readFile(o),r=JSON.parse(n);r.name=t.targetName,await e.writeFile(o,JSON.stringify(r,null,2))}}finally{await n.default.rm(i,{recursive:!0,force:!0})}}async function Ut(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 Wt(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 Gt(e){return e.metadata.framework===`vite`?`2. Access via ${Z(`import.meta.env.YOUR_VAR`)}`:e.metadata.framework===`bun-fullstack`?`2. Access via ${Z(`process.env.YOUR_VAR`)}`:`2. Import and use: ${Z(`import { env } from "${e.metadata.importPath}"`)}`}function Kt(e,t){if(t)return{message:i.default`
|
|
241
|
+
`};function Gt(e){let{validator:t,envKeys:n,framework:r}=e;switch(t){case`arktype`:return`${Bt(n,r)}\n`;case`zod`:return`${Wt(n,r)}\n`;case`valibot`:return`${Ut(n,r)}\n`;default:throw Error(`Unsupported validator: ${t}`)}}async function Kt(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]),await qt(r.default.join(a,o),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 s=r.default.join(i,`package.json`);if(await e.exists(s)){let n=await e.readFile(s),r=JSON.parse(n);r.name=t.targetName,await e.writeFile(s,JSON.stringify(r,null,2))}}finally{await n.default.rm(a,{recursive:!0,force:!0})}}async function qt(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 Jt(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 Yt(e){return e.metadata.framework===`vite`?`2. Access via ${X(`import.meta.env.YOUR_VAR`)}`:e.metadata.framework===`bun-fullstack`?`2. Access via ${X(`process.env.YOUR_VAR`)}`:`2. Import and use: ${X(`import { env } from "${e.metadata.importPath}"`)}`}function Xt(e,t){if(t)return{message:i.default`
|
|
242
242
|
Inside your AI assistant (e.g. Claude Code), use:
|
|
243
|
-
${
|
|
244
|
-
`,title:`Next steps`};let n=e.skill?.dlxCommand.join(` `)||`npx`,r=e.skill?.packageName||`yamcodes/arkenv`,a=
|
|
245
|
-
1. Check ${
|
|
243
|
+
${X(`/arkenv`)} - automatically refine your schema and configure integrations.
|
|
244
|
+
`,title:`Next steps`};let n=e.skill?.dlxCommand.join(` `)||`npx`,r=e.skill?.packageName||`yamcodes/arkenv`,a=Yt(e);return{message:i.default`
|
|
245
|
+
1. Check ${X(e.metadata.displayPath)} and refine your environment schema.
|
|
246
246
|
${a}
|
|
247
|
-
3. (Recommended) Install the AI skill: ${
|
|
248
|
-
Then run ${
|
|
249
|
-
`,title:`Next steps`}}var qt=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 ${Z(e.clone.example)}...`),await Ht(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 ${Z(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 ${Z(r.default.basename(t.path))}.`):this.reporter.info(`${Z(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} ${Z(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 ${Z(e.install.packageManager)}...`);let[t,n]=Wt(e.install.packageManager,e.install.dependencies);await this.workspace.execute(t,n)}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 ${Z(t.file)}`),n=!0):t.status===`error`&&this.reporter.warn(`Could not automatically update ${Z(t.file||`tsconfig.json`)}. Please ensure 'strict: true' is set manually.`)}if(e.bootstrap){if(e.bootstrap.framework===`vite`){let t=await this.workspace.findViteConfig();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 ${Z(r.default.basename(t))}`):(this.reporter.warn(`Could not automatically update ${Z(r.default.basename(t))}: ${n.error}`),this.reporter.info(`Please add ${Z(`@arkenv/vite-plugin`)} manually.`))}else this.reporter.info(`No Vite config found — please add ${Z(`@arkenv/vite-plugin`)} to your Vite config manually.`)}else if(e.bootstrap.framework===`bun-fullstack`){let t=await this.workspace.findBunConfig(),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`)}}let i=!1;if(e.skill&&process.env.SKIP_INSTALL!==`true`){this.reporter.step(`Installing ArkEnv agent skill...`);try{let[t,...n]=e.skill.dlxCommand,r=[...n,`skills`,`add`,e.skill.packageName];e.skill.isYes&&r.push(`--yes`),await this.workspace.execute(t,r),i=!0}catch(e){let t=e instanceof Error?e.message:String(e);this.reporter.warn(`Failed to install ArkEnv AI skill: ${t}`)}}let a=Kt(e,i);this.reporter.note(a.message,a.title),this.reporter.finish(`${bt} ArkEnv scaffolding complete. Happy coding!`,{path:e.metadata.displayPath,framework:e.metadata.framework,validator:e.metadata.validator,packageManager:e.metadata.packageManager,tsConfigUpdated:n,skillInstalled:i})}catch(e){throw t.stop(`Scaffolding failed.`),e}}};function Jt(e){switch(e){case`pnpm`:return[`pnpm`,`dlx`];case`yarn`:return[`yarn`,`dlx`];case`bun`:return[`bunx`];default:return[`npx`]}}function Yt(e){let{mode:n,options:i,packageManager:a,tsConfig:o,shouldUpdateTsConfig:s,cwd:c,existingFiles:l}=e,u={files:[],metadata:(0,t.shake)({displayPath:``,framework:i.framework,validator:i.validator,packageManager:a,importPath:``,mode:n,example:i.example,name:i.name})};if(n===`new`)return u.clone={repository:`https://github.com/yamcodes/arkenv.git`,example:i.example,targetName:i.name},u.install={packageManager:a,dependencies:[]},i.installSkill&&(u.skill={dlxCommand:Jt(a),packageName:`yamcodes/arkenv`,isYes:e.isYes}),u.metadata.displayPath=`./src/env.ts`,u.metadata.importPath=`./src/env`,u;let d=r.default.resolve(c,i.path),f=r.default.dirname(d),p=Vt(i),m=l.includes(d);(!m||i.overwriteEnvSchemaFile!==!1)&&u.files.push({path:d,content:p,action:m?`overwrite`:`create`,label:`environment schema`});let h=[`arkenv`,i.validator];if(i.framework===`vite`&&h.push(`@arkenv/vite-plugin`),i.framework===`bun-fullstack`&&i.bunFeatures?.length&&h.push(`@arkenv/bun-plugin`),u.install={packageManager:a,dependencies:h},s&&o.file&&(u.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(f,e),n=l.includes(t);if(i.envDtsHandling!==`skip`)if(i.envDtsHandling===`append`||!i.envDtsHandling&&n)u.files.push({path:t,content:d,action:`append`,label:`${i.framework} types`});else{let e=i.framework===`vite`?Lt(i.path):Rt(i.path);u.files.push({path:t,content:e,action:n?`overwrite`:`create`,label:`${i.framework} types`})}}(i.framework===`vite`||i.framework===`bun-fullstack`)&&(u.bootstrap=(0,t.shake)({framework:i.framework,bunFeatures:i.framework===`bun-fullstack`?i.bunFeatures:void 0})),i.installSkill&&(u.skill={dlxCommand:Jt(a),packageName:`yamcodes/arkenv`,isYes:e.isYes});let g=r.default.relative(c,d).replace(/\\/g,`/`),_=g.startsWith(`.`)?g:`./${g}`,v=_.replace(/\.(ts|js|tsx|jsx)$/,``);return u.metadata.displayPath=_,u.metadata.importPath=v,u.bootstrap&&(u.bootstrap.importPath=v),u}var Xt=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-vite-react`,name:`React + Vite`,framework:`vite`},{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`}]}}}},Zt=class{constructor(e,t,n,r,i=new Xt){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=Yt(t),r=new qt(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=await this.scanner.hasPackageJson(),n=await this.scanner.isEmptyDirectory();return t?await this.collectExistingProject(e):n||e.isForce?await this.collectNewProject(e):(this.logger.error(`Directory is not empty and no ${Z(`package.json`)} was found.`),this.logger.info(`To scaffold a new project, run ${Z(`arkenv init`)} in an empty directory or use ${Z(`--force`)} to proceed anyway.`),null)}finally{this.logger.interactiveStdout(!1)}}async collectExistingProject(e){let{isYes:n,isForce:i,isAgent:a}=e,o=await this.scanner.checkRequirements(process.cwd()),s=o.filter(e=>e.status===`fail`),c=o.filter(e=>e.status===`warn`);for(let e of c)this.logger.warn(`${e.requirement}: ${e.message}`);if(s.length>0)if(i){this.logger.warn(`Technical requirements not met, but continuing due to --force flag.`);for(let e of s)this.logger.warn(`${e.requirement}: ${e.message}`)}else{this.logger.error(`Technical requirements not met:`);for(let e of s)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 l=!1,u=await this.scanner.checkTsConfig();if(u.status===`not_strict`)if(n)l=!0;else{this.logger.warn(`TypeScript strict mode is not enabled in your ${Z(u.file)}.`);let e=await this.prompt.confirm(`ArkEnv requires ${Z(`strict`)} mode in your ${Z(u.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;l=!0}let d=await this.scanner.detectFramework(process.cwd(),u.parsed),f=d===`bun-fullstack`?await this.scanner.detectBunFeatures(process.cwd(),u.parsed):void 0,p=await this.scanner.suggestDefaultEnvPath(process.cwd(),u.parsed),m=r.default.resolve(process.cwd(),p),h=await this.scanner.getEnvExampleKeys(process.cwd(),u.parsed,m),g=!1;if(d===`vite`||d===`bun-fullstack`){let e=d===`vite`?`vite-env.d.ts`:`bun-env.d.ts`,t=r.default.dirname(m),n=r.default.join(t,e);g=await this.workspace.exists(n)}let _=await this.prompt.runWizard((0,t.shake)({mode:`existing`,framework:d,bunFeatures:f,defaultEnvPath:p,tsConfig:u.parsed??null,envKeys:h?.keys,envKeysSource:h?.source,hasTypeFile:g}),n);if(_===null)return null;if(a)_.installSkill=!1;else if(n)_.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;_.installSkill=e}let v=r.default.resolve(process.cwd(),_.path);if(await this.workspace.exists(v)&&_.overwriteEnvSchemaFile===void 0){let e=await this.prompt.confirm(`File ${Z(r.default.basename(v))} already exists. Overwrite?`,!1);if(e===null)return null;if(!e)return this.logger.cancel(`Operation cancelled.`),null;_.overwriteEnvSchemaFile=e}let y=await this.scanner.detectPackageManager(process.cwd(),u.parsed),b=[];await this.workspace.exists(v)&&b.push(v);let x;if(_.framework===`vite`?x=`vite-env.d.ts`:_.framework===`bun-fullstack`&&(x=`bun-env.d.ts`),x){let e=r.default.dirname(v),t=r.default.join(e,x);await this.workspace.exists(t)&&b.push(t)}return(0,t.shake)({mode:`existing`,cwd:process.cwd(),options:_,detectedFramework:d,detectedBunFeatures:f,packageManager:y,tsConfig:u,shouldUpdateTsConfig:l,existingFiles:b,isYes:n})}async collectNewProject(e){let{isYes:n,isAgent:r,example:i,name:a}=e,o=await this.registry.fetchRegistry(),s=await this.prompt.runWizard((0,t.shake)({mode:`new`,examples:o.examples,example:i,name:a}),n);if(s===null)return null;let c=this.detectPackageManager();return(0,t.shake)({mode:`new`,cwd:process.cwd(),options:s,detectedFramework:s.framework,packageManager:c,tsConfig:{status:`not_found`},shouldUpdateTsConfig:!1,existingFiles:[],isYes:n})}detectPackageManager(){let e=process.env.npm_config_user_agent||``;return e.includes(`pnpm`)?`pnpm`:e.includes(`yarn`)?`yarn`:e.includes(`bun`)?`bun`:`npm`}};function Qt(e){let t=new Nt(e),n=t.logger,r=new Dt(t.isQuiet,n.stdio),i=new Mt;return{cli:t,logger:n,workspace:r,prompt:i,initUseCase:new Zt(n,r,i,new yt),helpUseCase:new Ft(n)}}let $,$t=!1;async function en(){let{cli:e,logger:n,initUseCase:r,helpUseCase:i}=Qt(process.argv);$=n,tn(n),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 tn(e){let t=async t=>{$t&&process.exit(t),$t=!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))}en(),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)});
|
|
247
|
+
3. (Recommended) Install the AI skill: ${X(`${n} skills add ${r}`)}
|
|
248
|
+
Then run ${X(`/arkenv`)} inside your AI assistant to finish.
|
|
249
|
+
`,title:`Next steps`}}var Zt=class{constructor(e,t){this.workspace=e,this.reporter=t}async execute(e){let t=this.reporter.spinner();t.start(`Scaffolding ArkEnv configuration...`);try{e.clone&&(t.stop(`Starting new project scaffolding...`),this.reporter.step(`Cloning example ${X(e.clone.example)}...`),await Kt(this.workspace,e.clone),t.start(`Scaffolding complete, finalizing...`));for(let t of e.files){if(t.action===`append`){if(!e.bootstrap||e.bootstrap.framework!==`vite`&&e.bootstrap.framework!==`bun-fullstack`){this.reporter.warn(`Skipping safe-append for ${X(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 ${X(r.default.basename(t.path))}.`):this.reporter.info(`${X(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} ${X(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 ${X(e.install.packageManager)}...`);let[t,n]=Jt(e.install.packageManager,e.install.dependencies);await this.workspace.execute(t,n,e.install.cwd??e.cwd)}let n=!1;if(e.tsConfig){let t=await this.workspace.updateTsConfigToStrict(e.tsConfig.path);t.status===`updated`?(this.reporter.info(`Enforced strict: true in your ${X(t.file)}`),n=!0):t.status===`error`&&this.reporter.warn(`Could not automatically update ${X(t.file||`tsconfig.json`)}. Please ensure 'strict: true' is set manually.`)}if(e.bootstrap){if(e.bootstrap.framework===`vite`){let t=await this.workspace.findViteConfig(e.cwd);if(t){this.reporter.step(`Bootstrapping Vite plugin...`);let n=await this.workspace.bootstrapViteConfig(t,e.bootstrap.importPath||`./src/env`);n.success?n.updated&&this.reporter.info(`Updated ${X(r.default.basename(t))}`):(this.reporter.warn(`Could not automatically update ${X(r.default.basename(t))}: ${n.error}`),this.reporter.info(`Please add ${X(`@arkenv/vite-plugin`)} manually.`))}else this.reporter.info(`No Vite config found — please add ${X(`@arkenv/vite-plugin`)} to your Vite config manually.`)}else if(e.bootstrap.framework===`bun-fullstack`){let t=await this.workspace.findBunConfig(e.cwd),n=await this.workspace.bootstrapBunConfig(t,e.bootstrap.bunFeatures);n.success&&n.instructions?this.reporter.info(n.instructions):n.success||this.reporter.error(n.error||`Bun bootstrap failed`)}}let i=!1;if(e.skill&&process.env.SKIP_INSTALL!==`true`){this.reporter.step(`Installing ArkEnv agent skill...`);try{let[t,...n]=e.skill.dlxCommand,r=[...n,`skills`,`add`,e.skill.packageName];e.skill.isYes&&r.push(`--yes`),await this.workspace.execute(t,r,e.cwd),i=!0}catch(e){let t=e instanceof Error?e.message:String(e);this.reporter.warn(`Failed to install ArkEnv AI skill: ${t}`)}}let a=Xt(e,i);this.reporter.note(a.message,a.title),this.reporter.finish(`${xt} ArkEnv scaffolding complete. Happy coding!`,{path:e.metadata.displayPath,framework:e.metadata.framework,validator:e.metadata.validator,packageManager:e.metadata.packageManager,tsConfigUpdated:n,skillInstalled:i})}catch(e){throw t.stop(`Scaffolding failed.`),e}}};function Qt(e){switch(e){case`pnpm`:return[`pnpm`,`dlx`];case`yarn`:return[`yarn`,`dlx`];case`bun`:return[`bunx`];default:return[`npx`]}}function $t(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})};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:Qt(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),m=Gt(i),h=l.includes(f);(!h||i.overwriteEnvSchemaFile!==!1)&&d.files.push({path:f,content:m,action:h?`overwrite`:`create`,label:`environment schema`});let g=[`arkenv`,i.validator];if(i.framework===`vite`&&g.push(`@arkenv/vite-plugin`),i.framework===`bun-fullstack`&&i.bunFeatures?.length&&g.push(`@arkenv/bun-plugin`),d.install={packageManager:a,dependencies:g},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`?Vt(i.path):Ht(i.path);d.files.push({path:t,content:e,action:n?`overwrite`:`create`,label:`${i.framework} types`})}}(i.framework===`vite`||i.framework===`bun-fullstack`)&&(d.bootstrap=(0,t.shake)({framework:i.framework,bunFeatures:i.framework===`bun-fullstack`?i.bunFeatures:void 0})),i.installSkill&&(d.skill={dlxCommand:Qt(a),packageName:`yamcodes/arkenv`,isYes:e.isYes});let _=r.default.relative(c,f).replace(/\\/g,`/`),v=_.startsWith(`.`)?_:`./${_}`,y=v.replace(/\.(ts|js|tsx|jsx)$/,``);return d.metadata.displayPath=v,d.metadata.importPath=y,d.bootstrap&&(d.bootstrap.importPath=y),d}var en=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-vite-react`,name:`React + Vite`,framework:`vite`},{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`}]}}}},tn=class{constructor(e,t,n,r,i=new en){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=$t(t),r=new Zt(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 ${X(`package.json`)} was found.`),this.logger.info(`To scaffold a new project, run ${X(`arkenv init`)} in an empty directory or use ${X(`--force`)} to proceed anyway.`),null):await this.collectNewProject(n,s)}finally{this.logger.interactiveStdout(!1)}}async collectExistingProject(e,n){let{isYes:i,isForce:a,isAgent:o}=e,s=await this.scanner.checkRequirements(n),c=s.filter(e=>e.status===`fail`),l=s.filter(e=>e.status===`warn`);for(let e of l)this.logger.warn(`${e.requirement}: ${e.message}`);if(c.length>0)if(a){this.logger.warn(`Technical requirements not met, but continuing due to --force flag.`);for(let e of c)this.logger.warn(`${e.requirement}: ${e.message}`)}else{this.logger.error(`Technical requirements not met:`);for(let e of c)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 u=!1,d=await this.scanner.checkTsConfig(n);if(d.status===`not_strict`)if(i)u=!0;else{this.logger.warn(`TypeScript strict mode is not enabled in your ${X(d.file)}.`);let e=await this.prompt.confirm(`ArkEnv requires ${X(`strict`)} mode in your ${X(d.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;u=!0}let f=await this.scanner.detectFramework(n,d.parsed),p=f===`bun-fullstack`?await this.scanner.detectBunFeatures(n,d.parsed):void 0,m=await this.scanner.suggestDefaultEnvPath(n,d.parsed),h=r.default.resolve(n,m),g=await this.scanner.getEnvExampleKeys(n,d.parsed,h),_=!1;if(f===`vite`||f===`bun-fullstack`){let e=f===`vite`?`vite-env.d.ts`:`bun-env.d.ts`,t=r.default.dirname(h),n=r.default.join(t,e);_=await this.workspace.exists(n)}let v=await this.prompt.runWizard((0,t.shake)({mode:`existing`,framework:f,bunFeatures:p,defaultEnvPath:m,tsConfig:d.parsed??null,envKeys:g?.keys,envKeysSource:g?.source,hasTypeFile:_}),i);if(v===null)return null;if(o)v.installSkill=!1;else if(i)v.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;v.installSkill=e}let y=r.default.resolve(n,v.path);if(await this.workspace.exists(y)&&v.overwriteEnvSchemaFile===void 0){let e=await this.prompt.confirm(`File ${X(r.default.basename(y))} already exists. Overwrite?`,!1);if(e===null)return null;if(!e)return this.logger.cancel(`Operation cancelled.`),null;v.overwriteEnvSchemaFile=e}let b=await this.scanner.detectPackageManager(n,d.parsed),x=[];await this.workspace.exists(y)&&x.push(y);let S;if(v.framework===`vite`?S=`vite-env.d.ts`:v.framework===`bun-fullstack`&&(S=`bun-env.d.ts`),S){let e=r.default.dirname(y),t=r.default.join(e,S);await this.workspace.exists(t)&&x.push(t)}return(0,t.shake)({mode:`existing`,cwd:n,options:v,detectedFramework:f,detectedBunFeatures:p,packageManager:b,tsConfig:d,shouldUpdateTsConfig:u,existingFiles:x,isYes:i})}async collectNewProject(e,n=!0){let{isYes:r,example:i,name:a}=e,o=await this.registry.fetchRegistry(),s=await this.prompt.runWizard((0,t.shake)({mode:`new`,examples:o.examples,example:i,name:a}),r);if(s===null)return null;if(s.name===`.`&&!n)return this.logger.error(`Cannot scaffold into ${X(`.`)} because the current directory is not empty.`),this.logger.info(`Run ${X(`arkenv init`)} in an empty directory or choose a sub-directory name instead.`),null;let c=this.detectPackageManager();return(0,t.shake)({mode:`new`,cwd:process.cwd(),options:s,detectedFramework:s.framework,packageManager:c,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 nn(e){let t=new It(e),n=t.logger,r=new Ot(t.isQuiet,n.stdio),i=new Nt;return{cli:t,logger:n,workspace:r,prompt:i,initUseCase:new tn(n,r,i,new bt),helpUseCase:new zt(n)}}let $,rn=!1;async function an(){if(process.env.INIT_CWD)try{process.chdir(process.env.INIT_CWD)}catch{}let{cli:e,logger:n,initUseCase:r,helpUseCase:i}=nn(process.argv);$=n,on(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 on(e){let t=async t=>{rn&&process.exit(t),rn=!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))}an(),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)});
|