#!/usr/bin/env node
import {b as b$1,a as a$2}from'./chunk-C7EWIKNS.js';import {r,q as q$1}from'./chunk-SD5CAHKQ.js';import {b,a,G,ra as ra$1,ua,c as c$1,$,V as V$1,sa as sa$1,N,O,w,d,P,M,fa,ha as ha$1,K as K$1,L,I,J,ta,T as T$1,ba,H,e,ea,ka,ia as ia$1,la,B as B$1,x,y,A,z as z$1,S,ma,U as U$1,W,va,_,X as X$1,na,ga,qa,q as q$2,Z,k,R,Y as Y$1,Q,D as D$1,E,F,s,C,r as r$1,t,v,u}from'./chunk-BT5UJFAL.js';export{ka as fetchTree,la as getItemTargetPath,pa as getPreset,oa as getPresets,ma as getRegistries,da as getRegistriesConfig,na as getRegistriesIndex,aa as getRegistry,ia as getRegistryBaseColor,ha as getRegistryBaseColors,ga as getRegistryIcons,ba as getRegistryItems,fa as getRegistryStyles,ea as getShadcnRegistryIndex,ca as resolveRegistryItems,ja as resolveTree}from'./chunk-BT5UJFAL.js';import {c,o,n}from'./chunk-HW2MEAJZ.js';import {a as a$1,c as c$2,g,d as d$1,f,e as e$1}from'./chunk-WLJDV6SE.js';import {a as a$3}from'./chunk-CHWMSXYA.js';import*as ee from'path';import ee__default,{join}from'path';import {promises,existsSync}from'fs';import pr from'fast-glob';import T from'fs-extra';import Po from'open';import pe from'prompts';import mn from'dedent';import Fo,{tmpdir}from'os';import {execa}from'execa';import k$1 from'postcss';import _o from'postcss/lib/at-rule';import cr,{z}from'zod';import {twMerge}from'tailwind-merge';import {Project,ScriptKind,SyntaxKind,VariableDeclarationKind}from'ts-morph';import pn from'deepmerge';import {Command}from'commander';import {diffLines,structuredPatch,diffWords}from'diff';import {dim,yellow,bold,green,cyan,red}from'kleur/colors';import*as Ce from'fs/promises';import Ce__default from'fs/promises';import {StdioServerTransport}from'@modelcontextprotocol/sdk/server/stdio.js';import {randomBytes}from'crypto';var Ro=["next.config.*","vite.config.*","astro.config.*","remix.config.*","nuxt.config.*","svelte.config.*","gatsby-config.*","angular.json"];async function Y(e){if(T.existsSync(ee__default.resolve(e,"pnpm-workspace.yaml")))return  true;let t=ee__default.resolve(e,"package.json");if(T.existsSync(t))try{if((await T.readJson(t)).workspaces)return !0}catch{}return !!(T.existsSync(ee__default.resolve(e,"lerna.json"))||T.existsSync(ee__default.resolve(e,"nx.json")))}async function K(e){let t=await So(e);if(!t.length)return [];let r=await pr(t,{cwd:e,onlyDirectories:true,ignore:["**/node_modules/**"]}),n=[];for(let i of r){let o=ee__default.resolve(e,i);if(!T.existsSync(ee__default.resolve(o,"package.json")))continue;let s=T.existsSync(ee__default.resolve(o,"components.json")),c=Ro.some(a=>pr.sync(a,{cwd:o,dot:true}).length>0);(s||c)&&n.push({name:i,hasConfig:s});}return n}function q(e,t){b.break(),b.log(`It looks like you are running ${a.info(e)} from a monorepo root.`),b.log(`To use shadcn in a specific workspace, use the ${a.info("-c")} flag:`),b.break();for(let r of t)b.log(`  shadcn ${e} -c ${r.name}`);b.break();}async function So(e){let t=[],r=ee__default.resolve(e,"pnpm-workspace.yaml");if(T.existsSync(r)){let i=await T.readFile(r,"utf8"),o=Array.from(i.matchAll(/^\s*-\s*["']?([^"'\n#]+)["']?\s*$/gm));for(let s of o)t.push(s[1].trim());}let n=ee__default.resolve(e,"package.json");if(T.existsSync(n))try{let i=await T.readJson(n),o=Array.isArray(i.workspaces)?i.workspaces:i.workspaces?.packages;Array.isArray(o)&&t.push(...o.filter(s=>!s.startsWith("!")));}catch{}return Array.from(new Set(t))}async function Kr(e){let t={};if(!T.existsSync(e.cwd)||!T.existsSync(ee__default.resolve(e.cwd,"package.json")))return t["1"]=true,{errors:t,projectInfo:null};let r=w("Preflight checks.",{silent:e.silent}).start();T.existsSync(ee__default.resolve(e.cwd,"components.json"))&&!e.force&&(r?.fail(),b.break(),b.error(`A ${a.info("components.json")} file already exists at ${a.info(e.cwd)}.
To start over, remove the ${a.info("components.json")} file and run ${a.info("init")} again.`),b.break(),process.exit(1)),r?.succeed();let n=w("Verifying framework.",{silent:e.silent}).start(),i=e.existingConfig?.tailwind,o=await ra$1(e.cwd,{configCssFile:typeof i?.css=="string"?i.css:void 0});if(!o||o?.framework.name==="manual"){if(t["7"]=true,n?.fail(),!e.monorepo&&await Y(e.cwd)){let f=await K(e.cwd);f.length>0&&(q("init",f),process.exit(1));}b.break(),o?.framework.links.installation&&b.error(`We could not detect a supported framework at ${a.info(e.cwd)}.
Visit ${a.info(o?.framework.links.installation)} to manually configure your project.
Once configured, you can use the cli to add components.`),b.break(),process.exit(1);}n?.succeed(`Verifying framework. Found ${a.info(o.framework.label)}.`);let s="Validating Tailwind CSS.";o.tailwindVersion==="v4"&&(s=`Validating Tailwind CSS. Found ${a.info("v4")}.`);let c=w(s,{silent:e.silent}).start();o.tailwindVersion==="v3"&&(!o?.tailwindConfigFile||!o?.tailwindCssFile)?(t["5"]=true,c?.fail()):o.tailwindVersion==="v4"&&!o?.tailwindCssFile?(t["5"]=true,c?.fail()):o.tailwindVersion?c?.succeed():(t["5"]=true,c?.fail());let a$1=w("Validating import alias.",{silent:e.silent}).start();return o?.aliasPrefix?a$1?.succeed():(t["6"]=true,a$1?.fail()),Object.keys(t).length>0&&(t["5"]&&(b.break(),b.error(`No Tailwind CSS configuration found at ${a.info(e.cwd)}.`),b.error("It is likely you do not have Tailwind CSS installed or have an invalid configuration."),b.error("Install Tailwind CSS then try again."),o?.framework.links.tailwind&&b.error(`Visit ${a.info(o?.framework.links.tailwind)} to get started.`)),t["6"]&&(b.break(),b.error("No import alias found in your tsconfig.json file."),o?.framework.links.installation&&b.error(`Visit ${a.info(o?.framework.links.installation)} to learn how to set an import alias.`)),b.break(),process.exit(1)),{errors:t,projectInfo:o}}async function qr(e,t){let r=new Set,n=new Set,i=[...e];for(;i.length>0;){let o=i.shift();if(n.has(o))continue;n.add(o);let{registry:s}=q$2(o);s&&!d[s]&&r.add(s);try{let[c]=await Z([o],t,{useCache:!0});if(c?.registryDependencies)for(let a of c.registryDependencies){let{registry:f}=q$2(a);f&&!d[f]&&r.add(f),n.has(a)||i.push(a);}}catch(c){if(c instanceof k){let{registry:a}=q$2(o);a&&!d[a]&&r.add(a);continue}continue}}return Array.from(r)}async function V(e,t,r={}){r={silent:false,writeFile:true,...r};let i=(await qr(e,t)).filter(f=>!t.registries?.[f]&&!Object.keys(d).includes(f));if(i.length===0)return {config:t,newRegistries:[]};let o=await na({useCache:process.env.NODE_ENV!=="development"});if(!o)return {config:t,newRegistries:[]};let s={};for(let f of i)o[f]&&(s[f]=o[f]);if(Object.keys(s).length===0)return {config:t,newRegistries:[]};let c$1=Object.fromEntries(Object.entries(t.registries||{}).filter(([f])=>!Object.keys(d).includes(f))),a={...t,registries:{...c$1,...s}};if(r.writeFile){let{resolvedPaths:f,...l}=a,d=w("Updating components.json.",{silent:r.silent}).start(),m=c.parse(l);await T.writeFile(ee__default.resolve(t.resolvedPaths.cwd,"components.json"),JSON.stringify(m,null,2)+`
`,"utf-8"),d.succeed();}return {config:a,newRegistries:Object.keys(s)}}var Me={nova:{title:"Nova",description:"Lucide / Geist",style:"nova",baseColor:"neutral",theme:"neutral",iconLibrary:"lucide",font:"geist",fontHeading:"inherit",menuAccent:"subtle",menuColor:"default",radius:"default",rtl:false},vega:{title:"Vega",description:"Lucide / Inter",style:"vega",baseColor:"neutral",theme:"neutral",iconLibrary:"lucide",font:"inter",fontHeading:"inherit",menuAccent:"subtle",menuColor:"default",radius:"default",rtl:false},maia:{title:"Maia",description:"Hugeicons / Figtree",style:"maia",baseColor:"neutral",theme:"neutral",iconLibrary:"hugeicons",font:"figtree",fontHeading:"inherit",menuAccent:"subtle",menuColor:"default",radius:"default",rtl:false},lyra:{title:"Lyra",description:"Phosphor / JetBrains Mono",style:"lyra",baseColor:"neutral",theme:"neutral",iconLibrary:"phosphor",font:"jetbrains-mono",fontHeading:"inherit",menuAccent:"subtle",menuColor:"default",radius:"default",rtl:false},mira:{title:"Mira",description:"Hugeicons / Inter",style:"mira",baseColor:"neutral",theme:"neutral",iconLibrary:"hugeicons",font:"inter",fontHeading:"inherit",menuAccent:"subtle",menuColor:"default",radius:"default",rtl:false}};function jo(e){let t=new URL(`${c$1}/create`),{rtl:r,...n}=e??{};for(let[i,o]of Object.entries(n))o!==void 0&&t.searchParams.set(i,String(o));return r&&t.searchParams.set("rtl","true"),t.toString()}function We(e,t){let r=new URLSearchParams({base:e.base,style:e.style,baseColor:e.baseColor,theme:e.theme,iconLibrary:e.iconLibrary,font:e.font,rtl:String(e.rtl??false),menuAccent:e.menuAccent,menuColor:e.menuColor,radius:e.radius});return e.chartColor&&r.set("chartColor",e.chartColor),e.fontHeading&&e.fontHeading!=="inherit"&&r.set("fontHeading",e.fontHeading),t?.preset&&r.set("preset",t.preset),t?.template&&r.set("template",t.template),r.set("track","1"),`${c$1}/init?${r.toString()}`}async function Pe(){let{base:e}=await pe({type:"select",name:"base",message:`Select a ${a.info("component library")}`,choices:[{title:"Radix",value:"radix"},{title:"Base",value:"base"}]});return e||process.exit(1),e}async function Ue(e){let t=Object.entries(Me),{selectedPreset:r}=await pe({type:"select",name:"selectedPreset",message:`Which ${a.info("preset")} would you like to use?`,choices:[...t.map(([i,o])=>({title:o.title,description:o.description,value:i})),{title:"Custom",description:`Build your own at ${a.info(`${c$1}/create`)}`,value:"custom"}]});if(r||process.exit(1),r==="custom"){let i=jo({command:"init",rtl:e.rtl,base:e.base,...e.template&&{template:e.template}});b.break(),b.log(`  Build your custom preset on ${a.info(i)}`),b.log(`  Then ${a.info("copy and run the command")} from ui.shadcn.com.`),b.break();let{proceed:o}=await pe({type:"confirm",name:"proceed",message:"Open in browser?",initial:true});o&&await Po(i),process.exit(0);}let n=Me[r];return n||process.exit(1),{url:We({...n,base:e.base,rtl:e.rtl},{template:e.template}),base:e.base}}async function Be(e,t,r){let n=U$1(T$1({resolvedPaths:{cwd:t},...r?.registries&&{registries:r.registries}})),{config:i}=await V([e],n,{silent:true,writeFile:false});n=i,X$1(e,n);let[o]=await ba([e],{config:n,useCache:true}),s=o?.type==="registry:base"&&o.config?o.config:void 0,c=e;if(Eo(e)){let a=new URL(e);a.searchParams.delete("track"),c=a.toString();}return {registryBaseConfig:s,installStyleIndex:o?.extends!=="none",url:c}}function Eo(e){try{return new URL(e).pathname==="/init"&&e.startsWith(c$1)}catch{return  false}}var No=process.env.SHADCN_GITHUB_URL??"https://github.com/shadcn-ui/ui.git";function U(e){return {...e,frameworks:e.frameworks??[],scaffold:e.scaffold??Zr({title:e.title,templateDir:e.templateDir}),postInit:e.postInit??To}}function ye(e,{monorepo:t}){if(!t||!e.monorepo)return e;let r=e.monorepo,n={...e,templateDir:r.templateDir,defaultProjectName:r.defaultProjectName??r.templateDir,init:r.init??e.init,files:r.files??e.files};return n.scaffold=Zr({title:e.title,templateDir:r.templateDir}),n}function Oo(e){switch(e){case "pnpm":return ["--no-frozen-lockfile"];default:return []}}async function Ao(e,t){if(t==="pnpm")return;let r=ee__default.join(e,"pnpm-workspace.yaml"),n=ee__default.join(e,"package.json"),i=ee__default.join(e,"pnpm-lock.yaml");T.existsSync(i)&&await T.remove(i);let o=T.existsSync(r);if(T.existsSync(n)){let s=await T.readFile(n,"utf8"),c=JSON.parse(s);if(delete c.packageManager,o){let a=await T.readFile(r,"utf8"),f=[];for(let l of a.split(`
`)){let d=l.match(/^\s*-\s*["']?(.+?)["']?\s*$/);d&&f.push(d[1]);}c.workspaces=f,await T.remove(r);}await T.writeFile(n,JSON.stringify(c,null,2)+`
`);}o&&t==="npm"&&await Xr(e);}async function Xr(e){let t=await T.readdir(e,{withFileTypes:true});for(let r of t){if(r.name==="node_modules")continue;let n=ee__default.join(e,r.name);if(r.isDirectory())await Xr(n);else if(r.name==="package.json"){let i=await T.readFile(n,"utf8");if(!i.includes("workspace:"))continue;let o=JSON.parse(i),s=false;for(let c of ["dependencies","devDependencies","peerDependencies","optionalDependencies"]){let a=o[c];if(a)for(let[f,l]of Object.entries(a))typeof l=="string"&&l.startsWith("workspace:")&&(a[f]="*",s=true);}s&&await T.writeFile(n,JSON.stringify(o,null,2)+`
`);}}}function Zr({title:e,templateDir:t}){return async({projectPath:r,packageManager:n})=>{let i=w(`Creating a new ${e} project. This may take a few minutes.`).start();try{let o=process.env.SHADCN_TEMPLATE_DIR;if(o){let f=ee__default.resolve(o,t);await T.copy(f,r,{filter:l=>!l.includes("node_modules")});}else {let f=ee__default.join(Fo.tmpdir(),`shadcn-template-${Date.now()}`);await execa("git",["clone","--depth","1","--filter=blob:none","--sparse",No,f]),await execa("git",["-C",f,"sparse-checkout","set",`templates/${t}`]);let l=ee__default.resolve(f,"templates",t);await T.move(l,r),await T.remove(f);}await Ao(r,n);let c=["install",...Oo(n)];await execa(n,c,{cwd:r});let a=ee__default.join(r,"package.json");if(T.existsSync(a)){let f=await T.readFile(a,"utf8"),l=JSON.parse(f);l.name=ee__default.basename(r),await T.writeFile(a,JSON.stringify(l,null,2)+`
`);}i?.succeed(`Creating a new ${e} project.`);}catch(o){i?.fail(`Something went wrong creating a new ${e} project.`),$(o);}}}async function To({projectPath:e}){try{await execa("git",["init"],{cwd:e}),await execa("git",["add","-A"],{cwd:e}),await execa("git",["commit","-m","feat: initial commit"],{cwd:e});}catch{}}var Qr={"--font-heading":"cn-font-heading"};function Do(e){return e.startsWith("--")?e:`--${e}`}function we(e){let t=new Set;for(let r of e){for(let n of r.fonts??[]){let i=n.font?.variable;if(!i)continue;let o=Qr[i];o&&t.add(o);}for(let n of Object.values(r.cssVars??{}))for(let i of Object.keys(n??{})){let o=Qr[Do(i)];o&&t.add(o);}}return Array.from(t)}function en(e,t){if(e.includes("\0"))return  false;let r;try{r=e;let m="";for(;r!==m&&r.includes("%");)m=r,r=decodeURIComponent(r);}catch{return  false}let n=ee__default.normalize(r.replace(/\\/g,"/")),i=ee__default.normalize(t),o=m=>m.replace(/\[\.\.\..*?\]/g,"").includes("..");if(o(n)||o(r)||o(e))return  false;let s=m=>m.replace(/\[\.\.\..*?\]/g,""),c=s(e),a=s(r);if([/\.\.[\/\\]/,/[\/\\]\.\./,/\.\./,/\.\.%/,/\x00/,/[\x01-\x1f]/].some(m=>m.test(c)||m.test(a))||(e.includes("~")||r.includes("~"))&&(e.includes("../")||r.includes("../")))return  false;if(/^[a-zA-Z]:[\/\\]/.test(r))return process.platform==="win32"?r.toLowerCase().startsWith(t.toLowerCase()):false;if(ee__default.isAbsolute(n))return n.startsWith(i+ee__default.sep);let d=ee__default.resolve(i,n);return d.startsWith(i+ee__default.sep)||d===i}async function Ct(e,t,r){if(!t.resolvedPaths.tailwindCss||!Object.keys(e??{}).length)return;r={cleanupDefaultNextStyles:false,silent:false,tailwindVersion:"v3",overwriteCssVars:false,...r};let n=t.resolvedPaths.tailwindCss,i=ee__default.relative(t.resolvedPaths.cwd,n),o=w(`Updating CSS variables in ${a.info(i)}`,{silent:r.silent}).start(),s=await promises.readFile(n,"utf8"),c=await ze(s,e??{},t,{cleanupDefaultNextStyles:r.cleanupDefaultNextStyles,tailwindVersion:r.tailwindVersion,tailwindConfig:r.tailwindConfig,overwriteCssVars:r.overwriteCssVars});await promises.writeFile(n,c,"utf8"),o.succeed();}async function ze(e,t,r,n={cleanupDefaultNextStyles:false,tailwindVersion:"v3",tailwindConfig:void 0,overwriteCssVars:false}){n={cleanupDefaultNextStyles:false,tailwindVersion:"v3",tailwindConfig:void 0,overwriteCssVars:false,...n};let i=[Vo(t)];n.cleanupDefaultNextStyles&&i.push(nn()),n.tailwindVersion==="v4"&&(i=[],i.push(Bo({params:"dark (&:is(.dark *))"})),n.cleanupDefaultNextStyles&&i.push(nn()),i.push(Wo(t,{overwriteCssVars:n.overwriteCssVars})),i.push(Uo(t)),n.tailwindConfig&&(i.push(zo(n.tailwindConfig)),i.push(Go(n.tailwindConfig)),i.push(Jo(n.tailwindConfig))));let s=(await k$1(i).process(e,{from:void 0})).css;return s=s.replace(/\/\* ---break--- \*\//g,""),n.tailwindVersion==="v4"&&(s=s.replace(/(\n\s*\n)+/g,`

`)),s}function Vo(e){return {postcssPlugin:"update-css-vars",Once(t){let r=t.nodes.find(n=>n.type==="atrule"&&n.name==="layer"&&n.params==="base");r instanceof _o||(r=k$1.atRule({name:"layer",params:"base",nodes:[],raws:{semicolon:true,before:`
`,between:" "}}),t.append(r),t.insertBefore(r,k$1.comment({text:"---break---"}))),r!==void 0&&Object.entries(e).forEach(([n,i])=>{let o=n==="light"?":root":`.${n}`;Mo(r,o,i);});}}}function rn(e){let t=e.nodes.find(r=>r.type==="rule"&&r.selector===":root");if(t){let r=["--background","--foreground"];t.nodes.filter(n=>n.type==="decl"&&r.includes(n.prop)).forEach(n=>n.remove()),t.nodes.length===0&&t.remove();}}function nn(){return {postcssPlugin:"cleanup-default-next-styles",Once(e){let t=e.nodes.find(n=>n.type==="rule"&&n.selector==="body");t&&(t.nodes.find(n=>n.type==="decl"&&n.prop==="color"&&["rgb(var(--foreground-rgb))","var(--foreground)"].includes(n.value))?.remove(),t.nodes.find(n=>n.type==="decl"&&n.prop==="background"&&(n.value.startsWith("linear-gradient")||n.value==="var(--background)"))?.remove(),t.nodes.find(n=>n.type==="decl"&&n.prop==="font-family"&&n.value==="Arial, Helvetica, sans-serif")?.remove(),t.nodes.length===0&&t.remove()),rn(e);let r=e.nodes.find(n=>n.type==="atrule"&&n.params==="(prefers-color-scheme: dark)");r&&(rn(r),r.nodes.length===0&&r.remove());}}}function Mo(e,t,r){let n=e.nodes?.find(i=>i.type==="rule"&&i.selector===t);n||Object.keys(r).length>0&&(n=k$1.rule({selector:t,raws:{between:" ",before:`
  `}}),e.append(n)),Object.entries(r).forEach(([i,o])=>{let s=`--${i.replace(/^--/,"")}`,c=k$1.decl({prop:s,value:o,raws:{semicolon:true}}),a=n?.nodes.find(f=>f.type==="decl"&&f.prop===s);a?a.replaceWith(c):n?.append(c);});}function Wo(e,t){return {postcssPlugin:"update-css-vars-v4",Once(r){Object.entries(e).forEach(([n,i])=>{let o=n==="light"?":root":`.${n}`;if(n==="theme"){o="@theme";let c=Rt(r);Object.entries(i).forEach(([a,f])=>{let l=`--${a.replace(/^--/,"")}`,d=k$1.decl({prop:l,value:f,raws:{semicolon:true}}),m=c?.nodes?.find(h=>h.type==="decl"&&h.prop===l);t.overwriteCssVars?m?m.replaceWith(d):c?.append(d):m||c?.append(d);});return}let s=r.nodes?.find(c=>c.type==="rule"&&c.selector===o);!s&&Object.keys(i).length>0&&(s=k$1.rule({selector:o,nodes:[],raws:{semicolon:true,between:" ",before:`
`}}),r.append(s),r.insertBefore(s,k$1.comment({text:"---break---"}))),Object.entries(i).forEach(([c,a])=>{let f=`--${c.replace(/^--/,"")}`;f==="--sidebar-background"&&(f="--sidebar"),on(a)&&(a=`hsl(${a})`);let l=k$1.decl({prop:f,value:a,raws:{semicolon:true}}),d=s?.nodes.find(m=>m.type==="decl"&&m.prop===f);t.overwriteCssVars?d?d.replaceWith(l):s?.append(l):d||s?.append(l);});});}}}function Uo(e){return {postcssPlugin:"update-theme",Once(t){let r=Array.from(new Set(Object.keys(e).flatMap(o=>Object.keys(e[o]||{}))));if(!r.length)return;let n=Rt(t),i=n.nodes?.filter(o=>o.type==="decl"&&o.prop.startsWith("--"));for(let o of r){let s=Object.values(e).find(d=>d[o])?.[o];if(!s)continue;if(o==="radius"){let d={sm:"calc(var(--radius) * 0.6)",md:"calc(var(--radius) * 0.8)",lg:"var(--radius)",xl:"calc(var(--radius) * 1.4)","2xl":"calc(var(--radius) * 1.8)","3xl":"calc(var(--radius) * 2.2)","4xl":"calc(var(--radius) * 2.6)"};for(let[m,h]of Object.entries(d)){let g=k$1.decl({prop:`--radius-${m}`,value:h,raws:{semicolon:true}});n?.nodes?.find(w=>w.type==="decl"&&w.prop===g.prop)||n?.append(g);}continue}let c=on(s)||Yo(s)?`--color-${o.replace(/^--/,"")}`:`--${o.replace(/^--/,"")}`;c==="--color-sidebar-background"&&(c="--color-sidebar");let a=`var(--${o})`;c==="--color-sidebar"&&(a="var(--sidebar)");let f=k$1.decl({prop:c,value:a,raws:{semicolon:true}});n?.nodes?.find(d=>d.type==="decl"&&d.prop===f.prop)||(i?.length?n?.insertAfter(i[i.length-1],f):n?.append(f));}}}}function Rt(e){let t=e.nodes.find(r=>r.type==="atrule"&&r.name==="theme"&&r.params==="inline");return t||(t=k$1.atRule({name:"theme",params:"inline",nodes:[],raws:{semicolon:true,between:" ",before:`
`}}),e.append(t),e.insertBefore(t,k$1.comment({text:"---break---"}))),t}function Bo({params:e}){return {postcssPlugin:"add-custom-variant",Once(t){if(!t.nodes.find(n=>n.type==="atrule"&&n.name==="custom-variant")){let n=t.nodes.filter(o=>o.type==="atrule"&&o.name==="import"),i=k$1.atRule({name:"custom-variant",params:e,raws:{semicolon:true,before:`
`}});if(n.length>0){let o=n[n.length-1];t.insertAfter(o,i);}else t.insertAfter(t.nodes[0],i);t.insertBefore(i,k$1.comment({text:"---break---"}));}}}}function zo(e){return {postcssPlugin:"update-tailwind-config",Once(t){if(!e?.plugins)return;let n=Ho(t)==="single"?"'":'"',i=t.nodes.filter(s=>s.type==="atrule"&&s.name==="plugin"),o=i[i.length-1]||t.nodes[0];for(let s of e.plugins){let c=s.replace(/^require\(["']|["']\)$/g,"");if(i.some(f=>f.params.replace(/["']/g,"")===c))continue;let a=k$1.atRule({name:"plugin",params:`${n}${c}${n}`,raws:{semicolon:true,before:`
`}});t.insertAfter(o,a),t.insertBefore(a,k$1.comment({text:"---break---"}));}}}}function Jo(e){return {postcssPlugin:"update-tailwind-config-keyframes",Once(t){if(!e?.theme?.extend?.keyframes)return;let r=Rt(t),n=r.nodes?.filter(o=>o.type==="atrule"&&o.name==="keyframes"),i=z.record(z.string(),z.record(z.string(),z.string()));for(let[o,s]of Object.entries(e.theme.extend.keyframes)){if(typeof o!="string")continue;let c=i.safeParse(s);if(!c.success||n?.find(f=>f.type==="atrule"&&f.name==="keyframes"&&f.params===o))continue;let a=k$1.atRule({name:"keyframes",params:o,nodes:[],raws:{semicolon:true,between:" ",before:`
  `}});for(let[f,l]of Object.entries(c.data)){let d=k$1.rule({selector:f,nodes:Object.entries(l).map(([m,h])=>k$1.decl({prop:m,value:h,raws:{semicolon:true,before:`
      `,between:": "}})),raws:{semicolon:true,between:" ",before:`
    `}});a.append(d);}r.append(a),r.insertBefore(a,k$1.comment({text:"---break---"}));}}}}function Go(e){return {postcssPlugin:"update-tailwind-config-animation",Once(t){if(!e?.theme?.extend?.animation)return;let r=Rt(t),n=r.nodes?.filter(o=>o.type==="decl"&&o.prop.startsWith("--animate-")),i=z.record(z.string(),z.string()).safeParse(e.theme.extend.animation);if(i.success)for(let[o,s]of Object.entries(i.data)){let c=`--animate-${o}`;if(n?.find(f=>f.prop===c))continue;let a=k$1.decl({prop:c,value:s,raws:{semicolon:true,between:": ",before:`
  `}});r.append(a);}}}}function Ho(e){return e.nodes[0].toString().includes("'")?"single":"double"}function on(e){if(e.startsWith("hsl")||e.startsWith("rgb")||e.startsWith("#")||e.startsWith("oklch"))return  false;let t=e.split(" ");return t.length===3&&t.slice(1,3).every(r=>r.includes("%"))}function Yo(e){return e.startsWith("hsl")||e.startsWith("rgb")||e.startsWith("#")||e.startsWith("oklch")||e.includes("--color-")}async function Je(e,t,r){let n=e&&Object.keys(e).length>0,i=Object.keys(r.cssVars??{}).length>0;if(!t.resolvedPaths.tailwindCss||!n&&!i)return;r={silent:false,...r};let o=t.resolvedPaths.tailwindCss,s=ee__default.relative(t.resolvedPaths.cwd,o),c=w(`Updating ${a.info(s)}`,{silent:r.silent}).start(),a$1=await promises.readFile(o,"utf8");i&&(a$1=await ze(a$1,r.cssVars,t,{cleanupDefaultNextStyles:r.cleanupDefaultNextStyles,tailwindVersion:r.tailwindVersion,tailwindConfig:r.tailwindConfig,overwriteCssVars:r.overwriteCssVars})),n&&(a$1=await Xt(a$1,e)),await promises.writeFile(o,a$1,"utf8"),c.succeed();}async function Xt(e,t){let r=[Xo(t)],n=await k$1(r).process(e,{from:void 0}),i=n.css,o=n.root;if(o.nodes&&o.nodes.length>0){let s=o.nodes[o.nodes.length-1];s.type==="atrule"&&!s.nodes&&!i.trimEnd().endsWith(";")&&(i=i.trimEnd()+";");}return i=i.replace(/\/\* ---break--- \*\//g,""),i=i.replace(/(\n\s*\n)+/g,`

`),i=i.trimEnd(),i}function Xo(e){return {postcssPlugin:"update-css",Once(t){for(let[r,n]of Object.entries(e))if(r.startsWith("@")){let i=r.match(/@([a-zA-Z-]+)\s*(.*)/);if(!i)continue;let[,o,s]=i;if(o==="import"){if(!t.nodes?.find(a=>a.type==="atrule"&&a.name==="import"&&a.params===s)){let a=k$1.atRule({name:"import",params:s,raws:{semicolon:true}}),f=t.nodes?.filter(l=>l.type==="atrule"&&l.name==="import");if(f&&f.length>0){let l=f[f.length-1];a.raws.before=`
`,t.insertAfter(l,a);}else !t.nodes||t.nodes.length,a.raws.before="",t.prepend(a);}}else if(o==="plugin"){let c=s;s&&!s.startsWith('"')&&!s.startsWith("'")&&(c=`"${s}"`);let a=l=>l.startsWith('"')&&l.endsWith('"')||l.startsWith("'")&&l.endsWith("'")?l.slice(1,-1):l;if(!t.nodes?.find(l=>l.type!=="atrule"||l.name!=="plugin"?false:a(l.params)===a(s))){let l=k$1.atRule({name:"plugin",params:c,raws:{semicolon:true,before:`
`}}),d=t.nodes?.filter(h=>h.type==="atrule"&&h.name==="import"),m=t.nodes?.filter(h=>h.type==="atrule"&&h.name==="plugin");if(m&&m.length>0){let h=m[m.length-1];t.insertAfter(h,l);}else if(d&&d.length>0){let h=d[d.length-1];t.insertAfter(h,l),t.insertBefore(l,k$1.comment({text:"---break---"})),t.insertAfter(l,k$1.comment({text:"---break---"}));}else t.prepend(l),t.insertBefore(l,k$1.comment({text:"---break---"})),t.insertAfter(l,k$1.comment({text:"---break---"}));}}else if(typeof n=="object"&&Object.keys(n).length===0){if(!t.nodes?.find(a=>a.type==="atrule"&&a.name===o&&a.params===s)){let a=k$1.atRule({name:o,params:s,raws:{semicolon:true}});t.append(a),t.insertBefore(a,k$1.comment({text:"---break---"}));}}else if(o==="keyframes"){let c=t.nodes?.find(l=>l.type==="atrule"&&l.name==="theme"&&l.params==="inline");c||(c=k$1.atRule({name:"theme",params:"inline",raws:{semicolon:true,between:" ",before:`
`}}),t.append(c),t.insertBefore(c,k$1.comment({text:"---break---"})));let a=c.nodes?.find(l=>l.type==="atrule"&&l.name==="keyframes"&&l.params===s),f;if(a?(f=k$1.atRule({name:"keyframes",params:s,raws:{semicolon:true,between:" ",before:`
  `}}),a.replaceWith(f)):(f=k$1.atRule({name:"keyframes",params:s,raws:{semicolon:true,between:" ",before:`
  `}}),c.append(f)),typeof n=="object")for(let[l,d]of Object.entries(n))be(f,l,d);}else if(o==="utility"){let c=t.nodes?.find(a=>a.type==="atrule"&&a.name===o&&a.params===s);if(c){if(typeof n=="object")for(let[a,f]of Object.entries(n))if(typeof f=="string"){let l=c.nodes?.find(m=>m.type==="decl"&&m.prop===a),d=k$1.decl({prop:a,value:f,raws:{semicolon:true,before:`
    `}});l?l.replaceWith(d):c.append(d);}else if(a.startsWith("@")&&typeof f=="object"&&f!==null&&Object.keys(f).length===0){let l=a.match(/@([a-zA-Z-]+)\s*(.*)/);if(l){let[,d,m]=l;if(!c.nodes?.find(g=>g.type==="atrule"&&g.name===d&&g.params===m)){let g=k$1.atRule({name:d,params:m,raws:{semicolon:true,before:`
    `}});c.append(g);}}}else typeof f=="object"&&be(c,a,f);}else {let a=k$1.atRule({name:o,params:s,raws:{semicolon:true,between:" ",before:`
`}});if(t.append(a),t.insertBefore(a,k$1.comment({text:"---break---"})),typeof n=="object")for(let[f,l]of Object.entries(n))if(typeof l=="string"){let d=k$1.decl({prop:f,value:l,raws:{semicolon:true,before:`
    `}});a.append(d);}else if(f.startsWith("@")&&typeof l=="object"&&l!==null&&Object.keys(l).length===0){let d=f.match(/@([a-zA-Z-]+)\s*(.*)/);if(d){let[,m,h]=d;if(!a.nodes?.find(w=>w.type==="atrule"&&w.name===m&&w.params===h)){let w=k$1.atRule({name:m,params:h,raws:{semicolon:true,before:`
    `}});a.append(w);}}}else typeof l=="object"&&be(a,f,l);}}else o==="property"?be(t,r,n):an(t,o,s,n);}else be(t,r,n);}}}function an(e,t,r,n){let i=e.nodes?.find(o=>o.type==="atrule"&&o.name===t&&o.params===r);if(i||(i=k$1.atRule({name:t,params:r,raws:{semicolon:true,between:" ",before:`
`}}),e.append(i),e.insertBefore(i,k$1.comment({text:"---break---"}))),typeof n=="object")for(let[o,s]of Object.entries(n))if(o.startsWith("@")){let c=o.match(/@([a-zA-Z-]+)\s*(.*)/);if(c){let[,a,f]=c;an(i,a,f,s);}}else be(i,o,s);else if(typeof n=="string")try{let s=k$1.parse(`.temp{${n}}`).first;if(s&&s.nodes){let c=k$1.rule({selector:"temp",raws:{semicolon:!0,between:" ",before:`
  `}});s.nodes.forEach(a=>{if(a.type==="decl"){let f=a.clone();f.raws.before=`
    `,c.append(f);}}),c.nodes?.length&&i.append(c);}}catch(o){throw console.error("Error parsing at-rule content:",n,o),o}}function be(e,t,r){let n=e.nodes?.find(i=>i.type==="rule"&&i.selector===t);if(n||(n=k$1.rule({selector:t,raws:{semicolon:true,between:" ",before:`
  `}}),e.append(n)),typeof r=="object"){for(let[i,o]of Object.entries(r))if(i.startsWith("@")&&typeof o=="object"&&o!==null&&Object.keys(o).length===0){let s=i.match(/@([a-zA-Z-]+)\s*(.*)/);if(s){let[,c,a]=s;if(!n.nodes?.find(l=>l.type==="atrule"&&l.name===c&&l.params===a)){if(c==="apply"){let d=n.nodes?.find(m=>m.type==="atrule"&&m.name==="apply");if(d){d.params=twMerge(d.params,a);continue}}let l=k$1.atRule({name:c,params:a,raws:{semicolon:true,before:`
    `}});n.append(l);}}}else if(typeof o=="string"){let s=k$1.decl({prop:i,value:o,raws:{semicolon:true,before:`
    `}}),c=n.nodes?.find(a=>a.type==="decl"&&a.prop===i);c?c.replaceWith(s):n.append(s);}else if(typeof o=="object"){let s=i.startsWith("&")?t.replace(/^([^:]+)/,`$1${i.substring(1)}`):i;be(e,s,o);}}else if(typeof r=="string")try{let o=k$1.parse(`.temp{${r}}`).first;o&&o.nodes&&o.nodes.forEach(s=>{if(s.type==="decl"){let c=s.clone();c.raws.before=`
    `,n?.append(c);}});}catch(i){throw console.error("Error parsing rule content:",t,r,i),i}}async function D(e,t,r,n){if(e=Array.from(new Set(e)),t=Array.from(new Set(t)),!e?.length&&!t?.length)return;n={silent:false,...n};let i=w("Installing dependencies.",{silent:n.silent})?.start(),o=await ei(r),s="";if(Qo(r)&&o==="npm")if(n.silent)s="force";else {i.stopAndPersist(),b.warn(`
It looks like you are using React 19. 
Some packages may fail to install due to peer dependency issues in npm (see ${c$1}/react-19).
`);let c=await pe([{type:"select",name:"flag",message:"How would you like to proceed?",choices:[{title:"Use --force",value:"force"},{title:"Use --legacy-peer-deps",value:"legacy-peer-deps"}]}]);c&&(s=c.flag);}i?.start(),await ti(o,e,t,r.resolvedPaths.cwd,s),i?.succeed();}function Qo(e){let t=qa(e.resolvedPaths.cwd,false);if(!t?.dependencies?.react)return  false;let r=/^(?:\^|~)?19(?:\.\d+)*(?:-.*)?$/.test(t.dependencies.react),n=t.dependencies["react-day-picker"]?.startsWith("8");return r&&n}async function ei(e){return qa(e.resolvedPaths.cwd,false)?.dependencies?.expo?"expo":a$2(e.resolvedPaths.cwd)}async function ti(e,t,r,n,i){if(e==="npm")return ri(t,r,n,i);if(e==="deno")return ni(t,r,n);if(e==="expo")return oi(t,r,n);t?.length&&await execa(e,["add",...t],{cwd:n}),r?.length&&await execa(e,["add","-D",...r],{cwd:n});}async function ri(e,t,r,n){e.length&&await execa("npm",["install",...n?[`--${n}`]:[],...e],{cwd:r}),t.length&&await execa("npm",["install",...n?[`--${n}`]:[],"-D",...t],{cwd:r});}async function ni(e,t,r){e?.length&&await execa("deno",["add",...e.map(n=>`npm:${n}`)],{cwd:r}),t?.length&&await execa("deno",["add","-D",...t.map(n=>`npm:${n}`)],{cwd:r});}async function oi(e,t,r){e.length&&await execa("npx",["expo","install",...e],{cwd:r}),t.length&&await execa("npx",["expo","install","-- -D",...t],{cwd:r});}async function Qt(e,t$1,r){if(!e||Object.keys(e).length===0)return {envVarsAdded:[],envFileUpdated:null,envFileCreated:null};r={silent:false,...r};let n=w("Adding environment variables.",{silent:r.silent})?.start(),i=t$1.resolvedPaths.cwd,o=ee__default.join(i,".env.local"),s=t(i);s&&(o=s);let c=existsSync(o),a$1=ee__default.basename(o),f=Object.entries(e).map(([h,g])=>`${h}=${g}`).join(`
`),l=[],d=null,m=null;if(c){let h=await promises.readFile(o,"utf-8"),g=v(h,f);if(l=u(h,f),l.length>0){if(await promises.writeFile(o,g,"utf-8"),d=ee__default.relative(i,o),n?.succeed(`Added the following variables to ${a.info(a$1)}:`),!r.silent)for(let w of l)b.log(`  ${a.success("+")} ${w}`);}else n?.stop();}else if(await promises.writeFile(o,f+`
`,"utf-8"),m=ee__default.relative(i,o),l=Object.keys(e),n?.succeed(`Added the following variables to ${a.info(a$1)}:`),!r.silent)for(let h of l)b.log(`  ${a.success("+")} ${h}`);return !r.silent&&l.length>0&&b.break(),{envVarsAdded:l,envFileUpdated:d,envFileCreated:m}}var pi=new Set(["--font-sans","--font-serif","--font-mono"]);async function He(e,t){if(!e.fonts?.length)return e;let r=await ra$1(t.resolvedPaths.cwd);if(!r)return e;e.cssVars??={},e.cssVars.theme??={};let n=r.framework.name==="next-app"||r.framework.name==="next-pages";for(let i of e.fonts)if(n)e.cssVars.theme[i.font.variable]=`var(${i.font.variable})`;else {let o=i.name.replace("font-",""),s=i.font.dependency??`@fontsource-variable/${o}`;e.dependencies??=[],e.dependencies.push(s),e.css??={},e.css[`@import "${s}"`]={},e.cssVars.theme[i.font.variable]=i.font.family;}if(e.fonts.length>0){let i=new Map;for(let o of e.fonts){let s=o.font.selector??hi(o.font.variable);if(!s)continue;let c=o.font.variable.replace("--","");i.has(s)||i.set(s,[]),i.get(s).push(c);}e.css??={},e.css["@layer base"]??={};for(let[o,s]of Array.from(i.entries())){let c=s.join(" ");e.css["@layer base"][o]??={};let a=Object.keys(e.css["@layer base"][o]).find(f=>f.startsWith("@apply "));a?(delete e.css["@layer base"][o][a],e.css["@layer base"][o][`${a} ${c}`]={}):e.css["@layer base"][o][`@apply ${c}`]={};}}return e}async function Ye(e,t,r){if(!e?.length)return;let n=await ra$1(t.resolvedPaths.cwd);if(!n||n.framework.name!=="next-app"&&n.framework.name!=="next-pages")return;let i=w("Updating fonts.",{silent:r.silent})?.start();try{await mi(e,t,n),i?.succeed("Updating fonts.");}catch(o){throw i?.fail("Failed to update fonts."),o}}async function mi(e,t,r){let n=await di(t,r);if(!n)return;let i=await promises.readFile(n,"utf-8"),o=await ui(i,e,t);o!==i&&await promises.writeFile(n,o,"utf-8");}async function di(e,t){let r=e.resolvedPaths.cwd,n=t.isSrcDir,o=t.isTsx?"tsx":"jsx",s=n?[`src/app/layout.${o}`,`app/layout.${o}`]:[`app/layout.${o}`];for(let c of s){let a=ee__default.join(r,c);if(existsSync(a))return a}return null}async function ui(e,t,r){let i=new Project({compilerOptions:{}}).createSourceFile("layout.tsx",e,{scriptKind:ScriptKind.TSX}),o=t.filter(d=>d.font.provider==="google"),s=[],c=[];for(let d of o){let m=d.font.import;if(!m)continue;let h=i.getImportDeclaration(v=>v.getModuleSpecifierValue()==="next/font/google"),g=false;h?(g=h.getNamedImports().some($=>$.getName()===m),g||h.addNamedImport(m)):i.addImportDeclaration({moduleSpecifier:"next/font/google",namedImports:[m]});let w=wi(m,d.font.variable),C=gi(d),b=vi(i,d.font.variable),P=w;if(!(g&&!b&&kt(d.font.variable)&&!Ci(i,m))){if(b)b.setInitializer(`${m}(${C})`),b.getName()!==w&&b.rename(w),P=w;else {let v=Ri(i);i.insertVariableStatement(v,{declarationKind:VariableDeclarationKind.Const,declarations:[{name:w,initializer:`${m}(${C})`}]}).appendWhitespace(`
`);}s.push(P),yi(d)&&c.push(d.font.variable.replace("--",""));}}let a=new Set(["font-sans","font-serif","font-mono"]),f=[...c].reverse().find(d=>a.has(d)),l=c.filter(d=>!a.has(d));return f&&l.unshift(f),s.length>0&&Si(i,s,l,r),i.getFullText()}function gi(e){let t={};return e.font.subsets?.length&&(t.subsets=e.font.subsets),e.font.weight?.length&&(t.weight=e.font.weight),t.variable=e.font.variable,JSON.stringify(t).replace(/"([^"]+)":/g,"$1:").replace(/"/g,"'")}function kt(e){return pi.has(e)}function hi(e){return kt(e)?"html":null}function yi(e){return !e.font.selector&&kt(e.font.variable)}function wi(e,t){let r=bi(e);return kt(t)?r:`${r}${xi(t.replace(/^--font-/,""))}`}function bi(e){return e.split("_").map((t,r)=>r===0?t.toLowerCase():t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}function xi(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function vi(e,t){let r=e.getVariableStatements();for(let n of r)for(let i of n.getDeclarations()){let o=i.getInitializer();if(!o||o.getKind()!==SyntaxKind.CallExpression)continue;let c=o.getArguments();if(c.length===0)continue;let a=c[0].getText();if(a.includes("variable:")&&a.includes(t))return i}return null}function Ci(e,t){let r=e.getVariableStatements();for(let n of r)for(let i of n.getDeclarations()){let o=i.getInitializer();if(!o||o.getKind()!==SyntaxKind.CallExpression)continue;let s=o;if(s.getExpression().getText()!==t)continue;let c=s.getArguments();if(!c.length)continue;let a=c[0].getText();if(a.includes("variable:")&&a.includes("--font-heading"))return  true}return  false}function Ri(e){let t=e.getImportDeclarations();return t.length>0?t[t.length-1].getChildIndex()+1:0}function Si(e,t,r,n){let i=e.getDescendantsOfKind(SyntaxKind.JsxOpeningElement);for(let o of i){if(o.getTagNameNode().getText()!=="html")continue;let c=r.map(h=>`"${h}"`),a=t.map(h=>`${h}.variable`),f=[...c,...a],l=o.getAttribute("className");if(!l){Ge(e,n),o.addAttribute({name:"className",initializer:`{cn(${f.join(", ")})}`});return}if(l.getKind()!==SyntaxKind.JsxAttribute)return;let d=l.asKindOrThrow(SyntaxKind.JsxAttribute),m=d.getInitializer();if(!m)return;if(m.getKind()===SyntaxKind.StringLiteral){let h=m.getText().slice(1,-1);Ge(e,n),d.setInitializer(`{cn("${h}", ${f.join(", ")})}`);}else if(m.getKind()===SyntaxKind.JsxExpression){let h=m.asKindOrThrow(SyntaxKind.JsxExpression),g=h.getExpression();if(!g)return;let w=g.getText();if(w.startsWith("cn(")){let C=a.every(R=>w.includes(R)),b=r.every(R=>w.includes(`"${R}"`)),P=["font-sans","font-serif","font-mono"].filter(R=>!r.includes(R)).some(R=>w.includes(`"${R}"`));if(C&&b&&!P)continue;let v=$i(w,a);v=Ii(v);let $=Pi(v,f);h.replaceWithText(`{${$}}`);}else if(/^\w+\.variable$/.test(w)){if(a.includes(w)&&r.length===0)continue;Ge(e,n);let b=(w.split(".")[0]??"").toLowerCase().includes("heading")||r.length===0;h.replaceWithText(b?`{cn(${w}, ${f.join(", ")})}`:`{cn(${f.join(", ")})}`);}else if(w.startsWith("`")&&w.endsWith("`")){let C=ki(w);Ge(e,n);let b=new Set(f),P=new Set(["font-sans","font-serif","font-mono"].map($=>`"${$}"`)),v=C.filter($=>!b.has($)&&!P.has($));h.replaceWithText(`{cn(${[...v,...f].join(", ")})}`);}else Ge(e,n),h.replaceWithText(`{cn(${w}, ${f.join(", ")})}`);}}}function Ge(e,t){if(!e.getImportDeclaration(n=>n.getNamedImports().some(o=>o.getName()==="cn"))){let n=e.getImportDeclaration(i=>i.getModuleSpecifierValue().includes("/lib/utils"));n?n.getNamedImports().some(o=>o.getName()==="cn")||n.addNamedImport("cn"):e.addImportDeclaration({moduleSpecifier:t.aliases.utils,namedImports:["cn"]});}}function ki(e){let t=[],r=[],i=e.slice(1,-1).split(/(\$\{[^}]+\})/);for(let o of i)if(o)if(o.startsWith("${")&&o.endsWith("}")){let s=o.slice(2,-1).trim();s&&r.push(s);}else {let s=o.trim().split(/\s+/).filter(Boolean);for(let c of s)t.push(`"${c}"`);}return [...t,...r]}function $i(e,t){let r=e;for(let n of t)r=r.replace(new RegExp(`,?\\s*${n.replace(".","\\.")}`,"g"),"").replace(/cn\(\s*,/,"cn(");return r}function Ii(e){let t=e;for(let r of ["font-sans","font-serif","font-mono"])t=t.replace(new RegExp(`,?\\s*"${r}"`,"g"),"").replace(/cn\(\s*,/,"cn(");return t}function Pi(e,t){let r=t.join(", ");return e.replace(/\)$/,`, ${r})`)}async function re(e,t,r){r={overwrite:false,silent:false,isNewProject:false,...r};let n=await P(t);return n&&n.ui&&n.ui.resolvedPaths.cwd!==t.resolvedPaths.cwd?await Fi(e,t,n,{...r,isRemote:e?.length===1&&!!e[0].match(/\/chat\/b\//)}):await Ei(e,t,{...r,skipFonts:r.skipFonts})}async function Ei(e,t,r){if(!e.length)return;let n=w("Checking registry.",{silent:r.silent})?.start(),i=await _(e,U$1(t));if(!i)return n?.fail(),$(new Error("Failed to fetch components from registry."));try{fn(i.files??[],t.resolvedPaths.cwd);}catch(a){return n?.fail(),$(a)}n?.succeed();let o=await ta(t);r.skipFonts||(i=await He(i,t));let s=we([i]);await D(i.dependencies,i.devDependencies,t,{silent:r.silent}),await Y$1(i.tailwind?.config,t,{silent:r.silent,tailwindVersion:o}),await Qt(i.envVars,t,{silent:r.silent}),r.skipFonts||await Ye(i.fonts,t,{silent:r.silent}),await D$1(i.files,t,{overwrite:r.overwrite,silent:r.silent,path:r.path,supportedFontMarkers:s});let c=i.cssVars?r.overwriteCssVars??await ln(e,t):void 0;await Je(i.css,t,{silent:r.silent,cssVars:i.cssVars,cleanupDefaultNextStyles:r.isNewProject,overwriteCssVars:c,tailwindVersion:o,tailwindConfig:i.tailwind?.config}),i.docs&&b.info(i.docs);}async function Fi(e,t,r,n){if(!e.length)return;let i=w("Checking registry.",{silent:n.silent})?.start(),o=await _(e,U$1(t));if(!o)return i?.fail(),$(new Error("Failed to fetch components from registry."));try{fn(o.files??[],t.resolvedPaths.cwd);}catch(R){return i?.fail(),$(R)}i?.succeed();let s=[],c=[],a=[],f=w("Installing components.")?.start(),l=r.ui,d=await ta(l),m=R(t.resolvedPaths.cwd,l.resolvedPaths.ui);o=await He(o,t);let h=we([o]);await D(o.dependencies,o.devDependencies,l,{silent:true}),o.tailwind?.config&&(await Y$1(o.tailwind?.config,l,{silent:true,tailwindVersion:d}),c.push(ee__default.relative(m,l.resolvedPaths.tailwindConfig))),o.envVars&&await Qt(o.envVars,l,{silent:true}),await Ye(o.fonts,t,{silent:true});let g=new Map;for(let R of o.files??[]){let _=R.type||"registry:ui";g.has(_)||g.set(_,[]),g.get(_).push(R);}let w$1={"registry:ui":"ui","registry:hook":"hooks","registry:lib":"lib"};for(let R$1 of Array.from(g.keys())){let _=g.get(R$1),ue=w$1[R$1],De=ue&&r[ue]?r[ue]:t,rt=R(t.resolvedPaths.cwd,De.resolvedPaths.ui||De.resolvedPaths.cwd),Wt=await Q(rt,De.resolvedPaths.cwd)??De.resolvedPaths.cwd,Ut=await D$1(_,De,{overwrite:n.overwrite,silent:true,rootSpinner:f,isRemote:n.isRemote,isWorkspace:true,path:n.path,supportedFontMarkers:h});s.push(...Ut.filesCreated.map(Le=>ee__default.relative(rt,ee__default.join(Wt,Le)))),c.push(...Ut.filesUpdated.map(Le=>ee__default.relative(rt,ee__default.join(Wt,Le)))),a.push(...Ut.filesSkipped.map(Le=>ee__default.relative(rt,ee__default.join(Wt,Le))));}let C=o.cssVars?n.overwriteCssVars??await ln(e,t):void 0;await Je(o.css,l,{silent:true,cssVars:o.cssVars,overwriteCssVars:C,tailwindVersion:d,tailwindConfig:o.tailwind?.config}),(o.cssVars||o.css)&&c.push(ee__default.relative(m,l.resolvedPaths.tailwindCss)),f?.succeed();let b$1=Array.from(new Set(s)).sort(),P=Array.from(new Set(c.filter(R=>!s.includes(R)))).sort(),v=Array.from(new Set(a)).sort();if(!(b$1.length||P.length)&&!v.length&&w("No files updated.",{silent:n.silent})?.info(),b$1.length){w(`Created ${b$1.length} ${b$1.length===1?"file":"files"}:`,{silent:n.silent})?.succeed();for(let R of b$1)b.log(`  - ${R}`);}if(P.length){w(`Updated ${P.length} ${P.length===1?"file":"files"}:`,{silent:n.silent})?.info();for(let R of P)b.log(`  - ${R}`);}if(v.length){w(`Skipped ${v.length} ${v.length===1?"file":"files"}: (use --overwrite to overwrite)`,{silent:n.silent})?.info();for(let R of v)b.log(`  - ${R}`);}o.docs&&b.info(o.docs);}async function ln(e,t){let r=await ba(e,{config:t});return z.array(n).parse(r).some(i=>i.type==="registry:theme"||i.type==="registry:style"||i.type==="registry:font"||i.type==="registry:base")}function fn(e,t){for(let r of e)if(r?.target&&!en(r.target,t))throw new Error(`We found an unsafe file path "${r.target} in the registry item. Installation aborted.`)}async function fe(e){let t=ee__default.resolve(e.projectPath,"packages/ui"),r=ee__default.resolve(e.projectPath,"apps/web"),n=ee__default.resolve(t,"components.json"),i=await T.readJson(n);e.registryBaseConfig&&(i=pn(i,e.registryBaseConfig)),i.tailwind.baseColor="neutral",e.rtl&&(i.rtl=true),e.menuColor&&(i.menuColor=e.menuColor),e.menuAccent&&(i.menuAccent=e.menuAccent),e.iconLibrary&&(i.iconLibrary=e.iconLibrary),await T.writeJson(n,i,{spaces:2});let o=ee__default.resolve(r,"components.json"),s=await T.readJson(o);e.registryBaseConfig&&(s=pn(s,e.registryBaseConfig)),s.tailwind.baseColor="neutral",e.rtl&&(s.rtl=true),e.menuColor&&(s.menuColor=e.menuColor),e.menuAccent&&(s.menuAccent=e.menuAccent),e.iconLibrary&&(s.iconLibrary=e.iconLibrary),await T.writeJson(o,s,{spaces:2});let c$1=await O(t,c.parse(i)),{config:a}=await V(e.components,c$1,{silent:true});await re(e.components,a,{overwrite:true,silent:e.silent,isNewProject:true,skipFonts:true});let f=await O(r,c.parse(s)),l=await _(e.components,U$1(a));if(l?.fonts?.length){let m={},h=new Set;for(let g of l.fonts){let w=g.name.replace(/^font-heading-/,"").replace("font-",""),C=g.font.dependency??`@fontsource-variable/${w}`;m[g.font.variable]=g.font.family,h.add(C);}await D(Array.from(h),[],c$1,{silent:true}),await Ct({theme:m},c$1,{silent:e.silent,overwriteCssVars:false,tailwindVersion:"v4"}),await Je(Object.fromEntries(Array.from(h).map(g=>[`@import "${g}"`,{}])),c$1,{silent:e.silent});}let d=c$1.iconLibrary;if(d&&d in a$3){let m=[...a$3[d].packages];await D(m,[],c$1,{silent:true}),await D(m,[],f,{silent:true});}return f}var dn=U({name:"astro",title:"Astro",defaultProjectName:"astro-app",templateDir:"astro-app",frameworks:["astro"],create:async()=>{},files:[{type:"registry:page",path:"src/pages/index.astro",target:"src/pages/index.astro",content:mn`---
import Layout from "@/layouts/main.astro"
import { ComponentExample } from "@/components/component-example"
---

<Layout>
  <ComponentExample client:load />
</Layout>
`}],monorepo:{templateDir:"astro-monorepo",init:fe,files:[{type:"registry:page",path:"src/pages/index.astro",target:"src/pages/index.astro",content:mn`---
import "@workspace/ui/globals.css"
import { ComponentExample } from "@/components/component-example"
---

<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width" />
    <title>Astro App</title>
  </head>
  <body>
    <ComponentExample client:load />
  </body>
</html>
`}]}});var un=U({name:"laravel",title:"Laravel",description:"Requires `laravel new`",defaultProjectName:"laravel-app",templateDir:"laravel-app",frameworks:["laravel"],scaffold:async()=>{b.break(),b.log(`  Please create a new app with ${a.info("laravel new --react")} first then run ${a.info("shadcn init")}.`),b.log(`  See ${a.info(`${c$1}/docs/installation/laravel`)} for more information.`),b.break(),process.exit(0);},create:async()=>{}});var yn=U({name:"next",title:"Next.js",defaultProjectName:"next-app",templateDir:"next-app",frameworks:["next-app","next-pages"],create:async()=>{},files:[{type:"registry:page",path:"app/page.tsx",target:"app/page.tsx",content:mn`import { ComponentExample } from "@/components/component-example";

export default function Page() {
  return <ComponentExample />;
}
`}],monorepo:{templateDir:"next-monorepo",init:async e=>{let t=ee__default.resolve(e.projectPath,"packages/ui"),r=ee__default.resolve(e.projectPath,"apps/web"),n=ee__default.resolve(t,"components.json"),i=await T.readJson(n);e.registryBaseConfig&&(i=pn(i,e.registryBaseConfig)),i.tailwind.baseColor="neutral",e.rtl&&(i.rtl=true),await T.writeJson(n,i,{spaces:2});let o=ee__default.resolve(r,"components.json"),s=await T.readJson(o);e.registryBaseConfig&&(s=pn(s,e.registryBaseConfig)),s.tailwind.baseColor="neutral",e.rtl&&(s.rtl=true),await T.writeJson(o,s,{spaces:2});let c$1=await O(t,c.parse(i)),{config:a}=await V(e.components,c$1,{silent:true});await re(e.components,a,{overwrite:true,silent:e.silent,isNewProject:true,skipFonts:true});let f=await O(r,c.parse(s)),l=await _(e.components,U$1(a));if(l?.fonts?.length){let m={};for(let h of l.fonts)m[h.font.variable]=`var(${h.font.variable})`;await Ct({theme:m},c$1,{silent:e.silent,overwriteCssVars:false,tailwindVersion:"v4"}),await Ye(l.fonts,f,{silent:e.silent});}let d=c$1.iconLibrary;if(d&&d in a$3){let m=[...a$3[d].packages];await D(m,[],c$1,{silent:true}),await D(m,[],f,{silent:true});}return f},files:[{type:"registry:page",path:"app/page.tsx",target:"app/page.tsx",content:mn`import { ComponentExample } from "@/components/component-example";

export default function Page() {
  return <ComponentExample />;
}
`}]}});var bn=U({name:"react-router",title:"React Router",defaultProjectName:"react-router-app",templateDir:"react-router-app",frameworks:["react-router"],create:async()=>{},files:[{type:"registry:file",path:"app/routes/home.tsx",target:"app/routes/home.tsx",content:mn`import { ComponentExample } from "@/components/component-example";

export default function Home() {
  return <ComponentExample />;
}
`}],monorepo:{templateDir:"react-router-monorepo",init:fe,files:[{type:"registry:file",path:"app/routes/home.tsx",target:"app/routes/home.tsx",content:mn`import { ComponentExample } from "@/components/component-example";

export default function Home() {
  return <ComponentExample />;
}
`}]}});var vn=U({name:"start",title:"TanStack Start",defaultProjectName:"start-app",templateDir:"start-app",frameworks:["tanstack-start"],create:async()=>{},files:[{type:"registry:file",path:"src/routes/index.tsx",target:"src/routes/index.tsx",content:mn`import { createFileRoute } from "@tanstack/react-router";
import { ComponentExample } from "@/components/component-example";

export const Route = createFileRoute("/")({ component: App });

function App() {
  return (
    <ComponentExample />
  );
}
`}],monorepo:{templateDir:"start-monorepo",init:fe,files:[{type:"registry:file",path:"src/routes/index.tsx",target:"src/routes/index.tsx",content:mn`import { createFileRoute } from "@tanstack/react-router";
import { ComponentExample } from "@/components/component-example";

export const Route = createFileRoute("/")({ component: App });

function App() {
  return (
    <ComponentExample />
  );
}
`}]}});var Rn=U({name:"vite",title:"Vite",defaultProjectName:"vite-app",templateDir:"vite-app",frameworks:["vite"],create:async()=>{},files:[{type:"registry:file",path:"src/App.tsx",target:"src/App.tsx",content:mn`import { ComponentExample } from "@/components/component-example";

export function App() {
  return <ComponentExample />;
}

export default App;
`}],monorepo:{templateDir:"vite-monorepo",init:fe,files:[{type:"registry:file",path:"src/App.tsx",target:"src/App.tsx",content:mn`import { ComponentExample } from "@/components/component-example";

export function App() {
  return <ComponentExample />;
}

export default App;
`}]}});var B={next:yn,vite:Rn,start:vn,"react-router":bn,astro:dn,laravel:un};function Et(e){if(e){for(let[t,r]of Object.entries(B))if(r.frameworks.includes(e))return t}}async function Ft(e){let t=e.template&&e.template in B?e.template:"next",r=ye(B[t],{monorepo:e.monorepo}),n=e.name??r.defaultProjectName,i=e.components?.length===1&&!!e.components[0].match(/\/chat\/b\//);if(i&&(t="next"),!e.force){let{type:a$1,name:f}=await pe([{type:e.template||i?null:"select",name:"type",message:`The path ${a.info(e.cwd)} does not contain a package.json file.
  Would you like to start a new project?`,choices:Object.entries(B).map(([l,d])=>({title:d.title,value:l,description:d.description})),initial:0},{type:e.name?null:"text",name:"name",message:"What is your project named?",initial:n,format:l=>l.trim(),validate:l=>l.length>128?"Name should be less than 128 characters.":true}]);t=a$1??t,n=f??n;}let o=ye(B[t],{monorepo:e.monorepo}),s=await a$2(e.cwd,{withFallback:true}),c=ee__default.join(e.cwd,n);try{await T.access(e.cwd,T.constants.W_OK);}catch{b.break(),b.error(`The path ${a.info(e.cwd)} is not writable.`),b.error(`It is likely you do not have write permissions for this folder or the path ${a.info(e.cwd)} does not exist.`),b.break(),process.exit(1);}return T.existsSync(ee__default.resolve(e.cwd,n,"package.json"))&&(b.break(),b.error(`A project with the name ${a.info(n)} already exists.`),b.error("Please choose a different name and try again."),b.break(),process.exit(1)),await o.scaffold({projectPath:c,packageManager:s,cwd:e.cwd}),{projectPath:c,projectName:n,template:t}}async function X(e=process.cwd()){try{let{config:t}=await import('@dotenvx/dotenvx'),r=[".env.local",".env.development.local",".env.development",".env"];for(let n of r){let i=join(e,n);existsSync(i)&&t({path:i,overload:!1,quiet:!0});}}catch(t){b.warn("Failed to load env files:",t);}}var Ne=".bak";function kn(e){if(!T.existsSync(e))return null;let t=`${e}${Ne}`;try{return T.renameSync(e,t),t}catch(r){return console.error(`Failed to create backup of ${e}: ${r}`),null}}function $n(e){let t=`${e}${Ne}`;if(!T.existsSync(t))return  false;try{return T.renameSync(t,e),!0}catch(r){return console.error(`Warning: Could not restore backup file ${t}: ${r}`),false}}function In(e){let t=`${e}${Ne}`;if(!T.existsSync(t))return  false;try{return T.unlinkSync(t),!0}catch{return  false}}var _i=z.object({cwd:z.string(),name:z.string().optional(),preset:z.union([z.boolean(),z.string()]).optional(),components:z.array(z.string()).optional(),yes:z.boolean(),defaults:z.boolean(),force:z.boolean(),reinstall:z.boolean().optional(),silent:z.boolean(),isNewProject:z.boolean().default(false),cssVariables:z.boolean().default(true),rtl:z.boolean().optional(),base:z.enum(["radix","base"]).optional(),template:z.string().optional(),monorepo:z.boolean().optional(),existingConfig:z.record(z.unknown()).optional(),installStyleIndex:z.boolean().default(true),registryBaseConfig:c.deepPartial().optional(),menuColor:z.enum(["default","inverted","default-translucent","inverted-translucent"]).optional(),menuAccent:z.enum(["subtle","bold"]).optional(),iconLibrary:z.string().optional()}),Pn=new Command().name("init").alias("create").description("initialize your project and install dependencies").argument("[components...]","names, url or local path to component").option("-t, --template <template>","the template to use. (next, start, vite, react-router, laravel, astro)").option("-b, --base <base>","the component library to use. (radix, base)").option("--monorepo","scaffold a monorepo project.").option("--no-monorepo","skip the monorepo prompt.").option("-p, --preset [name]","use a preset configuration").option("-y, --yes","skip confirmation prompt.",true).option("-d, --defaults","use default configuration: --template=next --preset=base-nova",false).option("-f, --force","force overwrite of existing configuration.",false).option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).option("-n, --name <name>","the name for the new project.").option("-s, --silent","mute output.",false).option("--css-variables","use css variables for theming.",true).option("--no-css-variables","do not use css variables for theming.").option("--rtl","enable RTL support.").option("--no-rtl","disable RTL support.").option("--reinstall","re-install existing UI components.").option("--no-reinstall","do not re-install existing UI components.").action(async(e,t)=>{let r$1,n=[],i=()=>{r$1&&$n(r$1.replace(Ne,""));};process.on("exit",i);try{let o=_i.parse({...t,reinstall:t.reinstall,cwd:ee__default.resolve(t.cwd)}),s=new Map(Object.entries(Me)),c;if(o.defaults&&(o.template=o.template||"next",o.base=o.base||"base",o.reinstall=o.reinstall??!1),o.template&&!(o.template in B)&&(b.error(`Invalid template: ${a.info(o.template)}. Available templates: ${Object.keys(B).map(m=>a.info(m)).join(", ")}.`),b.break(),process.exit(1)),typeof o.preset=="string"&&!G(o.preset)&&!r(o.preset)){let m=Array.from(s.keys());s.has(o.preset)||(b.error(`Invalid preset: ${a.info(o.preset)}. Available presets: ${m.join(", ")}`),b.break(),process.exit(1));}let a$1=o.cwd,f=T.existsSync(ee__default.resolve(a$1,"components.json"));if(!o.monorepo&&!f&&await Y(a$1)){let m=await ra$1(a$1);if(!m||m.framework.name==="manual"){let h=await K(a$1);h.length>0&&(q("init",h),process.exit(1));}}if(f&&!o.force){let{overwrite:m}=await pe({type:"confirm",name:"overwrite",message:`A ${a.info("components.json")} file already exists. Would you like to overwrite it?`,initial:!1});m||(b.info(`  To start over, remove the ${a.info("components.json")} file and run ${a.info("init")} again.`),b.break(),process.exit(1)),o.force=!0;}let l;if(f){try{l=await T.readJson(ee__default.resolve(a$1,"components.json"));}catch{}l&&(o.existingConfig=l);let m=o.reinstall;if(m===void 0){let{reinstall:h}=await pe({type:"confirm",name:"reinstall",message:"Would you like to re-install existing UI components?",initial:!1});m=h;}if(m&&(n=await ua(a$1),n.length)){b.break(),b.log("  The following components will be re-installed and overwritten:");for(let h=0;h<n.length;h+=8)b.log(`  - ${n.slice(h,h+8).join(", ")}`);b.break();}}if(o.preset===void 0&&e.length===0&&!o.defaults){let m=T.existsSync(ee__default.resolve(a$1,"package.json"));if(!o.template&&!m){let{template:h}=await pe({type:"select",name:"template",message:"Select a template",choices:Object.entries(B).map(([g,w])=>({title:w.title,value:g,description:w.description,disabled:o.monorepo&&g==="laravel"}))});h||process.exit(1),o.template=h;}if(!o.template&&m){let h=await ra$1(a$1),g=Et(h?.framework.name);g&&(o.template=g);}if(o.template==="laravel"&&!m&&(b.break(),b.log(`  Please create a new app with ${a.info("laravel new --react")} first then run ${a.info("shadcn init")}.`),b.log(`  See ${a.info(`${c$1}/docs/installation/laravel`)} for more information.`),b.break(),process.exit(0)),o.monorepo===void 0&&!m&&o.template&&B[o.template]?.monorepo){let{monorepo:h}=await pe({type:"confirm",name:"monorepo",message:"Would you like to set up a monorepo?",initial:!1});o.monorepo=h;}o.base||(o.base=await Pe()),o.preset=!0;}if(o.preset!==void 0){let m=o.preset===!0?!0:o.preset;if(m===!0){let h=await Ue({rtl:o.rtl??!1,template:o.template,base:o.base});e=[h.url,...e],c=h.base;}if(typeof m=="string"){let h;if(G(m)){let g=new URL(m);o.rtl?g.searchParams.set("rtl","true"):o.rtl===!1&&g.searchParams.delete("rtl"),g.pathname==="/init"&&m.startsWith(c$1)&&g.searchParams.set("track","1"),h=g.toString(),c=g.searchParams.get("base")??void 0;}else if(r(m)){let g=q$1(m);g||(b.error(`Invalid preset code: ${a.info(m)}`),b.break(),process.exit(1)),h=We({...g,base:"radix",rtl:o.rtl??!1},{template:o.template,preset:m}),c=void 0;}else {let g=s.get(m);if(!g)throw new Error(`Unknown preset: ${m}`);h=We({...g,base:o.base??"radix",rtl:o.rtl??g.rtl},{template:o.template}),c=void 0;}e=[h,...e];}}let d=o.base??c??(l?.style?l.style.startsWith("base-")?"base":"radix":"");if(!d)if(e.length>0)d="radix";else {let m=await Pe();d=m,o.base=m;}if(o.defaults&&!e.some(G)&&(e=[We({...Me.nova,base:d,rtl:o.rtl??!1},{template:o.template}),...e]),e.length>0&&G(e[0])){let m=new URL(e[0]);m.searchParams.set("base",d),e[0]=m.toString();}if(l?.style){let m=await Wi(l.style,d);if(m!==d&&(d=m,e.length>0&&G(e[0]))){let h=new URL(e[0]);h.searchParams.set("base",m),e[0]=h.toString();}}if(n.length&&(e=[...e,...n]),o.components=e,await X(o.cwd),e.length>0){let m=ee__default.resolve(a$1,"components.json");f&&(r$1=kn(m)??void 0,r$1||b.warn(`Could not back up ${a.info("components.json")}.`));let{registryBaseConfig:h,installStyleIndex:g,url:w}=await Be(e[0],a$1,{registries:l?.registries});e[0]=w,g||(o.installStyleIndex=!1),h&&(o.registryBaseConfig=h);}await Nt(o),b.break(),b.log(`Project initialization completed.
You may now add components.`),process.removeListener("exit",i),In(ee__default.resolve(a$1,"components.json")),b.break();}catch(o){process.removeListener("exit",i),i(),b.break(),$(o);}finally{V$1();}});async function Nt(e){let t,r,n=e.template,i=n?ye(B[n],{monorepo:e.monorepo}):void 0;if(e.monorepo&&i?.init&&T.existsSync(ee__default.resolve(e.cwd,"package.json")))t=await ra$1(e.cwd);else if(e.skipPreflight)t=await ra$1(e.cwd);else {let v=await Kr(e);if(v.errors["1"]){let{projectPath:$,template:R}=await Ft(e);$||process.exit(1),e.cwd=$,e.isNewProject=true,r=R,t=await ra$1(e.cwd);}else t=v.projectInfo;}let s=r??n,c=s?ye(B[s],{monorepo:e.monorepo}):void 0,a$1=[...e.installStyleIndex?["index"]:[],...e.components??[],...c?["button"]:[]];if(c?.init){let v=await c.init({projectPath:e.cwd,components:a$1,registryBaseConfig:e.registryBaseConfig,rtl:e.rtl??false,menuColor:e.menuColor,menuAccent:e.menuAccent,iconLibrary:e.iconLibrary,silent:e.silent});return await c.postInit({projectPath:e.cwd}),v}let f=await sa$1(e.cwd,t),l=f?await Mi(f,e):await Vi(await N(e.cwd));if(!e.yes){let{proceed:v}=await pe({type:"confirm",name:"proceed",message:`Write configuration to ${a.info("components.json")}. Proceed?`,initial:true});v||process.exit(1);}let d$1=await O(e.cwd,l),{config:m}=await V(a$1,d$1,{silent:true});m.registries&&(l.registries=m.registries);let h=w("Writing components.json.").start(),g=ee__default.resolve(e.cwd,"components.json"),w$1=`${g}${Ne}`,C=(v,$)=>{let{registries:R,..._}=pn(v,$);return {..._,registries:R}};if(T.existsSync(w$1)){let v=await T.readJson(w$1);e.force?v.registries&&(l.registries={...v.registries,...l.registries||{}}):l=C(v,l);}e.registryBaseConfig&&(l=C(l,e.registryBaseConfig)),e.rtl!==void 0&&(l.rtl=e.rtl),l.registries=Object.fromEntries(Object.entries(l.registries||{}).filter(([v])=>!Object.keys(d).includes(v))),await promises.writeFile(g,`${JSON.stringify(l,null,2)}
`,"utf8"),h.succeed();let b=await O(e.cwd,l),P$1=await P(b);if(P$1){let v={};if(l.menuColor&&(v.menuColor=l.menuColor),l.menuAccent&&(v.menuAccent=l.menuAccent),l.rtl!==void 0&&(v.rtl=l.rtl),l.iconLibrary&&(v.iconLibrary=l.iconLibrary),Object.keys(v).length>0)for(let $ of Object.keys(P$1)){let R=P$1[$];if(R.resolvedPaths.cwd===b.resolvedPaths.cwd)continue;let _=ee__default.resolve(R.resolvedPaths.cwd,"components.json");if(T.existsSync(_)){let ue=await T.readJson(_);await T.writeJson(_,{...ue,...v},{spaces:2});}}}return M.clearCaches(),await re(a$1,b,{overwrite:true,overwriteCssVars:e.reinstall||void 0,silent:e.silent,isNewProject:e.isNewProject||t?.framework.name==="next-app"}),c&&await c.postInit({projectPath:e.cwd}),b}async function Vi(e=null){let[t,r]=await Promise.all([fa(),ha$1()]);b.info("");let n=await pe([{type:"toggle",name:"typescript",message:`Would you like to use ${a.info("TypeScript")} (recommended)?`,initial:e?.tsx??true,active:"yes",inactive:"no"},{type:"select",name:"style",message:`Which ${a.info("style")} would you like to use?`,choices:t.map(i=>({title:i.label,value:i.name}))},{type:"select",name:"tailwindBaseColor",message:`Which color would you like to use as the ${a.info("base color")}?`,choices:r.map(i=>({title:i.label,value:i.name}))},{type:"text",name:"tailwindCss",message:`Where is your ${a.info("global CSS")} file?`,initial:e?.tailwind.css??K$1},{type:"toggle",name:"tailwindCssVariables",message:`Would you like to use ${a.info("CSS variables")} for theming?`,initial:e?.tailwind.cssVariables??true,active:"yes",inactive:"no"},{type:"text",name:"tailwindPrefix",message:`Are you using a custom ${a.info("tailwind prefix eg. tw-")}? (Leave blank if not)`,initial:""},{type:"text",name:"tailwindConfig",message:`Where is your ${a.info("tailwind.config.js")} located?`,initial:e?.tailwind.config??L},{type:"text",name:"components",message:`Configure the import alias for ${a.info("components")}:`,initial:e?.aliases.components??I},{type:"text",name:"utils",message:`Configure the import alias for ${a.info("utils")}:`,initial:e?.aliases.utils??J},{type:"toggle",name:"rsc",message:`Are you using ${a.info("React Server Components")}?`,initial:e?.rsc??true,active:"yes",inactive:"no"}]);return n.style||process.exit(1),c.parse({$schema:"https://ui.shadcn.com/schema.json",style:n.style,tailwind:{config:n.tailwindConfig,css:n.tailwindCss,baseColor:n.tailwindBaseColor,cssVariables:n.tailwindCssVariables,prefix:n.tailwindPrefix},rsc:n.rsc,tsx:n.typescript,aliases:{utils:n.utils,components:n.components,lib:n.components.replace(/\/components$/,"lib"),hooks:n.components.replace(/\/components$/,"hooks")}})}async function Mi(e,t){let r=e.style,n="neutral",i=e.tailwind.cssVariables,o=e.iconLibrary??"lucide";if(!t.defaults){let[s,c]=await Promise.all([fa(),ta(e)]);r=(await pe([{type:c==="v4"||r?null:"select",name:"style",message:`Which ${a.info("style")} would you like to use?`,choices:s.map(f=>({title:f.name==="new-york"?"New York (Recommended)":f.label,value:f.name})),initial:0}])).style??r??"new-york";}return i=t.cssVariables,c.parse({$schema:e?.$schema,style:r,tailwind:{...e?.tailwind,baseColor:n,cssVariables:i},rsc:e?.rsc,tsx:e?.tsx,iconLibrary:o,rtl:t.rtl??e?.rtl??false,aliases:e?.aliases})}async function Wi(e,t){let r=e.startsWith("base-")?"base":"radix";if(t===r)return t;b.warn(`  You are switching from ${a.info(r)} to ${a.info(t)}.`),b.warn(`  Components outside the ${a.info("ui")} directory that depend on ${a.info(r)} primitives may need manual updates.`),b.break();let{proceed:n}=await pe({type:"confirm",name:"proceed",message:"Would you like to continue?",initial:false});return n?t:r}async function En(e){let t={};if(!T.existsSync(e.cwd)||!T.existsSync(ee__default.resolve(e.cwd,"package.json")))return t["1"]=true,{errors:t,config:null};if(!T.existsSync(ee__default.resolve(e.cwd,"components.json"))){if(await Y(e.cwd)){let r=await K(e.cwd);r.length>0&&(q("add [component]",r),process.exit(1));}return t["3"]=true,{errors:t,config:null}}try{let r=await N(e.cwd);return {errors:t,config:r}}catch{b.break(),b.error(`An invalid ${a.info("components.json")} file was found at ${a.info(e.cwd)}.
Before you can add components, you must create a valid ${a.info("components.json")} file by running the ${a.info("init")} command.`),b.error(`Learn more at ${a.info(`${c$1}/docs/components-json`)}.`),b.break(),process.exit(1);}}async function Nn(e,t,r={}){let n={files:[],dependencies:[],devDependencies:[],css:null,envVars:null,fonts:[],docs:null};if(!e.length)return n;let i=await _(e,U$1(t));if(!i)throw new Error("Failed to fetch components from registry.");r.skipFonts||(i=await He(i,t));let o=we([i]);return n.dependencies=Array.from(new Set(i.dependencies??[])),n.devDependencies=Array.from(new Set(i.devDependencies??[])),n.docs=i.docs??null,await Ui(i,t,n,r,o),await Bi(i,t,n,r),zi(i,t,n),r.skipFonts||Ji(i,n),n}async function Ui(e,t,r,n,i){let o=e.files;if(!o?.length)return;let[s$1,c]=await Promise.all([ra$1(t.resolvedPaths.cwd),t.tailwind.baseColor?ia$1(t.tailwind.baseColor):Promise.resolve(void 0)]);for(let a=0;a<o.length;a++){let f$1=o[a];if(!f$1.content)continue;let l=E(f$1,t,{isSrcDir:s$1?.isSrcDir,framework:s$1?.framework.name,commonRoot:F(o.map(b=>b.path),f$1.path),fileIndex:a});if(!l)continue;t.tsx||(l=l.replace(/\.tsx?$/,b=>b===".tsx"?".jsx":".js"));let d=existsSync(l),m=ee__default.relative(t.resolvedPaths.cwd,l),h=f$1.type==="registry:file"||f$1.type==="registry:item",g$1=s(l)||h?f$1.content:await B$1({filename:f$1.path,raw:f$1.content,config:t,baseColor:c,transformJsx:!t.tsx,isRemote:false,supportedFontMarkers:i},[x,y,a$1,A,c$2,g,C,d$1,f,z$1]),w="create",C$1;d&&(C$1=await promises.readFile(l,"utf-8"),r$1(C$1,g$1)?w="skip":w="overwrite"),r.files.push({path:m,action:w,content:g$1,...w==="overwrite"&&{existingContent:C$1},type:f$1.type??"registry:ui"});}}async function Bi(e,t,r,n){let i=e.css&&Object.keys(e.css).length>0,o=Object.keys(e.cssVars??{}).length>0;if(!t.resolvedPaths.tailwindCss||!i&&!o)return;let s=t.resolvedPaths.tailwindCss,c=existsSync(s),a=ee__default.relative(t.resolvedPaths.cwd,s),f=c?await promises.readFile(s,"utf8"):"",l=f;o&&(l=await ze(l,e.cssVars,t,{overwriteCssVars:n.overwriteCssVars})),i&&(l=await Xt(l,e.css));let d=0;if(e.cssVars)for(let m of Object.values(e.cssVars))m&&(d+=Object.keys(m).length);r.css={path:a,content:l,...c&&{existingContent:f},action:c?"update":"create",cssVarsCount:d};}function zi(e,t,r){if(!e.envVars||Object.keys(e.envVars).length===0)return;let n=ee__default.join(t.resolvedPaths.cwd,".env.local"),i=existsSync(n),o=ee__default.relative(t.resolvedPaths.cwd,n);r.envVars={path:o,variables:e.envVars,action:i?"update":"create"};}function Ji(e,t){if(e.fonts?.length)for(let r of e.fonts)t.fonts.push({name:r.font.family,provider:r.font.provider==="google"?"Google Fonts":r.font.provider});}var me=5,Yi=dim("\u250C"+"\u2500".repeat(46)),Ki=dim("\u2514"+"\u2500".repeat(46)),qi={create:"+",overwrite:"~",skip:"="},Xi={create:"create",overwrite:"overwrite",skip:"skip (identical)"};function Ke(e){return e==="create"?green(e):e==="overwrite"||e==="update"?yellow(e):dim(e)}function qe(e){return `${bold("\u250C")} ${bold(`shadcn add ${e.join(", ")}`)} ${dim("(dry run)")}`}function Tn(e,t){return e===t||e.includes(t)||e.endsWith(t)}function ve(e,t,r=n=>n){e.push(`${dim("\u2502")} ${Yi}`);for(let n of t)e.push(`${dim("\u2502")} ${dim("\u2502")} ${r(n)}`);e.push(`${dim("\u2502")} ${Ki}`);}function Dn(e,t,r={}){return r.diff?typeof r.diff=="string"?Qi(e,t,r.diff):es(e,t):r.view?typeof r.view=="string"?rs(e,t,r.view):ts(e,t):Zi(e,t)}function Zi(e,t){let r=[];r.push(qe(t)),r.push(dim("\u2502")),ns(e,r),On("Dependencies",e.dependencies,r),On("Dev Dependencies",e.devDependencies,r),os(e,r),is(e,r),ss(e,r);let n=e.files.filter(o=>o.action==="overwrite").length;n>0&&(r.push(yellow(`\u26A0 ${n} ${n===1?"file":"files"} will be overwritten.`)),r.push(dim("\u2502")));let i=[];return e.files.length>0&&i.push(`${e.files.length} ${e.files.length===1?"file":"files"}`),e.dependencies.length>0&&i.push(`${e.dependencies.length} ${e.dependencies.length===1?"dep":"deps"}`),e.css?.cssVarsCount&&i.push(`${e.css.cssVarsCount} CSS vars`),i.length>0&&(r.push(`${dim("\u2502")} ${dim(i.join(", "))}`),r.push(dim("\u2502"))),r.push(`${dim("\u2502")} ${dim("Run with --diff to view changes.")}`),r.push(`${dim("\u2502")} ${dim("Run with --view to view file contents.")}`),r.push(`${dim("\u2514")} ${dim("Run without --dry-run to apply.")}`),r.join(`
`)}function Qi(e,t,r){let n=[];n.push(qe(t)),n.push(dim("\u2502"));let i=_n(e.files,r),o=e.css&&Tn(e.css.path,r);if(i.length===0&&!o)n.push(`${dim("\u2502")} ${yellow(`No file matching "${r}" found.`)}`),n.push(dim("\u2502"));else {for(let s of i)Ln(s,n);if(o&&e.css){if(n.push(`${dim("\u251C")} ${bold(e.css.path)} ${dim("(")}${Ke(e.css.action)}${dim(")")}`),e.css.action==="create"||!e.css.existingContent)ve(n,e.css.content.split(`
`),s=>green(`+${s}`));else {let s=Vn(e.css.existingContent,e.css.content,e.css.path,{fullContext:true});ve(n,s);}n.push(dim("\u2502"));}}return n.push(`${dim("\u2514")} ${dim("Run without --dry-run to apply.")}`),n.join(`
`)}function es(e,t){let r=[];r.push(qe(t)),r.push(dim("\u2502"));let n=e.files.slice(0,me);if(n.length===0&&!e.css)r.push(`${dim("\u2502")} ${dim("No changes.")}`),r.push(dim("\u2502"));else {for(let s of n)Ln(s,r);e.files.length>me&&r.push(dim("\u2502"));}let i=e.files.length;return i>me&&r.push(`  ${dim(`Showing ${me} of ${i} files. Use --diff <path> to view a specific file.`)}`),r.push(`${dim("\u2514")} ${dim("Run without --dry-run to apply.")}`),r.join(`
`)}function ts(e,t){let r=[];r.push(qe(t)),r.push(dim("\u2502"));let n=e.files.slice(0,me);if(n.length===0&&!e.css)r.push(`${dim("\u2502")} ${dim("No files.")}`),r.push(dim("\u2502"));else {for(let s of n){let c=s.content.split(`
`);r.push(`${dim("\u251C")} ${bold(s.path)} ${dim("(")}${Ke(s.action)}${dim(")")} ${dim(`${c.length} lines`)}`),ve(r,c),r.push(dim("\u2502"));}e.files.length>me&&r.push(dim("\u2502"));}let i=e.files.length;return i>me&&r.push(`  ${dim(`Showing ${me} of ${i} files. Use --view <path> to view a specific file.`)}`),r.push(`${dim("\u2514")} ${dim("Run without --dry-run to apply.")}`),r.join(`
`)}function Ln(e,t){if(t.push(`${dim("\u251C")} ${bold(e.path)} ${dim("(")}${Ke(e.action)}${dim(")")}`),e.action==="skip")t.push(`${dim("\u2502")} ${dim("No changes.")}`);else if(e.action==="create")ve(t,e.content.split(`
`),r=>green(`+${r}`));else {let r=Vn(e.existingContent,e.content,e.path);ve(t,r);}t.push(dim("\u2502"));}function rs(e,t,r){let n=[];n.push(qe(t)),n.push(dim("\u2502"));let i=_n(e.files,r),o=e.css&&Tn(e.css.path,r);if(i.length===0&&!o)n.push(`${dim("\u2502")} ${yellow(`No file matching "${r}" found.`)}`),n.push(dim("\u2502"));else {for(let s of i){let c=s.content.split(`
`);n.push(`${dim("\u251C")} ${bold(s.path)} ${dim("(")}${Ke(s.action)}${dim(")")} ${dim(`${c.length} lines`)}`),ve(n,c),n.push(dim("\u2502"));}if(o&&e.css){let s=e.css.content.split(`
`);n.push(`${dim("\u251C")} ${bold(e.css.path)} ${dim("(")}${Ke(e.css.action)}${dim(")")} ${dim(`${s.length} lines`)}`),ve(n,s),n.push(dim("\u2502"));}}return n.push(`${dim("\u2514")} ${dim("Run without --dry-run to apply.")}`),n.join(`
`)}function ns(e,t){if(e.files.length===0)return;let r={create:0,overwrite:0,skip:0};for(let s of e.files)r[s.action]++;let n=[];r.create>0&&n.push(green(`+${r.create} new`)),r.overwrite>0&&n.push(yellow(`~${r.overwrite} overwrite`)),r.skip>0&&n.push(dim(`=${r.skip} skip`));let i=n.length>0?` ${n.join(dim(", "))}`:"";t.push(`${dim("\u251C")} ${bold("Files")} ${dim(`(${e.files.length})`)}${i}`);let o=Math.max(...e.files.map(s=>s.path.length));for(let s of e.files){let c=qi[s.action],a=Xi[s.action],f=" ".repeat(Math.max(1,o-s.path.length+2)),l=s.action==="create"?green:s.action==="overwrite"?yellow:dim,d=s.action==="skip"?dim(s.path):s.path;t.push(`${dim("\u2502")} ${l(c)} ${d}${f}${l(a)}`);}t.push(dim("\u2502"));}function On(e,t,r){if(t.length){r.push(`${dim("\u251C")} ${bold(e)} ${dim(`(${t.length})`)}`);for(let n of t)r.push(`${dim("\u2502")} ${green("+")} ${n}`);r.push(dim("\u2502"));}}function os(e,t){e.css&&(t.push(`${dim("\u251C")} ${bold("CSS")}`),e.css.cssVarsCount>0?t.push(`${dim("\u2502")} ${green("+")} ${e.css.cssVarsCount} CSS variables added to ${cyan(e.css.path)}`):t.push(`${dim("\u2502")} ${green("+")} Updated ${cyan(e.css.path)}`),t.push(dim("\u2502")));}function is(e,t){if(!e.envVars)return;let r=Object.keys(e.envVars.variables);t.push(`${dim("\u251C")} ${bold("Environment Variables")}`);for(let n of r)t.push(`${dim("\u2502")} ${green("+")} ${n}`);t.push(dim("\u2502"));}function ss(e,t){if(e.fonts.length){t.push(`${dim("\u251C")} ${bold("Fonts")}`);for(let r of e.fonts)t.push(`${dim("\u2502")} ${green("+")} ${r.name} ${dim(`(${r.provider})`)}`);t.push(dim("\u2502"));}}function _n(e,t){let r=e.filter(n=>n.path===t);return r.length>0?r:e.filter(n=>n.path.includes(t)||n.path.replace(/\\/g,"/").includes(t))}function Vn(e,t,r,n={}){if(ps(e,t))return [dim("  Formatting-only changes (spacing, quotes, semicolons).")];let i=An(e),o=An(t),s=n.fullContext?Math.max(i.split(`
`).length,o.split(`
`).length):3,c=structuredPatch(`a/${r}`,`b/${r}`,i,o,"","",{context:s});if(!c.hunks.length)return [dim("  No changes.")];let a=[dim(`--- a/${r}`),dim(`+++ b/${r}`)],f=t.split(`
`);for(let l of c.hunks){let{entries:d}=as(l,f);if(!d.some(C=>C.kind!=="context"))continue;let h=d.filter(C=>C.kind==="context").length,g=d.filter(C=>C.kind==="removed").length,w=d.filter(C=>C.kind==="added").length;a.push(cyan(`@@ -${l.oldStart},${h+g} +${l.newStart},${h+w} @@`));for(let C of d)a.push(C.formatted);}return a}function as(e,t){let r=[],n=e.newStart-1,i=0;for(;i<e.lines.length;){let o=e.lines[i];if(o.startsWith("-")){let s=[];for(;i<e.lines.length&&e.lines[i].startsWith("-");)s.push(e.lines[i].slice(1)),i++;for(;i<e.lines.length&&e.lines[i].startsWith("\\");)i++;let c=[];for(;i<e.lines.length&&e.lines[i].startsWith("+");)c.push(e.lines[i].slice(1)),i++;for(;i<e.lines.length&&e.lines[i].startsWith("\\");)i++;n=cs(s,c,t,n,r);}else if(o.startsWith("+")){let s=t[n]??o.slice(1);r.push({kind:"added",formatted:green(`+${s}`)}),n++,i++;}else if(o.startsWith("\\"))i++;else {let s=t[n]??o.slice(1);r.push({kind:"context",formatted:dim(` ${s}`)}),n++,i++;}}return {entries:r,newLineIndex:n}}function cs(e,t,r,n,i){if(ms(e,t)){for(let a=0;a<t.length;a++){let f=r[n]??t[a];i.push({kind:"context",formatted:dim(` ${f}`)}),n++;}return n}let o=ls(e),s=o.map(At),c=new Set;for(let a=0;a<t.length;a++){let f=r[n]??t[a],l=At(t[a]),d=s.findIndex((m,h)=>!c.has(h)&&m===l);if(d!==-1)c.add(d),i.push({kind:"context",formatted:dim(` ${f}`)});else {let m=s.findIndex((h,g)=>!c.has(g));if(m!==-1){c.add(m);let{oldHighlighted:h,newHighlighted:g}=fs(o[m],f);i.push({kind:"removed",formatted:h}),i.push({kind:"added",formatted:g});}else i.push({kind:"added",formatted:green(`+${f}`)});}n++;}for(let a=0;a<o.length;a++)c.has(a)||i.push({kind:"removed",formatted:red(`-${o[a]}`)});return n}function An(e){return e.split(`
`).map(t=>{let r=t.match(/^(\s*)/)?.[1]??"",n=t.slice(r.length);return r+n.replace(/['"]/g,'"').replace(/;$/g,"")}).join(`
`)}function ls(e){let t=[];for(let r=0;r<e.length;r++){let n=e[r];for(;r+1<e.length&&n.trimEnd().endsWith(":");)r++,n=n.trimEnd()+" "+e[r].trim();t.push(n);}return t}function fs(e,t){let r=diffWords(e,t),n="-",i="+";for(let o of r)o.added?i+=bold(green(o.value)):o.removed?n+=bold(red(o.value)):(n+=red(o.value),i+=green(o.value));return {oldHighlighted:n,newHighlighted:i}}function At(e){return e.replace(/\s+/g," ").trim().replace(/['"]/g,"'").replace(/;/g,"").replace(/,$/,"")}function ps(e,t){let r=n=>n.split(`
`).map(At).filter(i=>i.length>0).join(" ");return r(e)===r(t)}function ms(e,t){let r=n=>n.map(At).filter(i=>i.length>0).join(" ");return r(e)===r(t)}async function Wn(e,t){let r=ee__default.join(t.resolvedPaths.cwd,"app/page.tsx");if(!(await Ce__default.stat(r)).isFile())return;let[n]=await ba([e],{config:t});if(!n?.meta?.importSpecifier||!n?.meta?.moduleSpecifier)return;let i=`import { ${n?.meta?.importSpecifier} } from "${n.meta.moduleSpecifier}"

export default function Page() {
  return <${n?.meta?.importSpecifier} />
}`;await Ce__default.writeFile(r,i,"utf8");}var hs=z.object({components:z.array(z.string()).optional(),yes:z.boolean(),overwrite:z.boolean(),cwd:z.string(),all:z.boolean(),path:z.string().optional(),silent:z.boolean(),dryRun:z.boolean(),diff:z.union([z.string(),z.literal(true)]).optional(),view:z.union([z.string(),z.literal(true)]).optional()}),Un=new Command().name("add").description("add a component to your project").argument("[components...]","names, url or local path to component").option("-y, --yes","skip confirmation prompt.",false).option("-o, --overwrite","overwrite existing files.",false).option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).option("-a, --all","add all available components",false).option("-p, --path <path>","the path to add the component to.").option("-s, --silent","mute output.",false).option("--dry-run","preview changes without writing files.",false).option("--diff [path]","show diff for a file.").option("--view [path]","show file contents.").action(async(e$1,t)=>{try{let r=hs.parse({components:e$1,...t,cwd:ee__default.resolve(t.cwd)});await X(r.cwd);let n=r.dryRun||r.diff||r.view,i=await N(r.cwd);i||(i=T$1({style:"new-york",resolvedPaths:{cwd:r.cwd}}));let o=!1;if(e$1.length>0){let{config:g,newRegistries:w}=await V(e$1,i,{silent:r.silent,writeFile:!1});i=g,o=w.length>0;}let s,c=!0;if(e$1.length>0){let[g]=await ba([e$1[0]],{config:i});if(s=g?.type,c=s!=="registry:theme"&&s!=="registry:style"&&s!=="registry:base",H(g)&&!n){await re(e$1,i,r);return}if(!r.yes&&!n&&(s==="registry:style"||s==="registry:theme")){b.break();let{confirm:w}=await pe({type:"confirm",name:"confirm",message:a.warn(`You are about to install a new ${s.replace("registry:","")}. 
Existing CSS variables and components will be overwritten. Continue?`)});w||(b.break(),b.log("Installation cancelled."),b.break(),process.exit(1));}}r.components?.length||(r.components=await ys(r));let a$1=await ra$1(r.cwd);if(a$1?.tailwindVersion==="v4"){let g=e.filter(w=>r.components?.includes(w.name));g?.length&&(b.break(),g.forEach(w=>{b.warn(a.warn(w.message));}),b.break(),process.exit(1));}let{errors:f,config:l}=await En(r),d=!1;if(f["3"]){let{proceed:g}=await pe({type:"confirm",name:"proceed",message:`You need to create a ${a.info("components.json")} file to add components. Proceed?`,initial:!0});g||(b.break(),process.exit(1));let w=Et(a$1?.framework.name),C=await Pe(),{url:b$1}=await Ue({rtl:!1,base:C,template:w}),{registryBaseConfig:P,installStyleIndex:v,url:$}=await Be(b$1,r.cwd);l=await Nt({cwd:r.cwd,yes:!0,force:!0,defaults:!1,skipPreflight:!1,silent:r.silent&&!o,isNewProject:!1,cssVariables:!0,rtl:!1,installStyleIndex:v,components:[$,...r.components??[]],registryBaseConfig:P}),d=!0;}let m=!1;if(f["1"]){let{projectPath:g,template:w}=await Ft({cwd:r.cwd,force:r.overwrite,components:r.components});g||(b.break(),process.exit(1)),r.cwd=g;let C=await Pe(),{url:b$1}=await Ue({rtl:!1,base:C,template:w}),{registryBaseConfig:P,installStyleIndex:v,url:$}=await Be(b$1,r.cwd);l=await Nt({cwd:r.cwd,yes:!0,force:!0,defaults:!1,skipPreflight:!0,silent:!o&&r.silent,isNewProject:!0,cssVariables:!0,rtl:!1,installStyleIndex:v,components:[$,...r.components??[]],registryBaseConfig:P}),d=!0,m=r.components?.length===1&&!!r.components[0].match(/\/chat\/b\//);}if(!l)throw new Error(`Failed to read config at ${a.info(r.cwd)}.`);let{config:h}=await V(r.components,l,{silent:r.silent||o,writeFile:!n});if(l=h,n){let g=w("Resolving items.",{silent:r.silent}).start(),w$1=await Nn(r.components,l,{overwrite:r.overwrite});g.stop(),b.log(Dn(w$1,r.components,{diff:r.diff,view:r.view}));return}d||await re(r.components,l,r),m&&await Wn(r.components[0],l);}catch(r){b.break(),$(r);}finally{V$1();}});async function ys(e$1){let t=await ea();if(!t)return b.break(),$(new Error("Failed to fetch registry index.")),[];if(e$1.all)return t.map(i=>i.name).filter(i=>!e.some(o=>o.name===i));if(e$1.components?.length)return e$1.components;let{components:r}=await pe({type:"multiselect",name:"components",message:"Which components would you like to add?",hint:"Space to select. A to toggle all. Enter to submit.",instructions:false,choices:t.filter(i=>i.type==="registry:ui"&&!e.some(o=>o.name===i.name)).map(i=>({title:i.name,value:i.name,selected:e$1.all?true:e$1.components?.includes(i.name)}))});r?.length||(b.warn("No components selected. Exiting."),b.info(""),process.exit(1));let n=z.array(z.string()).safeParse(r);return n.success?n.data:(b.error(""),$(new Error("Something went wrong. Please try again.")),[])}async function Gn(e){let t={},r={cwd:e.cwd,registryFile:ee__default.resolve(e.cwd,e.registryFile),outputDir:ee__default.resolve(e.cwd,e.outputDir)};return T.existsSync(r.registryFile)||(t["13"]=true),await T.mkdir(r.outputDir,{recursive:true}),Object.keys(t).length>0&&(t["13"]&&(b.break(),b.error(`The path ${a.info(r.registryFile)} does not exist.`)),b.break(),process.exit(1)),{errors:t,resolvePaths:r}}var bs=z.object({cwd:z.string(),registryFile:z.string(),outputDir:z.string()}),Hn=new Command().name("build").description("build components for a shadcn registry").argument("[registry]","path to registry.json file","./registry.json").option("-o, --output <path>","destination directory for json files","./public/r").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).action(async(e,t)=>{try{let r=bs.parse({cwd:ee.resolve(t.cwd),registryFile:e,outputDir:t.output}),{resolvePaths:n$1}=await Gn(r),i=await Ce.readFile(n$1.registryFile,"utf-8"),o$1=o.safeParse(JSON.parse(i));o$1.success||(b.error(`Invalid registry file found at ${a.info(n$1.registryFile)}.`),process.exit(1));let s=w("Building registry...");for(let c of o$1.data.items){s.start(`Building ${c.name}...`),c.$schema="https://ui.shadcn.com/schema/registry-item.json";for(let f of c.files??[])f.content=await Ce.readFile(ee.resolve(n$1.cwd,f.path),"utf-8");let a$1=n.safeParse(c);if(!a$1.success){b.error(`Invalid registry item found for ${a.info(c.name)}.`);continue}await Ce.writeFile(ee.resolve(n$1.outputDir,`${a$1.data.name}.json`),JSON.stringify(a$1.data,null,2));}await Ce.copyFile(n$1.registryFile,ee.resolve(n$1.outputDir,"registry.json")),s.succeed("Building registry.");}catch(r){b.break(),$(r);}});var Rs=z.object({component:z.string().optional(),yes:z.boolean(),cwd:z.string(),path:z.string().optional()}),Kn=new Command().name("diff").description("[DEPRECATED] Use `add [component] --diff` instead.").argument("[component]","the component name").option("-y, --yes","skip confirmation prompt.",false).option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).action(async(e,t)=>{try{let r=Rs.parse({component:e,...t}),n=ee__default.resolve(r.cwd);existsSync(n)||(b.error(`The path ${n} does not exist. Please try again.`),process.exit(1));let i=await N(n);if(!i){if(await Y(n)){let a=await K(n);a.length>0&&(q("diff [component]",a),process.exit(1));}b.warn(`Configuration is missing. Please run ${a.success("init")} to create a components.json file.`),process.exit(1);}let o=await ea();if(o||($(new Error("Failed to fetch registry index.")),process.exit(1)),!r.component){let a$1=i.resolvedPaths.components,f=o.filter(d=>{for(let m of d.files??[]){let h=ee__default.resolve(a$1,typeof m=="string"?m:m.path);if(existsSync(h))return !0}return !1}),l=[];for(let d of f){let m=await Yn(d,i);m.length&&l.push({name:d.name,changes:m});}l.length||(b.info("No updates found."),process.exit(0)),b.info("The following components have updates available:");for(let d of l){b.info(`- ${d.name}`);for(let m of d.changes)b.info(`  - ${m.filePath}`);}b.break(),b.info(`Run ${a.success("diff <component>")} to see the changes.`),process.exit(0);}let s=o.find(a=>a.name===r.component);s||(b.error(`The component ${a.success(r.component)} does not exist.`),process.exit(1));let c=await Yn(s,i);c.length||(b.info(`No updates found for ${r.component}.`),process.exit(0));for(let a of c)b.info(`- ${a.filePath}`),await Ss(a.patch),b.info("");}catch(r){$(r);}});async function Yn(e,t){let r=await ka(t.style,[e]),n=await ia$1(t.tailwind.baseColor),i=we(r);if(!r)return [];let o=[];for(let s of r){let c=await la(t,s);if(c)for(let a of s.files??[]){let f$1=ee__default.resolve(c,typeof a=="string"?a:a.path);if(!existsSync(f$1))continue;let l=await promises.readFile(f$1,"utf8");if(typeof a=="string"||!a.content)continue;let d=await B$1({filename:a.path,raw:a.content,config:t,baseColor:n,supportedFontMarkers:i},[x,y,a$1,A,c$2,g,d$1,f,z$1]),m=diffLines(d,l);m.length>1&&o.push({filePath:f$1,patch:m});}}return o}async function Ss(e){e.forEach(t=>{if(t)return t.added?process.stdout.write(a.success(t.value)):t.removed?process.stdout.write(a.error(t.value)):process.stdout.write(t.value)});}var qn=new Command().name("docs").description("get docs, api references and usage examples for components").argument("<components...>","component names").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).option("-b, --base <base>","the base to use either 'base' or 'radix'. defaults to project base.").option("--json","output as JSON.",false).action(async(e,t)=>{try{let r=ee__default.resolve(t.cwd),n=await N(r),i=t.base??S(n?.style),o=await ea();o||(b.error("Failed to fetch the registry index."),process.exit(1));let s=[];for(let a$1 of e){let f=o.find(d=>d.name===a$1);f||(b.error(`Component ${a.info(a$1)} not found in the shadcn registry.`),process.exit(1));let l=f.meta?.links?.[i];if(!l||Object.keys(l).length===0){b.warn(`No documentation links available for ${a.info(a$1)}.`);continue}s.push({component:a$1,base:i,links:l});}if(t.json){console.log(JSON.stringify({base:i,results:s},null,2));return}let c=Math.max(...s.flatMap(a=>Object.keys(a.links).map(f=>f.length)));for(let{component:a$1,links:f}of s){b.log(a.info(a$1));for(let[l,d]of Object.entries(f))b.log(`  - ${l.padEnd(c+2)}${d}`);b.break();}}catch(r){$(r);}});var Zn="https://raw.githubusercontent.com/shadcn-ui/ui/refs/heads/main/apps/v4/registry/bases",Qn=new Command().name("info").description("get information about your project").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).option("--json","output as JSON.",false).action(async e=>{try{let t=ee__default.resolve(e.cwd);if(!existsSync(ee__default.resolve(t,"components.json"))&&await Y(t)){let c=await K(t);c.length>0&&(e.json?console.log(JSON.stringify({error:"monorepo_root",message:"You are running info from a monorepo root. Use the -c flag to specify a workspace.",targets:c.map(a=>a.name)},null,2)):q("info",c),process.exit(1));}let r=await ra$1(t),n=await N(t),i=await ua(t),o=S(n?.style),s=Es(r,n,i,o);if(e.json){console.log(JSON.stringify(s,null,2));return}Fs(s);}catch(t){$(t);}});function js(e){if(!e)return {};let t={};for(let[r,n]of Object.entries(e))t[r]=typeof n=="string"?n:n.url;return t}function Es(e,t,r,n){return {project:e?{framework:e.framework.label,frameworkName:e.framework.name,frameworkVersion:e.frameworkVersion??null,srcDirectory:e.isSrcDir,rsc:e.isRSC,typescript:e.isTsx,tailwindVersion:e.tailwindVersion??null,tailwindConfig:e.tailwindConfigFile??null,tailwindCss:e.tailwindCssFile??null,importAlias:e.aliasPrefix??null}:null,config:t?{style:t.style,base:n,rsc:t.rsc,typescript:t.tsx,iconLibrary:t.iconLibrary??null,rtl:t.rtl??false,menuColor:t.menuColor??null,menuAccent:t.menuAccent??null,aliases:{components:t.aliases.components,utils:t.aliases.utils,ui:t.aliases.ui??null,lib:t.aliases.lib??null,hooks:t.aliases.hooks??null},resolvedPaths:{cwd:t.resolvedPaths.cwd,tailwindConfig:t.resolvedPaths.tailwindConfig||null,tailwindCss:t.resolvedPaths.tailwindCss||null,utils:t.resolvedPaths.utils,components:t.resolvedPaths.components,lib:t.resolvedPaths.lib,hooks:t.resolvedPaths.hooks,ui:t.resolvedPaths.ui},registries:js(t.registries)}:null,components:r,links:{docs:`${c$1}/docs`,components:`${c$1}/docs/components/${n}/[component].md`,ui:`${Zn}/${n}/ui/[component].tsx`,examples:`${Zn}/${n}/examples/[component]-example.tsx`,schema:"https://ui.shadcn.com/schema.json"}}}function Fs(e){b.log(a.info("Project")),e.project?Ae({framework:`${e.project.framework} (${e.project.frameworkName})`,frameworkVersion:e.project.frameworkVersion??"-",srcDirectory:e.project.srcDirectory?"Yes":"No",rsc:e.project.rsc?"Yes":"No",typescript:e.project.typescript?"Yes":"No",tailwindVersion:e.project.tailwindVersion??"-",tailwindConfig:e.project.tailwindConfig??"-",tailwindCss:e.project.tailwindCss??"-",importAlias:e.project.importAlias??"-"}):b.log("  No project info detected."),b.break(),b.log(a.info("Configuration")),e.config?(Ae({style:e.config.style,base:e.config.base,rsc:e.config.rsc?"Yes":"No",typescript:e.config.typescript?"Yes":"No",iconLibrary:e.config.iconLibrary??"-",rtl:e.config.rtl?"Yes":"No",menuColor:e.config.menuColor??"-",menuAccent:e.config.menuAccent??"-"}),b.break(),b.log(a.info("Aliases")),Ae({components:e.config.aliases.components,utils:e.config.aliases.utils,ui:e.config.aliases.ui??"-",lib:e.config.aliases.lib??"-",hooks:e.config.aliases.hooks??"-"}),b.break(),b.log(a.info("Resolved Paths")),Ae({cwd:e.config.resolvedPaths.cwd,tailwindConfig:e.config.resolvedPaths.tailwindConfig??"-",tailwindCss:e.config.resolvedPaths.tailwindCss??"-",utils:e.config.resolvedPaths.utils,components:e.config.resolvedPaths.components,lib:e.config.resolvedPaths.lib,hooks:e.config.resolvedPaths.hooks,ui:e.config.resolvedPaths.ui}),Object.keys(e.config.registries).length>0&&(b.break(),b.log("registries:"),Ae(e.config.registries))):b.log("  No components.json found."),b.break(),b.log(a.info("Installed Components")),e.components.length>0?b.log(`  ${e.components.join(", ")}`):b.log("  No components installed."),b.break(),b.log(a.info("Links")),Ae(e.links),b.break();}function Ae(e){let t=Math.max(...Object.keys(e).map(r=>r.length));for(let[r,n]of Object.entries(e))b.log(`  ${r.padEnd(t+2)}${n}`);}var Re="latest",Lt=[{name:"claude",label:"Claude Code",configPath:".mcp.json",config:{mcpServers:{shadcn:{command:"npx",args:[`shadcn@${Re}`,"mcp"]}}}},{name:"cursor",label:"Cursor",configPath:".cursor/mcp.json",config:{mcpServers:{shadcn:{command:"npx",args:[`shadcn@${Re}`,"mcp"]}}}},{name:"vscode",label:"VS Code",configPath:".vscode/mcp.json",config:{servers:{shadcn:{command:"npx",args:[`shadcn@${Re}`,"mcp"]}}}},{name:"codex",label:"Codex",configPath:".codex/config.toml",config:`[mcp_servers.shadcn]
command = "npx"
args = ["shadcn@${Re}", "mcp"]
`},{name:"opencode",label:"OpenCode",configPath:"opencode.json",config:{$schema:"https://opencode.ai/config.json",mcp:{shadcn:{type:"local",command:["npx",`shadcn@${Re}`,"mcp"],enabled:true}}}}],Dt=[`shadcn@${Re}`],lr=new Command().name("mcp").description("MCP server and configuration commands").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).action(async e=>{try{await X(e.cwd);let t=new StdioServerTransport;await b$1.connect(t);}catch(t){b.break(),$(t);}}),Ls=cr.object({client:cr.enum(["claude","cursor","vscode","codex","opencode"]),cwd:cr.string()});lr.command("init").description("Initialize MCP configuration for your client").option("--client <client>",`MCP client (${Lt.map(e=>e.name).join(", ")})`).action(async(e,t)=>{try{let n=(t.parent?.opts()||{}).cwd||process.cwd(),i=e.client;if(!i){let f=await pe({type:"select",name:"client",message:"Which MCP client are you using?",choices:Lt.map(l=>({title:l.label,value:l.name}))});f.client||(b.break(),process.exit(1)),i=f.client;}let o=Ls.parse({client:i,cwd:n}),s=await N(o.cwd);if(o.client==="codex"){if(s)await D([],Dt,s,{silent:!1});else {let f=await a$2(o.cwd),l=f==="npm"?"install":"add",d=f==="npm"?"--save-dev":"-D",m=w("Installing dependencies...").start();await execa(f,[l,d,...Dt],{cwd:o.cwd}),m.succeed("Installing dependencies.");}b.break(),b.log("To configure the shadcn MCP server in Codex:"),b.break(),b.log(`1. Open or create the file ${a.info("~/.codex/config.toml")}`),b.log("2. Add the following configuration:"),b.log(),b.info(`[mcp_servers.shadcn]
command = "npx"
args = ["shadcn@${Re}", "mcp"]`),b.break(),b.info("3. Restart Codex to load the MCP server"),b.break(),process.exit(0);}let c=w("Configuring MCP server...").start(),a$1=await Vs(o);if(c.succeed("Configuring MCP server."),s)await D([],Dt,s,{silent:!1});else {let f=await a$2(o.cwd),l=f==="npm"?"install":"add",d=f==="npm"?"--save-dev":"-D",m=w("Installing dependencies...").start();await execa(f,[l,d,...Dt],{cwd:o.cwd}),m.succeed("Installing dependencies.");}b.break(),b.success(`Configuration saved to ${a$1}.`),b.break();}catch(r){$(r);}});var _s=(e,t)=>t;async function Vs(e){let{client:t,cwd:r}=e,n=Lt.find(a=>a.name===t);if(!n)throw new Error(`Unknown client: ${t}. Available clients: ${Lt.map(a=>a.name).join(", ")}`);let i=ee__default.join(r,n.configPath),o=ee__default.dirname(i);await T.ensureDir(o);let s={};try{let a=await promises.readFile(i,"utf-8");s=JSON.parse(a);}catch{}let c=pn(s,n.config,{arrayMerge:_s});return await promises.writeFile(i,JSON.stringify(c,null,2)+`
`,"utf-8"),n.configPath}var de={lucide:{name:"lucide-react",package:"lucide-react",import:"lucide-react"},radix:{name:"@radix-ui/react-icons",package:"@radix-ui/react-icons",import:"@radix-ui/react-icons"}};async function oo(e){if(!e.resolvedPaths.ui)throw new Error("We could not find a valid `ui` path in your `components.json` file. Please ensure you have a valid `ui` path in your `components.json` file.");let t=e.resolvedPaths.ui,[r,n]=await Promise.all([pr("**/*.{js,ts,jsx,tsx}",{cwd:t}),ga()]);if(Object.keys(n).length===0)throw new Error("Something went wrong fetching the registry icons.");let i=Object.entries(de).map(([l,d])=>({title:d.name,value:l})),o=await pe([{type:"select",name:"sourceLibrary",message:`Which icon library would you like to ${a.info("migrate from")}?`,choices:i},{type:"select",name:"targetLibrary",message:`Which icon library would you like to ${a.info("migrate to")}?`,choices:i}]);if(o.sourceLibrary===o.targetLibrary)throw new Error("You cannot migrate to the same icon library. Please choose a different icon library.");if(!(o.sourceLibrary in de&&o.targetLibrary in de))throw new Error("Invalid icon library. Please choose a valid icon library.");let s=de[o.sourceLibrary],c=de[o.targetLibrary],{confirm:a$1}=await pe({type:"confirm",name:"confirm",initial:true,message:`We will migrate ${a.info(r.length)} files in ${a.info(`./${ee__default.relative(e.resolvedPaths.cwd,t)}`)} from ${a.info(s.name)} to ${a.info(c.name)}. Continue?`});a$1||(b.info("Migration cancelled."),process.exit(0)),c.package&&await D([c.package],[],e,{silent:false});let f=w("Migrating icons...")?.start();await Promise.all(r.map(async l=>{f.text=`Migrating ${l}...`;let d=ee__default.join(t,l),m=await promises.readFile(d,"utf-8"),h=await Gs(m,o.sourceLibrary,o.targetLibrary,n);await promises.writeFile(d,h);})),f.succeed("Migration complete.");}async function Gs(e,t,r,n){let i=de[t]?.import,o=de[r]?.import,s=await promises.mkdtemp(ee__default.join(tmpdir(),"shadcn-")),c=new Project({compilerOptions:{}}),a=ee__default.join(s,`shadcn-icons-${randomBytes(4).toString("hex")}.tsx`),f=c.createSourceFile(a,e,{scriptKind:ScriptKind.TSX}),l=[];for(let d of f.getImportDeclarations()??[])if(d.getModuleSpecifier()?.getText()===`"${i}"`){for(let m of d.getNamedImports()??[]){let h=m.getName(),g=Object.values(n).find(w=>w[t]===h)?.[r];!g||l.includes(g)||(l.push(g),m.remove(),f.getDescendantsOfKind(SyntaxKind.JsxSelfClosingElement).filter(w=>w.getTagNameNode()?.getText()===h).forEach(w=>w.getTagNameNode()?.replaceWithText(g)));}d.getNamedImports()?.length===0&&d.remove();}return l.length>0&&f.addImportDeclaration({moduleSpecifier:o,namedImports:l.map(d=>({name:d}))}),await f.getText()}function Ys(e){return e.split("-").map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function Ks(e,t,r,n){let o=e.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").trim().split(",").map(s=>s.trim()).filter(Boolean);for(let s of o){let c=s.match(/^type\s+(\w+)(?:\s+as\s+(\w+))?$/),a=s.match(/^(\w+)\s+as\s+(\w+)$/);if(c){let f=c[1],l=c[2];n==="slot"&&f==="Slot"&&!l?r.push({name:"Slot",alias:"SlotPrimitive",isType:true}):r.push({name:f,alias:l,isType:true});}else if(a){let f=a[1],l=a[2];n==="slot"&&f==="Slot"&&l==="Slot"?r.push({name:"Slot",alias:"SlotPrimitive",isType:t}):r.push({name:f,alias:l,isType:t});}else n==="slot"&&s==="Slot"?r.push({name:"Slot",alias:"SlotPrimitive",isType:t}):r.push({name:s,isType:t});}}async function io(e,t={}){let r,n;if(t.path){if(n=e.resolvedPaths.cwd,t.path.includes("*"))r=await pr(t.path,{cwd:n,onlyFiles:true,ignore:["**/node_modules/**"]});else {let a=ee__default.resolve(n,t.path),f=await promises.stat(a).catch(()=>null);if(!f)throw new Error(`File not found: ${t.path}`);if(f.isDirectory())n=a,r=await pr("**/*.{js,ts,jsx,tsx}",{cwd:n,onlyFiles:true,ignore:["**/node_modules/**"]});else if(f.isFile())r=[t.path];else throw new Error(`Unsupported path type: ${t.path}`)}if(r.length===0)throw new Error(`No files found matching: ${t.path}`)}else {if(!e.resolvedPaths.ui)throw new Error("We could not find a valid `ui` path in your `components.json` file. Please ensure you have a valid `ui` path in your `components.json` file.");n=e.resolvedPaths.ui,r=await pr("**/*.{js,ts,jsx,tsx}",{cwd:n,onlyFiles:true});}if(!t.yes){let c=t.path?t.path:`./${ee__default.relative(e.resolvedPaths.cwd,n)}`,{confirm:a$1}=await pe({type:"confirm",name:"confirm",initial:true,message:`We will migrate ${a.info(r.length)} file(s) in ${a.info(c)} to ${a.info("radix-ui")}. Continue?`});a$1||(b.info("Migration cancelled."),process.exit(0));}let i=w("Migrating imports...")?.start(),o=new Set;await Promise.all(r.map(async c=>{i.text=`Migrating ${c}...`;let a=ee__default.join(n,c),f=await promises.readFile(a,"utf-8"),{content:l,replacedPackages:d}=await qs(f);d.forEach(m=>o.add(m)),await promises.writeFile(a,l);})),i.succeed("Migrating imports.");let s=w("Updating package.json...")?.start();try{let c=qa(e.resolvedPaths.cwd,!1);if(!c){s.fail("Could not read package.json"),b.warn("Could not update package.json. You may need to manually replace @radix-ui/react-* packages with radix-ui");return}let a$1=Array.from(o);if(a$1.length>0){if(c.dependencies||(c.dependencies={}),c.dependencies?.["radix-ui"]||c.devDependencies?.["radix-ui"])s.succeed("radix-ui already in package.json.");else {c.dependencies["radix-ui"]="latest";let l=ee__default.join(e.resolvedPaths.cwd,"package.json");await promises.writeFile(l,JSON.stringify(c,null,2)+`
`),s.succeed("Updated package.json."),await D(["radix-ui"],[],e,{silent:!1});}b.info(""),b.info("Migration complete. The following packages may be removed if no longer in use:"),b.info(a.info(a$1.join(", "))),b.info("Please review your codebase before removing.");}else s.succeed("No packages found in source files.");}catch{s.fail("Failed to update package.json"),b.warn("You may need to manually replace @radix-ui/react-* packages with radix-ui");}}async function qs(e){let t=/import\s+(?:(type)\s+)?(?:\*\s+as\s+(\w+)|{([^}]+)})\s+from\s+(["'])@radix-ui\/react-([^"']+)\4(;?)/g,r=[],n=[],i=[],o='"',s=false,c=e,a;for(;(a=t.exec(e))!==null;){let[g,w,C,b,P,v,$]=a;if(v==="icons"||v.startsWith("icons/"))continue;n.push(g),n.length===1&&(o=P,s=$===";"),i.push(`@radix-ui/react-${v}`);let R=!!w;if(C){let _=Ys(v);r.push({name:_,alias:C,isType:R});}else b&&Ks(b,R,r,v);}if(r.length===0)return {content:e,replacedPackages:[]};let f=r.filter((g,w,C)=>w===C.findIndex(b=>b.name===g.name&&b.alias===g.alias&&b.isType===g.isType)),d=`import { ${f.map(g=>{let w=g.isType?"type ":"";return g.alias?`${w}${g.name} as ${g.alias}`:`${w}${g.name}`}).join(", ")} } from ${o}radix-ui${o}${s?";":""}`;c=n.reduce((g,w,C)=>g.replace(w,C===0?d:""),c),c=c.replace(/\n\s*\n\s*\n/g,`

`),f.some(g=>g.name==="Slot"&&g.alias==="SlotPrimitive")&&(c=c.split(`
`).map(C=>{if(C.trim().startsWith("import "))return C;let b=C;return b=b.replace(/\b(asChild\s*\?\s*)Slot(\s*:)/g,"$1__SLOT_PLACEHOLDER__$2"),b=b.replace(/\bReact\.ComponentProps<typeof\s+Slot>/g,"React.ComponentProps<typeof __SLOT_PLACEHOLDER__>"),b=b.replace(/\bComponentProps<typeof\s+Slot>/g,"ComponentProps<typeof __SLOT_PLACEHOLDER__>"),b=b.replace(/(<\/?)Slot(\s*\/?>)/g,"$1__SLOT_PLACEHOLDER__$2"),b=b.replace(/\bSlot\b/g,(P,v,$)=>{let R=$.substring(0,v),_=(R.match(/"/g)||[]).length,ue=(R.match(/'/g)||[]).length;return _%2!==0||ue%2!==0?P:"__SLOT_PLACEHOLDER__"}),b=b.replace(/__SLOT_PLACEHOLDER__/g,"SlotPrimitive.Slot"),b}).join(`
`));let h=Array.from(new Set(i));return {content:c,replacedPackages:h}}var Zs=["sidebar.tsx","pagination.tsx","calendar.tsx"],Qs=`${c$1}/docs/rtl#manual-migration-optional`;async function so(e,t={}){let r,n;if(t.path){if(n=e.resolvedPaths.cwd,t.path.includes("*"))r=await pr(t.path,{cwd:n,onlyFiles:true,ignore:["**/node_modules/**"]});else {let f=ee__default.resolve(n,t.path),l=await promises.stat(f).catch(()=>null);if(!l)throw new Error(`File not found: ${t.path}`);if(l.isDirectory())n=f,r=await pr("**/*.{js,ts,jsx,tsx}",{cwd:n,onlyFiles:true,ignore:["**/node_modules/**"]});else if(l.isFile())r=[t.path];else throw new Error(`Unsupported path type: ${t.path}`)}if(r.length===0)throw new Error(`No files found matching: ${t.path}`)}else {if(!e.resolvedPaths.ui)throw new Error("Could not find a valid `ui` path in your `components.json`. Please provide a path or glob pattern.");n=e.resolvedPaths.ui,r=await pr("**/*.{js,ts,jsx,tsx}",{cwd:n,onlyFiles:true});}if(!t.yes){let a$1=t.path?t.path:`./${ee__default.relative(e.resolvedPaths.cwd,n)}`,{confirm:f}=await pe({type:"confirm",name:"confirm",initial:true,message:`We will migrate ${a.info(r.length)} file(s) in ${a.info(a$1)} to RTL. Continue?`});f||(b.info("Migration cancelled."),process.exit(0));}let i=w("Updating components.json...").start();try{let a=ee__default.resolve(e.resolvedPaths.cwd,"components.json"),f=JSON.parse(await promises.readFile(a,"utf-8"));f.rtl=!0,await promises.writeFile(a,JSON.stringify(f,null,2)+`
`),i.succeed("Updated components.json.");}catch{throw i.fail("Failed to update components.json."),new Error("Could not update components.json. Please manually set `rtl: true`.")}let o=w("Migrating files to RTL...").start(),s=0,c=[];if(await Promise.all(r.map(async a=>{o.text=`Migrating ${a}...`;let f=ee__default.join(n,a),l=await promises.readFile(f,"utf-8"),d=await e$1(l,true);d!==l&&(await promises.writeFile(f,d),s++);let m=ee__default.basename(a);Zs.includes(m)&&c.push(a);})),o.succeed(`Migration complete. ${s} file(s) transformed.`),c.length>0){b.break(),b.warn("The following components may need manual RTL adjustments:");for(let a of c)b.info(`  - ${a}`);b.break(),b.info(`See ${a.info(Qs)} for more information.`);}}async function co(e){let t={};if(!T.existsSync(e.cwd)||!T.existsSync(ee__default.resolve(e.cwd,"package.json")))return t["1"]=true,{errors:t,config:null};if(!T.existsSync(ee__default.resolve(e.cwd,"components.json")))return t["3"]=true,{errors:t,config:null};try{let r=await N(e.cwd);return {errors:t,config:r}}catch{b.break(),b.error(`An invalid ${a.info("components.json")} file was found at ${a.info(e.cwd)}.
Before you can run a migration, you must create a valid ${a.info("components.json")} file by running the ${a.info("init")} command.`),b.error(`Learn more at ${a.info(`${c$1}/docs/components-json`)}.`),b.break(),process.exit(1);}}var lo=[{name:"icons",description:"migrate your ui components to a different icon library."},{name:"radix",description:"migrate to radix-ui."},{name:"rtl",description:"migrate your components to support RTL (right-to-left)."}],ra=z.object({cwd:z.string(),list:z.boolean(),yes:z.boolean(),migration:z.string().refine(e=>e&&lo.some(t=>t.name===e),{message:"You must specify a valid migration. Run `shadcn migrate --list` to see available migrations."}).optional(),path:z.string().optional()}),fo=new Command().name("migrate").description("run a migration.").argument("[migration]","the migration to run.").argument("[path]","optional path or glob pattern to migrate.").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).option("-l, --list","list all migrations.",false).option("-y, --yes","skip confirmation prompt.",false).action(async(e,t,r)=>{try{let n=ra.parse({cwd:ee__default.resolve(r.cwd),migration:e,path:t,list:r.list,yes:r.yes});if(n.list||!n.migration){b.info("Available migrations:");for(let s of lo)b.info(`- ${s.name}: ${s.description}`);return}if(!n.migration)throw new Error("You must specify a migration. Run `shadcn migrate --list` to see available migrations.");let{errors:i,config:o}=await co(n);if(i["1"]||i["3"])throw new Error("No `components.json` file found. Ensure you are at the root of your project.");if(!o)throw new Error("Something went wrong reading your `components.json` file. Please ensure you have a valid `components.json` file.");n.migration==="icons"&&await oo(o),n.migration==="radix"&&await io(o,{yes:n.yes,path:n.path}),n.migration==="rtl"&&await so(o,{yes:n.yes,path:n.path});}catch(n){b.break(),$(n);}});var ia=z.object({cwd:z.string(),silent:z.boolean()}),mo=new Command().name("add").description("add registries to your project").argument("[registries...]","registries (@namespace) or registry URLs (@namespace=url)").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).option("-s, --silent","mute output.",false).action(async(e,t)=>{try{let r=ia.parse({cwd:ee__default.resolve(t.cwd),silent:t.silent}),n=e.length>0?e:await ca({silent:r.silent});await aa(n,r.cwd,{silent:r.silent});}catch(r){b.break(),$(r);}});function sa(e){let[t,...r]=e.split("="),n=r.length>0?r.join("="):void 0;if(!t.startsWith("@"))throw new Error(`Invalid registry namespace: ${a.info(t)}. Registry names must start with @ (e.g., @acme).`);return {namespace:t,url:n}}function hr(e,t,r){return `${e} ${e===1?t:r}`}async function aa(e,t,r){let n=ee__default.resolve(t,"components.json");if(!T.existsSync(n))throw new Error(`No ${a.info("components.json")} found. Run ${a.info("shadcn init")} first.`);let i=e.map(sa),o=i.filter(g=>!g.url),s=[];if(o.length>0){let g=w("Fetching registries.",{silent:r.silent}).start(),w$1=await ma();if(!w$1)throw g.fail(),new Error("Failed to fetch registries.");g.succeed(),s=w$1;}let c={};for(let{namespace:g,url:w}of i){if(g in d){b.warn(`${a.info(g)} is a built-in registry and cannot be added.`);continue}if(w){if(!w.includes("{name}"))throw new Error(`Invalid registry URL for ${a.info(g)}. URL must include {name} placeholder. Example: ${a.info(`${g}=https://example.com/r/{name}.json`)}`);c[g]=w;}else {let C=s.find(b=>b.name===g);if(!C)throw new Error(`Registry ${a.info(g)} not found. Provide a URL: ${a.info(`${g}=https://.../{name}.json`)}`);c[g]=C.url;}}if(Object.keys(c).length===0)return {addedRegistries:[]};let a$1=await T.readJson(n),f=a$1.registries||{},l={},d$1=[];for(let[g,w]of Object.entries(c))f[g]?d$1.push(g):l[g]=w;if(Object.keys(l).length===0){if(d$1.length>0&&!r.silent){w(`Skipped ${hr(d$1.length,"registry","registries")}: (already configured)`,{silent:r.silent})?.info();for(let g of d$1)b.log(`  - ${g}`);}else r.silent||b.info("No new registries to add.");return}let m={...a$1,registries:{...f,...l}},h=w("Updating components.json.",{silent:r.silent}).start();if(await T.writeJson(n,m,{spaces:2}),h.succeed(),!r.silent){let g=Object.keys(l);w(`Added ${hr(g.length,"registry","registries")}:`,{silent:r.silent})?.succeed();for(let w of g)b.log(`  - ${w}`);if(d$1.length>0){w(`Skipped ${hr(d$1.length,"registry","registries")}: (already configured)`,{silent:r.silent})?.info();for(let w of d$1)b.log(`  - ${w}`);}}}async function ca(e){let t=w("Fetching registries.",{silent:e.silent}).start(),r=await ma();if(!r)throw t.fail(),new Error("Failed to fetch registries.");t.succeed();let n=[...r].sort((o,s)=>o.name.localeCompare(s.name)),{selected:i}=await pe({type:"autocompleteMultiselect",name:"selected",message:"Which registries would you like to add?",hint:"Space to select. A to toggle all. Enter to submit.",instructions:false,choices:n.map(o=>({title:o.name,description:o.description,value:o.name}))});return i?.length||(b.warn("No registries selected. Exiting."),b.info(""),process.exit(1)),i}var uo=new Command().name("registry").description("manage registries").addCommand(mo);var pa=z.object({cwd:z.string(),query:z.string().optional(),limit:z.number().optional(),offset:z.number().optional()}),yo=new Command().name("search").alias("list").description("search items from registries").argument("<registries...>","the registry names or urls to search items from. Names must be prefixed with @.").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).option("-q, --query <query>","query string").option("-l, --limit <number>","maximum number of items to display per registry","100").option("-o, --offset <number>","number of items to skip","0").action(async(e,t)=>{try{let r=pa.parse({cwd:ee__default.resolve(t.cwd),query:t.query,limit:t.limit?parseInt(t.limit,10):void 0,offset:t.offset?parseInt(t.offset,10):void 0});await X(r.cwd);let n=T$1({style:"new-york",resolvedPaths:{cwd:r.cwd}}),i=U$1(n),o=ee__default.resolve(r.cwd,"components.json");if(T.existsSync(o)){let l=await T.readJson(o),d=c.partial().parse(l);i=U$1({...n,...d});}let s=i;try{let l=await N(r.cwd);l&&(s=U$1(l));}catch{}let{config:c$1,newRegistries:a}=await V(e.map(l=>`${l}/registry`),s,{silent:!0,writeFile:!1});a.length>0&&(s.registries=c$1.registries),W(e,s);let f=await va(e,{query:r.query,limit:r.limit,offset:r.offset,config:s});console.log(JSON.stringify(f,null,2)),process.exit(0);}catch(r){$(r);}finally{V$1();}});var da=z.object({cwd:z.string()}),vo=new Command().name("view").description("view items from the registry").argument("<items...>","the item names or URLs to view").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).action(async(e,t)=>{try{let r=da.parse({cwd:ee__default.resolve(t.cwd)});await X(r.cwd);let n=U$1({}),i=ee__default.resolve(r.cwd,"components.json");if(T.existsSync(i)){let f=await T.readJson(i),l=c.partial().parse(f);n=U$1(l);}let o=n;try{let f=await N(r.cwd);f&&(o=U$1(f));}catch{}let{config:s,newRegistries:c$1}=await V(e,o,{silent:!0,writeFile:!1});c$1.length>0&&(o.registries=s.registries),W(e,o);let a=await ba(e,{config:o});console.log(JSON.stringify(a,null,2)),process.exit(0);}catch(r){$(r);}finally{V$1();}});var Co={version:"4.1.0"};process.on("SIGINT",()=>process.exit(0));process.on("SIGTERM",()=>process.exit(0));async function ha(){let e=new Command().name("shadcn").description("build your component library").version(Co.version,"-v, --version","display the version number");e.addCommand(Pn).addCommand(Un).addCommand(Kn).addCommand(qn).addCommand(vo).addCommand(yo).addCommand(fo).addCommand(Qn).addCommand(Hn).addCommand(lr).addCommand(uo),e.parse();}ha();