UNPKG

@v0xoss/oss-cli

Version:

A CLI tool that unlocks seamless HeroUI integration (Previously NextUI CLI)

88 lines (85 loc) 49.7 kB
#!/usr/bin/env node import E from 'chalk'; import { Command } from 'commander'; import Pt from 'gradient-string'; import pr, { existsSync, readFileSync, mkdirSync, writeFileSync, renameSync } from 'node:fs'; import { exec, execSync } from 'node:child_process'; import sn from 'async-retry'; import { compareVersions } from 'compare-versions'; import pn, { oraPromise } from 'ora'; import { fileURLToPath } from 'node:url'; import Vn, { resolve, join, basename } from 'pathe'; import Cn from 'fast-glob'; import * as j from '@clack/prompts'; import { spinner, text, select, cancel, isCancel } from '@clack/prompts'; import { findUp } from 'find-up'; import ft from '@winches/prompts'; import { Readable } from 'node:stream'; import { pipeline } from 'node:stream/promises'; import Wn from 'tar'; var vt=["#F54180","#338EF7"],Ze=Pt(...vt),Zo=Ze("v0xoss CLI:"),s=class{constructor(){}static log(...t){console.log(...t);}static info(...t){console.info(...t.map(o=>E.blue(o)));}static success(...t){console.info(...t.map(o=>E.green(o)));}static warn(...t){console.warn(...t.map(o=>E.yellow(o)));}static error(...t){console.error(...t.map(o=>E.red(o)));}static grey(...t){console.log(...t.map(o=>E.gray(o)));}static gradient(t,o){this.log(Pt(...o?.colors??vt)(String(t)));}static prefix(t,...o){return this[t](Zo,...o)}static newLine(t){t||(t=1);for(let o=0;o<t;o++)this.log();}};function en(e,t){let o=0,n=e.length,r=t.length,i=0,a=0;for(;i<n&&a<r;)e[i]===t[a]&&(o++,a++),i++;return o}function be(e,t){let o=0,n="";for(let r of e){let i=en(r,t);i>o&&(o=i,n=r);}return n!==""?n:null}function et(e,t){let o=be(e,t);o?s.error(`Unknown option '${t}', Did you mean '${o}'?`):s.error(`Unknown option '${t}'`),process.exit(1);}var tt={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"}};var _=process.cwd(),v=e=>resolve(_,e),Pe=resolve(fileURLToPath(import.meta.url),"../components.json");function L(e="",t=""){try{return compareVersions(e,t)}catch{return 0}}async function ln(){if(!existsSync(Pe)){await St();return}let e=JSON.parse(readFileSync(Pe,"utf-8")),t=e.version,o=e.betaVersion,n=await G("latestVersion"),r=await G("betaVersion");(L(t,n)===-1||L(o,r)===-1)&&await St(n,r);}async function ot(){let e={};await ln();try{e=JSON.parse(readFileSync(Pe,"utf-8"));}catch(t){}return e}async function nt(e,t){t=t??`Executing ${e}`;let o=pn({discardStdin:!1,spinner:{frames:[`\u280B ${E.gray(`${t}.`)}`,`\u2819 ${E.gray(`${t}..`)}`,`\u2839 ${E.gray(`${t}...`)}`,`\u2838 ${E.gray(`${t}.`)}`,`\u283C ${E.gray(`${t}..`)}`,`\u2834 ${E.gray(`${t}...`)}`,`\u2826 ${E.gray(`${t}.`)}`,`\u2827 ${E.gray(`${t}..`)}`,`\u2807 ${E.gray(`${t}...`)}`,`\u280F ${E.gray(`${t}.`)}`],interval:150}});o.start();let n=await new Promise(r=>{exec(e,(i,a)=>{i&&(s.error(`Exec cmd ${e} error`),process.exit(1)),r(a.trim());});});return o.stop(),n}async function K(e){return x.heroUIComponentsPackageMap[e]?x.heroUIComponentsPackageMap[e].version:(await Tt(e)).version}var At=e=>`https://unpkg.com/@v0xoss/react@${e}/dist/components.json`;async function St(e,t){[e,t]=await Promise.all([e||G("latestVersion"),t||G("betaVersion")]);let o=At(e),[n,r]=await Promise.all([$t(o),R("beta")?$t(At(t),!1):Promise.resolve([])]),i=r.filter(p=>!n.find(m=>m.name===p.name));n.push(...i);let a={betaComponents:r,betaVersion:t,components:n,version:e};return writeFileSync(Pe,JSON.stringify(a,null,2),"utf-8"),a}async function $t(e,t=!0){let o;return await oraPromise(sn(async n=>{try{let r=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 r.text());}catch(r){n(r);}},{retries:3}),{failText(n){t&&s.prefix("error",`Update components data error: ${n}`),process.exit(1);},...t?{successText:E.greenBright(`Components data updated successfully! `)}:{},text:"Fetching components data..."}),o}process.env.CI==="true";var Lt=resolve(fileURLToPath(import.meta.url),"../.."),rt=e=>resolve(Lt,e),Rt=resolve(fileURLToPath(import.meta.url),".."),un=existsSync(join(Rt,"components.json")),Me=un?resolve(`${Rt}/.v0xoss-cli-cache`):resolve(join(Lt,".."),"node_modules/.v0xoss-cli-cache"),Oe=resolve(`${Me}/data.json`);var hn=30*6e4,it=!1;function st(e=it){it=!!e,!existsSync(Me)&&(mkdirSync(Me,{recursive:!0}),writeFileSync(Oe,JSON.stringify({}),"utf8"));}function Ne(){let e=readFileSync(Oe,"utf8");return JSON.parse(e)}function Ot(e,t,o){st();let n=o??Ne(),r=new Date,i=+r+hn;n[e]={...t,date:r,expiredDate:i,expiredFormatDate:new Date(i).toString(),formatDate:r.toString()},writeFileSync(Oe,JSON.stringify(n,void 0,2),"utf-8");}function xn(){return +new Date}function yn(e){return xn()-e}function Nt(e,t){if(it)return !0;let n=(t??Ne())[e];return n?.expiredDate?yn(n.expiredDate)>0:!0}async function Tt(e){let t=Ne();if(Nt(e,t)){let r={version:await nt(`npm view ${e} version`,`Fetching ${e} latest version`)};return Ot(e,r,t),r}return t[e]}async function B(e,t){let o=Ne();if(Nt(e,o)){let i={execResult:await nt(e,t)};return Ot(e,i,o),i.execResult}return o[e].execResult}async function He(e){return await B(`npm view ${e} dist-tags --json`,`Fetching ${e} tags`)}function Ht(e){return `@heroui/${e.replace("@heroui/","")}`}async function ve(e){if(x.betaHeroUIComponentsPackageMap[e])return x.betaHeroUIComponentsPackageMap[e].version;let t=await He(e);try{return JSON.parse(t).beta}catch(o){s.error(`Get beta version error: ${o}`),process.exit(1);}}async function _t(e){return await Promise.all(e.map(Ht).map(async o=>{let n=await ve(o);return `${Ht(o)}@${n}`}))}var _e=/([\^~])/;function Ft(e,t){return s.gradient(e),t}function qt(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}var re=(e,t)=>Cn.sync(e,{absolute:!0,cwd:_,deep:5,ignore:["node_modules/**","dist/**","build/**","coverage/**","public/**","out/**"],onlyFiles:!0,...t});function Fe(e){return e==="false"?!1:!!e}function Yt(e,t){return Object.fromEntries(Object.entries(e).filter(([o])=>!t.includes(o)))}function ie(e,t){return e=Q(e),t=Q(t),Ve(e,t)?Ve(e,t):je(e,t)?je(e,t):jt(e,t)?jt(e,t):t}function Ve(e,t){let o=e.split("."),n=t.split(".");return o[0]!==n[0]?E.redBright(n.join(".")):""}function je(e,t){let o=e.split("."),n=t.split(".");return o[1]!==n[1]?`${E.white(n[0])}${E.white(".")}${E.cyanBright(n.slice(1).join("."))}`:""}function jt(e,t){let o=e.split("."),n=t.split(".");return o[2]!==n[2]?`${E.white(n.slice(0,2).join("."))}${E.white(".")}${E.greenBright(n.slice(2).join("."))}`:""}function se(e,t){let o=e[t].replace(_e,""),n=e[t].match(_e)?.[1]||"";return {currentVersion:o,versionMode:n}}function ge(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(r=>r.trim()).map(r=>r.replace(/^[<=>^~]+\s*/,"").trim()).sort((r,i)=>t?compareVersions(i,r):compareVersions(r,i))[0]}function X(e,t){let o=e.replace(M,""),n=t-o.length>0?" ".repeat(t-o.length):"";return `${e}${n}`}function D(e){return e.replace(M,"")}function I(e,t=!0){let o;try{o=JSON.parse(readFileSync(e,"utf-8"));}catch(c){s.prefix("error",`Error reading package.json file: ${e} Error: ${c}`);}let n=o.devDependencies||{},r=o.dependencies||{},i={...n,...r},a=new Set(Object.keys(i)),p=x.heroUIComponents.map(c=>{let u=c.version,y=c.versionMode;if(a.has(c.package)){let f=se(i,c.package);u=t?`${f.currentVersion} new: ${u}`:f.currentVersion,y=f.versionMode;}return {...c,version:u,versionMode:y}}).filter(c=>a.has(c.package)),m=a.has(b);return {allDependencies:i,allDependenciesKeys:a,currentComponents:p,dependencies:r,devDependencies:n,isAllComponents:m,packageJson:o}}function Kt(e){return e.map(t=>{let n=x.heroUIComponentsMap[t]?.package;return n||t})}async function Bt(e,t,o=!0){let n=[];for(let r of e){let{currentVersion:i}=se(t,r),{versionMode:a}=se(t,r),p=(await B(`npm show ${r} homepage`)||"").replace(/\n/,""),m=(await B(`npm show ${r} description`)||"").replace(/\n/,""),c=x.heroUIComponentsPackageMap[r]?.version||await K(r);i=o?`${i} new: ${c}`:i;let u={description:m||"",docs:p||"",name:r,package:r,peerDependencies:{},status:"stable",style:"",version:i,versionMode:a};n.push(u);}return n}var zt="heroui-cli",Ie="framer-motion",Ae="tailwindcss",b="@v0xoss/react",F="@v0xoss/theme",Z="@v0xoss/system";var at="https://heroui.com/docs/guide/installation#global-installation",qe="https://heroui.com/docs/guide/installation#tailwind-css-setup";var Jt="https://heroui.com/docs/guide/installation#setup-pnpm-optional",Ye="https://heroui.com/docs/guide/installation#provider-setup",S={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()"},Ke={content:(e,t)=>{e.forEach(r=>{let i=Wt(r,t);e.push(...i);});let o=[...new Set(e.map(r=>r.style||r.name))];return o.length===1?`./node_modules/@heroui/theme/dist/components/${o[0]}.js`:`./node_modules/@heroui/theme/dist/components/(${o.reduce((r,i)=>r+=`${i}|`,"").replace(/\|$/,"")}).js`},plugins:"heroui()"},pt={import:"HeroUIProvider"},O={content:"public-hoist-pattern[]=*@heroui/*"};function Wt(e,t){let o=e.name,n=v(`node_modules/@heroui/${o}`),r=[e];if(!existsSync(n)&&t){let a=v("node_modules/.pnpm"),p=Cn.sync(`**/@heroui/${o}`,{absolute:!0,cwd:a,onlyDirectories:!0})[0];if(p)n=p;else return r}let{currentComponents:i}=I(join(n,"package.json"));if(i.length)for(let a of i){let p=Wt(a,t);r.push(...p);}return r}var x={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 G(e){let t=x[e];return t||(e==="latestVersion"?(t=await K(b),x[e]=t):e==="cliLatestVersion"?(t=await K(zt),x[e]=t):e==="betaVersion"&&(t=await ve(b),x[e]=t)),t}function R(e){return x[e]}function vn(e){let t=e.map(a=>a.name),o=e.map(a=>a.package),n=new Set(t),r=e.reduce((a,p)=>(a[p.name]=p,a),{}),i=e.reduce((a,p)=>(a[p.package]=p,a),{});return {heroUIComponentsKeys:t,heroUIComponentsKeysSet:n,heroUIComponentsMap:r,heroUIComponentsPackageMap:i,heroUIcomponentsPackages:o}}function ct({beta:e,heroUIComponents:t}){let{heroUIComponentsKeys:o,heroUIComponentsKeysSet:n,heroUIComponentsMap:r,heroUIComponentsPackageMap:i,heroUIcomponentsPackages:a}=vn(t);e?(x.betaHeroUIComponents=t,x.betaHeroUIIComponentsKeys=o,x.betaHeroUIComponentsKeysSet=n,x.betaHeroUIComponentsMap=r,x.betaHeroUIComponentsPackageMap=i,x.betaHeroUIcomponentsPackages=a):(x.heroUIComponents=t,x.heroUIComponentsKeys=o,x.heroUIComponentsKeysSet=n,x.heroUIComponentsMap=r,x.heroUIComponentsPackageMap=i,x.heroUIcomponentsPackages=a);}var Be=["package","version","status","docs"],Gt=["package","version","status"];var M=/\u001b\[[\d;]+m/g,U=tt.round,lt=" ",Se=`${U.vertical}${lt}`,Qt=`${lt}${U.vertical}${lt}`,Xt=/([\W\w]+)\snew:/,Zt=/new:\s([\W\w]+)/;function ae({commandName:e,components:t,message:o=`Current installed components: `,warnError:n=!0}){if(!t.length){n&&s.prefix("warn","No components found");return}let r={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 l=f.match(Zt)?.[1],g=f.match(Xt)?.[1],w=D(eo(g,l));r[y]=Math.max(r[y],Math.max(w.length,7)),r.originVersion=Math.max(r.originVersion,g.length);continue}r[y]=Math.max(r[y],f.length);}let i=t.reduce((u,y)=>{let f=Se;for(let l of Be){let g=X(y[l],r[l]);if(e!=="list"&&l==="version"){let w=g.match(Xt)?.[1]?.trim(),C=g.match(Zt)?.[1]?.trim();w===C?(g=g.replace(/\snew:\s[\W\w]+(\s+)?/,""),g=X(`${X(g,r.originVersion)} \u{1F680}latest`,r[l]),g=g.replace("latest",E.magentaBright.underline("latest"))):C&&(g=X(eo(X(w,r.originVersion),C),r[l]));}y.status==="stable"&&Gt.includes(l)?g=E.greenBright(g):y.status==="new"?g=E.magentaBright(g):y.status==="updated"&&(g=E.blueBright(g)),f+=g+Qt;}return u.push(f),u},[]),a=U.topLeft+Se.replace(/.*/g,U.horizontal).slice(1),p=Se,m=U.vertical+Se.replace(/.*/g,U.horizontal).slice(1);for(let u of Be)a+=`${U.horizontal.padEnd(r[u]+7,U.horizontal)}`,p+=E.redBright(qt(u).padEnd(r[u]))+Qt,m+=`${U.horizontal.padEnd(r[u]+7,U.horizontal)}`;a=a.slice(0,-2)+U.topRight,m=m.slice(0,-2)+U.vertical;let c=U.bottomLeft+Se.replace(/.*/g,U.horizontal).slice(1);for(let u of Be)c+=`${U.horizontal.padEnd(r[u]+7,U.horizontal)}`;c=c.slice(0,-2)+U.bottomRight,i=[a,p,m,...i,c],s.info(o),s.log(i.join(` `));}function to(){s.newLine(),s.log(E.redBright("Environment Info:")),s.log(E.blueBright(" System:")),s.log(E.blueBright(" OS:"),process.platform),s.log(E.blueBright(" CPU:"),process.arch),s.log(E.greenBright(" Binaries:")),s.log(E.greenBright(" Node:"),process.version),s.newLine();}function $e({align:e="center",borderStyle:t="round",center:o=!1,color:n,log:r=!0,padding:i=0,text:a,title:p}){let m=tt[t],c=n?Object.fromEntries(Object.entries(m).map(([$,T])=>[$,E[n](T)])):m,u=a.split(` `),y=u.map($=>$.replace(M,"")),f=i>0,l=i,g=o||f,w=y.reduce(($,T)=>T.length>$?T.length:$,0);w=f?w+l*4:w;let C=p?p.replace(M,""):"",d=p?C.length:0,P=w-d,h=2;for(;d+h+l>=w;)w+=Math.floor(d/2);P=w-d;let k=(()=>{if(p)if(e==="center"){let $=Math.floor(P/2)-1,T=Math.ceil(P/2)-1,Xe=$>0?c.horizontal.repeat($):"",W=T>0?c.horizontal.repeat(T):"";return `${Xe} ${p} ${W}`}else return e==="left"?` ${p} ${c.horizontal.repeat(P-2)}`:`${c.horizontal.repeat(P-2)} ${p} `;return c.horizontal.repeat(w)})(),A=c.topLeft+k+c.topRight,H=c.bottomLeft+c.horizontal.repeat(w)+c.bottomRight,J=u.reduce(($,T)=>{let Xe=T.replace(M,""),W=w-Xe.length,Wo=" ".repeat(W),kt=Math.floor(W/2),bt=Math.ceil(W/2),Go=kt>0?" ".repeat(kt):"",Qo=bt>0?" ".repeat(bt):"";if(o)$.push(`${c.vertical}${W?`${Go}${T}${Qo}`:T}${c.vertical}`);else if(i){let Xo=W-l*2;$.push(`${c.vertical}${" ".repeat(l*2)}${T}${" ".repeat(Xo)}${c.vertical}`);}else $.push(`${c.vertical}${W>0?`${T}${Wo}`:T}${c.vertical}`);return $},[]);if(g)for(let $=0;$<l;$++)J.unshift(`${c.vertical}${" ".repeat(w)}${c.vertical}`),J.push(`${c.vertical}${" ".repeat(w)}${c.vertical}`);return J=[A,...J,H],r&&s.log(J.join(` `)),J.join(` `)}function eo(e,t){return `${E.white(`${e} ->`)} ${E.yellowBright(`${t} (new)`)}`}var ze={private:!1,name:"@v0xoss/oss-cli",type:"module",license:"MIT",version:"0.0.3",homepage:"https://github.com/vezham/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:"v0xOSS <oss-developers@vezham.com>",repository:{type:"git",url:"https://github.com/vezham/heroui-cli.git"},bugs:{url:"https://github.com/vezham/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",postbuild:"pnpm run update:components",prepublishOnly:"pnpm run build","v:ws:changeset":"changeset","v:ws:changeset:checklist-release":"bash v/bin/checklist-release/bin/main.sh","v:ws:changeset:update-versions":"bash v/bin/update-versions/bin/main.sh","v:ws:git:cleanup-release":"bash v/bin/cleanup-release/bin/main.sh","v:ws:npm:unpublish":"bash v/bin/npm-unpublish/bin/main.sh"},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:{"@changesets/changelog-github":"0.5.0","@changesets/cli":"2.27.10","@changesets/get-github-info":"0.6.0","@changesets/get-release-plan":"4.0.5","@changesets/types":"6.0.0","@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 oo(e){let t=/import {?\s*([\W\w]+?)\s*}? from ["'](.+)["']/g,o=e.match(t)??[],n=[];for(let i of o)n.push(r(i));return n.length?n:[];function r(i){let a=/import {?\s*([\W\w]+?)\s*}? from ["'](.+)["']/,p=i.match(a)??[];return [p[1]??"",p[2]??""]}}function no(e){return e.replace(/^["'`](.*)["'`]$/,"$1")}function q(e,t){let o=new RegExp(`\\s*${e}:\\s\\[([\\w\\W]*?)\\]\\s*`);return o.test(t)?t.match(o)?.[1]?.split(/,\s/g).map(n=>no(n.trim())).filter(Boolean)??[]:[]}function fe(e,t,o,n){let r=new RegExp(`\\s*${e}:\\s\\[([\\w\\W]*?)\\]\\s*`),i=n??o.map(u=>JSON.stringify(u)).join(", ");if(r.test(t)){let u=e==="content"?` ${e}: [${i}]`:` ${e}: [${o}]`;return t.replace(r,u)}let a=t.split(` `),p=a.findIndex(u=>u.includes("content:")),m=a.findIndex(u=>u.includes("module.exports =")),c=p!==-1?p-1:m!==-1?m:0;return e==="content"?a.splice(c+1,0,` ${e}: [${i}],`):a.splice(c+1,0,` ${e}: [${o.map(u=>no(u))}],`),a.join(` `)}var de="".padEnd(7),io="Missing";async function so(e){let{all:t,allDependencies:o,isHeroUIAll:n,upgradeOptionList:r}=e,i=[],a=new Set,p=await Sn(t,n,o,a),m=r.map(l=>({...l,latestVersion:ie(l.version,l.latestVersion)})),c=await Promise.all(r.map(l=>Ue(l.package,o,a,l.peerDependencies))),u=await $n([...a]),y=[...m,...p.allOutputList],f=[...c.flat(),...p.allPeerDepList,...u].filter((l,g,w)=>g===w.findIndex(C=>C.package===l.package));return An(y,f),i=[...y,...f].filter((l,g,w)=>!l.isLatest&&g===w.findIndex(C=>C.package===l.package)),Un(i),i}function ro(e,t=!1){if(!e.length)return "";let o=[],n={latestVersion:0,package:0,version:0};for(let r of e)for(let i in r){if(!Object.prototype.hasOwnProperty.call(r,i)||!r[i])continue;i==="version"&&(r[i]=r[i].replace(_e,""));let a=i==="version"?r[i].replace(M,"").length:r[i].length;n[i]=Math.max(n[i],a);}for(let r of e){if(r.isLatest){if(t)continue;o.push(` ${E.white(`${`${r.package}@${r.versionMode||""}${r.latestVersion}`.padEnd(n.package+de.length+de.length)}`)}${E.greenBright("latest").padStart(n.version)}${de}`);continue}o.push(` ${E.white(`${r.package.padEnd(n.package+de.length)}${de}${X(`${r.versionMode||""}${r.version}`,n.version)} -> ${r.versionMode||""}${r.latestVersion}`)}${de}`);}return o.join(` `)}async function Ue(e,t,o,n){if(n=n||JSON.parse(await B(`npm show ${e} peerDependencies --json`))||{},!n||!Object.keys(n).length)return [];let r=[];for(let[i,a]of Object.entries(n)){if(r.some(y=>y.package===i))continue;let p=t[i],m=Q(a);if(!p){o.add({name:i,version:m});continue}let{versionMode:c}=se(t,i),u=L(p,m)>=0;u?m=Q(p):m=await K(i),r.push({isLatest:u,latestVersion:u?m:ie(p,m),package:i,version:p,versionMode:c});}return r}function An(e,t){let o=e.length===1?"Component":"Components",n={components:{color:"blue",text:"",title:E.blue(o)},peerDependencies:{color:"yellow",text:"",title:E.yellow("PeerDependencies")}},r=ro(e),i=ro(t,!0),a=t.filter(p=>!p.isLatest);r.length&&$e({...n.components,text:r}),s.newLine(),a.length&&s.log(E.gray(`Required min version: ${a.map(p=>`${p.package}>=${p.latestVersion.replace(M,"")}`).join(", ")}`)),i.length&&$e({...n.peerDependencies,text:i});}async function Sn(e,t,o,n){if(!e||!t)return {allOutputList:[],allPeerDepList:[]};let r=x.latestVersion,{currentVersion:i,versionMode:a}=se(o,b),p=ie(i,r),m=L(i,r)>=0,c=await Ue(b,o,n),u=await Ue(F,o,n),y=[{isLatest:m,latestVersion:p,package:b,version:i,versionMode:a}],f=[...c,...u];return {allOutputList:y,allPeerDepList:f}}async function $n(e){let t=[];for(let o of e){let n={isLatest:!1,latestVersion:o.version,package:o.name,version:E.red(io),versionMode:""};t.push(n);}return t}function Un(e){let t={major:0,minor:0,patch:0};for(let n of e){if(n.version===io){t.major++;continue}let r=D(n.latestVersion);Ve(n.version,r)?t.major++:je(n.version,r)?t.minor++:t.patch++;}let o=Object.entries(t).reduce((n,[r,i])=>i?`${n}${E.yellowBright(i)} ${r}, `:n,"").replace(/, $/,"");return o&&(s.log(o),s.newLine()),t}function ao({dependencies:e,devDependencies:t,upgradePackageList:o}){for(let n of o){let r=D(n.latestVersion);if(t[n.package]){t[n.package]=r;continue}e[n.package]=r;}}function pe(e,t){let{errorInfo:o,missingDependencies:n,tailwindName:r}=t;return e==="missingDependencies"?{level:"error",name:"missingDependencies",outputFn:()=>{s.log("You have not installed the required dependencies"),s.newLine(),s.log("The required dependencies are:"),n.forEach(i=>{s.log(`- ${i}`);}),s.newLine(),s.log(`See more info here: ${E.underline(at)}`);}}:e==="incorrectTailwind"?{level:"error",name:"incorrectTailwind",outputFn:()=>{s.log(`Your ${r} is incorrect`),s.newLine(),s.log("The missing part is:"),o.forEach(i=>{s.log(`- need to add ${i}`);}),s.newLine(),s.log(`See more info here: ${E.underline(`${qe}-1`)}`);}}:{level:"error",name:"incorrectApp",outputFn:()=>{s.log("Your App.tsx is incorrect"),s.newLine(),s.log("The missing part is:"),o.forEach(i=>{s.log(`- need to add ${i}`);}),s.newLine(),s.log(`See more info here: ${E.underline(at)}`);}}}async function ce(e,t,o){let n=[],{allDependencies:r,beta:i,packageNames:a,peerDependencies:p}=o??{},m=[];if(p){let c=await Tn({allDependencies:r,packageNames:a});m.push(...c);}if(e==="all"){let c=t.has(b),u=t.has(Ie),y=t.has(Ae);if(c&&u&&!m.length)return [!0];!c&&n.push(i?`${b}@${x.betaVersion}`:b),!u&&n.push(Ie),!y&&n.push(Ae);}else if(e==="partial"){let c=t.has(Ie),u=t.has(Ae),y=t.has(Z),f=t.has(F);if(c&&y&&f&&!m.length)return [!0];!c&&n.push(Ie);let l=await He(Z),g=await He(F);!y&&n.push(i?`${Z}@${l}`:Z),!f&&n.push(i?`${F}@${g}`:F),!u&&n.push(Ae);}return [!1,...n,...p?m:[]]}async function Tn(e){let{allDependencies:t,packageNames:o}=e,n=[];for(let r of o){let i=await Ue(r,t,new Set);for(let a of i)if(!a.isLatest){let p=n.findIndex(u=>u.includes(a.package)),c=D(n[p]||"")?.match(/@([\d.]+)/)?.[1];c&&L(c,D(a.latestVersion))<=0&&n.splice(p,1),n.push(`${a.package}@${a.latestVersion}`);}}return n}function le(e,t,o,n,r,i){if(e==="partial"&&!o.length)return [!0];let a=[],p=r??readFileSync(t,"utf-8"),m=q("content",p),c=q("plugins",p);if(e==="all"){let y=q("darkMode",p).some(g=>g.includes("class"))||/darkMode:\s*["'`]class/.test(p),f=m.some(g=>g.includes(S.content)),l=c.some(g=>S.checkPluginsRegex.test(g));if(y&&f&&l)return [!0];!y&&a.push(S.darkMode),!f&&a.push(S.content),!l&&a.push(S.plugins);}else if(e==="partial"){let u=Ke.content(o,n),y=!1,f=m.some(g=>g.includes(S.content)?(y=!0,!0):g.includes(u));i&&y&&s.log(` ${E.yellow("Attention")} Individual components from HeroUI do not require the "${E.bold(S.content)}" in the tailwind config For optimized bundle sizes, consider using "${E.bold(u)}" instead`);let l=c.some(g=>S.checkPluginsRegex.test(g));if(f&&l)return [!0];!f&&a.push(u),!l&&a.push(S.plugins);}return [!1,...a]}function Te(e,t){let o=[];if(e==="all"||e==="partial"){let n=readFileSync(t,"utf-8"),i=oo(n).some(([a])=>a.includes(pt.import));if(i)return [!0];!i&&o.push(pt.import);}return [!1,...o]}function he(e){let t=[],o;if(e){try{o=readFileSync(e,"utf-8");let n=o.includes(O.content);if(n)return [!0];!n&&t.push(O.content);}catch(n){t.push(`Error reading .npmrc file: ${e} Error: ${n}`);}return [!1,...t]}return [!1,...t]}async function xe(e=[],t=!0){let o=[];for(let n of e)if(!x.heroUIComponentsKeysSet.has(n)){let r=be(x.heroUIComponentsKeys,n);o.push([n,r]);}if(o.length){let[n,r]=o.reduce((i,[a,p])=>[i[0]+E.underline(a)+", ",i[1]+(p?E.underline(p)+", ":"")],["",""]);return t&&s.prefix("error",`Illegal components: ${n.replace(/, $/,"")}${r?` ${"".padEnd(12)}It may be a typo, did you mean ${r.replace(/, $/,"")}?`:""}`),!1}return !0}var ut=new Map;async function oe(e,t){return new Promise((o,n)=>{try{let{cache:r=!0,logCmd:i=!0}=t||{};ut.has(e)&&r&&o(ut.get(e)),i&&(s.newLine(),s.log(`${e}`));let a=execSync(e,{stdio:"inherit",...t?Yt(t,["logCmd"]):{}});if(a){let p=a.toString();o(p),ut.set(e,p);}o("");}catch(r){n(r);}})}var lo=e=>{isCancel(e)&&(cancel(`${E.red("\u2716")} Operation cancelled`),process.exit(0));},mo=async e=>{let t=await text(e);return lo(t),t},De=async e=>{let t=await select(e);return lo(t),t},po=spinner(),uo=async e=>{let{failText:t,successText:o,task:n,text:r}=e,i=null;try{po.start(r),i=await(n instanceof Promise?n:Promise.resolve(n)),po.stop(o);}catch{cancel(t??i??"Task failed"),process.exit(0);}return i};async function Je(e){try{await e();}catch(t){t&&(await De({message:`${E.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 oe("pnpm install --force"),await e());}}async function gt(e,t=[]){if(R("debug"))for(let o of t)s.warn(`Debug: ${o}`);else await Je(()=>oe(e));}function fo(e,t){if(!e.length||!R("debug"))return;let{dependencies:o,packageJson:n}=I(t);for(let r of e){let i=x.heroUIComponentsMap[r];i&&(o[i.package]=`${i.package}@${i.version}`);}writeFileSync(t,JSON.stringify({...n,dependencies:o},null,2),"utf-8");}function ho(e,t){if(!e.length||!R("debug"))return;let{dependencies:o,packageJson:n}=I(t);for(let r of e){let i=x.heroUIComponentsMap[r];i&&delete o[i.package];}writeFileSync(t,JSON.stringify({...n,dependencies:o},null,2),"utf-8");}var dt={onCancel:()=>{s.log(`${E.red("\u2716")} Operation cancelled`),process.exit(0);}};async function ye(e,t){return (await ft({hint:"- Space to select. Return to submit",message:e,min:1,name:"value",type:"autocompleteMultiselect",...t?{choices:t}:{}},dt)).value}async function me(e,t){return (await ft({message:e,name:"value",type:"select",...t?{choices:t}:{}},dt)).value}async function xo(e,t){return (await ft({hint:"- Space to select. Return to submit",message:e,min:1,name:"value",type:"multiselect",...t?{choices:t}:{}},dt)).value}var We=["npm","bun","pnpm","yarn"];var yo={"bun.lockb":"bun","npm-shrinkwrap.json":"npm","package-lock.json":"npm","pnpm-lock.yaml":"pnpm","yarn.lock":"yarn"};async function z(e=_){let t,o=await findUp(Object.keys(yo),{cwd:e});return o?t=yo[Vn.basename(o)]:t=await me("No agent found, please choose one",We.map(n=>({title:n,value:n}))),t}function Co(e,t){let{format:o=!1,write:n=!0}=t,r=readFileSync(e,"utf-8");r=`import {HeroUIProvider} from "@heroui/react"; ${r}`,r=Fn(r),n&&writeFileSync(e,r,"utf-8"),o&&execSync(`npx prettier --write ${e}`,{stdio:"ignore"});}function Fn(e){let t=/return\s*\(([\S\s]*?)\);/g;return e.replace(t,(n,r)=>`return ( <HeroUIProvider> ${r.trim()} </HeroUIProvider> );`)}function Qe(e,t){let{errorInfoList:o,format:n=!1,tailwindPath:r,write:i=!0}=t;if(!o.length)return;let a=readFileSync(r,"utf-8"),p=q("content",a),m=q("plugins",a);for(let c of o){let[u,y]=qn(c);if(u==="content"){if(p.includes(S.content))continue;p=p.filter(l=>!l.includes("@heroui/theme/dist/")),p.push(y),a=fe("content",a,p,p.map((l,g,w)=>g===0?w.length===1?` ${JSON.stringify(l)} `:` ${JSON.stringify(l)}`:w.length-1===g?` ${JSON.stringify(l)} `:` ${JSON.stringify(l)}`).join(`, `));}else u==="plugins"&&(m.push(y),a=fe("plugins",a,m),a=`${S.importContent(r.endsWith(".ts"))} ${a}`);if(e==="all"&&u==="darkMode"){let f=a.indexOf("plugins")-1,l=S.darkMode;a=`${a.slice(0,f)} ${l}, ${a.slice(f)}`;}}if(i&&writeFileSync(r,a,"utf-8"),n)try{execSync(`npx prettier --write ${r}`,{stdio:"ignore"});}catch{s.warn(`Prettier failed to format ${r}`);}}function qn(e){return S.darkMode.includes(e)?["darkMode",e]:S.plugins.includes(e)?["plugins",e]:["content",e]}function Ce(e,t=!0,o=!0,n=void 0){if(!existsSync(e))t&&writeFileSync(e,O.content,"utf-8");else {let r=readFileSync(e,"utf-8");r=`${O.content} ${r}`,t&&writeFileSync(e,r,"utf-8");}if(!n){s.newLine(),s.log(`Added the required content in file: ${e}`),o&&!R("debug")&&(s.newLine(),s.log("Pnpm restructure will be run now"),execSync("pnpm install",{stdio:"inherit"}));return}n({message:`Added the required content in file: ${e}`,runInstall:o});}var wo="https://codeload.github.com/heroui-inc/next-app-template/tar.gz/main",ko="https://codeload.github.com/heroui-inc/next-pages-template/tar.gz/main",bo="https://codeload.github.com/heroui-inc/vite-template/tar.gz/main",Po="next-app-template-main",vo="next-pages-template-main",Io="vite-template-main",Ao="next-app-template",So="next-pages-template",$o="vite-template";function Uo(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 Eo(e,t){let{addApp:o=!1,all:n=!1,appPath:r,beta:i=!1,packagePath:a=v("package.json"),tailwindPath:p=re("**/tailwind.config.(j|t)s")[0]}=t;var{allDependencies:m,allDependenciesKeys:w,currentComponents:C}=I(a);let c=t.prettier??w.has("prettier"),u=!!m[b];if(!e.length&&!n){let h=x.heroUIComponents.filter(k=>!C.some(A=>A.name===k.name));h.length||(s.success("\u2705 All components have been added"),process.exit(0)),e=await ye("Which components would you like to add?",h.map(k=>({description:k.description,title:k.name,value:k.name})));}else n&&(e=[b]);if(!n&&!xe(e,!0))return;var{allDependenciesKeys:w,currentComponents:C}=I(a);let y=C.map(h=>h.name),f=e.filter(h=>y.includes(h)||u&&h===b);if(f.length&&!R("debug")){s.prefix("error",`\u274C You have already added the following components: ${f.map(h=>E.underline(h)).join(", ")}`);return}if(o&&!r){s.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 l=await z(),g=l==="npm"?"install":"add";if(n){let[,...h]=await ce("all",w,{allDependencies:m,beta:i,packageNames:[b],peerDependencies:!0});h=h.map(k=>D(k)),h.length&&(s.info(`Adding required dependencies: ${[...h].map(k=>E.underline(k)).join(", ")}`),await gt(`${l} ${g} ${[...h].join(" ")}`,h));}else {let h=i?await _t(e):e.map(H=>x.heroUIComponentsMap[H].package),[,...k]=await ce("partial",w,{allDependencies:m,beta:i,packageNames:h,peerDependencies:!0}),A=[...k,...h].map(H=>D(H));s.info(`Adding required dependencies: ${[...A].map(H=>E.underline(H)).join(", ")}`),await gt(`${l} ${g} ${[...A].join(" ")}`,A);}R("debug")&&fo(e,a);var{allDependenciesKeys:w,currentComponents:C}=I(a);let d=n?"all":"partial",P=l==="pnpm";if(p){let[,...h]=le(d,p,C,P,void 0,!0);Qe(d,{errorInfoList:h,format:c,tailwindPath:p}),s.newLine(),s.log(`Tailwind CSS settings have been updated in: ${p}`);}else {let h=Ke.content(C,P),k=Uo(d,h),A=v("tailwind.config.js");writeFileSync(A,k,"utf-8"),s.newLine(),s.info(`Tailwind CSS configuration file created at: ${A}`);}if(o&&r&&existsSync(r)){let[h]=Te(d,r);h||(Co(r,{format:c}),s.newLine(),s.info(`HeroUIProvider successfully added to the App file at: ${r}`),s.warn("Please check the placement of HeroUIProvider in the App file to ensure it's correctly integrated.'"));}if(l==="pnpm"){let h=v(".npmrc");if(!existsSync(h))writeFileSync(v(".npmrc"),O.content,"utf-8");else {let[k]=he(h);k||Ce(h);}}s.newLine(),s.success("\u2705 Components added successfully"),(w.has(b)||n)&&C.length&&(s.newLine(),s.log(`${E.yellow("Attention")} Individual components from HeroUI do not require the \`@heroui/react\` package. For optimized bundle sizes, consider using individual components.`),s.log("The redundant dependencies are:"),[...new Set(C)].forEach(h=>{s.log(`- ${h.package}`);})),s.newLine(),s.grey(`Please check the ${E.bold("HeroUIProvider")} whether in the correct place (ignore if added) See more info here: ${Ye}`),R("debug")&&ho(e,a),process.exit(0);}async function Ro(e){let{appPath:t=re("**/App.(j|t)sx")[0],checkApp:o=!1,checkPnpm:n=!0,checkTailwind:r=!0,packagePath:i=v("package.json"),tailwindPath:a=re("**/tailwind.config.(j|t)s")}=e,p=Fe(o),m=Fe(n),c=Fe(r),u=[a].flat(),{allDependencies:y,allDependenciesKeys:f,currentComponents:l,isAllComponents:g}=I(i);if(!l.length&&!g){s.prefix("error",`\u274C No ${E.underline("HeroUI components")} found in your project. Please consult the installation guide at: https://heroui.com/docs/guide/installation#global-installation`);return}let w=[];if(g&&l.length&&w.push({level:"warn",name:"redundantDependencies",outputFn:()=>{s.log("You have installed some unnecessary dependencies. Consider removing them for optimal performance."),s.newLine(),s.log("The following dependencies are redundant:"),l.forEach(C=>{s.log(`- ${C.package}`);});}}),c&&!u.length&&w.push({level:"error",name:"missingTailwind",outputFn:()=>{s.log("Missing tailwind.config.(j|t)s file. To set up, visit: "+E.underline(qe));}}),p&&!t&&w.push({level:"error",name:"missingApp",outputFn:()=>{s.log("App.(j|t)sx file not found. Please specify the path using: doctor --appPath=[yourAppPath]");}}),g){let[C,...d]=await ce("all",f,{allDependencies:y,packageNames:[b],peerDependencies:!0});if(l.length){let[P,...h]=await ce("partial",f,{allDependencies:y,packageNames:l.map(k=>k.package),peerDependencies:!0});C=P||C,d=[...h,...d].filter((k,A,H)=>(k=D(k).replace(/@[\d.]+/g,""),H.findIndex(J=>D(J).replace(/@[\d.]+/g,"")===k)===A));}if(C||w.push(pe("missingDependencies",{missingDependencies:d})),c)for(let P of u){let[h,...k]=le("all",P);if(!h){let A=basename(P);w.push(pe("incorrectTailwind",{errorInfo:k,tailwindName:A}));}}if(p&&t){let[P,...h]=Te("all",t);P||w.push(pe("incorrectApp",{errorInfo:h}));}}else if(l.length){let[C,...d]=await ce("partial",f,{allDependencies:y,packageNames:l.map(P=>P.package),peerDependencies:!0});if(C||w.push(pe("missingDependencies",{missingDependencies:d})),c){let P=await z()==="pnpm";for(let h of u){let[k,...A]=le("partial",h,l,P,void 0,!0);if(!k){let H=basename(h);w.push(pe("incorrectTailwind",{errorInfo:A,tailwindName:H}));}}}if(p&&t){let[P,...h]=Te("partial",t);P||w.push(pe("incorrectApp",{errorInfo:h}));}}if(m&&await z()==="pnpm"){let d=v(".npmrc"),[P,...h]=he(d);P||w.push({level:"error",name:"incorrectPnpm",outputFn:()=>{s.log(`The pnpm setup is incorrect Please update your configuration according to the guidelines provided at: `+E.underline(Jt)),s.newLine(),s.log("Required changes:"),h.forEach(k=>{s.log(`- Add ${k}`);});}});}if(!w.length){s.newLine(),s.success("\u2705 Your project has no detected issues.");return}s.prefix("error",`\u274C Your project has ${E.underline(w.length)} issue${w.length===1?"":"s"} that require attention`),s.newLine();for(let C=0;C<w.length;C++){let d=w[C];s[d.level](`\u2757\uFE0FIssue ${C+1}: ${E.bold(d.name)}`),s.newLine(),d.outputFn(),s.newLine();}process.exit(0);}async function Mo(e){let{packagePath:t=v("package.json")}=e,{currentComponents:o}=I(t);ae({components:o}),to(),process.exit(0);}var Kn="package-lock=true";function Oo(e){writeFileSync(e,Kn,"utf-8");}async function Gn(e){let t=await fetch(e);if(!t.body)throw new Error(`Failed to download: ${e}`);return Readable.fromWeb(t.body)}async function No(e,t){await sn(async o=>{try{await pipeline(await Gn(t),Wn.x({cwd:e}));}catch(n){o(new Error(`Failed to download ${t} Error: ${n}`));}},{retries:3});}function Ho(e,t){e&&(Object.keys(Re).includes(e)||et(Object.keys(Re),e)),t&&(We.includes(t)||et(We,t));}var Re={app:Ao,pages:So,vite:$o};async function Vo(e,t){let{package:o="npm",template:n}=t;Ho(n,o),j.intro(E.cyanBright("Create a new project"));let{packageName:r,projectName:i,template:a}=await Zn(o,e,n),{run:p}=ge(r);existsSync(rt(`${_}/${i}`))&&(j.cancel(`The project name ${E.redBright(i)} already exists`),process.exit(1)),a==="app"?(await yt(wo),Ct(Po,i)):a==="pages"?(await yt(ko),Ct(vo,i)):a==="vite"&&(await yt(bo),Ct(Io,i));let m=rt(`${_}/${i}/.npmrc`);Oo(m),r==="pnpm"&&Ce(m,!0,!1,({message:c})=>{j.log.message(c);}),j.note(`cd ${E.cyanBright(i)} ${E.cyanBright(r)} install`,"Next steps"),j.outro(`\u{1F680} Get started with ${E.cyanBright(`${r} ${p} dev`)}`),process.exit(0);}async function yt(e){await uo({failText:"Template creation failed",successText:"Template created successfully!",task:No(_,e),text:"Creating template..."});}function Ct(e,t){try{renameSync(join(_,e),join(_,t));}catch(o){o&&(j.cancel(`rename Error: ${o}`),process.exit(0));}}async function Zn(e,t,o){let n=[{hint:"A Next.js 14 with app directory template pre-configured with HeroUI (v2) and Tailwind CSS.",label:E.gray("App"),value:"app"},{hint:"A Next.js 14 with pages directory template pre-configured with HeroUI (v2) and Tailwind CSS.",label:E.gray("Pages"),value:"pages"},{hint:"A Vite template pre-configured with HeroUI (v2) and Tailwind CSS.",label:E.gray("Vite"),value:"vite"}];return o=await De({initialValue:o,message:"Select a template (Enter to select)",options:n}),t=await mo({initialValue:t??Re[o],message:"New project name (Enter to skip with default name)",placeholder:t??Re[o]}),e=await De({initialValue:e,message:"Select a package manager (Enter to select)",options:[{label:E.gray("npm"),value:"npm"},{label:E.gray("yarn"),value:"yarn"},{label:E.gray("pnpm"),value:"pnpm"},{label:E.gray("bun"),value:"bun"}]}),{packageName:e,projectName:t,template:o}}async function jo(e){let{packagePath:t=v("package.json"),remote:o=!1}=e,n=x.heroUIComponents;try{if(!o){let{currentComponents:r}=await I(t);n=r;}if(!n.length){s.warn(`No HeroUI components detected in the specified package.json at: ${t}`);return}o?ae({commandName:"list",components:n}):ae({components:n});}catch(r){s.prefix("error",`An error occurred while attempting to list the components: ${r}`);}process.exit(0);}async function Fo(e,t){let{remove:o}=ge(t);await oe(`${t} ${o} ${e.join(" ")}`);}async function qo(e,t){let{currentComponents:o,isHeroUIAll:n,isPnpm:r,prettier:i,tailwindPath:a}=t;if(a&&!existsSync(a)){s.prefix("warn","No tailwind.config.(j|t)s found remove action skipped");return}let p=readFileSync(a,"utf-8"),m=q("content",p),c=q("plugins",p),u=m.some(f=>f.includes(S.content));if(!o.length&&!n){let f=c.findIndex(l=>l.includes("heroui"));f!==-1&&c.splice(f,1),p=fe("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=fe("content",p,m);}writeFileSync(a,p,"utf-8");let[,...y]=le(e,a,o,r,void 0,!0);Qe(e,{errorInfoList:y,format:i,tailwindPath:a}),s.newLine(),s.info(`Remove the removed components tailwind content in file: ${a}`);}async function Ko(e,t){let{all:o=!1,packagePath:n=v("package.json"),tailwindPath:r=re("**/tailwind.config.(j|t)s")[0]}=t;var{allDependencies:l,allDependenciesKeys:i,currentComponents:g}=I(n);let a=await z(),p=t.prettier??i.has("prettier"),m=!!l[b];if(!g.length&&!m){s.prefix("error",`No HeroUI components detected in your package.json at: ${n}`);return}if(o||m)e=m?[b]:g.map(C=>C.package);else if(!e.length)e=await ye("Select the components to remove",g.map(C=>({title:C.package,value:C.package})));else {if(!xe(e))return;e=Kt(e);}let c=e.includes(b)?await Bt(e,l):g.filter(C=>e.some(d=>d.includes(C.package)||d.includes(C.name)));ae({components:c,message:E.yellowBright("\u2757\uFE0F Components slated for removal:")}),await me("Confirm removal of these components:",[{title:"Yes",value:!0},{title:"No",value:!1}])||process.exit(0);let y=[...e];g.filter(C=>!e.includes(C.package)).length||(l[F]&&y.push(F),l[Z]&&y.push(Z)),await Fo(y,a);var{allDependencies:l,currentComponents:g}=I(n,!1);if(m=!!l[b],qo(m?"all":"partial",{currentComponents:g,isHeroUIAll:m,isPnpm:a==="pnpm",prettier:p,tailwindPath:r}),!g.length&&!m){if(a==="pnpm"){let C=v(".npmrc");if(existsSync(C)){let d=readFileSync(C,"utf-8");d=d.replace(O.content,""),s.newLine(),s.info("Removing specified .npmrc file content"),writeFileSync(C,d,"utf-8");}}s.newLine(),s.warn(`No HeroUI components remain installed. Ensure the HeroUIProvider is also removed if necessary. For more information, visit: ${Ye}`);}s.newLine(),s.success(`\u2705 Successfully removed the specified HeroUI components: ${e.map(C=>E.underline(C)).join(", ")}`),process.exit(0);}async function Bo(e){if(e==="pnpm"){let t=v(".npmrc");if(!existsSync(t))writeFileSync(v(".npmrc"),O.content,"utf-8");else {let[o]=he(t);o||Ce(t);}}}function zo(e,t,o){let n=e.match(/(^\w+$)/)?.[1];if(n)return t.includes(n);let r=L(e,t);return o&&r===1&&!e.includes("beta")?!1:r>=0}async function Jo(e,t){let{all:o=!1,beta:n=!1,packagePath:r=v("package.json"),write:i=!1}=t,{allDependencies:a,currentComponents:p,dependencies:m,devDependencies:c,packageJson:u}=I(r,!1),y=!!a[b],f=[];if(await Promise.all(p.map(async d=>{let P=x.heroUIComponentsMap[d.name]?.version||await K(d.package),h=n?await ve(d.package):P,k=zo(d.version,h,n);f.push({...d,isLatest:k,latestVersion:h});})),!f.length&&!y){s.prefix("error",`No HeroUI components detected in your package.json at: ${r}`);return}if(o)e=p.map(d=>d.package);else if(e.length){if(!xe(e))return}else {if(y){let d={isLatest:L(x.latestVersion,Q(a[b]))<=0,latestVersion:x.latestVersion,package:b,version:Q(a[b])};f.push(d);}f.every(d=>d.isLatest)&&(s.success("\u2705 All HeroUI packages are up to date"),process.exit(0)),e=await ye("Select the components to upgrade",f.map(d=>{let P=zo(d.version,d.latestVersion,n);return {disabled:P,disabledMessage:"Already up to date",title:`${d.package}${P?"":`@${d.version} -> ${ie(d.version,d.latestVersion)}`}`,value:d.package}}));}e=e.map(d=>x.heroUIComponentsMap[d]?.package?x.heroUIComponentsMap[d].package:d);let l=f.filter(d=>e.includes(d.package)),g=await so({all:o,allDependencies:a,isHeroUIAll:y,upgradeOptionList:l}),w=[],C=await z();if(g.length){let d=await me("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:P}=ge(C);d||await me("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}])&&(w=await xo("Select the packages you want to exclude from the upgrade:",g.map(k=>({description:`${k.version} -> ${ie(k.version,k.latestVersion)}`,title:k.package,value:k.package})))),g=g.filter(h=>!w.some(k=>h.package===k)),i?(ao({dependencies:m,devDependencies:c,upgradePackageList:g}),pr.writeFileSync(r,JSON.stringify(u,null,2),"utf-8"),s.newLine(),s.success("\u2705 Upgrade version written to package.json"),process.exit(0)):await Je(()=>oe(`${C} ${P} ${g.reduce((h,k,A)=>`${h}${A===0?"":" "}${k.package}@${k.latestVersion.replace(M,"")}`,"")}`));}Bo(C),s.newLine(),s.success("\u2705 Upgrade complete. All components are up to date."),process.exit(0);}var wt=["add","env","init","list","upgrade","doctor","remove"],Y=new Command;Y.name("heroui").usage("[command]").description(Ft(` HeroUI CLI v${ze.version} `,"")).version(ze.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 n=t.args?.[0];if(n&&!wt.includes(n)){o=!0;let r=be(wt,n);r?s.error(`Unknown command '${n}', Did you mean '${E.underline(r)}'?`):s.error(`Unknown command '${n}'`);}}if(!o){let r=(await B("heroui --help")).split(` `);r=r.filter(i=>i&&!i.includes("HeroUI CLI v")),r=r.map(i=>{let a=i.match(/(\w+)\s\[/)?.[1];return a?i.replace(a,E.cyan(a)):i}),s.log(r.join(` `));}process.exit(0);});Y.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., app, pages").option("-p --package [string]","The package manager to use for the new project","npm").action(Vo);Y.command("add").description("Adds components to your project").argument("[components...]","Names of components 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).action(Eo);Y.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(Jo);Y.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(Ko);Y.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(jo);Y.command("env").description("Displays debugging information for the local environment").option("-p --packagePath [string]","Specify the path to the package.json file").action(Mo);Y.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(Ro);Y.hook("preAction",async e=>{let t=e.args?.[0],o=e.rawArgs.slice(2),n=o.includes("--no-cache"),r=o.includes("--debug")||o.includes("-d");if(st(n),x.debug=r,x.beta=o.includes("-b")||o.includes("--beta"),t&&wt.includes(t)){let m=(await ot()).components,c=(await ot()).betaComponents;ct({beta:!1,heroUIComponents:m}),x.beta&&ct({beta:!0,heroUIComponents:c});}let[i,a]=await Promise.all([G("cliLatestVersion"),G("latestVersion")]);x.latestVersion=a,x.cliLatestVersion=i;let p=ze.version;L(p,i)===-1&&($e({center:!0,color:"yellow",padding:1,text:`${E.gray(`Available upgrade: v${p} -> ${E.greenBright(`v${i}`)} Run \`${E.cyan("npm install -g heroui-cli@latest")}\` to upgrade Changelog: ${E.underline("https://github.com/vezham/heroui-cli/releases")}`)}`,title:Ze("HeroUI CLI")}),s.newLine());});Y.parseAsync(process.argv).catch(async e=>{s.newLine(),s.error("Unexpected error. Please report it as a bug:"),s.log(e),s.newLine(),process.exit(1);}); //# sourceMappingURL=out.js.map //# sourceMappingURL=index.js.map