#!/usr/bin/env node
import R from 'chalk';
import { Command } from 'commander';
import kt, { existsSync, readFileSync, mkdirSync, writeFileSync, renameSync, readdirSync, statSync } from 'node:fs';
import { join as join$1, basename as basename$1 } from 'node:path';
import * as V from '@clack/prompts';
import { spinner, text, select, cancel, isCancel, confirm } from '@clack/prompts';
import Tn, { resolve, join, basename } from 'pathe';
import { findUp } from 'find-up';
import { fileURLToPath } from 'node:url';
import at from '@winches/prompts';
import Dt from 'gradient-string';
import { exec, execSync } from 'node:child_process';
import { validate, compareVersions } from 'compare-versions';
import Xn from 'fast-glob';
import Io from 'async-retry';
import _n, { oraPromise } from 'ora';
import { Readable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import gr from 'tar';

var _=process.cwd(),P=e=>resolve(_,e),$e=resolve(fileURLToPath(import.meta.url),"../components.json");var Lt=["#F54180","#338EF7"],st=Dt(...Lt),Sn=st("HeroUI CLI:"),a=class{constructor(){}static log(...t){console.log(...t);}static info(...t){console.info(...t.map(o=>R.blue(o)));}static success(...t){console.info(...t.map(o=>R.green(o)));}static warn(...t){console.warn(...t.map(o=>R.yellow(o)));}static error(...t){console.error(...t.map(o=>R.red(o)));}static grey(...t){console.log(...t.map(o=>R.gray(o)));}static gradient(t,o){this.log(Dt(...o?.colors??Lt)(String(t)));}static prefix(t,...o){return this[t](Sn,...o)}static newLine(t){t||(t=1);for(let o=0;o<t;o++)this.log();}};var pt={onCancel:()=>{a.log(`${R.red("\u2716")} Operation cancelled`),process.exit(0);}};async function ye(e,t){return (await at({hint:"- Space to select. Return to submit",message:e,min:1,name:"value",type:"autocompleteMultiselect",...t?{choices:t}:{}},pt)).value}async function se(e,t){return (await at({message:e,name:"value",type:"select",...t?{choices:t}:{}},pt)).value}async function Mt(e,t){return (await at({hint:"- Space to select. Return to submit",message:e,min:1,name:"value",type:"multiselect",...t?{choices:t}:{}},pt)).value}var _e=["npm","bun","pnpm","yarn"];var Ot={"bun.lockb":"bun","npm-shrinkwrap.json":"npm","package-lock.json":"npm","pnpm-lock.yaml":"pnpm","yarn.lock":"yarn"};async function N(e=_){let t,o=await findUp(Object.keys(Ot),{cwd:e});return o?t=Ot[Tn.basename(o)]:t=await se("No agent found, please choose one",_e.map(r=>({title:r,value:r}))),t}var ct={bold:{bottomLeft:"\u2517",bottomRight:"\u251B",horizontal:"\u2501",topLeft:"\u250F",topRight:"\u2513",vertical:"\u2503"},classic:{bottomLeft:"+",bottomRight:"+",horizontal:"-",topLeft:"+",topRight:"+",vertical:"|"},double:{bottomLeft:"\u255A",bottomRight:"\u255D",horizontal:"\u2550",topLeft:"\u2554",topRight:"\u2557",vertical:"\u2551"},doubleSingle:{bottomLeft:"\u2558",bottomRight:"\u255B",horizontal:"\u2550",topLeft:"\u2552",topRight:"\u2555",vertical:"\u2502"},round:{bottomLeft:"\u2570",bottomRight:"\u256F",horizontal:"\u2500",topLeft:"\u256D",topRight:"\u256E",vertical:"\u2502"},single:{bottomLeft:"\u2514",bottomRight:"\u2518",horizontal:"\u2500",topLeft:"\u250C",topRight:"\u2510",vertical:"\u2502"},singleDouble:{bottomLeft:"\u2559",bottomRight:"\u255C",horizontal:"\u2500",topLeft:"\u2553",topRight:"\u2556",vertical:"\u2551"}};function E(e="",t=""){if(!validate(e))return -1;try{return compareVersions(e,t)}catch{return 0}}async function jn(){if(!existsSync($e)){await _t();return}let e=JSON.parse(readFileSync($e,"utf-8")),t=e.version,o=e.betaVersion,r=await ae("latestVersion"),n=await ae("betaVersion");(E(t,r)===-1||o&&E(o,n)===-1)&&await _t(r,n);}async function lt(){let e={};await jn();try{e=JSON.parse(readFileSync($e,"utf-8"));}catch(t){}return e}async function mt(e,t){t=t??`Executing ${e}`;let o=_n({discardStdin:!1,spinner:{frames:[`\u280B ${R.gray(`${t}.`)}`,`\u2819 ${R.gray(`${t}..`)}`,`\u2839 ${R.gray(`${t}...`)}`,`\u2838 ${R.gray(`${t}.`)}`,`\u283C ${R.gray(`${t}..`)}`,`\u2834 ${R.gray(`${t}...`)}`,`\u2826 ${R.gray(`${t}.`)}`,`\u2827 ${R.gray(`${t}..`)}`,`\u2807 ${R.gray(`${t}...`)}`,`\u280F ${R.gray(`${t}.`)}`],interval:150}});o.start();let r=await new Promise(n=>{exec(e,(i,s)=>{i&&(a.error(`Exec cmd ${e} error`),process.exit(1)),n(s.trim());});});return o.stop(),r}async function J(e){return g.heroUIComponentsPackageMap[e]?g.heroUIComponentsPackageMap[e].version:(await Vt(e)).version}var Ht=e=>`https://unpkg.com/@heroui/react@${e}/dist/components.json`;async function _t(e,t){[e,t]=await Promise.all([e||ae("latestVersion"),t||ae("betaVersion")]);let o=Ht(e),[r,n]=await Promise.all([Nt(o),L("beta")&&t?Nt(Ht(t),!1):Promise.resolve([])]),i=n.filter(p=>!r.find(m=>m.name===p.name));r.push(...i);let s={betaComponents:n,betaVersion:t,components:r,version:e};return writeFileSync($e,JSON.stringify(s,null,2),"utf-8"),s}async function Nt(e,t=!0){let o;return await oraPromise(Io(async r=>{try{let n=await fetch(e,{body:null,headers:{"Content-Type":"application/json",accept:"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7"},method:"GET",mode:"cors"});o=JSON.parse(await n.text());}catch(n){r(n);}},{retries:3}),{failText(r){t&&a.prefix("error",`Update components data error: ${r}`),process.exit(1);},...t?{successText:R.greenBright(`Components data updated successfully!
`)}:{},text:"Fetching components data..."}),o}process.env.CI==="true";var Kt=resolve(fileURLToPath(import.meta.url),"../.."),ut=e=>resolve(Kt,e),Yt=resolve(fileURLToPath(import.meta.url),".."),Fn=existsSync(join(Yt,"components.json")),Ne=Fn?resolve(`${Yt}/.heroui-cli-cache`):resolve(join(Kt,".."),"node_modules/.heroui-cli-cache"),je=resolve(`${Ne}/data.json`);var Bn=30*6e4,ft=!1;function dt(e=ft){ft=!!e,!existsSync(Ne)&&(mkdirSync(Ne,{recursive:!0}),writeFileSync(je,JSON.stringify({}),"utf8"));}function Ve(){let e=readFileSync(je,"utf8");return JSON.parse(e)}function zt(e,t,o){dt();let r=o??Ve(),n=new Date,i=+n+Bn;r[e]={...t,date:n,expiredDate:i,expiredFormatDate:new Date(i).toString(),formatDate:n.toString()},writeFileSync(je,JSON.stringify(r,void 0,2),"utf-8");}function zn(){return +new Date}function Jn(e){return zn()-e}function Jt(e,t){if(ft)return !0;let r=(t??Ve())[e];return r?.expiredDate?Jn(r.expiredDate)>0:!0}async function Vt(e){let t=Ve();if(Jt(e,t)){let n={version:await mt(`npm view ${e} version`,`Fetching ${e} latest version`)};return zt(e,n,t),n}return t[e]}async function W(e,t){let o=Ve();if(Jt(e,o)){let i={execResult:await mt(e,t)};return zt(e,i,o),i.execResult}return o[e].execResult}async function Fe(e){return await W(`npm view ${e} dist-tags --json`,`Fetching ${e} tags`)}function Wt(e){return `@heroui/${e.replace("@heroui/","")}`}async function Se(e){if(g.betaHeroUIComponentsPackageMap[e])return g.betaHeroUIComponentsPackageMap[e].version;let t=await Fe(e);try{return JSON.parse(t).beta}catch(o){a.error(`Get beta version error: ${o}`),process.exit(1);}}async function Gt(e){return await Promise.all(e.map(Wt).map(async o=>{let r=await Se(o);return `${Wt(o)}@${r}`}))}function A(e,t=!0){let o;try{o=JSON.parse(readFileSync(e,"utf-8"));}catch(c){a.prefix("error",`Error reading package.json file: ${e} 
Error: ${c}`);}let r=o.devDependencies||{},n=o.dependencies||{},i={...r,...n},s=new Set(Object.keys(i)),p=g.heroUIComponents.map(c=>{let u=c.version,y=c.versionMode;if(s.has(c.package)){let f=G(i,c.package);u=t?`${f.currentVersion} new: ${u}`:f.currentVersion,y=f.versionMode;}return {...c,version:u,versionMode:y}}).filter(c=>s.has(c.package)),m=s.has(I);return {allDependencies:i,allDependenciesKeys:s,currentComponents:p,dependencies:n,devDependencies:r,isAllComponents:m,packageJson:o}}function Xt(e){return e.map(t=>{let r=g.heroUIComponentsMap[t]?.package;return r||t})}async function Qt(e,t,o=!0){let r=[];for(let n of e){let{currentVersion:i}=G(t,n),{versionMode:s}=G(t,n),p=(await W(`npm show ${n} homepage`)||"").replace(/\n/,""),m=(await W(`npm show ${n} description`)||"").replace(/\n/,""),c=g.heroUIComponentsPackageMap[n]?.version||await J(n);i=o?`${i} new: ${c}`:i;let u={description:m||"",docs:p||"",name:n,package:n,peerDependencies:{},status:"stable",style:"",version:i,versionMode:s};r.push(u);}return r}var Zt="heroui-cli",qe="framer-motion",Ke="tailwindcss",I="@heroui/react",F="@heroui/theme",oe="@heroui/system";var eo="@heroui",gt="https://heroui.com/docs/guide/installation#global-installation",Ye="https://heroui.com/docs/guide/installation#tailwind-css-setup";var to="https://heroui.com/docs/guide/installation#setup-pnpm-optional",Be="https://heroui.com/docs/guide/installation#provider-setup",v={checkPluginsRegex:/heroui(([\W\w]+)?)/,content:"./node_modules/@heroui/theme/dist/**/*.{js,ts,jsx,tsx}",darkMode:'darkMode: "class"',importContent:(e=!1)=>e?"import {heroui} from '@heroui/theme';":"const {heroui} = require('@heroui/theme');",plugins:"heroui()"},ze={content:(e,t)=>{e.forEach(n=>{let i=oo(n,t);e.push(...i);});let o=[...new Set(e.map(n=>n.style||n.name))];return o.length===1?`./node_modules/@heroui/theme/dist/components/${o[0]}.js`:`./node_modules/@heroui/theme/dist/components/(${o.reduce((n,i)=>n+=`${i}|`,"").replace(/\|$/,"")}).js`},plugins:"heroui()"},ht={import:"HeroUIProvider"},O={content:"public-hoist-pattern[]=*@heroui/*"};function oo(e,t){let o=e.name,r=P(`node_modules/@heroui/${o}`),n=[e];if(!existsSync(r)&&t){let s=P("node_modules/.pnpm"),p=Xn.sync(`**/@heroui/${o}`,{absolute:!0,cwd:s,onlyDirectories:!0})[0];if(p)r=p;else return n}let{currentComponents:i}=A(join(r,"package.json"));if(i.length)for(let s of i){let p=oo(s,t);n.push(...p);}return n}var g={debug:!1,beta:!1,cliLatestVersion:"",latestVersion:"",betaVersion:"",betaHeroUIComponents:[],betaHeroUIIComponentsKeys:[],betaHeroUIComponentsKeysSet:new Set,betaHeroUIComponentsMap:{},betaHeroUIComponentsPackageMap:{},betaHeroUIcomponentsPackages:[],heroUIComponents:[],heroUIComponentsKeys:[],heroUIComponentsKeysSet:new Set,heroUIComponentsMap:{},heroUIComponentsPackageMap:{},heroUIcomponentsPackages:[]};async function ae(e){let t=g[e];return t||(e==="latestVersion"?(t=await J(I),g[e]=t):e==="cliLatestVersion"?(t=await J(Zt),g[e]=t):e==="betaVersion"&&(t=await Se(I),g[e]=t)),t}function L(e){return g[e]}function Zn(e){let t=e.map(s=>s.name),o=e.map(s=>s.package),r=new Set(t),n=e.reduce((s,p)=>(s[p.name]=p,s),{}),i=e.reduce((s,p)=>(s[p.package]=p,s),{});return {heroUIComponentsKeys:t,heroUIComponentsKeysSet:r,heroUIComponentsMap:n,heroUIComponentsPackageMap:i,heroUIcomponentsPackages:o}}function yt({beta:e,heroUIComponents:t}){let{heroUIComponentsKeys:o,heroUIComponentsKeysSet:r,heroUIComponentsMap:n,heroUIComponentsPackageMap:i,heroUIcomponentsPackages:s}=Zn(t);e?(g.betaHeroUIComponents=t,g.betaHeroUIIComponentsKeys=o,g.betaHeroUIComponentsKeysSet=r,g.betaHeroUIComponentsMap=n,g.betaHeroUIComponentsPackageMap=i,g.betaHeroUIcomponentsPackages=s):(g.heroUIComponents=t,g.heroUIComponentsKeys=o,g.heroUIComponentsKeysSet=r,g.heroUIComponentsMap=n,g.heroUIComponentsPackageMap=i,g.heroUIcomponentsPackages=s);}var Je=["package","version","status","docs"],no=["package","version","status"];function ro(){return g.beta?{components:g.betaHeroUIComponents,componentsKeys:g.betaHeroUIIComponentsKeys,componentsKeysSet:g.betaHeroUIComponentsKeysSet,componentsMap:g.betaHeroUIComponentsMap,componentsPackageMap:g.betaHeroUIComponentsPackageMap,componentsPackages:g.betaHeroUIcomponentsPackages}:{components:g.heroUIComponents,componentsKeys:g.heroUIComponentsKeys,componentsKeysSet:g.heroUIComponentsKeysSet,componentsMap:g.heroUIComponentsMap,componentsPackageMap:g.heroUIComponentsPackageMap,componentsPackages:g.heroUIcomponentsPackages}}var M=/\u001b\[[\d;]+m/g,U=ct.round,xt="   ",Ue=`${U.vertical}${xt}`,io=`${xt}${U.vertical}${xt}`,so=/([\W\w]+)\snew:/,ao=/new:\s([\W\w]+)/;function pe({commandName:e,components:t,message:o=`Current installed components:
`,warnError:r=!0}){if(!t.length){r&&a.prefix("warn","No components found");return}let n={description:0,docs:0,name:0,originVersion:0,package:0,peerDependencies:0,status:0,style:0,version:0};for(let u of t)for(let y in u){let f=String(u[y]);if(y==="version"){let d=f.match(ao)?.[1],l=f.match(so)?.[1],x=D(po(l,d));n[y]=Math.max(n[y],Math.max(x.length,7)),n.originVersion=Math.max(n.originVersion,l.length);continue}n[y]=Math.max(n[y],f.length);}let i=t.reduce((u,y)=>{let f=Ue;for(let d of Je){let l=ne(y[d],n[d]);if(e!=="list"&&d==="version"){let x=l.match(so)?.[1]?.trim(),C=l.match(ao)?.[1]?.trim();x===C?(l=l.replace(/\snew:\s[\W\w]+(\s+)?/,""),l=ne(`${ne(l,n.originVersion)} \u{1F680}latest`,n[d]),l=l.replace("latest",R.magentaBright.underline("latest"))):C&&(l=ne(po(ne(x,n.originVersion),C),n[d]));}y.status==="stable"&&no.includes(d)?l=R.greenBright(l):y.status==="new"?l=R.magentaBright(l):y.status==="updated"&&(l=R.blueBright(l)),f+=l+io;}return u.push(f),u},[]),s=U.topLeft+Ue.replace(/.*/g,U.horizontal).slice(1),p=Ue,m=U.vertical+Ue.replace(/.*/g,U.horizontal).slice(1);for(let u of Je)s+=`${U.horizontal.padEnd(n[u]+7,U.horizontal)}`,p+=R.redBright(lo(u).padEnd(n[u]))+io,m+=`${U.horizontal.padEnd(n[u]+7,U.horizontal)}`;s=s.slice(0,-2)+U.topRight,m=m.slice(0,-2)+U.vertical;let c=U.bottomLeft+Ue.replace(/.*/g,U.horizontal).slice(1);for(let u of Je)c+=`${U.horizontal.padEnd(n[u]+7,U.horizontal)}`;c=c.slice(0,-2)+U.bottomRight,i=[s,p,m,...i,c],a.info(o),a.log(i.join(`
`));}function co(){a.newLine(),a.log(R.redBright("Environment Info:")),a.log(R.blueBright("  System:")),a.log(R.blueBright("    OS:"),process.platform),a.log(R.blueBright("    CPU:"),process.arch),a.log(R.greenBright("  Binaries:")),a.log(R.greenBright("    Node:"),process.version),a.newLine();}function Ee({align:e="center",borderStyle:t="round",center:o=!1,color:r,log:n=!0,padding:i=0,text:s,title:p}){let m=ct[t],c=r?Object.fromEntries(Object.entries(m).map(([S,T])=>[S,R[r](T)])):m,u=s.split(`
`),y=u.map(S=>S.replace(M,"")),f=i>0,d=i,l=o||f,x=y.reduce((S,T)=>T.length>S?T.length:S,0);x=f?x+d*4:x;let C=p?p.replace(M,""):"",h=p?C.length:0,b=x-h,w=2;for(;h+w+d>=x;)x+=Math.floor(h/2);b=x-h;let k=(()=>{if(p)if(e==="center"){let S=Math.floor(b/2)-1,T=Math.ceil(b/2)-1,it=S>0?c.horizontal.repeat(S):"",te=T>0?c.horizontal.repeat(T):"";return `${it} ${p} ${te}`}else return e==="left"?` ${p} ${c.horizontal.repeat(b-2)}`:`${c.horizontal.repeat(b-2)} ${p} `;return c.horizontal.repeat(x)})(),$=c.topLeft+k+c.topRight,H=c.bottomLeft+c.horizontal.repeat(x)+c.bottomRight,ee=u.reduce((S,T)=>{let it=T.replace(M,""),te=x-it.length,In=" ".repeat(te),Et=Math.floor(te/2),Tt=Math.ceil(te/2),Pn=Et>0?" ".repeat(Et):"",An=Tt>0?" ".repeat(Tt):"";if(o)S.push(`${c.vertical}${te?`${Pn}${T}${An}`:T}${c.vertical}`);else if(i){let $n=te-d*2;S.push(`${c.vertical}${" ".repeat(d*2)}${T}${" ".repeat($n)}${c.vertical}`);}else S.push(`${c.vertical}${te>0?`${T}${In}`:T}${c.vertical}`);return S},[]);if(l)for(let S=0;S<d;S++)ee.unshift(`${c.vertical}${" ".repeat(x)}${c.vertical}`),ee.push(`${c.vertical}${" ".repeat(x)}${c.vertical}`);return ee=[$,...ee,H],n&&a.log(ee.join(`
`)),ee.join(`
`)}function po(e,t){return `${R.white(`${e} ->`)} ${R.yellowBright(`${t} (new)`)}`}var We=/([\^~])/;function fo(e,t){return a.gradient(e),t}function lo(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}var le=(e,t)=>Xn.sync(e,{absolute:!0,cwd:_,deep:5,ignore:["node_modules/**","dist/**","build/**","coverage/**","public/**","out/**"],onlyFiles:!0,...t});function Qe(e){return e==="false"?!1:!!e}function go(e,t){return Object.fromEntries(Object.entries(e).filter(([o])=>!t.includes(o)))}function X(e,t){return e=q(e),t=q(t),Ge(e,t)?Ge(e,t):Xe(e,t)?Xe(e,t):uo(e,t)?uo(e,t):t}function Ge(e,t){let o=e.split("."),r=t.split(".");return o[0]!==r[0]?R.redBright(r.join(".")):""}function Xe(e,t){let o=e.split("."),r=t.split(".");return o[1]!==r[1]?`${R.white(r[0])}${R.white(".")}${R.cyanBright(r.slice(1).join("."))}`:""}function uo(e,t){let o=e.split("."),r=t.split(".");return o[2]!==r[2]?`${R.white(r.slice(0,2).join("."))}${R.white(".")}${R.greenBright(r.slice(2).join("."))}`:""}function G(e,t){let o=e[t].replace(We,""),r=e[t].match(We)?.[1]||"";return {currentVersion:o,versionMode:r}}function Ce(e){return {bun:{install:"add",remove:"remove",run:"run"},npm:{install:"install",remove:"uninstall",run:"run"},pnpm:{install:"add",remove:"remove",run:"run"},yarn:{install:"add",remove:"remove",run:"run"}}[e]}function q(e,t=!1){return e.split("||").map(n=>n.trim()).map(n=>n.replace(/^[<=>^~]+\s*/,"").trim()).sort((n,i)=>t?compareVersions(i,n):compareVersions(n,i))[0]}function ne(e,t){let o=e.replace(M,""),r=t-o.length>0?" ".repeat(t-o.length):"";return `${e}${r}`}function D(e){return e.replace(M,"")}var Ct=new Map;async function K(e,t){return new Promise((o,r)=>{try{let{cache:n=!0,logCmd:i=!0}=t||{};Ct.has(e)&&n&&o(Ct.get(e)),i&&(a.newLine(),a.log(`${e}`));let s=execSync(e,{stdio:"inherit",...t?go(t,["logCmd"]):{}});if(s){let p=s.toString();o(p),Ct.set(e,p);}o("");}catch(n){r(n);}})}var wt=e=>{isCancel(e)&&(cancel(`${R.red("\u2716")} Operation cancelled`),process.exit(0));},xo=async e=>{let t=await text(e);return wt(t),t},we=async e=>{let t=await select(e);return wt(t),t};var ho=spinner(),Co=async e=>{let{failText:t,successText:o,task:r,text:n}=e,i=null;try{ho.start(n),i=await(r instanceof Promise?r:Promise.resolve(r)),ho.stop(o);}catch{cancel(t??i??"Task failed"),process.exit(0);}return i},wo=async e=>{let t=await confirm(e);return wt(t),t},ko=async()=>{let t=readdirSync(process.cwd()).filter(r=>statSync(join(process.cwd(),r)).isDirectory()).map(r=>({label:r,value:r})).filter(r=>!["node_modules","dist","build","output",/^\./].some(n=>typeof n=="string"?r.value.includes(n):n.test(r.value)));return t.length?await we({message:"Please select the directory to add the codebase",options:t}):"src"};async function bo(e){let t=e.match(/^https?:\/\//)?.[0]??"",[o,r,n,i,s]=e.replace(t,"").split("/");return {baseStorageUrl:`${t}${o}/sandbox/files/${n}?sandboxId=${i}`,chatTitle:s,sandboxId:i,userId:r??""}}async function hr(e){let t=await fetch(e);if(!t.body)throw new Error(`Failed to download: ${e}`);return Readable.fromWeb(t.body)}async function Po(e,t){await Io(async o=>{try{await pipeline(await hr(t),gr.x({cwd:e}));}catch(r){o(new Error(`Failed to download ${t} Error: ${r}`));}},{retries:3});}async function Ao(e,t){let{fetchInfo:o,throwError:r=!0,...n}=t??{},i=`Fetching ${o??basename$1(e)}`,s=_n({discardStdin:!1,spinner:{frames:[`\u280B ${R.gray(`${i}.`)}`,`\u2819 ${R.gray(`${i}..`)}`,`\u2839 ${R.gray(`${i}...`)}`,`\u2838 ${R.gray(`${i}.`)}`,`\u283C ${R.gray(`${i}..`)}`,`\u2834 ${R.gray(`${i}...`)}`,`\u2826 ${R.gray(`${i}.`)}`,`\u2827 ${R.gray(`${i}..`)}`,`\u2807 ${R.gray(`${i}...`)}`,`\u280F ${R.gray(`${i}.`)}`],interval:150}});s.start();try{return await Io(async()=>{let p=await fetch(e,{...n,headers:{Accept:"application/json",...n?.headers}});if(!p.ok&&r)throw new Error(`Request failed with status ${p.status}`);return p},{retries:2})}catch(p){throw p instanceof Error&&p.message.includes("fetch failed")?new Error("Connection failed. Please check your network connection."):p}finally{s.stop();}}async function $o(e,t){return (await(await Ao(e,{fetchInfo:"codebase files",headers:{userId:t}})).json()).entries??{}}function Ze(e){let t=/import {?\s*([\W\w]+?)\s*}? from ["'](.+)["']/g,o=e.match(t)??[],r=[];for(let i of o)r.push(n(i));return r.length?r:[];function n(i){let s=/import {?\s*([\W\w]+?)\s*}? from ["'](.+)["']/,p=i.match(s)??[];return [p[1]??"",p[2]??""]}}function vo(e){return e.replace(/^["'`](.*)["'`]$/,"$1")}function B(e,t){let o=new RegExp(`\\s*${e}:\\s\\[([\\w\\W]*?)\\]\\s*`);return o.test(t)?t.match(o)?.[1]?.split(/,\s/g).map(r=>vo(r.trim())).filter(Boolean)??[]:[]}function ke(e,t,o,r){let n=new RegExp(`\\s*${e}:\\s\\[([\\w\\W]*?)\\]\\s*`),i=r??o.map(u=>JSON.stringify(u)).join(", ");if(n.test(t)){let u=e==="content"?`
  ${e}: [${i}]`:`
  ${e}: [${o}]`;return t.replace(n,u)}let s=t.split(`
`),p=s.findIndex(u=>u.includes("content:")),m=s.findIndex(u=>u.includes("module.exports =")),c=p!==-1?p-1:m!==-1?m:0;return e==="content"?s.splice(c+1,0,`  ${e}: [${i}],`):s.splice(c+1,0,`  ${e}: [${o.map(u=>vo(u))}],`),s.join(`
`)}function yr(e){return Ze(e).map(r=>r.find(n=>n.includes("./"))).filter(Boolean)}async function Uo(e){let{content:t,entries:o,filePath:r}=e,n=[];async function i(s){let p=yr(s);p.length!==0&&await Promise.all(p.map(async m=>{let c=o?.find(l=>basename$1(l.name).includes(basename$1(m))),u=c?.name.split(".").pop(),y=`${m.split("/").pop()}`,f=`src/${m.replace(/.*?\//,"")}${u?`.${u}`:""}`;if(n.some(l=>l.fileName===y))return;let d=c?.content??"";n.push({fileContent:d,fileName:y,filePath:f}),await i(d);}));}try{await i(t),n.push({fileContent:t,fileName:r.split("/").pop(),filePath:r});}catch(s){a.error(s),process.exit(1);}return n}function bt(e,t,o){if(t.includes("/")){let r=t.split("/").slice(0,-1).join("/");kt.mkdirSync(`${e}/${r}`,{recursive:!0}),kt.writeFileSync(`${e}/${t}`,o,"utf8");}else kt.writeFileSync(`${e}/${t}`,o,"utf8");}var kr=/^https?:\/\//,It="App.tsx";function et(e){return e.some(t=>kr.test(t))}async function To(e,t){V.intro(R.cyan("Starting to add HeroUI Chat codebase"));let o=resolve(process.cwd(),t.directory??await ko()),{baseStorageUrl:r,chatTitle:n,userId:i}=await bo(e[0]),s=n?`${n}.tsx`:void 0;kt.existsSync(o)||(a.error(`Directory ${o} does not exist`),process.exit(1));let m=await $o(r,i),c=m.find(y=>y.name.includes(It)),u=m.find(y=>y.name.includes("package.json"))?.content;if(c){let y=await Uo({content:c.content,entries:m,filePath:"src/App.tsx"});for(let f of y){if(f.fileName.includes(It)){bt(o,`${s||It}`,f.fileContent);continue}bt(o,`${f.filePath.replace("src/","")}`,f.fileContent);}}if(u){let y=JSON.parse(u),{allDependenciesKeys:f}=A(join$1(process.cwd(),"package.json")),d=Object.keys(y.dependencies).filter(l=>!f.has(l));if(d.length>0){V.log.warn(`The project is missing the following dependencies to run the codebase: ${d.join(", ")}`);let l=await wo({message:"Do you want to add the missing dependencies?"}),x=await N(),h=`${x} ${x==="npm"?"install":"add"} ${d.map(b=>`${b}@${y.dependencies[b]}`).join(" ")}`;if(l)try{await K(h);}catch{V.log.error(`Failed to install dependencies. Please add ${d.join(" ")} manually.`);}else V.note(`Run \`${h}\` to start!`,"Next steps");}}V.outro(R.green("\u2705 HeroUI Chat codebase added successfully!"));}function br(e,t){let o=0,r=e.length,n=t.length,i=0,s=0;for(;i<r&&s<n;)e[i]===t[s]&&(o++,s++),i++;return o}function Te(e,t){let o=0,r="";for(let n of e){let i=br(n,t);i>o&&(o=i,r=n);}return r!==""?r:null}function Pt(e,t){let o=Te(e,t);o?a.error(`Unknown option '${t}', Did you mean '${o}'?`):a.error(`Unknown option '${t}'`),process.exit(1);}var tt={name:"heroui-cli",private:!1,type:"module",license:"MIT",version:"1.2.3",homepage:"https://github.com/heroui-inc/heroui-cli#readme",description:"A CLI tool that unlocks seamless HeroUI integration (Previously NextUI CLI)",keywords:["UI","CLI","Tool","NextUI","Template","Integration","Add Component","HeroUI"],author:{name:"HeroUI",email:"support@heroui.com",url:"https://github.com/heroui-inc"},repository:{type:"git",url:"https://github.com/heroui-inc/heroui-cli.git"},bugs:{url:"https://github.com/heroui-inc/heroui-cli/issues"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},files:["dist"],bin:{heroui:"./dist/index.js"},main:"./dist/index.js",module:"./dist/index.js",types:"./dist/index.d.ts",scripts:{dev:"tsup --watch","link:cli":"pnpm link --global","link:remove":"pnpm uninstall --global heroui-cli",build:"tsup","update:components":"tsx src/scripts/update/update-components.ts","sync:docs":"tsx src/scripts/sync/sync.ts","clean:cache":"tsx src/scripts/cache/clean.ts",lint:"eslint . --max-warnings=0","lint:fix":"eslint . --max-warnings=0 --fix","check:prettier":"prettier --check .","check:types":"tsc --noEmit",changelog:"npx conventional-changelog -p angular -i CHANGELOG.md -s --commit-path .",release:"bumpp --execute='pnpm run changelog' --all",prepare:"husky install",prebuild:"pnpm run update:components",prepublishOnly:"pnpm run build"},dependencies:{"@clack/prompts":"0.7.0","@winches/prompts":"0.0.7","async-retry":"1.3.3",chalk:"5.3.0",commander:"11.0.0","compare-versions":"6.1.1","fast-glob":"3.3.2","find-up":"7.0.0","gradient-string":"2.0.2",ora:"8.0.1",pathe:"1.1.2",tar:"6.2.1"},devDependencies:{"@commitlint/cli":"17.7.1","@commitlint/config-conventional":"17.7.0","@types/gradient-string":"1.1.3","@types/node":"20.11.30","@typescript-eslint/eslint-plugin":"6.7.2","@typescript-eslint/parser":"6.7.2",bumpp:"9.4.0","clean-package":"2.2.0","commitlint-plugin-function-rules":"2.0.2","conventional-changelog-cli":"4.1.0",eslint:"8.50.0","eslint-config-prettier":"9.0.0","eslint-import-resolver-typescript":"3.6.1","eslint-plugin-import":"2.28.1","eslint-plugin-prettier":"5.0.0","eslint-plugin-sort-destructure-keys":"1.5.0","eslint-plugin-sort-keys-fix":"1.1.2","eslint-plugin-unicorn":"52.0.0","eslint-plugin-unused-imports":"3.0.0",husky:"8.0.3","lint-staged":"14.0.1",prettier:"3.3.2",tsup:"7.2.0",tsx:"4.7.1",typescript:"5.2.2"},engines:{pnpm:">=9.x"},packageManager:"pnpm@9.6.0"};function Ro(e,t=!0){let r=ro().components.filter(i=>i.peerDependencies[e]),n="";return t?n=r.map(p=>p.peerDependencies[e]).reduce((p,m)=>E(p,m)>0?m:p)||"":n=r[0]?.version||"",q(n)}async function me(e){return g.beta?await Se(e):await J(e)}async function Do(e){let o=Object.keys(e).filter(n=>!g.heroUIcomponentsPackages.includes(n)&&n.startsWith(eo));return o.length?await Promise.all(o.map(async n=>{let{currentVersion:i,versionMode:s}=G(e,n),p=await me(n),m=E(i,p)>=0;return {isLatest:m,latestVersion:X(i,m?i:p),package:n,version:i,versionMode:s}})):[]}var ue="".padEnd(7),Mo="Missing";async function Oo(e){let{all:t,allDependencies:o,isHeroUIAll:r,upgradeOptionList:n}=e,i=[],s=new Set,p=await Ar(t,r,o,s),m=await Do(o),c=n.map(l=>({...l,latestVersion:X(l.version,l.latestVersion)})),u=await Promise.all(n.map(l=>Re(l.package,o,s,l.peerDependencies))),y=await $r([...s]),f=[...c,...p.allOutputList],d=[...m,...u.flat(),...p.allPeerDepList,...y].filter((l,x,C)=>x===C.findIndex(h=>h.package===l.package)&&!f.some(h=>h.package===l.package));return Pr(f,d),i=[...f,...d].filter((l,x,C)=>!l.isLatest&&x===C.findIndex(h=>h.package===l.package)),vr(i),i}function Lo(e,t=!1){if(!e.length)return "";let o=[],r={latestVersion:0,package:0,version:0};for(let n of e)for(let i in n){if(!Object.prototype.hasOwnProperty.call(n,i)||!n[i])continue;i==="version"&&(n[i]=n[i].replace(We,""));let s=i==="version"?n[i].replace(M,"").length:n[i].length;r[i]=Math.max(r[i],s);}for(let n of e){if(n.isLatest){if(t)continue;o.push(`  ${R.white(`${`${n.package}@${n.versionMode||""}${n.latestVersion}`.padEnd(r.package+ue.length+ue.length)}`)}${ue}${R.greenBright("latest").padStart(r.version)}${ue}`);continue}o.push(`  ${R.white(`${n.package.padEnd(r.package+ue.length)}${ue}${ne(`${n.versionMode||""}${n.version}`,r.version)}  ->  ${n.versionMode||""}${n.latestVersion}`)}${ue}`);}return o.join(`
`)}async function Re(e,t,o,r){if(r=r||JSON.parse(await W(`npm show ${e} peerDependencies --json`))||{},!r||!Object.keys(r).length)return [];let n=[];for(let[i,s]of Object.entries(r)){if(n.some(y=>y.package===i))continue;let p=t[i],m=q(s);if(!p){o.add({name:i,version:m});continue}let{versionMode:c}=G(t,i),u=E(p,m)>=0;u?m=q(p):m=await J(i),n.push({isLatest:u,latestVersion:u?m:X(p,m),package:i,version:p,versionMode:c});}return n}function Pr(e,t){let o=e.length===1?"Component":"Components",r={components:{color:"blue",text:"",title:R.blue(o)},peerDependencies:{color:"yellow",text:"",title:R.yellow("PeerDependencies")}},n=Lo(e),i=Lo(t,!0),s=t.filter(p=>!p.isLatest);n.length&&Ee({...r.components,text:n}),a.newLine(),s.length&&a.log(R.gray(`Required min version: ${s.map(p=>`${p.package}>=${p.latestVersion.replace(M,"")}`).join(", ")}`)),i.length&&Ee({...r.peerDependencies,text:i});}async function Ar(e,t,o,r){if(!e||!t)return {allOutputList:[],allPeerDepList:[]};let n=await me(I),{currentVersion:i,versionMode:s}=G(o,I),p=X(i,n),m=E(i,n)>=0,c=await Re(I,o,r),u=await Re(F,o,r),y=[{isLatest:m,latestVersion:p,package:I,version:i,versionMode:s}],f=[...c,...u];return {allOutputList:y,allPeerDepList:f}}async function $r(e){let t=[];for(let o of e){let r={isLatest:!1,latestVersion:o.version,package:o.name,version:R.red(Mo),versionMode:""};t.push(r);}return t}function vr(e){let t={major:0,minor:0,patch:0};for(let r of e){if(r.version===Mo){t.major++;continue}let n=D(r.latestVersion);Ge(r.version,n)?t.major++:Xe(r.version,n)?t.minor++:t.patch++;}let o=Object.entries(t).reduce((r,[n,i])=>i?`${r}${R.yellowBright(i)} ${n}, `:r,"").replace(/, $/,"");return o&&(a.log(o),a.newLine()),t}function Ho({dependencies:e,devDependencies:t,upgradePackageList:o}){for(let r of o){let n=D(r.latestVersion);if(t[r.package]){t[r.package]=n;continue}e[r.package]=n;}}function fe(e,t){let{errorInfo:o,missingDependencies:r,tailwindName:n}=t;return e==="missingDependencies"?{level:"error",name:"missingDependencies",outputFn:()=>{a.log("You have not installed the required dependencies"),a.newLine(),a.log("The required dependencies are:"),r.forEach(i=>{a.log(`- ${i}`);}),a.newLine(),a.log(`See more info here: ${R.underline(gt)}`);}}:e==="incorrectTailwind"?{level:"error",name:"incorrectTailwind",outputFn:()=>{a.log(`Your ${n} is incorrect`),a.newLine(),a.log("The missing part is:"),o.forEach(i=>{a.log(`- need to add ${i}`);}),a.newLine(),a.log(`See more info here: ${R.underline(`${Ye}-1`)}`);}}:{level:"error",name:"incorrectApp",outputFn:()=>{a.log("Your App.tsx is incorrect"),a.newLine(),a.log("The missing part is:"),o.forEach(i=>{a.log(`- need to add ${i}`);}),a.newLine(),a.log(`See more info here: ${R.underline(gt)}`);}}}async function de(e,t,o){let r=[],{allDependencies:n,beta:i,packageNames:s,peerDependencies:p}=o??{},m=[],c=t.has(qe),u=t.has(Ke),y=`${Ke}@${Ro(Ke)}`;if(p){let f=await Sr({allDependencies:n,packageNames:s});m.push(...f);}if(e==="all"){let f=t.has(I);if(f&&c&&u&&!m.length)return [!0];!f&&r.push(i?`${I}@${g.betaVersion}`:I),!c&&r.push(qe),!u&&r.push(y);}else if(e==="partial"){let f=t.has(oe),d=t.has(F);if(c&&f&&d&&u&&!m.length)return [!0];let l=await Fe(oe),x=await Fe(F);!c&&r.push(qe),!f&&r.push(i?`${oe}@${l}`:oe),!d&&r.push(i?`${F}@${x}`:F),!u&&r.push(y);}return [!1,...r,...p?m:[]]}async function Sr(e){let{allDependencies:t,packageNames:o}=e,r=[];for(let n of o){let i=await Re(n,t,new Set);for(let s of i)if(!s.isLatest){let p=r.findIndex(u=>u.includes(s.package)),c=D(r[p]||"")?.match(/@([\d.]+)/)?.[1];c&&E(c,D(s.latestVersion))<=0&&r.splice(p,1),r.push(`${s.package}@${s.latestVersion}`);}}return r}function ge(e,t,o,r,n,i){if(e==="partial"&&!o.length)return [!0];let s=[],p=n??readFileSync(t,"utf-8"),m=B("content",p),c=B("plugins",p);if(e==="all"){let y=B("darkMode",p).some(l=>l.includes("class"))||/darkMode:\s*["'`]class/.test(p),f=m.some(l=>l.includes(v.content.replace("{js,ts,jsx,tsx}",""))),d=c.some(l=>v.checkPluginsRegex.test(l));if(y&&f&&d)return [!0];!y&&s.push(v.darkMode),!f&&s.push(v.content),!d&&s.push(v.plugins);}else if(e==="partial"){let u=ze.content(o,r),y=!1,f=m.some(l=>l.includes(v.content.replace("{js,ts,jsx,tsx}",""))?(y=!0,!0):l.includes(u));i&&y&&a.log(`
${R.yellow("Attention")} Individual components from HeroUI do not require the "${R.bold(v.content)}" in the tailwind config
For optimized bundle sizes, consider using "${R.bold(u)}" instead`);let d=c.some(l=>v.checkPluginsRegex.test(l));if(f&&d)return [!0];!f&&s.push(u),!d&&s.push(v.plugins);}return [!1,...s]}function De(e,t){let o=[];if(e==="all"||e==="partial"){let r=readFileSync(t,"utf-8"),i=Ze(r).some(([s])=>s.includes(ht.import));if(i)return [!0];!i&&o.push(ht.import);}return [!1,...o]}function be(e){let t=[],o;if(e){try{o=readFileSync(e,"utf-8");let r=o.includes(O.content);if(r)return [!0];!r&&t.push(O.content);}catch(r){t.push(`Error reading .npmrc file: ${e} 
Error: ${r}`);}return [!1,...t]}return [!1,...t]}async function Ie(e=[],t=!0){let o=[];for(let r of e)if(!g.heroUIComponentsKeysSet.has(r)){let n=Te(g.heroUIComponentsKeys,r);o.push([r,n]);}if(o.length){let[r,n]=o.reduce((i,[s,p])=>[i[0]+R.underline(s)+", ",i[1]+(p?R.underline(p)+", ":"")],["",""]);return t&&a.prefix("error",`Illegal components: ${r.replace(/, $/,"")}${n?`
${"".padEnd(12)}It may be a typo, did you mean ${n.replace(/, $/,"")}?`:""}`),!1}return !0}async function ot(e){try{await e();}catch(t){t&&(await we({message:`${R.red("Error: ")}a unexpected error occurred, run "pnpm install" maybe can fix it or report it as a bug`,options:[{label:"Re-run pnpm install",value:"re-run-pnpm-install"},{label:"Exit",value:"exit"}]})==="exit"&&process.exit(1),await K("pnpm install --force"),await e());}}async function $t(e,t=[]){if(L("debug"))for(let o of t)a.warn(`Debug: ${o}`);else await ot(()=>K(e));}function No(e,t){if(!e.length||!L("debug"))return;let{dependencies:o,packageJson:r}=A(t);for(let n of e){let i=g.heroUIComponentsMap[n];i&&(o[i.package]=`${i.package}@${i.version}`);}writeFileSync(t,JSON.stringify({...r,dependencies:o},null,2),"utf-8");}function jo(e,t){if(!e.length||!L("debug"))return;let{dependencies:o,packageJson:r}=A(t);for(let n of e){let i=g.heroUIComponentsMap[n];i&&delete o[i.package];}writeFileSync(t,JSON.stringify({...r,dependencies:o},null,2),"utf-8");}function Vo(e,t){let{format:o=!1,write:r=!0}=t,n=readFileSync(e,"utf-8");n=`import {HeroUIProvider} from "@heroui/react";
${n}`,n=Tr(n),r&&writeFileSync(e,n,"utf-8"),o&&execSync(`npx prettier --write ${e}`,{stdio:"ignore"});}function Tr(e){let t=/return\s*\(([\S\s]*?)\);/g;return e.replace(t,(r,n)=>`return (
      <HeroUIProvider>
        ${n.trim()}
      </HeroUIProvider>
    );`)}function rt(e,t){let{errorInfoList:o,format:r=!1,tailwindPath:n,write:i=!0}=t;if(!o.length)return;let s=readFileSync(n,"utf-8"),p=B("content",s),m=B("plugins",s);for(let c of o){let[u,y]=Rr(c);if(u==="content"){if(p.includes(v.content))continue;p=p.filter(d=>!d.includes("@heroui/theme/dist/")),p.push(y),s=ke("content",s,p,p.map((d,l,x)=>l===0?x.length===1?`
    ${JSON.stringify(d)}
`:`
    ${JSON.stringify(d)}`:x.length-1===l?`    ${JSON.stringify(d)}
  `:`    ${JSON.stringify(d)}`).join(`,
`));}else u==="plugins"&&(m.push(y),s=ke("plugins",s,m),s=`${v.importContent(n.endsWith(".ts"))}
${s}`);if(e==="all"&&u==="darkMode"){let f=s.indexOf("plugins")-1,d=v.darkMode;s=`${s.slice(0,f)} ${d},
${s.slice(f)}`;}}if(i&&writeFileSync(n,s,"utf-8"),r)try{execSync(`npx prettier --write ${n}`,{stdio:"ignore"});}catch{a.warn(`Prettier failed to format ${n}`);}}function Rr(e){return v.darkMode.includes(e)?["darkMode",e]:v.plugins.includes(e)?["plugins",e]:["content",e]}function Pe(e,t=!0,o=!0,r=void 0){if(!existsSync(e))t&&writeFileSync(e,O.content,"utf-8");else {let n=readFileSync(e,"utf-8");n=`${O.content}
${n}`,t&&writeFileSync(e,n,"utf-8");}if(!r){a.newLine(),a.log(`Added the required content in file: ${e}`),o&&!L("debug")&&(a.newLine(),a.log("Pnpm restructure will be run now"),execSync("pnpm install",{stdio:"inherit"}));return}r({message:`Added the required content in file: ${e}`,runInstall:o});}var Fo="https://codeload.github.com/heroui-inc/next-app-template/tar.gz/main",qo="https://codeload.github.com/heroui-inc/next-pages-template/tar.gz/main",Ko="https://codeload.github.com/heroui-inc/vite-template/tar.gz/main",Yo="https://codeload.github.com/heroui-inc/remix-template/tar.gz/main",Bo="https://github.com/heroui-inc/laravel-template/archive/refs/heads/master.zip",zo="next-app-template-main",Jo="next-pages-template-main",Wo="vite-template-main",Go="remix-template-main",Xo="laravel-template-main",Qo="next-app-template",Zo="next-pages-template",en="vite-template",tn="remix-template",on="laravel-template";function nn(e,t){return e==="all"?`// tailwind.config.js
const {heroui} = require("@heroui/react");

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    "./node_modules/@heroui/theme/dist/**/*.{js,ts,jsx,tsx}",
  ],
  theme: {
    extend: {},
  },
  darkMode: "class",
  plugins: [heroui()],
};`:`// tailwind.config.js
const {heroui} = require("@heroui/theme");

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: [
    ${JSON.stringify(t)},
  ],
  theme: {
    extend: {},
  },
  darkMode: "class",
  plugins: [heroui()],
};`}async function an(e,t){et(e)&&(await To(e,t),process.exit(0));let{addApp:o=!1,all:r=!1,appPath:n,beta:i=!1,packagePath:s=P("package.json"),tailwindPath:p=le("**/tailwind.config.(j|t)s")[0]}=t;var{allDependencies:m,allDependenciesKeys:x,currentComponents:C}=A(s);let c=t.prettier??x.has("prettier"),u=!!m[I];if(!e.length&&!r){let w=g.heroUIComponents.filter(k=>!C.some($=>$.name===k.name));w.length||(a.success("\u2705 All components have been added"),process.exit(0)),e=await ye("Which components would you like to add?",w.map(k=>({description:k.description,title:k.name,value:k.name})));}else r&&(e=[I]);if(!r&&!Ie(e,!0))return;var{allDependenciesKeys:x,currentComponents:C}=A(s);let y=C.map(w=>w.name),f=e.filter(w=>y.includes(w)||u&&w===I);if(f.length&&!L("debug")){a.prefix("error",`\u274C You have already added the following components: ${f.map(w=>R.underline(w)).join(", ")}`);return}if(o&&!n){a.prefix("error","\u274C App.(j|t)sx file not found. Please specify the appPath if the default search path does not locate your file.  'add --appPath=yourAppPath'");return}let d=await N(),l=d==="npm"?"install":"add";if(r){let[,...w]=await de("all",x,{allDependencies:m,beta:i,packageNames:[I],peerDependencies:!0});w=w.map(k=>D(k)),w.length&&(a.info(`Adding required dependencies: ${[...w].map(k=>R.underline(k)).join(", ")}`),await $t(`${d} ${l} ${[...w].join(" ")}`,w));}else {let w=i?await Gt(e):e.map(H=>g.heroUIComponentsMap[H].package),[,...k]=await de("partial",x,{allDependencies:m,beta:i,packageNames:w,peerDependencies:!0}),$=[...k,...w].map(H=>D(H));a.info(`Adding required dependencies: ${[...$].map(H=>R.underline(H)).join(", ")}`),await $t(`${d} ${l} ${[...$].join(" ")}`,$);}L("debug")&&No(e,s);var{allDependenciesKeys:x,currentComponents:C}=A(s);let h=r?"all":"partial",b=d==="pnpm";if(p){let[,...w]=ge(h,p,C,b,void 0,!0);rt(h,{errorInfoList:w,format:c,tailwindPath:p}),a.newLine(),a.log(`Tailwind CSS settings have been updated in: ${p}`);}else {let w=ze.content(C,b),k=nn(h,w),$=P("tailwind.config.js");writeFileSync($,k,"utf-8"),a.newLine(),a.info(`Tailwind CSS configuration file created at: ${$}`);}if(o&&n&&existsSync(n)){let[w]=De(h,n);w||(Vo(n,{format:c}),a.newLine(),a.info(`HeroUIProvider successfully added to the App file at: ${n}`),a.warn("Please check the placement of HeroUIProvider in the App file to ensure it's correctly integrated.'"));}if(d==="pnpm"){let w=P(".npmrc");if(!existsSync(w))writeFileSync(P(".npmrc"),O.content,"utf-8");else {let[k]=be(w);k||Pe(w);}}a.newLine(),a.success("\u2705 Components added successfully"),(x.has(I)||r)&&C.length&&(a.newLine(),a.log(`${R.yellow("Attention")} Individual components from HeroUI do not require the \`@heroui/react\` package. For optimized bundle sizes, consider using individual components.`),a.log("The redundant dependencies are:"),[...new Set(C)].forEach(w=>{a.log(`- ${w.package}`);})),a.newLine(),a.grey(`Please check the ${R.bold("HeroUIProvider")} whether in the correct place (ignore if added)
See more info here: ${Be}`),L("debug")&&jo(e,s),process.exit(0);}async function cn(e){let{appPath:t=le("**/App.(j|t)sx")[0],checkApp:o=!1,checkPnpm:r=!0,checkTailwind:n=!0,packagePath:i=P("package.json"),tailwindPath:s=le("**/tailwind.config.(j|t)s")}=e,p=Qe(o),m=Qe(r),c=Qe(n),u=[s].flat(),{allDependencies:y,allDependenciesKeys:f,currentComponents:d,isAllComponents:l}=A(i);if(!d.length&&!l){a.prefix("error",`\u274C No ${R.underline("HeroUI components")} found in your project. Please consult the installation guide at: https://heroui.com/docs/guide/installation#global-installation`);return}let x=[];if(l&&d.length&&x.push({level:"warn",name:"redundantDependencies",outputFn:()=>{a.log("You have installed some unnecessary dependencies. Consider removing them for optimal performance."),a.newLine(),a.log("The following dependencies are redundant:"),d.forEach(C=>{a.log(`- ${C.package}`);});}}),c&&!u.length&&x.push({level:"error",name:"missingTailwind",outputFn:()=>{a.log("Missing tailwind.config.(j|t)s file. To set up, visit: "+R.underline(Ye));}}),p&&!t&&x.push({level:"error",name:"missingApp",outputFn:()=>{a.log("App.(j|t)sx file not found. Please specify the path using: doctor --appPath=[yourAppPath]");}}),l){let[C,...h]=await de("all",f,{allDependencies:y,packageNames:[I],peerDependencies:!0});if(d.length){let[b,...w]=await de("partial",f,{allDependencies:y,packageNames:d.map(k=>k.package),peerDependencies:!0});C=b||C,h=[...w,...h].filter((k,$,H)=>(k=D(k).replace(/@[\d.]+/g,""),H.findIndex(ee=>D(ee).replace(/@[\d.]+/g,"")===k)===$));}if(C||x.push(fe("missingDependencies",{missingDependencies:h})),c)for(let b of u){let[w,...k]=ge("all",b);if(!w){let $=basename(b);x.push(fe("incorrectTailwind",{errorInfo:k,tailwindName:$}));}}if(p&&t){let[b,...w]=De("all",t);b||x.push(fe("incorrectApp",{errorInfo:w}));}}else if(d.length){let[C,...h]=await de("partial",f,{allDependencies:y,packageNames:d.map(b=>b.package),peerDependencies:!0});if(C||x.push(fe("missingDependencies",{missingDependencies:h})),c){let b=await N()==="pnpm";for(let w of u){let[k,...$]=ge("partial",w,d,b,void 0,!0);if(!k){let H=basename(w);x.push(fe("incorrectTailwind",{errorInfo:$,tailwindName:H}));}}}if(p&&t){let[b,...w]=De("partial",t);b||x.push(fe("incorrectApp",{errorInfo:w}));}}if(m&&await N()==="pnpm"){let h=P(".npmrc"),[b,...w]=be(h);b||x.push({level:"error",name:"incorrectPnpm",outputFn:()=>{a.log(`The pnpm setup is incorrect 
Please update your configuration according to the guidelines provided at: `+R.underline(to)),a.newLine(),a.log("Required changes:"),w.forEach(k=>{a.log(`- Add ${k}`);});}});}if(!x.length){a.newLine(),a.success("\u2705 Your project has no detected issues.");return}a.prefix("error",`\u274C Your project has ${R.underline(x.length)} issue${x.length===1?"":"s"} that require attention`),a.newLine();for(let C=0;C<x.length;C++){let h=x[C];a[h.level](`\u2757\uFE0FIssue ${C+1}: ${R.bold(h.name)}`),a.newLine(),h.outputFn(),a.newLine();}process.exit(0);}async function ln(e){let{packagePath:t=P("package.json")}=e,{currentComponents:o}=A(t);pe({components:o}),co(),process.exit(0);}var Lr="package-lock=true";function mn(e){writeFileSync(e,Lr,"utf-8");}function un(e,t){e&&(Object.keys(he).includes(e)||Pt(Object.keys(he),e)),t&&(_e.includes(t)||Pt(_e,t));}var he={app:Qo,laravel:on,pages:Zo,remix:tn,vite:en};async function dn(e,t){let{package:o="npm",template:r}=t;un(r,o),V.intro(R.cyanBright("Create a new project"));let{packageName:n,projectName:i,template:s}=await Hr(o,e,r),{run:p}=Ce(n);existsSync(ut(`${_}/${i}`))&&(V.cancel(`The project name ${R.redBright(i)} already exists`),process.exit(1)),s==="app"?(await Oe(Fo),He(zo,i)):s==="pages"?(await Oe(qo),He(Jo,i)):s==="vite"?(await Oe(Ko),He(Wo,i)):s==="remix"?(await Oe(Yo),He(Go,i)):s==="laravel"?(await Oe(Bo),He(Xo,i)):_exhaustiveCheck=s;let m=ut(`${_}/${i}/.npmrc`);mn(m),n==="pnpm"&&Pe(m,!0,!1,({message:c})=>{V.log.message(c);}),V.note(`cd ${R.cyanBright(i)}
${R.cyanBright(n)} install`,"Next steps"),V.outro(`\u{1F680} Get started with ${R.cyanBright(`${n} ${p} dev`)}`),process.exit(0);}async function Oe(e){await Co({failText:"Template creation failed",successText:"Template created successfully!",task:Po(_,e),text:"Creating template..."});}function He(e,t){try{renameSync(join(_,e),join(_,t));}catch(o){o&&(V.cancel(`rename Error: ${o}`),process.exit(0));}}async function Hr(e,t,o){return o=await we({initialValue:o,message:"Select a template (Enter to select)",options:[{hint:"A Next.js 15 with app directory template pre-configured with HeroUI (v2) and Tailwind CSS.",label:"App",value:"app"},{hint:"A Next.js 15 with pages directory template pre-configured with HeroUI (v2) and Tailwind CSS.",label:"Pages",value:"pages"},{hint:"A Vite template pre-configured with HeroUI (v2) and Tailwind CSS.",label:"Vite",value:"vite"},{hint:"A Remix template pre-configured with HeroUI (v2) and Tailwind CSS.",label:"Remix",value:"remix"},{hint:"A Laravel template pre-configured with HeroUI (v2) and Tailwind CSS.",label:"Laravel",value:"laravel"}]}),t=await xo({initialValue:t??he[o],message:"New project name (Enter to skip with default name)",placeholder:t??he[o]}),e=await we({initialValue:e,message:"Select a package manager (Enter to select)",options:[{label:R.gray("npm"),value:"npm"},{label:R.gray("yarn"),value:"yarn"},{label:R.gray("pnpm"),value:"pnpm"},{label:R.gray("bun"),value:"bun"}]}),{packageName:e,projectName:t,template:o}}async function gn(e){let{packagePath:t=P("package.json"),remote:o=!1}=e,r=g.heroUIComponents;try{if(!o){let{currentComponents:n}=await A(t);r=n;}if(!r.length){a.warn(`No HeroUI components detected in the specified package.json at: ${t}`);return}o?pe({commandName:"list",components:r}):pe({components:r});}catch(n){a.prefix("error",`An error occurred while attempting to list the components: ${n}`);}process.exit(0);}async function hn(e,t){let{remove:o}=Ce(t);await K(`${t} ${o} ${e.join(" ")}`);}async function yn(e,t){let{currentComponents:o,isHeroUIAll:r,isPnpm:n,prettier:i,tailwindPath:s}=t;if(s&&!existsSync(s)){a.prefix("warn","No tailwind.config.(j|t)s found remove action skipped");return}let p=readFileSync(s,"utf-8"),m=B("content",p),c=B("plugins",p),u=m.some(f=>f.includes(v.content));if(!o.length&&!r){let f=c.findIndex(d=>d.includes("heroui"));f!==-1&&c.splice(f,1),p=ke("plugins",p,c),p=p.replace(/(const|var|let|import)[\W\w]+?heroui.*?;\n/,"");}if(!u){for(;m.some(f=>f.includes("heroui"));)m.splice(m.findIndex(f=>f.includes("heroui")),1);p=ke("content",p,m);}writeFileSync(s,p,"utf-8");let[,...y]=ge(e,s,o,n,void 0,!0);rt(e,{errorInfoList:y,format:i,tailwindPath:s}),a.newLine(),a.info(`Remove the removed components tailwind content in file: ${s}`);}async function Cn(e,t){let{all:o=!1,packagePath:r=P("package.json"),tailwindPath:n=le("**/tailwind.config.(j|t)s")[0]}=t;var{allDependencies:d,allDependenciesKeys:i,currentComponents:l}=A(r);let s=await N(),p=t.prettier??i.has("prettier"),m=!!d[I];if(!l.length&&!m){a.prefix("error",`No HeroUI components detected in your package.json at: ${r}`);return}if(o||m)e=m?[I]:l.map(C=>C.package);else if(!e.length)e=await ye("Select the components to remove",l.map(C=>({title:C.package,value:C.package})));else {if(!Ie(e))return;e=Xt(e);}let c=e.includes(I)?await Qt(e,d):l.filter(C=>e.some(h=>h.includes(C.package)||h.includes(C.name)));pe({components:c,message:R.yellowBright("\u2757\uFE0F Components slated for removal:")}),await se("Confirm removal of these components:",[{title:"Yes",value:!0},{title:"No",value:!1}])||process.exit(0);let y=[...e];l.filter(C=>!e.includes(C.package)).length||(d[F]&&y.push(F),d[oe]&&y.push(oe)),await hn(y,s);var{allDependencies:d,currentComponents:l}=A(r,!1);if(m=!!d[I],yn(m?"all":"partial",{currentComponents:l,isHeroUIAll:m,isPnpm:s==="pnpm",prettier:p,tailwindPath:n}),!l.length&&!m){if(s==="pnpm"){let C=P(".npmrc");if(existsSync(C)){let h=readFileSync(C,"utf-8");h=h.replace(O.content,""),a.newLine(),a.info("Removing specified .npmrc file content"),writeFileSync(C,h,"utf-8");}}a.newLine(),a.warn(`No HeroUI components remain installed. Ensure the HeroUIProvider is also removed if necessary.
For more information, visit: ${Be}`);}a.newLine(),a.success(`\u2705 Successfully removed the specified HeroUI components: ${e.map(C=>R.underline(C)).join(", ")}`),process.exit(0);}async function wn(e){if(e==="pnpm"){let t=P(".npmrc");if(!existsSync(t))writeFileSync(P(".npmrc"),O.content,"utf-8");else {let[o]=be(t);o||Pe(t);}}}function kn(e,t,o){let r=e.match(/(^\w+$)/)?.[1];if(r)return t.includes(r);let n=E(e,t);return o&&n===1&&!e.includes("beta")?!1:n>=0}async function bn(e,t){let{all:o=!1,beta:r=!1,packagePath:n=P("package.json"),write:i=!1}=t,{allDependencies:s,currentComponents:p,dependencies:m,devDependencies:c,packageJson:u}=A(n,!1),y=!!s[I],f=[];if(await Promise.all(p.map(async h=>{let b=await me(h.package),w=kn(h.version,b,r);f.push({...h,isLatest:w,latestVersion:b});})),!f.length&&!y){a.prefix("error",`No HeroUI components detected in your package.json at: ${n}`);return}if(o)e=p.map(h=>h.package);else if(e.length){if(!Ie(e))return}else {if(y){let h=await me(I),b={isLatest:E(h,q(s[I]))<=0,latestVersion:h,package:I,version:q(s[I])};f.push(b);}f.every(h=>h.isLatest)&&(a.success("\u2705 All HeroUI packages are up to date"),process.exit(0)),e=await ye("Select the components to upgrade",f.map(h=>{let b=kn(h.version,h.latestVersion,r);return {disabled:b,disabledMessage:"Already up to date",title:`${h.package}${b?"":`@${h.version} -> ${X(h.version,h.latestVersion)}`}`,value:h.package}}));}e=e.map(h=>g.heroUIComponentsMap[h]?.package?g.heroUIComponentsMap[h].package:h);let d=f.filter(h=>e.includes(h.package)),l=await Oo({all:o,allDependencies:s,isHeroUIAll:y,upgradeOptionList:d}),x=[],C=await N();if(l.length){let h=await se("Would you like to proceed with the upgrade?",[{title:"Yes",value:!0},{description:"Select this if you wish to exclude certain packages from the upgrade",title:"No",value:!1}]),{install:b}=Ce(C);h||await se("Would you like to exclude any packages from the upgrade?",[{description:"Select this to choose packages to exclude",title:"Yes",value:!0},{description:"Select this to proceed without excluding any packages",title:"No",value:!1}])&&(x=await Mt("Select the packages you want to exclude from the upgrade:",l.map(k=>({description:`${k.version} -> ${X(k.version,k.latestVersion)}`,title:k.package,value:k.package})))),l=l.filter(w=>!x.some(k=>w.package===k)),i?(Ho({dependencies:m,devDependencies:c,upgradePackageList:l}),kt.writeFileSync(n,JSON.stringify(u,null,2),"utf-8"),a.newLine(),a.success("\u2705 Upgrade version written to package.json"),process.exit(0)):await ot(()=>K(`${C} ${b} ${l.reduce((w,k,$)=>`${w}${$===0?"":" "}${k.package}@${k.latestVersion.replace(M,"")}`,"")}`));}wn(C),a.newLine(),a.success("\u2705 Upgrade complete. All components are up to date."),process.exit(0);}var Ut=["add","env","init","list","upgrade","doctor","remove"],z=new Command;z.name("heroui").usage("[command]").description(fo(`
HeroUI CLI v${tt.version}
`,"")).version(tt.version,"-v, --version","Output the current version").helpOption("-h, --help","Display help for command").allowUnknownOption().option("--no-cache","Disable cache, by default data will be cached for 30m after the first request").option("-d, --debug","Debug mode will not install dependencies").action(async(e,t)=>{let o=!1;if(t){let r=t.args?.[0];if(r&&!Ut.includes(r)){o=!0;let n=Te(Ut,r);n?a.error(`Unknown command '${r}', Did you mean '${R.underline(n)}'?`):a.error(`Unknown command '${r}'`);}}if(!o){let n=(await W("heroui --help")).split(`
`);n=n.filter(i=>i&&!i.includes("HeroUI CLI v")),n=n.map(i=>{let s=i.match(/(\w+)\s\[/)?.[1];return s?i.replace(s,R.cyan(s)):i}),a.log(n.join(`
`));}process.exit(0);});z.command("init").description("Initializes a new project").argument("[projectName]","Name of the project to initialize").option("-t --template [string]",`Specify a template for the new project, e.g. ${Object.keys(he).join(", ")}`).option("-p --package [string]","The package manager to use for the new project","npm").action(dn);z.command("add").description(`1. Adds components to your project
2. Adds HeroUI Chat codebase to your project`).argument("[targets...]","Names of components, HeroUI Chat codebase url to add").option("-a --all [boolean]","Add all components",!1).option("-p --packagePath [string]","Specify the path to the package.json file").option("-tw --tailwindPath [string]","Specify the path to the tailwind.config.js file").option("-app --appPath [string]","Specify the path to the App.tsx file").option("--prettier [boolean]","Apply Prettier formatting to the added content").option("--addApp [boolean]","Include App.tsx file content that requires a provider",!1).option("-b --beta [boolean]","Add beta components",!1).option("-d --directory [string]","Add HeroUI Chat codebase to a specific directory").action(an);z.command("upgrade").description("Upgrades project components to the latest versions").argument("[components...]","Names of components to upgrade").option("-p --packagePath [string]","Specify the path to the package.json file").option("-a --all [boolean]","Upgrade all components",!1).option("-w --write [boolean]","Write the upgrade version to package.json file",!1).option("-b --beta [boolean]","Upgrade beta components",!1).action(bn);z.command("remove").description("Removes components from the project").argument("[components...]","Names of components to remove").option("-p --packagePath [string]","Specify the path to the package.json file").option("-a --all [boolean]","Remove all components",!1).option("-tw --tailwindPath [string]","Specify the path to the tailwind.config.js file").option("--prettier [boolean]","Apply Prettier formatting to the added content").action(Cn);z.command("list").description("Lists all components, showing status, descriptions, and versions").option("-p --packagePath [string]","Specify the path to the package.json file").option("-r --remote","List all components available remotely").action(gn);z.command("env").description("Displays debugging information for the local environment").option("-p --packagePath [string]","Specify the path to the package.json file").action(ln);z.command("doctor").description("Checks for issues in the project").option("-p --packagePath [string]","Specify the path to the package.json file").option("-tw --tailwindPath [string]","Specify the path to the tailwind.config.js file").option("-app --appPath [string]","Specify the path to the App.tsx file").option("-ca --checkApp [boolean]","Check the App.tsx file",!1).option("-ct --checkTailwind [boolean]","Check the tailwind.config.js file",!0).option("-cp --checkPnpm [boolean]","Check for Pnpm",!0).action(cn);z.hook("preAction",async e=>{let t=e.args?.[0],o=e.rawArgs.slice(2),r=o.includes("--no-cache"),n=o.includes("--debug")||o.includes("-d"),i=e.args?.slice(1);if(et(i)||!t)return;if(dt(r),g.debug=n,g.beta=o.includes("-b")||o.includes("--beta"),t&&Ut.includes(t)){let m=(await lt()).components,c=(await lt()).betaComponents;yt({beta:!1,heroUIComponents:m}),g.beta&&yt({beta:!0,heroUIComponents:c});}let[s]=await Promise.all([ae("cliLatestVersion")]);g.cliLatestVersion=s;let p=tt.version;E(p,s)===-1&&(Ee({center:!0,color:"yellow",padding:1,text:`${R.gray(`Available upgrade: v${p} -> ${R.greenBright(`v${s}`)}
Run \`${R.cyan("npm install -g heroui-cli@latest")}\` to upgrade
Changelog: ${R.underline("https://github.com/heroui-inc/heroui-cli/releases")}`)}`,title:st("HeroUI CLI")}),a.newLine());});z.parseAsync(process.argv).catch(async e=>{a.newLine(),a.error("Unexpected error. Please report it as a bug:"),a.log(e),a.newLine(),process.exit(1);});
//# sourceMappingURL=out.js.map
//# sourceMappingURL=index.js.map