shadcn
Version:
Add components to your apps.
59 lines (56 loc) • 53.3 kB
JavaScript
#!/usr/bin/env node
import { G, p, a, r, m, g, n, q, h, I, L, d, e, b, c, f, o, H, A, z as z$2, O as O$1, M, P as P$1, i, S, s, U as U$1, Q as Q$1, W, V, k as k$1, j, t, u, K, J, l } from './chunk-7Y6F47JO.js';
export { G as BASE_COLORS, R as clearRegistryCache, Q as fetchRegistry, O as fetchTree, P as getItemTargetPath, M as getRegistryBaseColor, L as getRegistryBaseColors, J as getRegistryIcons, H as getRegistryIndex, K as getRegistryItem, W as getRegistryParentMap, I as getRegistryStyles, V as getRegistryTypeAliasMap, T as registryGetTheme, S as registryResolveItemsTree, U as resolveRegistryItems, N as resolveTree } from './chunk-7Y6F47JO.js';
import * as N from 'path';
import N__default, { basename } from 'path';
import { promises, existsSync } from 'fs';
import L$1 from 'fs-extra';
import h$1 from 'postcss';
import Bt from 'postcss/lib/at-rule';
import { z as z$1 } from 'zod';
import { detect } from '@antfu/ni';
import { execa } from 'execa';
import $e from 'prompts';
import Ar, { tmpdir } from 'os';
import { Project, ScriptKind, SyntaxKind } from 'ts-morph';
import { transformFromAstSync } from '@babel/core';
import { parse } from '@babel/parser';
import gr from '@babel/plugin-transform-typescript';
import * as re from 'recast';
import { Command } from 'commander';
import * as U from 'fs/promises';
import U__default from 'fs/promises';
import { diffLines } from 'diff';
import { randomBytes } from 'crypto';
import ci from 'fast-glob';
var P="1";var O="3";var z="5",ve="6",at="7";var Ie="13";async function lt(e){let t={};if(!L$1.existsSync(e.cwd)||!L$1.existsSync(N__default.resolve(e.cwd,"package.json")))return t[P]=!0,{errors:t,projectInfo:null};let r=q("Preflight checks.",{silent:e.silent}).start();L$1.existsSync(N__default.resolve(e.cwd,"components.json"))&&!e.force&&(r?.fail(),p.break(),p.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.`),p.break(),process.exit(1)),r?.succeed();let i=q("Verifying framework.",{silent:e.silent}).start(),o=await m(e.cwd);(!o||o?.framework.name==="manual")&&(t[at]=!0,i?.fail(),p.break(),o?.framework.links.installation&&p.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.`),p.break(),process.exit(1)),i?.succeed(`Verifying framework. Found ${a.info(o.framework.label)}.`);let n="Validating Tailwind CSS.";o.tailwindVersion==="v4"&&(n=`Validating Tailwind CSS config. Found ${a.info("v4")}.`);let s=q(n,{silent:e.silent}).start();o.tailwindVersion==="v3"&&(!o?.tailwindConfigFile||!o?.tailwindCssFile)?(t[z]=!0,s?.fail()):o.tailwindVersion==="v4"&&!o?.tailwindCssFile?(t[z]=!0,s?.fail()):o.tailwindVersion?s?.succeed():(t[z]=!0,s?.fail());let a$1=q("Validating import alias.",{silent:e.silent}).start();return o?.aliasPrefix?a$1?.succeed():(t[ve]=!0,a$1?.fail()),Object.keys(t).length>0&&(t[z]&&(p.break(),p.error(`No Tailwind CSS configuration found at ${a.info(e.cwd)}.`),p.error("It is likely you do not have Tailwind CSS installed or have an invalid configuration."),p.error("Install Tailwind CSS then try again."),o?.framework.links.tailwind&&p.error(`Visit ${a.info(o?.framework.links.tailwind)} to get started.`)),t[ve]&&(p.break(),p.error("No import alias found in your tsconfig.json file."),o?.framework.links.installation&&p.error(`Visit ${a.info(o?.framework.links.installation)} to learn how to set an import alias.`)),p.break(),process.exit(1)),{errors:t,projectInfo:o}}async function Pe(e,t,r){if(!t.resolvedPaths.tailwindCss||!Object.keys(e??{}).length)return;r={cleanupDefaultNextStyles:!1,silent:!1,tailwindVersion:"v3",...r};let i=t.resolvedPaths.tailwindCss,o=N__default.relative(t.resolvedPaths.cwd,i),n=q(`Updating ${a.info(o)}`,{silent:r.silent}).start(),s=await promises.readFile(i,"utf8"),a$1=await Ut(s,e??{},t,{cleanupDefaultNextStyles:r.cleanupDefaultNextStyles,tailwindVersion:r.tailwindVersion,tailwindConfig:r.tailwindConfig});await promises.writeFile(i,a$1,"utf8"),n.succeed();}async function Ut(e,t,r,i={cleanupDefaultNextStyles:!1,tailwindVersion:"v3",tailwindConfig:void 0}){i={cleanupDefaultNextStyles:!1,tailwindVersion:"v3",tailwindConfig:void 0,...i};let o=[Gt(t)];if(i.cleanupDefaultNextStyles&&o.push(ft()),i.tailwindVersion==="v4"){if(o=[],r.resolvedPaths?.cwd){let a=l(r.resolvedPaths.cwd);!a?.dependencies?.["tailwindcss-animate"]&&!a?.devDependencies?.["tailwindcss-animate"]&&o.push(Ht({params:"tw-animate-css"}));}o.push(Xt({params:"dark (&:is(.dark *))"})),i.cleanupDefaultNextStyles&&o.push(ft()),o.push(Yt(t)),o.push(qt(t)),i.tailwindConfig&&(o.push(Qt(i.tailwindConfig)),o.push(er(i.tailwindConfig)),o.push(Zt(i.tailwindConfig)));}r.tailwind.cssVariables&&o.push(Kt({tailwindVersion:i.tailwindVersion}));let s=(await h$1(o).process(e,{from:void 0})).css;return s=s.replace(/\/\* ---break--- \*\//g,""),i.tailwindVersion==="v4"&&(s=s.replace(/(\n\s*\n)+/g,`
`)),s}function Kt({tailwindVersion:e}){return {postcssPlugin:"update-base-layer",Once(t){let r=[{selector:"*",apply:e==="v4"?"border-border outline-ring/50":"border-border"},{selector:"body",apply:"bg-background text-foreground"}],i=t.nodes.find(o=>o.type==="atrule"&&o.name==="layer"&&o.params==="base"&&r.every(({selector:n,apply:s})=>o.nodes?.some(a=>a.type==="rule"&&a.selector===n&&a.nodes.some(l=>l.type==="atrule"&&l.name==="apply"&&l.params===s))));i||(i=h$1.atRule({name:"layer",params:"base",raws:{semicolon:!0,between:" ",before:`
`}}),t.append(i),t.insertBefore(i,h$1.comment({text:"---break---"}))),r.forEach(({selector:o,apply:n})=>{i?.nodes?.find(a=>a.type==="rule"&&a.selector===o)||i?.append(h$1.rule({selector:o,nodes:[h$1.atRule({name:"apply",params:n,raws:{semicolon:!0,before:`
`}})],raws:{semicolon:!0,between:" ",before:`
`}}));});}}}function Gt(e){return {postcssPlugin:"update-css-vars",Once(t){let r=t.nodes.find(i=>i.type==="atrule"&&i.name==="layer"&&i.params==="base");r instanceof Bt||(r=h$1.atRule({name:"layer",params:"base",nodes:[],raws:{semicolon:!0,before:`
`,between:" "}}),t.append(r),t.insertBefore(r,h$1.comment({text:"---break---"}))),r!==void 0&&Object.entries(e).forEach(([i,o])=>{let n=i==="light"?":root":`.${i}`;Jt(r,n,o);});}}}function pt(e){let t=e.nodes.find(r=>r.type==="rule"&&r.selector===":root");if(t){let r=["--background","--foreground"];t.nodes.filter(i=>i.type==="decl"&&r.includes(i.prop)).forEach(i=>i.remove()),t.nodes.length===0&&t.remove();}}function ft(){return {postcssPlugin:"cleanup-default-next-styles",Once(e){let t=e.nodes.find(i=>i.type==="rule"&&i.selector==="body");t&&(t.nodes.find(i=>i.type==="decl"&&i.prop==="color"&&["rgb(var(--foreground-rgb))","var(--foreground)"].includes(i.value))?.remove(),t.nodes.find(i=>i.type==="decl"&&i.prop==="background"&&(i.value.startsWith("linear-gradient")||i.value==="var(--background)"))?.remove(),t.nodes.find(i=>i.type==="decl"&&i.prop==="font-family"&&i.value==="Arial, Helvetica, sans-serif")?.remove(),t.nodes.length===0&&t.remove()),pt(e);let r=e.nodes.find(i=>i.type==="atrule"&&i.params==="(prefers-color-scheme: dark)");r&&(pt(r),r.nodes.length===0&&r.remove());}}}function Jt(e,t,r){let i=e.nodes?.find(o=>o.type==="rule"&&o.selector===t);i||Object.keys(r).length>0&&(i=h$1.rule({selector:t,raws:{between:" ",before:`
`}}),e.append(i)),Object.entries(r).forEach(([o,n])=>{let s=`--${o.replace(/^--/,"")}`,a=h$1.decl({prop:s,value:n,raws:{semicolon:!0}}),l=i?.nodes.find(p=>p.type==="decl"&&p.prop===s);l?l.replaceWith(a):i?.append(a);});}function Yt(e){return {postcssPlugin:"update-css-vars-v4",Once(t){Object.entries(e).forEach(([r,i])=>{let o=r==="light"?":root":`.${r}`,n=t.nodes?.find(s=>s.type==="rule"&&s.selector===o);!n&&Object.keys(i).length>0&&(n=h$1.rule({selector:o,nodes:[],raws:{semicolon:!0,between:" ",before:`
`}}),t.append(n),t.insertBefore(n,h$1.comment({text:"---break---"}))),Object.entries(i).forEach(([s,a])=>{let l=`--${s.replace(/^--/,"")}`;l==="--sidebar-background"&&(l="--sidebar"),dt(a)&&(a=`hsl(${a})`);let p=h$1.decl({prop:l,value:a,raws:{semicolon:!0}});n?.nodes.find(f=>f.type==="decl"&&f.prop===l)||n?.append(p);});});}}}function qt(e){return {postcssPlugin:"update-theme",Once(t){let r=Array.from(new Set(Object.keys(e).flatMap(n=>Object.keys(e[n]||{}))));if(!r.length)return;let i=ke(t),o=i.nodes?.filter(n=>n.type==="decl"&&n.prop.startsWith("--"));for(let n of r){let s=Object.values(e).find(f=>f[n])?.[n];if(!s)continue;if(n==="radius"){let f={sm:"calc(var(--radius) - 4px)",md:"calc(var(--radius) - 2px)",lg:"var(--radius)",xl:"calc(var(--radius) + 4px)"};for(let[w,b]of Object.entries(f)){let I=h$1.decl({prop:`--radius-${w}`,value:b,raws:{semicolon:!0}});i?.nodes?.find(g=>g.type==="decl"&&g.prop===I.prop)||i?.append(I);}continue}let a=dt(s)||rr(s)?`--color-${n.replace(/^--/,"")}`:`--${n.replace(/^--/,"")}`;a==="--color-sidebar-background"&&(a="--color-sidebar");let l=`var(--${n})`;a==="--color-sidebar"&&(l="var(--sidebar)");let p=h$1.decl({prop:a,value:l,raws:{semicolon:!0}});i?.nodes?.find(f=>f.type==="decl"&&f.prop===p.prop)||(o?.length?i?.insertAfter(o[o.length-1],p):i?.append(p));}}}}function ke(e){let t=e.nodes.find(r=>r.type==="atrule"&&r.name==="theme"&&r.params==="inline");return t||(t=h$1.atRule({name:"theme",params:"inline",nodes:[],raws:{semicolon:!0,between:" ",before:`
`}}),e.append(t),e.insertBefore(t,h$1.comment({text:"---break---"}))),t}function Xt({params:e}){return {postcssPlugin:"add-custom-variant",Once(t){if(!t.nodes.find(i=>i.type==="atrule"&&i.name==="custom-variant")){let i=t.nodes.filter(n=>n.type==="atrule"&&n.name==="import"),o=h$1.atRule({name:"custom-variant",params:e,raws:{semicolon:!0,before:`
`}});if(i.length>0){let n=i[i.length-1];t.insertAfter(n,o);}else t.insertAfter(t.nodes[0],o);t.insertBefore(o,h$1.comment({text:"---break---"}));}}}}function Ht({params:e}){return {postcssPlugin:"add-custom-import",Once(t){let r=t.nodes.filter(n=>n.type==="atrule"&&n.name==="import"),i=t.nodes.find(n=>n.type==="atrule"&&n.name==="custom-variant");if(!r.some(n=>n.params.replace(/["']/g,"")===e)){let n=h$1.atRule({name:"import",params:`"${e}"`,raws:{semicolon:!0,before:`
`}});if(r.length>0){let s=r[r.length-1];t.insertAfter(s,n);}else i?(t.insertBefore(i,n),t.insertBefore(i,h$1.comment({text:"---break---"}))):(t.prepend(n),t.insertAfter(n,h$1.comment({text:"---break---"})));}}}}function Qt(e){return {postcssPlugin:"update-tailwind-config",Once(t){if(!e?.plugins)return;let i=tr(t)==="single"?"'":'"',o=t.nodes.filter(s=>s.type==="atrule"&&s.name==="plugin"),n=o[o.length-1]||t.nodes[0];for(let s of e.plugins){let a=s.replace(/^require\(["']|["']\)$/g,"");if(o.some(p=>p.params.replace(/["']/g,"")===a))continue;let l=h$1.atRule({name:"plugin",params:`${i}${a}${i}`,raws:{semicolon:!0,before:`
`}});t.insertAfter(n,l),t.insertBefore(l,h$1.comment({text:"---break---"}));}}}}function Zt(e){return {postcssPlugin:"update-tailwind-config-keyframes",Once(t){if(!e?.theme?.extend?.keyframes)return;let r=ke(t),i=r.nodes?.filter(n=>n.type==="atrule"&&n.name==="keyframes"),o=z$1.record(z$1.string(),z$1.record(z$1.string(),z$1.string()));for(let[n,s]of Object.entries(e.theme.extend.keyframes)){if(typeof n!="string")continue;let a=o.safeParse(s);if(!a.success||i?.find(p=>p.type==="atrule"&&p.name==="keyframes"&&p.params===n))continue;let l=h$1.atRule({name:"keyframes",params:n,nodes:[],raws:{semicolon:!0,between:" ",before:`
`}});for(let[p,d]of Object.entries(a.data)){let f=h$1.rule({selector:p,nodes:Object.entries(d).map(([w,b])=>h$1.decl({prop:w,value:b,raws:{semicolon:!0,before:`
`,between:": "}})),raws:{semicolon:!0,between:" ",before:`
`}});l.append(f);}r.append(l),r.insertBefore(l,h$1.comment({text:"---break---"}));}}}}function er(e){return {postcssPlugin:"update-tailwind-config-animation",Once(t){if(!e?.theme?.extend?.animation)return;let r=ke(t),i=r.nodes?.filter(n=>n.type==="decl"&&n.prop.startsWith("--animate-")),o=z$1.record(z$1.string(),z$1.string()).safeParse(e.theme.extend.animation);if(o.success)for(let[n,s]of Object.entries(o.data)){let a=`--animate-${n}`;if(i?.find(p=>p.prop===a))continue;let l=h$1.decl({prop:a,value:s,raws:{semicolon:!0,between:": ",before:`
`}});r.append(l);}}}}function tr(e){return e.nodes[0].toString().includes("'")?"single":"double"}function dt(e){if(e.startsWith("hsl")||e.startsWith("rgb")||e.startsWith("#")||e.startsWith("oklch"))return !1;let t=e.split(" ");return t.length===3&&t.slice(1,3).every(r=>r.includes("%"))}function rr(e){return e.startsWith("hsl")||e.startsWith("rgb")||e.startsWith("#")||e.startsWith("oklch")}async function Q(e,{withFallback:t}={withFallback:!1}){let r=await detect({programmatic:!0,cwd:e});if(r==="yarn@berry")return "yarn";if(r==="pnpm@6")return "pnpm";if(r==="bun")return "bun";if(r==="deno")return "deno";if(!t)return r??"npm";let i=process.env.npm_config_user_agent||"";return i.startsWith("yarn")?"yarn":i.startsWith("pnpm")?"pnpm":i.startsWith("bun")?"bun":"npm"}async function B(e,t,r){if(e=Array.from(new Set(e)),!e?.length)return;r={silent:!1,...r};let i=q("Installing dependencies.",{silent:r.silent})?.start(),o=await Q(t.resolvedPaths.cwd),n="";if(sr(t)&&o==="npm")if(r.silent)n="force";else {i.stopAndPersist(),p.warn(`
It looks like you are using React 19.
Some packages may fail to install due to peer dependency issues in npm (see https://ui.shadcn.com/react-19).
`);let s=await $e([{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"}]}]);s&&(n=s.flag);}i?.start(),await execa(o,[o==="npm"?"install":"add",...o==="npm"&&n?[`--${n}`]:[],...e],{cwd:t.resolvedPaths.cwd}),i?.succeed();}function sr(e){let t=l(e.resolvedPaths.cwd);return t?.dependencies?.react?/^(?:\^|~)?19(?:\.\d+)*(?:-.*)?$/.test(t.dependencies.react):!1}var Z=async({sourceFile:e,config:t,baseColor:r})=>(t.tailwind?.cssVariables||!r?.inlineColors||e.getDescendantsOfKind(SyntaxKind.StringLiteral).forEach(i=>{let o=i.getText();if(o){let n=lr(o.replace(/"/g,""),r.inlineColors);i.replaceWithText(`"${n.trim()}"`);}}),e);function Te(e){if(!e.includes("/")&&!e.includes(":"))return [null,e,null];let t=[],[r,i]=e.split("/");if(!r.includes(":"))return [null,r,i];let o=r.split(":"),n=o.pop(),s=o.join(":");return t.push(s??null,n??null,i??null),t}var cr=["bg-","text-","border-","ring-offset-","ring-"];function lr(e,t){e.includes(" border ")&&(e=e.replace(" border "," border border-border "));let r=e.split(" "),i=new Set,o=new Set;for(let n of r){let[s,a,l]=Te(n),p=cr.find(f=>a?.startsWith(f));if(!p){i.has(n)||i.add(n);continue}let d=a?.replace(p,"");if(d&&d in t.light){i.add([s,`${p}${t.light[d]}`].filter(Boolean).join(":")+(l?`/${l}`:"")),o.add(["dark",s,`${p}${t.dark[d]}`].filter(Boolean).join(":")+(l?`/${l}`:""));continue}i.has(n)||i.add(n);}return [...Array.from(i),...Array.from(o)].join(" ").trim()}var k={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"}};var ut="lucide",ee=async({sourceFile:e,config:t})=>{if(!t.iconLibrary||!(t.iconLibrary in k))return e;let r=await J(),i=ut,o=t.iconLibrary;if(i===o)return e;let n=[];for(let s of e.getImportDeclarations()??[])if(s.getModuleSpecifier()?.getText()===`"${k[ut].import}"`){for(let a of s.getNamedImports()??[]){let l=a.getName(),p=r[l]?.[o];!p||n.includes(p)||(n.push(p),a.remove(),e.getDescendantsOfKind(SyntaxKind.JsxSelfClosingElement).filter(d=>d.getTagNameNode()?.getText()===l).forEach(d=>d.getTagNameNode()?.replaceWithText(p)));}s.getNamedImports()?.length===0&&s.remove();}if(n.length>0){let s=e.addImportDeclaration({moduleSpecifier:k[o]?.import,namedImports:n.map(a=>({name:a}))});pr(e)||s.replaceWithText(s.getText().replace(";",""));}return e};function pr(e){return e.getImportDeclarations()?.[0]?.getText().endsWith(";")??!1}var te=async({sourceFile:e,config:t,isRemote:r})=>{let o=`@${t.aliases?.utils?.split("/")[0]?.slice(1)}/lib/utils`,n=e.getImportDeclarations();for(let s of n){let a=fr(s.getModuleSpecifierValue(),t,r);s.setModuleSpecifier(a),(o===a||a==="@/lib/utils")&&s.getNamedImports().find(d=>d.getName()==="cn")&&s.setModuleSpecifier(o===a?a.replace(o,t.aliases.utils):t.aliases.utils);}return e};function fr(e,t,r=!1){if(!e.startsWith("@/")&&!r)return e;if(r&&e.startsWith("@/")&&(e=e.replace(/^@\//,"@/registry/new-york/")),!e.startsWith("@/registry/")){let i=t.aliases.components.split("/")[0];return e.replace(/^@\//,`${i}/`)}return e.match(/^@\/registry\/(.+)\/ui/)?e.replace(/^@\/registry\/(.+)\/ui/,t.aliases.ui??`${t.aliases.components}/ui`):t.aliases.components&&e.match(/^@\/registry\/(.+)\/components/)?e.replace(/^@\/registry\/(.+)\/components/,t.aliases.components):t.aliases.lib&&e.match(/^@\/registry\/(.+)\/lib/)?e.replace(/^@\/registry\/(.+)\/lib/,t.aliases.lib):t.aliases.hooks&&e.match(/^@\/registry\/(.+)\/hooks/)?e.replace(/^@\/registry\/(.+)\/hooks/,t.aliases.hooks):e.replace(/^@\/registry\/[^/]+/,t.aliases.components)}var hr={sourceType:"module",allowImportExportEverywhere:!0,allowReturnOutsideFunction:!0,startLine:1,tokens:!0,plugins:["asyncGenerators","bigInt","classPrivateMethods","classPrivateProperties","classProperties","classStaticBlock","decimal","decorators-legacy","doExpressions","dynamicImport","exportDefaultFrom","exportNamespaceFrom","functionBind","functionSent","importAssertions","importMeta","nullishCoalescingOperator","numericSeparator","objectRestSpread","optionalCatchBinding","optionalChaining",["pipelineOperator",{proposal:"minimal"}],["recordAndTuple",{syntaxType:"hash"}],"throwExpressions","topLevelAwait","v8intrinsic","typescript","jsx"]},gt=async({sourceFile:e,config:t})=>{let r=e.getFullText();if(t.tsx)return r;let i=re.parse(r,{parser:{parse:n=>parse(n,hr)}}),o=transformFromAstSync(i,r,{cloneInputAst:!1,code:!1,ast:!0,plugins:[gr],configFile:!1});if(!o||!o.ast)throw new Error("Failed to transform JSX");return re.print(o.ast).code};var yr=/^["']use client["']$/g,ie=async({sourceFile:e,config:t})=>{if(t.rsc)return e;let r=e.getFirstChildByKind(SyntaxKind.ExpressionStatement);return r&&yr.test(r.getText())&&r.remove(),e};var oe=async({sourceFile:e,config:t})=>(t.tailwind?.prefix&&(e.getDescendantsOfKind(SyntaxKind.CallExpression).filter(r=>r.getExpression().getText()==="cva").forEach(r=>{if(r.getArguments()[0]?.isKind(SyntaxKind.StringLiteral)){let i=r.getArguments()[0];i&&i.replaceWithText(`"${$(i.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`);}r.getArguments()[1]?.isKind(SyntaxKind.ObjectLiteralExpression)&&r.getArguments()[1]?.getDescendantsOfKind(SyntaxKind.PropertyAssignment).find(i=>i.getName()==="variants")?.getDescendantsOfKind(SyntaxKind.PropertyAssignment).forEach(i=>{i.getDescendantsOfKind(SyntaxKind.PropertyAssignment).forEach(o=>{let n=o.getInitializerIfKind(SyntaxKind.StringLiteral);n&&n?.replaceWithText(`"${$(n.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`);});});}),e.getDescendantsOfKind(SyntaxKind.JsxAttribute).forEach(r=>{if(r.getName()==="className"){if(r.getInitializer()?.isKind(SyntaxKind.StringLiteral)){let i=r.getInitializer();i&&i.replaceWithText(`"${$(i.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`);}if(r.getInitializer()?.isKind(SyntaxKind.JsxExpression)){let i=r.getInitializer()?.getDescendantsOfKind(SyntaxKind.CallExpression).find(o=>o.getExpression().getText()==="cn");i&&i.getArguments().forEach(o=>{(o.isKind(SyntaxKind.ConditionalExpression)||o.isKind(SyntaxKind.BinaryExpression))&&o.getChildrenOfKind(SyntaxKind.StringLiteral).forEach(n=>{n.replaceWithText(`"${$(n.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`);}),o.isKind(SyntaxKind.StringLiteral)&&o.replaceWithText(`"${$(o.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`);});}}r.getName()==="classNames"&&r.getInitializer()?.isKind(SyntaxKind.JsxExpression)&&r.getDescendantsOfKind(SyntaxKind.PropertyAssignment).forEach(i=>{if(i.getInitializer()?.isKind(SyntaxKind.CallExpression)){let o=i.getInitializerIfKind(SyntaxKind.CallExpression);o&&o.getArguments().forEach(n=>{n.isKind(SyntaxKind.ConditionalExpression)&&n.getChildrenOfKind(SyntaxKind.StringLiteral).forEach(s=>{s.replaceWithText(`"${$(s.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`);}),n.isKind(SyntaxKind.StringLiteral)&&n.replaceWithText(`"${$(n.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`);});}if(i.getInitializer()?.isKind(SyntaxKind.StringLiteral)&&i.getName()!=="variant"){let o=i.getInitializer();o&&o.replaceWithText(`"${$(o.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`);}});})),e);function $(e,t=""){let r=e.split(" "),i=[];for(let o of r){let[n,s,a]=Te(o);n?a?i.push(`${n}:${t}${s}/${a}`):i.push(`${n}:${t}${s}`):a?i.push(`${t}${s}/${a}`):i.push(`${t}${s}`);}return i.join(" ")}var vr=new Project({compilerOptions:{}});async function Ir(e){let t=await promises.mkdtemp(N__default.join(tmpdir(),"shadcn-"));return N__default.join(t,e)}async function ne(e,t=[te,ie,Z,oe,ee]){let r=await Ir(e.filename),i=vr.createSourceFile(r,e.raw,{scriptKind:ScriptKind.TSX});for(let o of t)await o({sourceFile:i,...e});return e.transformJsx?await gt({sourceFile:i,...e}):i.getText()}async function Ne(e,t,r){if(!e?.length)return {filesCreated:[],filesUpdated:[],filesSkipped:[]};r={overwrite:!1,force:!1,silent:!1,isRemote:!1,...r};let i=q("Updating files.",{silent:r.silent})?.start(),[o,n]=await Promise.all([m(t.resolvedPaths.cwd),M(t.tailwind.baseColor)]),s=[],a$1=[],l=[];for(let d of e){if(!d.content)continue;let f=kr(d,t,{isSrcDir:o?.isSrcDir,framework:o?.framework.name,commonRoot:Er(e.map(E=>E.path),d.path)});if(!f)continue;let w=basename(d.path),b=N__default.dirname(f);t.tsx||(f=f.replace(/\.tsx?$/,E=>E===".tsx"?".jsx":".js"));let I=existsSync(f),g=await ne({filename:d.path,raw:d.content,config:t,baseColor:n,transformJsx:!t.tsx,isRemote:r.isRemote},[te,ie,Z,oe,ee]);if(I){let E=await promises.readFile(f,"utf-8"),[ge,C]=await Promise.all([yt(E),yt(g)]);if(ge===C){l.push(N__default.relative(t.resolvedPaths.cwd,f));continue}}if(I&&!r.overwrite){i.stop(),r.rootSpinner&&r.rootSpinner.stop();let{overwrite:E}=await $e({type:"confirm",name:"overwrite",message:`The file ${a.info(w)} already exists. Would you like to overwrite?`,initial:!1});if(!E){l.push(N__default.relative(t.resolvedPaths.cwd,f)),r.rootSpinner&&r.rootSpinner.start();continue}i?.start(),r.rootSpinner&&r.rootSpinner.start();}existsSync(b)||await promises.mkdir(b,{recursive:!0}),await promises.writeFile(f,g,"utf-8"),I?a$1.push(N__default.relative(t.resolvedPaths.cwd,f)):s.push(N__default.relative(t.resolvedPaths.cwd,f));}if(!(s.length||a$1.length)&&!l.length&&i?.info("No files updated."),s.length){if(i?.succeed(`Created ${s.length} ${s.length===1?"file":"files"}:`),!r.silent)for(let d of s)p.log(` - ${d}`);}else i?.stop();if(a$1.length&&(q(`Updated ${a$1.length} ${a$1.length===1?"file":"files"}:`,{silent:r.silent})?.info(),!r.silent))for(let d of a$1)p.log(` - ${d}`);if(l.length&&(q(`Skipped ${l.length} ${a$1.length===1?"file":"files"}: (files might be identical, use --overwrite to overwrite)`,{silent:r.silent})?.info(),!r.silent))for(let d of l)p.log(` - ${d}`);return r.silent||p.break(),{filesCreated:s,filesUpdated:a$1,filesSkipped:l}}function kr(e,t,r){if(e.target){if(e.target.startsWith("~/"))return N__default.join(t.resolvedPaths.cwd,e.target.replace("~/",""));let n=e.target;return e.type==="registry:page"&&(n=Or(n,r.framework),!n)?"":r.isSrcDir?N__default.join(t.resolvedPaths.cwd,"src",n.replace("src/","")):N__default.join(t.resolvedPaths.cwd,n.replace("src/",""))}let i=Tr(e,t),o=Nr(e.path,i);return N__default.join(i,o)}function Tr(e,t){return e.type==="registry:ui"?t.resolvedPaths.ui:e.type==="registry:lib"?t.resolvedPaths.lib:e.type==="registry:block"||e.type==="registry:component"?t.resolvedPaths.components:e.type==="registry:hook"?t.resolvedPaths.hooks:t.resolvedPaths.components}function Er(e,t){let r=e.map(s=>s.replace(/^\//,"")),i=t.replace(/^\//,""),o=i.split("/").slice(0,-1).join("/");if(!o)return "";let n=o.split("/");for(let s=n.length;s>0;s--){let a=n.slice(0,s).join("/");if(r.some(p=>p!==i&&p.startsWith(a+"/")))return "/"+a}return "/"+o}function Nr(e,t){let r=e.replace(/^\/|\/$/g,""),i=t.replace(/^\/|\/$/g,""),o=r.split("/"),n=i.split("/"),s=n[n.length-1],a=o.findIndex(l=>l===s);return a===-1?o[o.length-1]:o.slice(a+1).join("/")}async function yt(e){return e.replace(/\r\n/g,`
`).trim()}function Or(e,t){if(!t)return "";if(t==="next-app")return e;if(t==="next-pages"){let r=e.replace(/^app\//,"pages/");return r=r.replace(/\/page(\.[jt]sx?)$/,"$1"),r}if(t==="react-router"){let r=e.replace(/^app\//,"app/routes/");return r=r.replace(/\/page(\.[jt]sx?)$/,"$1"),r}if(t==="laravel"){let r=e.replace(/^app\//,"resources/js/pages/");return r=r.replace(/\/page(\.[jt]sx?)$/,"$1"),r}return ""}async function se(e,t,r){r={overwrite:!1,silent:!1,isNewProject:!1,...r};let i$1=await i(t);return i$1&&i$1.ui&&i$1.ui.resolvedPaths.cwd!==t.resolvedPaths.cwd?await Dr(e,t,i$1,{...r,isRemote:e?.length===1&&!!e[0].match(/\/chat\/b\//)}):await $r(e,t,r)}async function $r(e,t,r$1){let i=q("Checking registry.",{silent:r$1.silent})?.start(),o$1=await S(e,t);if(!o$1)return i?.fail(),r(new Error("Failed to fetch components from registry."));i?.succeed();let n=await o(t);await s(o$1.tailwind?.config,t,{silent:r$1.silent,tailwindVersion:n}),await Pe(o$1.cssVars,t,{cleanupDefaultNextStyles:r$1.isNewProject,silent:r$1.silent,tailwindVersion:n,tailwindConfig:o$1.tailwind?.config}),await B(o$1.dependencies,t,{silent:r$1.silent}),await Ne(o$1.files,t,{overwrite:r$1.overwrite,silent:r$1.silent}),o$1.docs&&p.info(o$1.docs);}async function Dr(e,t,r$1,i){let o$1=q("Checking registry.",{silent:i.silent})?.start(),n=await U$1(e,t),s$1=await Q$1(n),a=z$1.array(z$2).parse(s$1);if(!a)return o$1?.fail(),r(new Error("Failed to fetch components from registry."));o$1?.succeed();let l=W(a),p$1=V(),d=[],f=[],w=[],b=q("Installing components.")?.start();for(let g of a){let E=p$1.get(g.type),ge=l.get(g.name);if(!E)continue;let C=g.type==="registry:ui"||ge?.type==="registry:ui"?r$1.ui:t,We=await o(C),V=k$1(t.resolvedPaths.cwd,C.resolvedPaths.ui),he=await j(V,C.resolvedPaths.cwd)??C.resolvedPaths.cwd;g.tailwind?.config&&(await s(g.tailwind?.config,C,{silent:!0,tailwindVersion:We}),f.push(N__default.relative(V,C.resolvedPaths.tailwindConfig))),g.cssVars&&(await Pe(g.cssVars,C,{silent:!0,tailwindVersion:We,tailwindConfig:g.tailwind?.config}),f.push(N__default.relative(V,C.resolvedPaths.tailwindCss))),await B(g.dependencies,C,{silent:!0});let we=await Ne(g.files,C,{overwrite:i.overwrite,silent:!0,rootSpinner:b,isRemote:i.isRemote});d.push(...we.filesCreated.map(M=>N__default.relative(V,N__default.join(he,M)))),f.push(...we.filesUpdated.map(M=>N__default.relative(V,N__default.join(he,M)))),w.push(...we.filesSkipped.map(M=>N__default.relative(V,N__default.join(he,M))));}if(b?.succeed(),d.sort(),f.sort(),w.sort(),!(d.length||f.length)&&!w.length&&q("No files updated.",{silent:i.silent})?.info(),d.length){q(`Created ${d.length} ${d.length===1?"file":"files"}:`,{silent:i.silent})?.succeed();for(let g of d)p.log(` - ${g}`);}if(f.length){q(`Updated ${f.length} ${f.length===1?"file":"files"}:`,{silent:i.silent})?.info();for(let g of f)p.log(` - ${g}`);}if(w.length){q(`Skipped ${w.length} ${f.length===1?"file":"files"}: (use --overwrite to overwrite)`,{silent:i.silent})?.info();for(let g of w)p.log(` - ${g}`);}}var Fr="https://codeload.github.com/shadcn-ui/ui/tar.gz/main",F={next:"next","next-monorepo":"next-monorepo"};async function ce(e){e={srcDir:!1,...e};let t=e.template&&F[e.template]?e.template:"next",r$1=t===F.next?"my-app":"my-monorepo",i="latest",o=e.components?.length===1&&!!e.components[0].match(/\/chat\/b\//);if(e.components&&o)try{let[a]=await Q$1(e.components),{meta:l}=z$1.object({meta:z$1.object({nextVersion:z$1.string()})}).parse(a);i=l.nextVersion,t=F.next;}catch(a){p.break(),r(a);}if(!e.force){let{type:a$1,name:l}=await $e([{type:e.template||o?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:[{title:"Next.js",value:"next"},{title:"Next.js (Monorepo)",value:"next-monorepo"}],initial:0},{type:"text",name:"name",message:"What is your project named?",initial:r$1,format:p=>p.trim(),validate:p=>p.length>128?"Name should be less than 128 characters.":!0}]);t=a$1??t,r$1=l;}let n=await Q(e.cwd,{withFallback:!0}),s=`${e.cwd}/${r$1}`;try{await L$1.access(e.cwd,L$1.constants.W_OK);}catch{p.break(),p.error(`The path ${a.info(e.cwd)} is not writable.`),p.error(`It is likely you do not have write permissions for this folder or the path ${a.info(e.cwd)} does not exist.`),p.break(),process.exit(1);}return L$1.existsSync(N__default.resolve(e.cwd,r$1,"package.json"))&&(p.break(),p.error(`A project with the name ${a.info(r$1)} already exists.`),p.error("Please choose a different name and try again."),p.break(),process.exit(1)),t===F.next&&await Lr(s,{version:i,cwd:e.cwd,packageManager:n,srcDir:!!e.srcDir}),t===F["next-monorepo"]&&await Vr(s,{packageManager:n}),{projectPath:s,projectName:r$1,template:t}}async function Lr(e,t){let r=q("Creating a new Next.js project. This may take a few minutes.").start(),i=["--tailwind","--eslint","--typescript","--app",t.srcDir?"--src-dir":"--no-src-dir","--no-import-alias",`--use-${t.packageManager}`];(t.version.startsWith("15")||t.version.startsWith("latest")||t.version.startsWith("canary"))&&i.push("--turbopack");try{await execa("npx",[`create-next-app@${t.version}`,e,"--silent",...i],{cwd:t.cwd});}catch{p.break(),p.error("Something went wrong creating a new Next.js project. Please try again."),process.exit(1);}r?.succeed("Creating a new Next.js project.");}async function Vr(e,t){let r$1=q("Creating a new Next.js monorepo. This may take a few minutes.").start();try{let i=N__default.join(Ar.tmpdir(),`shadcn-template-${Date.now()}`);await L$1.ensureDir(i);let o=await fetch(Fr);if(!o.ok)throw new Error(`Failed to download template: ${o.statusText}`);let n=N__default.resolve(i,"template.tar.gz");await L$1.writeFile(n,Buffer.from(await o.arrayBuffer())),await execa("tar",["-xzf",n,"-C",i,"--strip-components=2","ui-main/templates/monorepo-next"]);let s=N__default.resolve(i,"monorepo-next");await L$1.move(s,e),await L$1.remove(i),await execa(t.packageManager,["install"],{cwd:e});let a=process.cwd();await execa("git",["--version"],{cwd:e}),await execa("git",["init"],{cwd:e}),await execa("git",["add","-A"],{cwd:e}),await execa("git",["commit","-m","Initial commit"],{cwd:e}),await execa("cd",[a]),r$1?.succeed("Creating a new Next.js monorepo.");}catch(i){r$1?.fail("Something went wrong creating a new Next.js monorepo."),r(i);}}async function bt(e,t,r){if(!e)return;r={silent:!1,...r};let i=N__default.relative(t.resolvedPaths.cwd,t.resolvedPaths.tailwindConfig),o=q(`Updating ${a.info(i)}`,{silent:r.silent}).start(),n=await promises.readFile(t.resolvedPaths.tailwindConfig,"utf8"),s=await Wr(n,e,t);await promises.writeFile(t.resolvedPaths.tailwindConfig,s,"utf8"),o?.succeed();}async function Wr(e,t$1,r){let i=await t(e,r),o=i.getDescendantsOfKind(SyntaxKind.ObjectLiteralExpression).find(n=>n.getProperties().some(s=>s.isKind(SyntaxKind.PropertyAssignment)&&s.getName()==="content"));return o?(zr(o,t$1),i.getFullText()):e}async function zr(e,t){let r=u(e),i=e.getProperty("content");if(!i){let o={name:"content",initializer:`[${r}${t.join(`${r}, ${r}`)}${r}]`};return e.addPropertyAssignment(o),e}if(i.isKind(SyntaxKind.PropertyAssignment)){let o=i.getInitializer();if(o?.isKind(SyntaxKind.ArrayLiteralExpression))for(let n of t){let s=`${r}${n}${r}`;o.getElements().map(a=>a.getText()).includes(s)||o.addElement(s);}return e}return e}var Kr=z$1.object({cwd:z$1.string(),components:z$1.array(z$1.string()).optional(),yes:z$1.boolean(),defaults:z$1.boolean(),force:z$1.boolean(),silent:z$1.boolean(),isNewProject:z$1.boolean(),srcDir:z$1.boolean().optional(),cssVariables:z$1.boolean(),template:z$1.string().optional().refine(e=>e?F[e]:!0,{message:"Invalid template. Please use 'next' or 'next-monorepo'."}),baseColor:z$1.string().optional().refine(e=>e?G.find(t=>t.name===e):!0,{message:`Invalid base color. Please use '${G.map(e=>e.name).join("', '")}'`})}),St=new Command().name("init").description("initialize your project and install dependencies").argument("[components...]","the components to add or a url to the component.").option("-t, --template <template>","the template to use. (next, next-monorepo)").option("-b, --base-color <base-color>","the base color to use. (neutral, gray, zinc, stone, slate)",void 0).option("-y, --yes","skip confirmation prompt.",!0).option("-d, --defaults,","use default configuration.",!1).option("-f, --force","force overwrite of existing configuration.",!1).option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).option("-s, --silent","mute output.",!1).option("--src-dir","use the src directory when creating a new project.",!1).option("--no-src-dir","do not use the src directory when creating a new project.").option("--css-variables","use css variables for theming.",!0).option("--no-css-variables","do not use css variables for theming.").action(async(e,t)=>{try{let r=Kr.parse({cwd:N__default.resolve(t.cwd),isNewProject:!1,components:e,...t});await me(r),p.log(`${a.success("Success!")} Project initialization completed.
You may now add components.`),p.break();}catch(r$1){p.break(),r(r$1);}});async function me(e){let t,r;if(e.skipPreflight)t=await m(e.cwd);else {let p=await lt(e);if(p.errors[P]){let{projectPath:d,template:f}=await ce(e);d||process.exit(1),e.cwd=d,e.isNewProject=!0,r=f;}t=p.projectInfo;}if(r==="next-monorepo")return e.cwd=N__default.resolve(e.cwd,"apps/web"),await g(e.cwd);let i=await n(e.cwd,t),o=i?await Jr(i,e):await Gr(await g(e.cwd));if(!e.yes){let{proceed:p}=await $e({type:"confirm",name:"proceed",message:`Write configuration to ${a.info("components.json")}. Proceed?`,initial:!0});p||process.exit(0);}let n$1=q("Writing components.json.").start(),s=N__default.resolve(e.cwd,"components.json");await promises.writeFile(s,JSON.stringify(o,null,2),"utf8"),n$1.succeed();let a$1=await h(e.cwd,o),l=["index",...e.components||[]];return await se(l,a$1,{overwrite:!0,silent:e.silent,isNewProject:e.isNewProject||t?.framework.name==="next-app"}),e.isNewProject&&e.srcDir&&await bt(["./src/**/*.{js,ts,jsx,tsx,mdx}"],a$1,{silent:e.silent}),a$1}async function Gr(e$1=null){let[t,r]=await Promise.all([I(),L()]);p.info("");let i=await $e([{type:"toggle",name:"typescript",message:`Would you like to use ${a.info("TypeScript")} (recommended)?`,initial:e$1?.tsx??!0,active:"yes",inactive:"no"},{type:"select",name:"style",message:`Which ${a.info("style")} would you like to use?`,choices:t.map(o=>({title:o.label,value:o.name}))},{type:"select",name:"tailwindBaseColor",message:`Which color would you like to use as the ${a.info("base color")}?`,choices:r.map(o=>({title:o.label,value:o.name}))},{type:"text",name:"tailwindCss",message:`Where is your ${a.info("global CSS")} file?`,initial:e$1?.tailwind.css??d},{type:"toggle",name:"tailwindCssVariables",message:`Would you like to use ${a.info("CSS variables")} for theming?`,initial:e$1?.tailwind.cssVariables??!0,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$1?.tailwind.config??e},{type:"text",name:"components",message:`Configure the import alias for ${a.info("components")}:`,initial:e$1?.aliases.components??b},{type:"text",name:"utils",message:`Configure the import alias for ${a.info("utils")}:`,initial:e$1?.aliases.utils??c},{type:"toggle",name:"rsc",message:`Are you using ${a.info("React Server Components")}?`,initial:e$1?.rsc??!0,active:"yes",inactive:"no"}]);return f.parse({$schema:"https://ui.shadcn.com/schema.json",style:i.style,tailwind:{config:i.tailwindConfig,css:i.tailwindCss,baseColor:i.tailwindBaseColor,cssVariables:i.tailwindCssVariables,prefix:i.tailwindPrefix},rsc:i.rsc,tsx:i.typescript,aliases:{utils:i.utils,components:i.components,lib:i.components.replace(/\/components$/,"lib"),hooks:i.components.replace(/\/components$/,"hooks")}})}async function Jr(e,t){let r=e.style,i=t.baseColor,o$1=e.tailwind.cssVariables;if(!t.defaults){let[n,s,a$1]=await Promise.all([I(),L(),o(e)]),l=await $e([{type:a$1==="v4"?null:"select",name:"style",message:`Which ${a.info("style")} would you like to use?`,choices:n.map(p=>({title:p.name==="new-york"?"New York (Recommended)":p.label,value:p.name})),initial:0},{type:t.baseColor?null:"select",name:"tailwindBaseColor",message:`Which color would you like to use as the ${a.info("base color")}?`,choices:s.map(p=>({title:p.label,value:p.name}))}]);r=l.style??"new-york",i=l.tailwindBaseColor??i,o$1=t.cssVariables;}return f.parse({$schema:e?.$schema,style:r,tailwind:{...e?.tailwind,baseColor:i,cssVariables:o$1},rsc:e?.rsc,tsx:e?.tsx,aliases:e?.aliases,iconLibrary:e?.iconLibrary})}async function vt(e){let t={};if(!L$1.existsSync(e.cwd)||!L$1.existsSync(N__default.resolve(e.cwd,"package.json")))return t[P]=!0,{errors:t,config:null};if(!L$1.existsSync(N__default.resolve(e.cwd,"components.json")))return t[O]=!0,{errors:t,config:null};try{let r=await g(e.cwd);return {errors:t,config:r}}catch{p.break(),p.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.`),p.error(`Learn more at ${a.info("https://ui.shadcn.com/docs/components-json")}.`),p.break(),process.exit(1);}}async function Ct(e,t){let r=N__default.join(t.resolvedPaths.cwd,"app/page.tsx");if(!(await U__default.stat(r)).isFile())return;let i=await K(e,t.style);if(!i?.meta?.importSpecifier||!i?.meta?.moduleSpecifier)return;let o=`import { ${i?.meta?.importSpecifier} } from "${i.meta.moduleSpecifier}"
export default function Page() {
return <${i?.meta?.importSpecifier} />
}`;await U__default.writeFile(r,o,"utf8");}var _e=[{name:"toast",deprecatedBy:"sonner",message:"The toast component is deprecated. Use the sonner component instead."},{name:"toaster",deprecatedBy:"sonner",message:"The toaster component is deprecated. Use the sonner component instead."}],Xr=z$1.object({components:z$1.array(z$1.string()).optional(),yes:z$1.boolean(),overwrite:z$1.boolean(),cwd:z$1.string(),all:z$1.boolean(),path:z$1.string().optional(),silent:z$1.boolean(),srcDir:z$1.boolean().optional(),cssVariables:z$1.boolean()}),kt=new Command().name("add").description("add a component to your project").argument("[components...]","the components to add or a url to the component.").option("-y, --yes","skip confirmation prompt.",!1).option("-o, --overwrite","overwrite existing files.",!1).option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).option("-a, --all","add all available components",!1).option("-p, --path <path>","the path to add the component to.").option("-s, --silent","mute output.",!1).option("--src-dir","use the src directory when creating a new project.",!1).option("--no-src-dir","do not use the src directory when creating a new project.").option("--css-variables","use css variables for theming.",!0).option("--no-css-variables","do not use css variables for theming.").action(async(e,t)=>{try{let r=Xr.parse({components:e,cwd:N__default.resolve(t.cwd),...t}),i=r.components?.some(l=>l.includes("theme-"));if(!r.yes&&i){p.break();let{confirm:l}=await $e({type:"confirm",name:"confirm",message:a.warn(`You are about to install a new theme.
Existing CSS variables will be overwritten. Continue?`)});l||(p.break(),p.log("Theme installation cancelled."),p.break(),process.exit(1));}if(r.components?.length||(r.components=await Hr(r)),(await m(r.cwd))?.tailwindVersion==="v4"){let l=_e.filter(p=>r.components?.includes(p.name));l?.length&&(p.break(),l.forEach(p$1=>{p.warn(a.warn(p$1.message));}),p.break(),process.exit(1));}let{errors:n,config:s}=await vt(r);if(n[O]){let{proceed:l}=await $e({type:"confirm",name:"proceed",message:`You need to create a ${a.info("components.json")} file to add components. Proceed?`,initial:!0});l||(p.break(),process.exit(1)),s=await me({cwd:r.cwd,yes:!0,force:!0,defaults:!1,skipPreflight:!1,silent:!0,isNewProject:!1,srcDir:r.srcDir,cssVariables:r.cssVariables});}let a$1=!1;if(n[P]){let{projectPath:l,template:p$1}=await ce({cwd:r.cwd,force:r.overwrite,srcDir:r.srcDir,components:r.components});l||(p.break(),process.exit(1)),r.cwd=l,p$1==="next-monorepo"?(r.cwd=N__default.resolve(r.cwd,"apps/web"),s=await g(r.cwd)):(s=await me({cwd:r.cwd,yes:!0,force:!0,defaults:!1,skipPreflight:!0,silent:!0,isNewProject:!0,srcDir:r.srcDir,cssVariables:r.cssVariables}),a$1=r.components?.length===1&&!!r.components[0].match(/\/chat\/b\//));}if(!s)throw new Error(`Failed to read config at ${a.info(r.cwd)}.`);await se(r.components,s,r),a$1&&await Ct(r.components[0],s);}catch(r$1){p.break(),r(r$1);}});async function Hr(e){let t=await H();if(!t)return p.break(),r(new Error("Failed to fetch registry index.")),[];if(e.all)return t.map(o=>o.name).filter(o=>!_e.some(n=>n.name===o));if(e.components?.length)return e.components;let{components:r$1}=await $e({type:"multiselect",name:"components",message:"Which components would you like to add?",hint:"Space to select. A to toggle all. Enter to submit.",instructions:!1,choices:t.filter(o=>o.type==="registry:ui"&&!_e.some(n=>n.name===o.name)).map(o=>({title:o.name,value:o.name,selected:e.all?!0:e.components?.includes(o.name)}))});r$1?.length||(p.warn("No components selected. Exiting."),p.info(""),process.exit(1));let i=z$1.array(z$1.string()).safeParse(r$1);return i.success?i.data:(p.error(""),r(new Error("Something went wrong. Please try again.")),[])}async function Nt(e){let t={},r={cwd:e.cwd,registryFile:N__default.resolve(e.cwd,e.registryFile),outputDir:N__default.resolve(e.cwd,e.outputDir)};return L$1.existsSync(r.registryFile)||(t[Ie]=!0),await L$1.mkdir(r.outputDir,{recursive:!0}),Object.keys(t).length>0&&(t[Ie]&&(p.break(),p.error(`The path ${a.info(r.registryFile)} does not exist.`)),p.break(),process.exit(1)),{errors:t,resolvePaths:r}}var Zr=z$1.object({cwd:z$1.string(),registryFile:z$1.string(),outputDir:z$1.string()}),Ot=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=Zr.parse({cwd:N.resolve(t.cwd),registryFile:e,outputDir:t.output}),{resolvePaths:i}=await Nt(r),o=await U.readFile(i.registryFile,"utf-8"),n=A.safeParse(JSON.parse(o));n.success||(p.error(`Invalid registry file found at ${a.info(i.registryFile)}.`),process.exit(1));let s=q("Building registry...");for(let a$1 of n.data.items){if(!a$1.files)continue;s.start(`Building ${a$1.name}...`),a$1.$schema="https://ui.shadcn.com/schema/registry-item.json";for(let p of a$1.files)p.content=await U.readFile(N.resolve(i.cwd,p.path),"utf-8");let l=z$2.safeParse(a$1);if(!l.success){p.error(`Invalid registry item found for ${a.info(a$1.name)}.`);continue}await U.writeFile(N.resolve(i.outputDir,`${l.data.name}.json`),JSON.stringify(l.data,null,2));}s.succeed("Building registry.");}catch(r$1){p.break(),r(r$1);}});var ii=z$1.object({component:z$1.string().optional(),yes:z$1.boolean(),cwd:z$1.string(),path:z$1.string().optional()}),$t=new Command().name("diff").description("check for updates against the registry").argument("[component]","the component name").option("-y, --yes","skip confirmation prompt.",!1).option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).action(async(e,t)=>{try{let r$1=ii.parse({component:e,...t}),i=N__default.resolve(r$1.cwd);existsSync(i)||(p.error(`The path ${i} does not exist. Please try again.`),process.exit(1));let o=await g(i);o||(p.warn(`Configuration is missing. Please run ${a.success("init")} to create a components.json file.`),process.exit(1));let n=await H();if(n||(r(new Error("Failed to fetch registry index.")),process.exit(1)),!r$1.component){let l=o.resolvedPaths.components,p$1=n.filter(f=>{for(let w of f.files??[]){let b=N__default.resolve(l,typeof w=="string"?w:w.path);if(existsSync(b))return !0}return !1}),d=[];for(let f of p$1){let w=await jt(f,o);w.length&&d.push({name:f.name,changes:w});}d.length||(p.info("No updates found."),process.exit(0)),p.info("The following components have updates available:");for(let f of d){p.info(`- ${f.name}`);for(let w of f.changes)p.info(` - ${w.filePath}`);}p.break(),p.info(`Run ${a.success("diff <component>")} to see the changes.`),process.exit(0);}let s=n.find(l=>l.name===r$1.component);s||(p.error(`The component ${a.success(r$1.component)} does not exist.`),process.exit(1));let a$1=await jt(s,o);a$1.length||(p.info(`No updates found for ${r$1.component}.`),process.exit(0));for(let l of a$1)p.info(`- ${l.filePath}`),await oi(l.patch),p.info("");}catch(r$1){r(r$1);}});async function jt(e,t){let r=await O$1(t.style,[e]),i=await M(t.tailwind.baseColor);if(!r)return [];let o=[];for(let n of r){let s=await P$1(t,n);if(s)for(let a of n.files??[]){let l=N__default.resolve(s,typeof a=="string"?a:a.path);if(!existsSync(l))continue;let p=await promises.readFile(l,"utf8");if(typeof a=="string"||!a.content)continue;let d=await ne({filename:a.path,raw:a.content,config:t,baseColor:i}),f=diffLines(d,p);f.length>1&&o.push({filePath:l,patch:f});}}return o}async function oi(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 Dt=new Command().name("info").description("get information about your project").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).action(async e=>{p.info("> project info"),console.log(await m(e.cwd)),p.break(),p.info("> components.json"),console.log(await g(e.cwd));});async function _t(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,i]=await Promise.all([ci("**/*.{js,ts,jsx,tsx}",{cwd:t}),J()]);if(Object.keys(i).length===0)throw new Error("Something went wrong fetching the registry icons.");let o=Object.entries(k).map(([d,f])=>({title:f.name,value:d})),n=await $e([{type:"select",name:"sourceLibrary",message:`Which icon library would you like to ${a.info("migrate from")}?`,choices:o},{type:"select",name:"targetLibrary",message:`Which icon library would you like to ${a.info("migrate to")}?`,choices:o}]);if(n.sourceLibrary===n.targetLibrary)throw new Error("You cannot migrate to the same icon library. Please choose a different icon library.");if(!(n.sourceLibrary in k&&n.targetLibrary in k))throw new Error("Invalid icon library. Please choose a valid icon library.");let s=k[n.sourceLibrary],a$1=k[n.targetLibrary],{confirm:l}=await $e({type:"confirm",name:"confirm",initial:!0,message:`We will migrate ${a.info(r.length)} files in ${a.info(`./${N__default.relative(e.resolvedPaths.cwd,t)}`)} from ${a.info(s.name)} to ${a.info(a$1.name)}. Continue?`});l||(p.info("Migration cancelled."),process.exit(0)),a$1.package&&await B([a$1.package],e,{silent:!1});let p$1=q("Migrating icons...")?.start();await Promise.all(r.map(async d=>{p$1.text=`Migrating ${d}...`;let f=N__default.join(t,d),w=await promises.readFile(f,"utf-8"),b=await fi(w,n.sourceLibrary,n.targetLibrary,i);await promises.writeFile(f,b);})),p$1.succeed("Migration complete.");}async function fi(e,t,r,i){let o=k[t]?.import,n=k[r]?.import,s=await promises.mkdtemp(N__default.join(tmpdir(),"shadcn-")),a=new Project({compilerOptions:{}}),l=N__default.join(s,`shadcn-icons-${randomBytes(4).toString("hex")}.tsx`),p=a.createSourceFile(l,e,{scriptKind:ScriptKind.TSX}),d=[];for(let f of p.getImportDeclarations()??[])if(f.getModuleSpecifier()?.getText()===`"${o}"`){for(let w of f.getNamedImports()??[]){let b=w.getName(),I=Object.values(i).find(g=>g[t]===b)?.[r];!I||d.includes(I)||(d.push(I),w.remove(),p.getDescendantsOfKind(SyntaxKind.JsxSelfClosingElement).filter(g=>g.getTagNameNode()?.getText()===b).forEach(g=>g.getTagNameNode()?.replaceWithText(I)));}f.getNamedImports()?.length===0&&f.remove();}return d.length>0&&p.addImportDeclaration({moduleSpecifier:n,namedImports:d.map(f=>({name:f}))}),await p.getText()}async function Lt(e){let t={};if(!L$1.existsSync(e.cwd)||!L$1.existsSync(N__default.resolve(e.cwd,"package.json")))return t[P]=!0,{errors:t,config:null};if(!L$1.existsSync(N__default.resolve(e.cwd,"components.json")))return t[O]=!0,{errors:t,config:null};try{let r=await g(e.cwd);return {errors:t,config:r}}catch{p.break(),p.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.`),p.error(`Learn more at ${a.info("https://ui.shadcn.com/docs/components-json")}.`),p.break(),process.exit(1);}}var Vt=[{name:"icons",description:"migrate your ui components to a different icon library."}],gi=z$1.object({cwd:z$1.string(),list:z$1.boolean(),migration:z$1.string().refine(e=>e&&Vt.some(t=>t.name===e),{message:"You must specify a valid migration. Run `shadcn migrate --list` to see available migrations."}).optional()}),Mt=new Command().name("migrate").description("run a migration.").argument("[migration]","t