shadcn 2.1.6 → 2.1.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,30 +1,30 @@
1
1
  #!/usr/bin/env node
2
- import pi from"path";import{promises as ni}from"fs";import xt from"path";import Ke from"path";var I="1";var j="3";var ge="5",ue="6",Ae="7";import he from"path";var k={"next-app":{name:"next-app",label:"Next.js",links:{installation:"https://ui.shadcn.com/docs/installation/next",tailwind:"https://tailwindcss.com/docs/guides/nextjs"}},"next-pages":{name:"next-pages",label:"Next.js",links:{installation:"https://ui.shadcn.com/docs/installation/next",tailwind:"https://tailwindcss.com/docs/guides/nextjs"}},remix:{name:"remix",label:"Remix",links:{installation:"https://ui.shadcn.com/docs/installation/remix",tailwind:"https://tailwindcss.com/docs/guides/remix"}},vite:{name:"vite",label:"Vite",links:{installation:"https://ui.shadcn.com/docs/installation/vite",tailwind:"https://tailwindcss.com/docs/guides/vite"}},astro:{name:"astro",label:"Astro",links:{installation:"https://ui.shadcn.com/docs/installation/astro",tailwind:"https://tailwindcss.com/docs/guides/astro"}},laravel:{name:"laravel",label:"Laravel",links:{installation:"https://ui.shadcn.com/docs/installation/laravel",tailwind:"https://tailwindcss.com/docs/guides/laravel"}},gatsby:{name:"gatsby",label:"Gatsby",links:{installation:"https://ui.shadcn.com/docs/installation/gatsby",tailwind:"https://tailwindcss.com/docs/guides/gatsby"}},manual:{name:"manual",label:"Manual",links:{installation:"https://ui.shadcn.com/docs/installation/manual",tailwind:"https://tailwindcss.com/docs/installation"}}};import z from"path";import{cyan as Ft,green as Dt,red as _t,yellow as zt}from"kleur/colors";var c={error:_t,warn:zt,info:Ft,success:Dt};import{createMatchPath as Kt}from"tsconfig-paths";async function T(e,t){return Kt(t.absoluteBaseUrl,t.paths)(e,void 0,()=>!0,[".ts",".tsx"])}import{cosmiconfig as Mt}from"cosmiconfig";import{loadConfig as Wt}from"tsconfig-paths";import{z as h}from"zod";var Le="@/components",Fe="@/lib/utils",De="app/globals.css",_e="tailwind.config.js";var Ut=Mt("components",{searchPlaces:["components.json"]}),K=h.object({$schema:h.string().optional(),style:h.string(),rsc:h.coerce.boolean().default(!1),tsx:h.coerce.boolean().default(!0),tailwind:h.object({config:h.string(),css:h.string(),baseColor:h.string(),cssVariables:h.boolean().default(!0),prefix:h.string().default("").optional()}),aliases:h.object({components:h.string(),utils:h.string(),ui:h.string().optional(),lib:h.string().optional(),hooks:h.string().optional()}),iconLibrary:h.string().optional()}).strict(),Vt=K.extend({resolvedPaths:h.object({cwd:h.string(),tailwindConfig:h.string(),tailwindCss:h.string(),utils:h.string(),components:h.string(),lib:h.string(),hooks:h.string(),ui:h.string()})});async function C(e){let t=await Bt(e);return t?(t.iconLibrary||(t.iconLibrary=t.style==="new-york"?"radix":"lucide"),await M(e,t)):null}async function M(e,t){let r=await Wt(e);if(r.resultType==="failed")throw new Error(`Failed to load ${t.tsx?"tsconfig":"jsconfig"}.json. ${r.message??""}`.trim());return Vt.parse({...t,resolvedPaths:{cwd:e,tailwindConfig:z.resolve(e,t.tailwind.config),tailwindCss:z.resolve(e,t.tailwind.css),utils:await T(t.aliases.utils,r),components:await T(t.aliases.components,r),ui:t.aliases.ui?await T(t.aliases.ui,r):z.resolve(await T(t.aliases.components,r)??e,"ui"),lib:t.aliases.lib?await T(t.aliases.lib,r):z.resolve(await T(t.aliases.utils,r)??e,".."),hooks:t.aliases.hooks?await T(t.aliases.hooks,r):z.resolve(await T(t.aliases.components,r)??e,"..","hooks")}})}async function Bt(e){try{let t=await Ut.search(e);return t?K.parse(t.config):null}catch{let r=`${e}/components.json`;throw new Error(`Invalid configuration found in ${c.info(r)}.`)}}import Gt from"path";import Jt from"fs-extra";function J(e="",t=!0){let r=Gt.join(e,"package.json");return Jt.readJSONSync(r,{throws:t})}import Y from"fast-glob";import ye from"fs-extra";import{loadConfig as Yt}from"tsconfig-paths";var H=["**/node_modules/**",".next","public","dist","build"];async function E(e){let[t,r,i,n,o,s,l]=await Promise.all([Y.glob("**/{next,vite,astro}.config.*|gatsby-config.*|composer.json",{cwd:e,deep:3,ignore:H}),ye.pathExists(he.resolve(e,"src")),qt(e),Qt(e),Ht(e),Xt(e),J(e,!1)]),f=await ye.pathExists(he.resolve(e,`${r?"src/":""}app`)),d={framework:k.manual,isSrcDir:r,isRSC:!1,isTsx:i,tailwindConfigFile:n,tailwindCssFile:o,aliasPrefix:s};return t.find(p=>p.startsWith("next.config."))?.length?(d.framework=f?k["next-app"]:k["next-pages"],d.isRSC=f,d):t.find(p=>p.startsWith("astro.config."))?.length?(d.framework=k.astro,d):t.find(p=>p.startsWith("gatsby-config."))?.length?(d.framework=k.gatsby,d):t.find(p=>p.startsWith("composer.json"))?.length?(d.framework=k.laravel,d):Object.keys(l?.dependencies??{}).find(p=>p.startsWith("@remix-run/"))?(d.framework=k.remix,d):(t.find(p=>p.startsWith("vite.config."))?.length&&(d.framework=k.vite),d)}async function Ht(e){let t=await Y.glob(["**/*.css","**/*.scss"],{cwd:e,deep:5,ignore:H});if(!t.length)return null;for(let r of t)if((await ye.readFile(he.resolve(e,r),"utf8")).includes("@tailwind base"))return r;return null}async function Qt(e){let t=await Y.glob("tailwind.config.*",{cwd:e,deep:3,ignore:H});return t.length?t[0]:null}async function Xt(e){let t=await Yt(e);if(t?.resultType==="failed"||!t?.paths)return null;for(let[r,i]of Object.entries(t.paths))if(i.includes("./*")||i.includes("./src/*")||i.includes("./app/*")||i.includes("./resources/js/*"))return r.at(0)??null;return null}async function qt(e){return(await Y.glob("tsconfig.*",{cwd:e,deep:1,ignore:H})).length>0}async function ze(e,t=null){let[r,i]=await Promise.all([C(e),t?Promise.resolve(t):E(e)]);if(r)return r;if(!i||!i.tailwindConfigFile||!i.tailwindCssFile)return null;let n={$schema:"https://ui.shadcn.com/schema.json",rsc:i.isRSC,tsx:i.isTsx,style:"new-york",tailwind:{config:i.tailwindConfigFile,baseColor:"zinc",css:i.tailwindCssFile,cssVariables:!0,prefix:""},iconLibrary:"lucide",aliases:{components:`${i.aliasPrefix}/components`,ui:`${i.aliasPrefix}/components/ui`,hooks:`${i.aliasPrefix}/hooks`,lib:`${i.aliasPrefix}/lib`,utils:`${i.aliasPrefix}/lib/utils`}};return await M(e,n)}var a={error(...e){console.log(c.error(e.join(" ")))},warn(...e){console.log(c.warn(e.join(" ")))},info(...e){console.log(c.info(e.join(" ")))},success(...e){console.log(c.success(e.join(" ")))},log(...e){console.log(e.join(" "))},break(){console.log("")}};import Zt from"ora";function y(e,t){return Zt({text:e,isSilent:t?.silent})}import we from"fs-extra";async function Me(e){let t={};if(!we.existsSync(e.cwd)||!we.existsSync(Ke.resolve(e.cwd,"package.json")))return t[I]=!0,{errors:t,projectInfo:null};let r=y("Preflight checks.",{silent:e.silent}).start();we.existsSync(Ke.resolve(e.cwd,"components.json"))&&!e.force&&(r?.fail(),a.break(),a.error(`A ${c.info("components.json")} file already exists at ${c.info(e.cwd)}.
3
- To start over, remove the ${c.info("components.json")} file and run ${c.info("init")} again.`),a.break(),process.exit(1)),r?.succeed();let i=y("Verifying framework.",{silent:e.silent}).start(),n=await E(e.cwd);(!n||n?.framework.name==="manual")&&(t[Ae]=!0,i?.fail(),a.break(),n?.framework.links.installation&&a.error(`We could not detect a supported framework at ${c.info(e.cwd)}.
4
- Visit ${c.info(n?.framework.links.installation)} to manually configure your project.
5
- Once configured, you can use the cli to add components.`),a.break(),process.exit(1)),i?.succeed(`Verifying framework. Found ${c.info(n.framework.label)}.`);let o=y("Validating Tailwind CSS.",{silent:e.silent}).start();!n?.tailwindConfigFile||!n?.tailwindCssFile?(t[ge]=!0,o?.fail()):o?.succeed();let s=y("Validating import alias.",{silent:e.silent}).start();return n?.aliasPrefix?s?.succeed():(t[ue]=!0,s?.fail()),Object.keys(t).length>0&&(t[ge]&&(a.break(),a.error(`No Tailwind CSS configuration found at ${c.info(e.cwd)}.`),a.error("It is likely you do not have Tailwind CSS installed or have an invalid configuration."),a.error("Install Tailwind CSS then try again."),n?.framework.links.tailwind&&a.error(`Visit ${c.info(n?.framework.links.tailwind)} to get started.`)),t[ue]&&(a.break(),a.error("No import alias found in your tsconfig.json file."),n?.framework.links.installation&&a.error(`Visit ${c.info(n?.framework.links.installation)} to learn how to set an import alias.`)),a.break(),process.exit(1)),{errors:t,projectInfo:n}}import{z as er}from"zod";function x(e){if(a.error("Something went wrong. Please check the error below for more details."),a.error("If the problem persists, please open an issue on GitHub."),a.error(""),typeof e=="string"&&(a.error(e),a.break(),process.exit(1)),e instanceof er.ZodError){a.error("Validation failed:");for(let[t,r]of Object.entries(e.flatten().fieldErrors))a.error(`- ${c.info(t)}: ${r}`);a.break(),process.exit(1)}e instanceof Error&&(a.error(e.message),a.break(),process.exit(1)),a.break(),process.exit(1)}import dr from"path";import{z as m}from"zod";var We=m.enum(["registry:style","registry:lib","registry:example","registry:block","registry:component","registry:ui","registry:hook","registry:theme","registry:page"]),Ue=m.object({path:m.string(),content:m.string().optional(),type:We,target:m.string().optional()}),tr=m.object({config:m.object({content:m.array(m.string()).optional(),theme:m.record(m.string(),m.any()).optional(),plugins:m.array(m.string()).optional()}).optional()}),rr=m.object({light:m.record(m.string(),m.string()).optional(),dark:m.record(m.string(),m.string()).optional()}),_=m.object({name:m.string(),type:We,description:m.string().optional(),dependencies:m.array(m.string()).optional(),devDependencies:m.array(m.string()).optional(),registryDependencies:m.array(m.string()).optional(),files:m.array(Ue).optional(),tailwind:tr.optional(),cssVars:rr.optional(),meta:m.record(m.string(),m.any()).optional(),docs:m.string().optional()}),xe=m.array(_.extend({files:m.array(m.union([m.string(),Ue])).optional()})),Ve=m.array(m.object({name:m.string(),label:m.string()})),Be=m.record(m.string(),m.record(m.string(),m.string())),Ge=m.object({inlineColors:m.object({light:m.record(m.string(),m.string()),dark:m.record(m.string(),m.string())}),cssVars:m.object({light:m.record(m.string(),m.string()),dark:m.record(m.string(),m.string())}),inlineColorsTemplate:m.string(),cssVarsTemplate:m.string()}),Je=_.pick({dependencies:!0,devDependencies:!0,files:!0,tailwind:!0,cssVars:!0,docs:!0});import{promises as be}from"fs";import{tmpdir as ir}from"os";import W from"path";import nr from"deepmerge";import or from"stringify-object";import{Project as sr,QuoteKind as ar,ScriptKind as Ye,SyntaxKind as u}from"ts-morph";async function He(e,t,r){if(!e)return;r={silent:!1,...r};let i=W.relative(t.resolvedPaths.cwd,t.resolvedPaths.tailwindConfig),n=y(`Updating ${c.info(i)}`,{silent:r.silent}).start(),o=await be.readFile(t.resolvedPaths.tailwindConfig,"utf8"),s=await cr(o,e,t);await be.writeFile(t.resolvedPaths.tailwindConfig,s,"utf8"),n?.succeed()}async function cr(e,t,r){let i=await Q(e,r),n=i.getDescendantsOfKind(u.ObjectLiteralExpression).find(s=>s.getProperties().some(l=>l.isKind(u.PropertyAssignment)&&l.getName()==="content"));if(!n)return e;let o=Se(n);return lr(n,{name:"darkMode",value:"class"},{quoteChar:o}),t.plugins?.forEach(s=>{mr(n,s)}),t.theme&&await pr(n,t.theme),i.getFullText()}function lr(e,t,{quoteChar:r}){let i=e.getProperty("darkMode");if(!i){let n={name:t.name,initializer:`[${r}${t.value}${r}]`};return t.name==="darkMode"?(e.insertPropertyAssignment(0,n),e):(e.addPropertyAssignment(n),e)}if(i.isKind(u.PropertyAssignment)){let n=i.getInitializer(),o=`${r}${t.value}${r}`;if(n?.isKind(u.StringLiteral)){let s=n.getText();return n.replaceWithText(`[${s}, ${o}]`),e}if(n?.isKind(u.ArrayLiteralExpression)){if(n.getElements().map(s=>s.getText()).includes(o))return e;n.addElement(o)}return e}return e}async function pr(e,t){e.getProperty("theme")||e.addPropertyAssignment({name:"theme",initializer:"{}"}),Qe(e);let i=(e.getPropertyOrThrow("theme")?.asKindOrThrow(u.PropertyAssignment)).getInitializer();if(i?.isKind(u.ObjectLiteralExpression)){let n=i.getText(),o=await fr(n),s=nr(o,t),l=or(s).replace(/\'\"/g,"'").replace(/\"\'/g,"'").replace(/\'\[/g,"[").replace(/\]\'/g,"]").replace(/\'\\\'/g,"'").replace(/\\\'/g,"'").replace(/\\\'\'/g,"'").replace(/\'\'/g,"'");i.replaceWithText(l)}Xe(e)}function mr(e,t){let r=e.getProperty("plugins");if(!r)return e.addPropertyAssignment({name:"plugins",initializer:`[${t}]`}),e;if(r.isKind(u.PropertyAssignment)){let i=r.getInitializer();if(i?.isKind(u.ArrayLiteralExpression)){if(i.getElements().map(n=>n.getText().replace(/["']/g,"")).includes(t.replace(/["']/g,"")))return e;i.addElement(t)}return e}return e}async function Q(e,t){let r=await be.mkdtemp(W.join(ir(),"shadcn-")),i=t?.resolvedPaths?.tailwindConfig||"tailwind.config.ts",n=W.join(r,`shadcn-${W.basename(i)}`);return new sr({compilerOptions:{}}).createSourceFile(n,e,{scriptKind:W.extname(i)===".ts"?Ye.TS:Ye.JS})}function Se(e){return e.getFirstDescendantByKind(u.StringLiteral)?.getQuoteKind()===ar.Single?"'":'"'}function Qe(e){let t=e.getProperties();for(let r=0;r<t.length;r++){let i=t[r];if(i.isKind(u.SpreadAssignment)){let n=i.asKindOrThrow(u.SpreadAssignment),o=n.getExpression().getText();e.insertPropertyAssignment(r,{name:`___${o.replace(/^\.\.\./,"")}`,initializer:`"...${o.replace(/^\.\.\./,"")}"`}),n.remove()}else if(i.isKind(u.PropertyAssignment)){let o=i.asKindOrThrow(u.PropertyAssignment).getInitializer();o&&o.isKind(u.ObjectLiteralExpression)&&Qe(o.asKindOrThrow(u.ObjectLiteralExpression))}}}function Xe(e){let t=e.getProperties();for(let r=0;r<t.length;r++){let i=t[r];if(i.isKind(u.PropertyAssignment)){let n=i,o=n.getInitializer();if(o?.isKind(u.StringLiteral)){let s=o.getLiteralValue();s.startsWith("...")&&(e.insertSpreadAssignment(r,{expression:s.slice(3)}),n.remove())}else o?.isKind(u.ObjectLiteralExpression)&&Xe(o)}}}async function fr(e){let r=(await Q(`const theme = ${e}`,null)).getStatements()[0];if(r?.getKind()===u.VariableStatement){let n=(r.getDeclarationList()?.getDeclarations()[0]).getInitializer();if(n?.isKind(u.ObjectLiteralExpression))return await qe(n)}throw new Error("Invalid input: not an object literal")}function qe(e){let t={};for(let r of e.getProperties())if(r.isKind(u.PropertyAssignment)){let i=r.getName().replace(/\'/g,"");r.getInitializer()?.isKind(u.ObjectLiteralExpression)?t[i]=qe(r.getInitializer()):t[i]=Ze(r.getInitializer())}return t}function Ze(e){switch(e.kind){case u.StringLiteral:return e.text;case u.NumericLiteral:return Number(e.text);case u.TrueKeyword:return!0;case u.FalseKeyword:return!1;case u.NullKeyword:return null;case u.ArrayLiteralExpression:return e.elements.map(Ze);default:return e.getText()}}function et(e){let t={};for(let r of Object.keys(e)){let i=r.split("-"),n=i[0],o=i.slice(1).join("-");o===""?typeof t[n]=="object"?t[n].DEFAULT=`hsl(var(--${r}))`:t[n]=`hsl(var(--${r}))`:(typeof t[n]!="object"&&(t[n]={DEFAULT:`hsl(var(--${n}))`}),t[n][o]=`hsl(var(--${r}))`)}for(let[r,i]of Object.entries(t))typeof i=="object"&&i.DEFAULT===`hsl(var(--${r}))`&&!(r in e)&&delete i.DEFAULT;return t}import U from"deepmerge";import{HttpsProxyAgent as gr}from"https-proxy-agent";import ur from"node-fetch";import{z as hr}from"zod";var yr=process.env.REGISTRY_URL??"https://ui.shadcn.com/r",wr=process.env.https_proxy?new gr(process.env.https_proxy):void 0;async function V(){try{let[e]=await $(["index.json"]);return xe.parse(e)}catch(e){a.error(`
6
- `),x(e)}}async function Ie(){try{let[e]=await $(["styles/index.json"]);return Ve.parse(e)}catch(e){return a.error(`
7
- `),x(e),[]}}async function X(){try{let[e]=await $(["icons/index.json"]);return Be.parse(e)}catch(e){return x(e),{}}}async function tt(e,t){try{let[r]=await $([Re(e)?e:`styles/${t}/${e}.json`]);return _.parse(r)}catch(r){return a.break(),x(r),null}}async function Ce(){return[{name:"neutral",label:"Neutral"},{name:"gray",label:"Gray"},{name:"zinc",label:"Zinc"},{name:"stone",label:"Stone"},{name:"slate",label:"Slate"}]}async function B(e){try{let[t]=await $([`colors/${e}.json`]);return Ge.parse(t)}catch(t){x(t)}}async function rt(e,t){try{let r=t.map(n=>`styles/${e}/${n.name}.json`),i=await $(r);return xe.parse(i)}catch(r){x(r)}}async function it(e,t,r){if(r)return r;if(t.type==="registry:ui")return e.resolvedPaths.ui??e.resolvedPaths.components;let[i,n]=t.type?.split(":")??[];return i in e.resolvedPaths?dr.join(e.resolvedPaths[i],n):null}async function $(e){try{return await Promise.all(e.map(async r=>{let i=st(r),n=await ur(i,{agent:wr});if(!n.ok){let o={400:"Bad request",401:"Unauthorized",403:"Forbidden",404:"Not found",500:"Internal server error"};if(n.status===401)throw new Error(`You are not authorized to access the component at ${c.info(i)}.
8
- If this is a remote registry, you may need to authenticate.`);if(n.status===404)throw new Error(`The component at ${c.info(i)} was not found.
9
- It may not exist at the registry. Please make sure it is a valid component.`);if(n.status===403)throw new Error(`You do not have access to the component at ${c.info(i)}.
10
- If this is a remote registry, you may need to authenticate or a token.`);let s=await n.json(),l=s&&typeof s=="object"&&"error"in s?s.error:n.statusText||o[n.status];throw new Error(`Failed to fetch from ${c.info(i)}.
11
- ${l}`)}return n.json()}))}catch(t){return a.error(`
12
- `),x(t),[]}}function nt(e,t,r){return r||(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:(e.type==="registry:page",t.resolvedPaths.components))}async function ot(e,t){try{if(!await V())return null;e.includes("index")&&e.unshift("index");let i=[];for(let p of e){let g=await xr(p,t);i.push(...g)}let n=Array.from(new Set(i)),o=await $(n),s=hr.array(_).parse(o);if(!s)return null;if(e.includes("index")&&t.tailwind.baseColor){let p=await br(t.tailwind.baseColor,t);p&&s.unshift(p)}let l={};s.forEach(p=>{l=U(l,p.tailwind??{})});let f={};s.forEach(p=>{f=U(f,p.cssVars??{})});let d="";return s.forEach(p=>{p.docs&&(d+=`${p.docs}
13
- `)}),Je.parse({dependencies:U.all(s.map(p=>p.dependencies??[])),devDependencies:U.all(s.map(p=>p.devDependencies??[])),files:U.all(s.map(p=>p.files??[])),tailwind:l,cssVars:f,docs:d})}catch(r){return x(r),null}}async function xr(e,t){let r=new Set,i=[];async function n(o){let s=st(Re(o)?o:`styles/${t.style}/${o}.json`);if(!r.has(s)){r.add(s);try{let[l]=await $([s]),f=_.parse(l);if(i.push(s),f.registryDependencies)for(let d of f.registryDependencies)await n(d)}catch(l){console.error(`Error fetching or parsing registry item at ${o}:`,l)}}}return await n(e),Array.from(new Set(i))}async function br(e,t){let r=await B(e);if(!r)return null;let i={name:e,type:"registry:theme",tailwind:{config:{theme:{extend:{borderRadius:{lg:"var(--radius)",md:"calc(var(--radius) - 2px)",sm:"calc(var(--radius) - 4px)"},colors:{}}}}},cssVars:{light:{radius:"0.5rem"},dark:{}}};return t.tailwind.cssVariables&&(i.tailwind.config.theme.extend.colors={...i.tailwind.config.theme.extend.colors,...et(r.cssVars.dark)},i.cssVars={light:{...r.cssVars.light,...i.cssVars.light},dark:{...r.cssVars.dark,...i.cssVars.dark}}),i}function st(e){if(Re(e)){let t=new URL(e);return t.pathname.match(/\/chat\/b\//)&&!t.pathname.endsWith("/json")&&(t.pathname=`${t.pathname}/json`),t.toString()}return`${yr}/${e}`}function Re(e){try{return new URL(e),!0}catch{return!1}}import{promises as at}from"fs";import Sr from"path";import F from"postcss";import Ir from"postcss/lib/at-rule";async function lt(e,t,r){if(!e||!Object.keys(e).length||!t.resolvedPaths.tailwindCss)return;r={cleanupDefaultNextStyles:!1,silent:!1,...r};let i=t.resolvedPaths.tailwindCss,n=Sr.relative(t.resolvedPaths.cwd,i),o=y(`Updating ${c.info(n)}`,{silent:r.silent}).start(),s=await at.readFile(i,"utf8"),l=await Cr(s,e,t,{cleanupDefaultNextStyles:r.cleanupDefaultNextStyles});await at.writeFile(i,l,"utf8"),o.succeed()}async function Cr(e,t,r,i){i={cleanupDefaultNextStyles:!1,...i};let n=[Pr(t)];return i.cleanupDefaultNextStyles&&n.push(vr()),r.tailwind.cssVariables&&n.push(Rr()),(await F(n).process(e,{from:void 0})).css}function Rr(){return{postcssPlugin:"update-base-layer",Once(e){let t=[{selector:"*",apply:"border-border"},{selector:"body",apply:"bg-background text-foreground"}],r=e.nodes.find(i=>i.type==="atrule"&&i.name==="layer"&&i.params==="base"&&t.every(({selector:n,apply:o})=>i.nodes?.some(s=>s.type==="rule"&&s.selector===n&&s.nodes.some(l=>l.type==="atrule"&&l.name==="apply"&&l.params===o))));r||(r=F.atRule({name:"layer",params:"base",raws:{semicolon:!0,between:" ",before:`
2
+ import gi from"path";import{promises as li}from"fs";import Ct from"path";import Be from"path";var I="1";var j="3";var he="5",ye="6",Ke="7";import we from"path";var E={"next-app":{name:"next-app",label:"Next.js",links:{installation:"https://ui.shadcn.com/docs/installation/next",tailwind:"https://tailwindcss.com/docs/guides/nextjs"}},"next-pages":{name:"next-pages",label:"Next.js",links:{installation:"https://ui.shadcn.com/docs/installation/next",tailwind:"https://tailwindcss.com/docs/guides/nextjs"}},remix:{name:"remix",label:"Remix",links:{installation:"https://ui.shadcn.com/docs/installation/remix",tailwind:"https://tailwindcss.com/docs/guides/remix"}},vite:{name:"vite",label:"Vite",links:{installation:"https://ui.shadcn.com/docs/installation/vite",tailwind:"https://tailwindcss.com/docs/guides/vite"}},astro:{name:"astro",label:"Astro",links:{installation:"https://ui.shadcn.com/docs/installation/astro",tailwind:"https://tailwindcss.com/docs/guides/astro"}},laravel:{name:"laravel",label:"Laravel",links:{installation:"https://ui.shadcn.com/docs/installation/laravel",tailwind:"https://tailwindcss.com/docs/guides/laravel"}},gatsby:{name:"gatsby",label:"Gatsby",links:{installation:"https://ui.shadcn.com/docs/installation/gatsby",tailwind:"https://tailwindcss.com/docs/guides/gatsby"}},manual:{name:"manual",label:"Manual",links:{installation:"https://ui.shadcn.com/docs/installation/manual",tailwind:"https://tailwindcss.com/docs/installation"}}};import z from"path";import{cyan as zt,green as Mt,red as Wt,yellow as Ut}from"kleur/colors";var l={error:Wt,warn:Ut,info:zt,success:Mt};import{createMatchPath as Vt}from"tsconfig-paths";async function T(e,t){return Vt(t.absoluteBaseUrl,t.paths)(e,void 0,()=>!0,[".ts",".tsx"])}import{cosmiconfig as Bt}from"cosmiconfig";import{loadConfig as Gt}from"tsconfig-paths";import{z as h}from"zod";var ze="@/components",Me="@/lib/utils",We="app/globals.css",Ue="tailwind.config.js";var Jt=Bt("components",{searchPlaces:["components.json"]}),M=h.object({$schema:h.string().optional(),style:h.string(),rsc:h.coerce.boolean().default(!1),tsx:h.coerce.boolean().default(!0),tailwind:h.object({config:h.string(),css:h.string(),baseColor:h.string(),cssVariables:h.boolean().default(!0),prefix:h.string().default("").optional()}),aliases:h.object({components:h.string(),utils:h.string(),ui:h.string().optional(),lib:h.string().optional(),hooks:h.string().optional()}),iconLibrary:h.string().optional()}).strict(),Yt=M.extend({resolvedPaths:h.object({cwd:h.string(),tailwindConfig:h.string(),tailwindCss:h.string(),utils:h.string(),components:h.string(),lib:h.string(),hooks:h.string(),ui:h.string()})});async function C(e){let t=await Ht(e);return t?(t.iconLibrary||(t.iconLibrary=t.style==="new-york"?"radix":"lucide"),await W(e,t)):null}async function W(e,t){let r=await Gt(e);if(r.resultType==="failed")throw new Error(`Failed to load ${t.tsx?"tsconfig":"jsconfig"}.json. ${r.message??""}`.trim());return Yt.parse({...t,resolvedPaths:{cwd:e,tailwindConfig:z.resolve(e,t.tailwind.config),tailwindCss:z.resolve(e,t.tailwind.css),utils:await T(t.aliases.utils,r),components:await T(t.aliases.components,r),ui:t.aliases.ui?await T(t.aliases.ui,r):z.resolve(await T(t.aliases.components,r)??e,"ui"),lib:t.aliases.lib?await T(t.aliases.lib,r):z.resolve(await T(t.aliases.utils,r)??e,".."),hooks:t.aliases.hooks?await T(t.aliases.hooks,r):z.resolve(await T(t.aliases.components,r)??e,"..","hooks")}})}async function Ht(e){try{let t=await Jt.search(e);return t?M.parse(t.config):null}catch{let r=`${e}/components.json`;throw new Error(`Invalid configuration found in ${l.info(r)}.`)}}import Qt from"path";import Xt from"fs-extra";function Y(e="",t=!0){let r=Qt.join(e,"package.json");return Xt.readJSONSync(r,{throws:t})}import H from"fast-glob";import xe from"fs-extra";import{loadConfig as qt}from"tsconfig-paths";import{z as _}from"zod";var Q=["**/node_modules/**",".next","public","dist","build"],pn=_.object({compilerOptions:_.object({paths:_.record(_.string().or(_.array(_.string())))})});async function k(e){let[t,r,i,n,o,s,c]=await Promise.all([H.glob("**/{next,vite,astro}.config.*|gatsby-config.*|composer.json",{cwd:e,deep:3,ignore:Q}),xe.pathExists(we.resolve(e,"src")),rr(e),er(e),Zt(e),tr(e),Y(e,!1)]),f=await xe.pathExists(we.resolve(e,`${r?"src/":""}app`)),d={framework:E.manual,isSrcDir:r,isRSC:!1,isTsx:i,tailwindConfigFile:n,tailwindCssFile:o,aliasPrefix:s};return t.find(p=>p.startsWith("next.config."))?.length?(d.framework=f?E["next-app"]:E["next-pages"],d.isRSC=f,d):t.find(p=>p.startsWith("astro.config."))?.length?(d.framework=E.astro,d):t.find(p=>p.startsWith("gatsby-config."))?.length?(d.framework=E.gatsby,d):t.find(p=>p.startsWith("composer.json"))?.length?(d.framework=E.laravel,d):Object.keys(c?.dependencies??{}).find(p=>p.startsWith("@remix-run/"))?(d.framework=E.remix,d):(t.find(p=>p.startsWith("vite.config."))?.length&&(d.framework=E.vite),d)}async function Zt(e){let t=await H.glob(["**/*.css","**/*.scss"],{cwd:e,deep:5,ignore:Q});if(!t.length)return null;for(let r of t)if((await xe.readFile(we.resolve(e,r),"utf8")).includes("@tailwind base"))return r;return null}async function er(e){let t=await H.glob("tailwind.config.*",{cwd:e,deep:3,ignore:Q});return t.length?t[0]:null}async function tr(e){let t=await qt(e);if(t?.resultType==="failed"||!Object.entries(t?.paths).length)return null;for(let[r,i]of Object.entries(t.paths))if(i.includes("./*")||i.includes("./src/*")||i.includes("./app/*")||i.includes("./resources/js/*"))return r.replace(/\/\*$/,"")??null;return Object.keys(t?.paths)?.[0].replace(/\/\*$/,"")??null}async function rr(e){return(await H.glob("tsconfig.*",{cwd:e,deep:1,ignore:Q})).length>0}async function Ve(e,t=null){let[r,i]=await Promise.all([C(e),t?Promise.resolve(t):k(e)]);if(r)return r;if(!i||!i.tailwindConfigFile||!i.tailwindCssFile)return null;let n={$schema:"https://ui.shadcn.com/schema.json",rsc:i.isRSC,tsx:i.isTsx,style:"new-york",tailwind:{config:i.tailwindConfigFile,baseColor:"zinc",css:i.tailwindCssFile,cssVariables:!0,prefix:""},iconLibrary:"lucide",aliases:{components:`${i.aliasPrefix}/components`,ui:`${i.aliasPrefix}/components/ui`,hooks:`${i.aliasPrefix}/hooks`,lib:`${i.aliasPrefix}/lib`,utils:`${i.aliasPrefix}/lib/utils`}};return await W(e,n)}var a={error(...e){console.log(l.error(e.join(" ")))},warn(...e){console.log(l.warn(e.join(" ")))},info(...e){console.log(l.info(e.join(" ")))},success(...e){console.log(l.success(e.join(" ")))},log(...e){console.log(e.join(" "))},break(){console.log("")}};import ir from"ora";function y(e,t){return ir({text:e,isSilent:t?.silent})}import be from"fs-extra";async function Ge(e){let t={};if(!be.existsSync(e.cwd)||!be.existsSync(Be.resolve(e.cwd,"package.json")))return t[I]=!0,{errors:t,projectInfo:null};let r=y("Preflight checks.",{silent:e.silent}).start();be.existsSync(Be.resolve(e.cwd,"components.json"))&&!e.force&&(r?.fail(),a.break(),a.error(`A ${l.info("components.json")} file already exists at ${l.info(e.cwd)}.
3
+ To start over, remove the ${l.info("components.json")} file and run ${l.info("init")} again.`),a.break(),process.exit(1)),r?.succeed();let i=y("Verifying framework.",{silent:e.silent}).start(),n=await k(e.cwd);(!n||n?.framework.name==="manual")&&(t[Ke]=!0,i?.fail(),a.break(),n?.framework.links.installation&&a.error(`We could not detect a supported framework at ${l.info(e.cwd)}.
4
+ Visit ${l.info(n?.framework.links.installation)} to manually configure your project.
5
+ Once configured, you can use the cli to add components.`),a.break(),process.exit(1)),i?.succeed(`Verifying framework. Found ${l.info(n.framework.label)}.`);let o=y("Validating Tailwind CSS.",{silent:e.silent}).start();!n?.tailwindConfigFile||!n?.tailwindCssFile?(t[he]=!0,o?.fail()):o?.succeed();let s=y("Validating import alias.",{silent:e.silent}).start();return n?.aliasPrefix?s?.succeed():(t[ye]=!0,s?.fail()),Object.keys(t).length>0&&(t[he]&&(a.break(),a.error(`No Tailwind CSS configuration found at ${l.info(e.cwd)}.`),a.error("It is likely you do not have Tailwind CSS installed or have an invalid configuration."),a.error("Install Tailwind CSS then try again."),n?.framework.links.tailwind&&a.error(`Visit ${l.info(n?.framework.links.tailwind)} to get started.`)),t[ye]&&(a.break(),a.error("No import alias found in your tsconfig.json file."),n?.framework.links.installation&&a.error(`Visit ${l.info(n?.framework.links.installation)} to learn how to set an import alias.`)),a.break(),process.exit(1)),{errors:t,projectInfo:n}}import{z as nr}from"zod";function x(e){if(a.error("Something went wrong. Please check the error below for more details."),a.error("If the problem persists, please open an issue on GitHub."),a.error(""),typeof e=="string"&&(a.error(e),a.break(),process.exit(1)),e instanceof nr.ZodError){a.error("Validation failed:");for(let[t,r]of Object.entries(e.flatten().fieldErrors))a.error(`- ${l.info(t)}: ${r}`);a.break(),process.exit(1)}e instanceof Error&&(a.error(e.message),a.break(),process.exit(1)),a.break(),process.exit(1)}import yr from"path";import{z as m}from"zod";var Je=m.enum(["registry:style","registry:lib","registry:example","registry:block","registry:component","registry:ui","registry:hook","registry:theme","registry:page"]),Ye=m.object({path:m.string(),content:m.string().optional(),type:Je,target:m.string().optional()}),or=m.object({config:m.object({content:m.array(m.string()).optional(),theme:m.record(m.string(),m.any()).optional(),plugins:m.array(m.string()).optional()}).optional()}),sr=m.object({light:m.record(m.string(),m.string()).optional(),dark:m.record(m.string(),m.string()).optional()}),K=m.object({name:m.string(),type:Je,description:m.string().optional(),dependencies:m.array(m.string()).optional(),devDependencies:m.array(m.string()).optional(),registryDependencies:m.array(m.string()).optional(),files:m.array(Ye).optional(),tailwind:or.optional(),cssVars:sr.optional(),meta:m.record(m.string(),m.any()).optional(),docs:m.string().optional()}),Se=m.array(K.extend({files:m.array(m.union([m.string(),Ye])).optional()})),He=m.array(m.object({name:m.string(),label:m.string()})),Qe=m.record(m.string(),m.record(m.string(),m.string())),Xe=m.object({inlineColors:m.object({light:m.record(m.string(),m.string()),dark:m.record(m.string(),m.string())}),cssVars:m.object({light:m.record(m.string(),m.string()),dark:m.record(m.string(),m.string())}),inlineColorsTemplate:m.string(),cssVarsTemplate:m.string()}),qe=K.pick({dependencies:!0,devDependencies:!0,files:!0,tailwind:!0,cssVars:!0,docs:!0});import{promises as Ie}from"fs";import{tmpdir as ar}from"os";import U from"path";import lr from"deepmerge";import cr from"stringify-object";import{Project as pr,QuoteKind as mr,ScriptKind as Ze,SyntaxKind as g}from"ts-morph";async function et(e,t,r){if(!e)return;r={silent:!1,...r};let i=U.relative(t.resolvedPaths.cwd,t.resolvedPaths.tailwindConfig),n=y(`Updating ${l.info(i)}`,{silent:r.silent}).start(),o=await Ie.readFile(t.resolvedPaths.tailwindConfig,"utf8"),s=await fr(o,e,t);await Ie.writeFile(t.resolvedPaths.tailwindConfig,s,"utf8"),n?.succeed()}async function fr(e,t,r){let i=await X(e,r),n=i.getDescendantsOfKind(g.ObjectLiteralExpression).find(s=>s.getProperties().some(c=>c.isKind(g.PropertyAssignment)&&c.getName()==="content"));if(!n)return e;let o=Ce(n);return dr(n,{name:"darkMode",value:"class"},{quoteChar:o}),t.plugins?.forEach(s=>{ur(n,s)}),t.theme&&await gr(n,t.theme),i.getFullText()}function dr(e,t,{quoteChar:r}){let i=e.getProperty("darkMode");if(!i){let n={name:t.name,initializer:`[${r}${t.value}${r}]`};return t.name==="darkMode"?(e.insertPropertyAssignment(0,n),e):(e.addPropertyAssignment(n),e)}if(i.isKind(g.PropertyAssignment)){let n=i.getInitializer(),o=`${r}${t.value}${r}`;if(n?.isKind(g.StringLiteral)){let s=n.getText();return n.replaceWithText(`[${s}, ${o}]`),e}if(n?.isKind(g.ArrayLiteralExpression)){if(n.getElements().map(s=>s.getText()).includes(o))return e;n.addElement(o)}return e}return e}async function gr(e,t){e.getProperty("theme")||e.addPropertyAssignment({name:"theme",initializer:"{}"}),Re(e);let i=(e.getPropertyOrThrow("theme")?.asKindOrThrow(g.PropertyAssignment)).getInitializer();if(i?.isKind(g.ObjectLiteralExpression)){let n=i.getText(),o=await hr(n),s=lr(o,t,{arrayMerge:(f,d)=>d}),c=cr(s).replace(/\'\.\.\.(.*)\'/g,"...$1").replace(/\'\"/g,"'").replace(/\"\'/g,"'").replace(/\'\[/g,"[").replace(/\]\'/g,"]").replace(/\'\\\'/g,"'").replace(/\\\'/g,"'").replace(/\\\'\'/g,"'").replace(/\'\'/g,"'");i.replaceWithText(c)}ve(e)}function ur(e,t){let r=e.getProperty("plugins");if(!r)return e.addPropertyAssignment({name:"plugins",initializer:`[${t}]`}),e;if(r.isKind(g.PropertyAssignment)){let i=r.getInitializer();if(i?.isKind(g.ArrayLiteralExpression)){if(i.getElements().map(n=>n.getText().replace(/["']/g,"")).includes(t.replace(/["']/g,"")))return e;i.addElement(t)}return e}return e}async function X(e,t){let r=await Ie.mkdtemp(U.join(ar(),"shadcn-")),i=t?.resolvedPaths?.tailwindConfig||"tailwind.config.ts",n=U.join(r,`shadcn-${U.basename(i)}`);return new pr({compilerOptions:{}}).createSourceFile(n,e,{scriptKind:U.extname(i)===".ts"?Ze.TS:Ze.JS})}function Ce(e){return e.getFirstDescendantByKind(g.StringLiteral)?.getQuoteKind()===mr.Single?"'":'"'}function Re(e){let t=e.getProperties();for(let r=0;r<t.length;r++){let i=t[r];if(i.isKind(g.SpreadAssignment)){let n=i.asKindOrThrow(g.SpreadAssignment),o=n.getExpression().getText();e.insertPropertyAssignment(r,{name:`"___${o.replace(/^\.\.\./,"")}"`,initializer:`"...${o.replace(/^\.\.\./,"")}"`}),n.remove()}else if(i.isKind(g.PropertyAssignment)){let o=i.asKindOrThrow(g.PropertyAssignment).getInitializer();o&&o.isKind(g.ObjectLiteralExpression)?Re(o.asKindOrThrow(g.ObjectLiteralExpression)):o&&o.isKind(g.ArrayLiteralExpression)&&tt(o.asKindOrThrow(g.ArrayLiteralExpression))}}}function tt(e){let t=e.getElements();for(let r=0;r<t.length;r++){let i=t[r];if(i.isKind(g.ObjectLiteralExpression))Re(i.asKindOrThrow(g.ObjectLiteralExpression));else if(i.isKind(g.ArrayLiteralExpression))tt(i.asKindOrThrow(g.ArrayLiteralExpression));else if(i.isKind(g.SpreadElement)){let n=i.getText();e.removeElement(r),e.insertElement(r,`"${n}"`)}}}function ve(e){let t=e.getProperties();for(let r=0;r<t.length;r++){let i=t[r];if(i.isKind(g.PropertyAssignment)){let n=i,o=n.getInitializer();if(o&&o.isKind(g.StringLiteral)){let s=o.asKindOrThrow(g.StringLiteral).getLiteralValue();s.startsWith("...")&&(e.insertSpreadAssignment(r,{expression:s.slice(3)}),n.remove())}else o?.isKind(g.ObjectLiteralExpression)?ve(o):o&&o.isKind(g.ArrayLiteralExpression)&&rt(o.asKindOrThrow(g.ArrayLiteralExpression))}}}function rt(e){let t=e.getElements();for(let r=0;r<t.length;r++){let i=t[r];if(i.isKind(g.ObjectLiteralExpression))ve(i.asKindOrThrow(g.ObjectLiteralExpression));else if(i.isKind(g.ArrayLiteralExpression))rt(i.asKindOrThrow(g.ArrayLiteralExpression));else if(i.isKind(g.StringLiteral)){let n=i.getText(),o=/(?:^['"])(\.\.\..*)(?:['"]$)/g;o.test(n)&&(e.removeElement(r),e.insertElement(r,n.replace(o,"$1")))}}}async function hr(e){let r=(await X(`const theme = ${e}`,null)).getStatements()[0];if(r?.getKind()===g.VariableStatement){let n=(r.getDeclarationList()?.getDeclarations()[0]).getInitializer();if(n?.isKind(g.ObjectLiteralExpression))return await q(n)}throw new Error("Invalid input: not an object literal")}function q(e){let t={};for(let r of e.getProperties())if(r.isKind(g.PropertyAssignment)){let i=r.getName().replace(/\'/g,"");r.getInitializer()?.isKind(g.ObjectLiteralExpression)?t[i]=q(r.getInitializer()):r.getInitializer()?.isKind(g.ArrayLiteralExpression)?t[i]=it(r.getInitializer()):t[i]=Pe(r.getInitializer())}return t}function it(e){let t=[];for(let r of e.getElements())r.isKind(g.ObjectLiteralExpression)?t.push(q(r.asKindOrThrow(g.ObjectLiteralExpression))):r.isKind(g.ArrayLiteralExpression)?t.push(it(r.asKindOrThrow(g.ArrayLiteralExpression))):t.push(Pe(r));return t}function Pe(e){switch(e.getKind()){case g.StringLiteral:return e.getText();case g.NumericLiteral:return Number(e.getText());case g.TrueKeyword:return!0;case g.FalseKeyword:return!1;case g.NullKeyword:return null;case g.ArrayLiteralExpression:return e.getElements().map(Pe);case g.ObjectLiteralExpression:return q(e);default:return e.getText()}}function nt(e){let t={};for(let r of Object.keys(e)){let i=r.split("-"),n=i[0],o=i.slice(1).join("-");o===""?typeof t[n]=="object"?t[n].DEFAULT=`hsl(var(--${r}))`:t[n]=`hsl(var(--${r}))`:(typeof t[n]!="object"&&(t[n]={DEFAULT:`hsl(var(--${n}))`}),t[n][o]=`hsl(var(--${r}))`)}for(let[r,i]of Object.entries(t))typeof i=="object"&&i.DEFAULT===`hsl(var(--${r}))`&&!(r in e)&&delete i.DEFAULT;return t}import V from"deepmerge";import{HttpsProxyAgent as wr}from"https-proxy-agent";import xr from"node-fetch";import{z as br}from"zod";var Sr=process.env.REGISTRY_URL??"https://ui.shadcn.com/r",Ir=process.env.https_proxy?new wr(process.env.https_proxy):void 0;async function B(){try{let[e]=await O(["index.json"]);return Se.parse(e)}catch(e){a.error(`
6
+ `),x(e)}}async function Ee(){try{let[e]=await O(["styles/index.json"]);return He.parse(e)}catch(e){return a.error(`
7
+ `),x(e),[]}}async function Z(){try{let[e]=await O(["icons/index.json"]);return Qe.parse(e)}catch(e){return x(e),{}}}async function ot(e,t){try{let[r]=await O([ke(e)?e:`styles/${t}/${e}.json`]);return K.parse(r)}catch(r){return a.break(),x(r),null}}async function Te(){return[{name:"neutral",label:"Neutral"},{name:"gray",label:"Gray"},{name:"zinc",label:"Zinc"},{name:"stone",label:"Stone"},{name:"slate",label:"Slate"}]}async function G(e){try{let[t]=await O([`colors/${e}.json`]);return Xe.parse(t)}catch(t){x(t)}}async function st(e,t){try{let r=t.map(n=>`styles/${e}/${n.name}.json`),i=await O(r);return Se.parse(i)}catch(r){x(r)}}async function at(e,t,r){if(r)return r;if(t.type==="registry:ui")return e.resolvedPaths.ui??e.resolvedPaths.components;let[i,n]=t.type?.split(":")??[];return i in e.resolvedPaths?yr.join(e.resolvedPaths[i],n):null}async function O(e){try{return await Promise.all(e.map(async r=>{let i=pt(r),n=await xr(i,{agent:Ir});if(!n.ok){let o={400:"Bad request",401:"Unauthorized",403:"Forbidden",404:"Not found",500:"Internal server error"};if(n.status===401)throw new Error(`You are not authorized to access the component at ${l.info(i)}.
8
+ If this is a remote registry, you may need to authenticate.`);if(n.status===404)throw new Error(`The component at ${l.info(i)} was not found.
9
+ It may not exist at the registry. Please make sure it is a valid component.`);if(n.status===403)throw new Error(`You do not have access to the component at ${l.info(i)}.
10
+ If this is a remote registry, you may need to authenticate or a token.`);let s=await n.json(),c=s&&typeof s=="object"&&"error"in s?s.error:n.statusText||o[n.status];throw new Error(`Failed to fetch from ${l.info(i)}.
11
+ ${c}`)}return n.json()}))}catch(t){return a.error(`
12
+ `),x(t),[]}}function lt(e,t,r){return r||(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:(e.type==="registry:page",t.resolvedPaths.components))}async function ct(e,t){try{if(!await B())return null;e.includes("index")&&e.unshift("index");let i=[];for(let p of e){let u=await Cr(p,t);i.push(...u)}let n=Array.from(new Set(i)),o=await O(n),s=br.array(K).parse(o);if(!s)return null;if(e.includes("index")&&t.tailwind.baseColor){let p=await Rr(t.tailwind.baseColor,t);p&&s.unshift(p)}let c={};s.forEach(p=>{c=V(c,p.tailwind??{})});let f={};s.forEach(p=>{f=V(f,p.cssVars??{})});let d="";return s.forEach(p=>{p.docs&&(d+=`${p.docs}
13
+ `)}),qe.parse({dependencies:V.all(s.map(p=>p.dependencies??[])),devDependencies:V.all(s.map(p=>p.devDependencies??[])),files:V.all(s.map(p=>p.files??[])),tailwind:c,cssVars:f,docs:d})}catch(r){return x(r),null}}async function Cr(e,t){let r=new Set,i=[];async function n(o){let s=pt(ke(o)?o:`styles/${t.style}/${o}.json`);if(!r.has(s)){r.add(s);try{let[c]=await O([s]),f=K.parse(c);if(i.push(s),f.registryDependencies)for(let d of f.registryDependencies)await n(d)}catch(c){console.error(`Error fetching or parsing registry item at ${o}:`,c)}}}return await n(e),Array.from(new Set(i))}async function Rr(e,t){let r=await G(e);if(!r)return null;let i={name:e,type:"registry:theme",tailwind:{config:{theme:{extend:{borderRadius:{lg:"var(--radius)",md:"calc(var(--radius) - 2px)",sm:"calc(var(--radius) - 4px)"},colors:{}}}}},cssVars:{light:{radius:"0.5rem"},dark:{}}};return t.tailwind.cssVariables&&(i.tailwind.config.theme.extend.colors={...i.tailwind.config.theme.extend.colors,...nt(r.cssVars.dark)},i.cssVars={light:{...r.cssVars.light,...i.cssVars.light},dark:{...r.cssVars.dark,...i.cssVars.dark}}),i}function pt(e){if(ke(e)){let t=new URL(e);return t.pathname.match(/\/chat\/b\//)&&!t.pathname.endsWith("/json")&&(t.pathname=`${t.pathname}/json`),t.toString()}return`${Sr}/${e}`}function ke(e){try{return new URL(e),!0}catch{return!1}}import{promises as mt}from"fs";import vr from"path";import F from"postcss";import Pr from"postcss/lib/at-rule";async function dt(e,t,r){if(!e||!Object.keys(e).length||!t.resolvedPaths.tailwindCss)return;r={cleanupDefaultNextStyles:!1,silent:!1,...r};let i=t.resolvedPaths.tailwindCss,n=vr.relative(t.resolvedPaths.cwd,i),o=y(`Updating ${l.info(n)}`,{silent:r.silent}).start(),s=await mt.readFile(i,"utf8"),c=await Er(s,e,t,{cleanupDefaultNextStyles:r.cleanupDefaultNextStyles});await mt.writeFile(i,c,"utf8"),o.succeed()}async function Er(e,t,r,i){i={cleanupDefaultNextStyles:!1,...i};let n=[kr(t)];return i.cleanupDefaultNextStyles&&n.push(jr()),r.tailwind.cssVariables&&n.push(Tr()),(await F(n).process(e,{from:void 0})).css}function Tr(){return{postcssPlugin:"update-base-layer",Once(e){let t=[{selector:"*",apply:"border-border"},{selector:"body",apply:"bg-background text-foreground"}],r=e.nodes.find(i=>i.type==="atrule"&&i.name==="layer"&&i.params==="base"&&t.every(({selector:n,apply:o})=>i.nodes?.some(s=>s.type==="rule"&&s.selector===n&&s.nodes.some(c=>c.type==="atrule"&&c.name==="apply"&&c.params===o))));r||(r=F.atRule({name:"layer",params:"base",raws:{semicolon:!0,between:" ",before:`
14
14
  `}}),e.append(r)),t.forEach(({selector:i,apply:n})=>{r?.nodes?.find(s=>s.type==="rule"&&s.selector===i)||r?.append(F.rule({selector:i,nodes:[F.atRule({name:"apply",params:n,raws:{semicolon:!0,before:`
15
15
  `}})],raws:{semicolon:!0,between:" ",before:`
16
- `}}))})}}}function Pr(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 Ir||(r=F.atRule({name:"layer",params:"base",nodes:[],raws:{semicolon:!0,before:`
17
- `,between:" "}}),t.append(r)),r!==void 0&&Object.entries(e).forEach(([i,n])=>{let o=i==="light"?":root":`.${i}`;kr(r,o,n)})}}}function ct(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 vr(){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.length===0&&t.remove()),ct(e);let r=e.nodes.find(i=>i.type==="atrule"&&i.params==="(prefers-color-scheme: dark)");r&&(ct(r),r.nodes.length===0&&r.remove())}}}function kr(e,t,r){let i=e.nodes?.find(n=>n.type==="rule"&&n.selector===t);i||Object.keys(r).length>0&&(i=F.rule({selector:t,raws:{between:" ",before:`
18
- `}}),e.append(i)),Object.entries(r).forEach(([n,o])=>{let s=`--${n.replace(/^--/,"")}`,l=F.decl({prop:s,value:o,raws:{semicolon:!0}}),f=i?.nodes.find(d=>d.type==="decl"&&d.prop===s);f?f.replaceWith(l):i?.append(l)})}import{detect as Tr}from"@antfu/ni";async function q(e,{withFallback:t}={withFallback:!1}){let r=await Tr({programmatic:!0,cwd:e});if(r==="yarn@berry")return"yarn";if(r==="pnpm@6")return"pnpm";if(r==="bun")return"bun";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"}import{execa as Er}from"execa";import jr from"prompts";async function Z(e,t,r){if(e=Array.from(new Set(e)),!e?.length)return;r={silent:!1,...r};let i=y("Installing dependencies.",{silent:r.silent})?.start(),n=await q(t.resolvedPaths.cwd),o="";if($r(t)&&n==="npm"){i.stopAndPersist(),a.warn(`
16
+ `}}))})}}}function kr(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 Pr||(r=F.atRule({name:"layer",params:"base",nodes:[],raws:{semicolon:!0,before:`
17
+ `,between:" "}}),t.append(r)),r!==void 0&&Object.entries(e).forEach(([i,n])=>{let o=i==="light"?":root":`.${i}`;Or(r,o,n)})}}}function ft(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 jr(){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.length===0&&t.remove()),ft(e);let r=e.nodes.find(i=>i.type==="atrule"&&i.params==="(prefers-color-scheme: dark)");r&&(ft(r),r.nodes.length===0&&r.remove())}}}function Or(e,t,r){let i=e.nodes?.find(n=>n.type==="rule"&&n.selector===t);i||Object.keys(r).length>0&&(i=F.rule({selector:t,raws:{between:" ",before:`
18
+ `}}),e.append(i)),Object.entries(r).forEach(([n,o])=>{let s=`--${n.replace(/^--/,"")}`,c=F.decl({prop:s,value:o,raws:{semicolon:!0}}),f=i?.nodes.find(d=>d.type==="decl"&&d.prop===s);f?f.replaceWith(c):i?.append(c)})}import{detect as $r}from"@antfu/ni";async function ee(e,{withFallback:t}={withFallback:!1}){let r=await $r({programmatic:!0,cwd:e});if(r==="yarn@berry")return"yarn";if(r==="pnpm@6")return"pnpm";if(r==="bun")return"bun";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"}import{execa as Lr}from"execa";import Nr from"prompts";async function te(e,t,r){if(e=Array.from(new Set(e)),!e?.length)return;r={silent:!1,...r};let i=y("Installing dependencies.",{silent:r.silent})?.start(),n=await ee(t.resolvedPaths.cwd),o="";if(Ar(t)&&n==="npm"){i.stopAndPersist(),a.warn(`
19
19
  It looks like you are using React 19.
20
20
  Some packages may fail to install due to peer dependency issues in npm (see https://ui.shadcn.com/react-19).
21
- `);let s=await jr([{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&&(o=s.flag)}i?.start(),await Er(n,[n==="npm"?"install":"add",...n==="npm"&&o?[`--${o}`]:[],...e],{cwd:t.resolvedPaths.cwd}),i?.succeed()}function $r(e){let t=J(e.resolvedPaths.cwd);return t?.dependencies?.react?/^(?:\^|~)?19(?:\.\d+)*(?:-.*)?$/.test(t.dependencies.react):!1}import{existsSync as dt,promises as gt}from"fs";import N,{basename as Qr}from"path";import{promises as Vr}from"fs";import{tmpdir as Br}from"os";import ft from"path";import{SyntaxKind as Or}from"ts-morph";var ee=async({sourceFile:e,config:t,baseColor:r})=>(t.tailwind?.cssVariables||!r?.inlineColors||e.getDescendantsOfKind(Or.StringLiteral).forEach(i=>{let n=i.getText();if(n){let o=Ar(n.replace(/"/g,""),r.inlineColors);i.replaceWithText(`"${o.trim()}"`)}}),e);function Pe(e){if(!e.includes("/")&&!e.includes(":"))return[null,e,null];let t=[],[r,i]=e.split("/");if(!r.includes(":"))return[null,r,i];let n=r.split(":"),o=n.pop(),s=n.join(":");return t.push(s??null,o??null,i??null),t}var Nr=["bg-","text-","border-","ring-offset-","ring-"];function Ar(e,t){e.includes(" border ")&&(e=e.replace(" border "," border border-border "));let r=e.split(" "),i=new Set,n=new Set;for(let o of r){let[s,l,f]=Pe(o),d=Nr.find(g=>l?.startsWith(g));if(!d){i.has(o)||i.add(o);continue}let p=l?.replace(d,"");if(p&&p in t.light){i.add([s,`${d}${t.light[p]}`].filter(Boolean).join(":")+(f?`/${f}`:"")),n.add(["dark",s,`${d}${t.dark[p]}`].filter(Boolean).join(":")+(f?`/${f}`:""));continue}i.has(o)||i.add(o)}return[...Array.from(i),...Array.from(n)].join(" ").trim()}var R={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"}};import{SyntaxKind as Lr}from"ts-morph";var pt="lucide",te=async({sourceFile:e,config:t})=>{if(!t.iconLibrary||!(t.iconLibrary in R))return e;let r=await X(),i=pt,n=t.iconLibrary;if(i===n)return e;let o=[];for(let s of e.getImportDeclarations()??[])if(s.getModuleSpecifier()?.getText()===`"${R[pt].import}"`){for(let l of s.getNamedImports()??[]){let f=l.getName(),d=r[f]?.[n];!d||o.includes(d)||(o.push(d),l.remove(),e.getDescendantsOfKind(Lr.JsxSelfClosingElement).filter(p=>p.getTagNameNode()?.getText()===f).forEach(p=>p.getTagNameNode()?.replaceWithText(d)))}s.getNamedImports()?.length===0&&s.remove()}if(o.length>0){let s=e.addImportDeclaration({moduleSpecifier:R[n]?.import,namedImports:o.map(l=>({name:l}))});Fr(e)||s.replaceWithText(s.getText().replace(";",""))}return e};function Fr(e){return e.getImportDeclarations()?.[0]?.getText().endsWith(";")??!1}var re=async({sourceFile:e,config:t})=>{let r=e.getImportDeclarations();for(let i of r){let n=Dr(i.getModuleSpecifierValue(),t);i.setModuleSpecifier(n),n=="@/lib/utils"&&i.getNamedImports().find(l=>l.getName()==="cn")&&i.setModuleSpecifier(n.replace(/^@\/lib\/utils/,t.aliases.utils))}return e};function Dr(e,t){if(!e.startsWith("@/"))return e;if(!e.startsWith("@/registry/")){let r=t.aliases.components.charAt(0);return e.replace(/^@\//,`${r}/`)}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)}import{transformFromAstSync as _r}from"@babel/core";import{parse as zr}from"@babel/parser";import Kr from"@babel/plugin-transform-typescript";import*as ie from"recast";var Mr={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"]},mt=async({sourceFile:e,config:t})=>{let r=e.getFullText();if(t.tsx)return r;let i=ie.parse(r,{parser:{parse:o=>zr(o,Mr)}}),n=_r(i,r,{cloneInputAst:!1,code:!1,ast:!0,plugins:[Kr],configFile:!1});if(!n||!n.ast)throw new Error("Failed to transform JSX");return ie.print(n.ast).code};import{SyntaxKind as Wr}from"ts-morph";var Ur=/^["']use client["']$/g,ne=async({sourceFile:e,config:t})=>{if(t.rsc)return e;let r=e.getFirstChildByKind(Wr.ExpressionStatement);return r&&Ur.test(r.getText())&&r.remove(),e};import{Project as Gr,ScriptKind as Jr}from"ts-morph";import{SyntaxKind as w}from"ts-morph";var oe=async({sourceFile:e,config:t})=>(t.tailwind?.prefix&&(e.getDescendantsOfKind(w.CallExpression).filter(r=>r.getExpression().getText()==="cva").forEach(r=>{if(r.getArguments()[0]?.isKind(w.StringLiteral)){let i=r.getArguments()[0];i&&i.replaceWithText(`"${O(i.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`)}r.getArguments()[1]?.isKind(w.ObjectLiteralExpression)&&r.getArguments()[1]?.getDescendantsOfKind(w.PropertyAssignment).find(i=>i.getName()==="variants")?.getDescendantsOfKind(w.PropertyAssignment).forEach(i=>{i.getDescendantsOfKind(w.PropertyAssignment).forEach(n=>{let o=n.getInitializerIfKind(w.StringLiteral);o&&o?.replaceWithText(`"${O(o.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`)})})}),e.getDescendantsOfKind(w.JsxAttribute).forEach(r=>{if(r.getName()==="className"){if(r.getInitializer()?.isKind(w.StringLiteral)){let i=r.getInitializer();i&&i.replaceWithText(`"${O(i.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`)}if(r.getInitializer()?.isKind(w.JsxExpression)){let i=r.getInitializer()?.getDescendantsOfKind(w.CallExpression).find(n=>n.getExpression().getText()==="cn");i&&i.getArguments().forEach(n=>{(n.isKind(w.ConditionalExpression)||n.isKind(w.BinaryExpression))&&n.getChildrenOfKind(w.StringLiteral).forEach(o=>{o.replaceWithText(`"${O(o.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`)}),n.isKind(w.StringLiteral)&&n.replaceWithText(`"${O(n.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`)})}}r.getName()==="classNames"&&r.getInitializer()?.isKind(w.JsxExpression)&&r.getDescendantsOfKind(w.PropertyAssignment).forEach(i=>{if(i.getInitializer()?.isKind(w.CallExpression)){let n=i.getInitializerIfKind(w.CallExpression);n&&n.getArguments().forEach(o=>{o.isKind(w.ConditionalExpression)&&o.getChildrenOfKind(w.StringLiteral).forEach(s=>{s.replaceWithText(`"${O(s.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`)}),o.isKind(w.StringLiteral)&&o.replaceWithText(`"${O(o.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`)})}if(i.getInitializer()?.isKind(w.StringLiteral)&&i.getName()!=="variant"){let n=i.getInitializer();n&&n.replaceWithText(`"${O(n.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`)}})})),e);function O(e,t=""){let r=e.split(" "),i=[];for(let n of r){let[o,s,l]=Pe(n);o?l?i.push(`${o}:${t}${s}/${l}`):i.push(`${o}:${t}${s}`):l?i.push(`${t}${s}/${l}`):i.push(`${t}${s}`)}return i.join(" ")}var Yr=new Gr({compilerOptions:{}});async function Hr(e){let t=await Vr.mkdtemp(ft.join(Br(),"shadcn-"));return ft.join(t,e)}async function se(e,t=[re,ne,ee,oe,te]){let r=await Hr(e.filename),i=Yr.createSourceFile(r,e.raw,{scriptKind:Jr.TSX});for(let n of t)await n({sourceFile:i,...e});return e.transformJsx?await mt({sourceFile:i,...e}):i.getText()}import Xr from"prompts";function qr(e,t,r){return r.startsWith("~/")?N.join(t.resolvedPaths.cwd,r.replace("~/","")):e?.isSrcDir?N.join(t.resolvedPaths.cwd,"src",r):N.join(t.resolvedPaths.cwd,r)}async function ut(e,t,r){if(!e?.length)return;r={overwrite:!1,force:!1,silent:!1,...r};let i=y("Updating files.",{silent:r.silent})?.start(),[n,o]=await Promise.all([E(t.resolvedPaths.cwd),B(t.tailwind.baseColor)]),s=[],l=[],f=[];for(let p of e){if(!p.content)continue;let g=nt(p,t),b=Qr(p.path),S=N.join(g,b);p.target&&(S=qr(n,t,p.target),g=N.dirname(S)),t.tsx||(S=S.replace(/\.tsx?$/,de=>de===".tsx"?".jsx":".js"));let A=dt(S);if(A&&!r.overwrite){i.stop();let{overwrite:de}=await Xr({type:"confirm",name:"overwrite",message:`The file ${c.info(b)} already exists. Would you like to overwrite?`,initial:!1});if(!de){f.push(N.relative(t.resolvedPaths.cwd,S));continue}i?.start()}dt(g)||await gt.mkdir(g,{recursive:!0});let L=await se({filename:p.path,raw:p.content,config:t,baseColor:o,transformJsx:!t.tsx},[re,ne,ee,oe,te]);await gt.writeFile(S,L,"utf-8"),A?l.push(N.relative(t.resolvedPaths.cwd,S)):s.push(N.relative(t.resolvedPaths.cwd,S))}if(!(s.length||l.length)&&!f.length&&i?.info("No files updated."),s.length){if(i?.succeed(`Created ${s.length} ${s.length===1?"file":"files"}:`),!r.silent)for(let p of s)a.log(` - ${p}`)}else i?.stop();if(l.length&&(y(`Updated ${l.length} ${l.length===1?"file":"files"}:`,{silent:r.silent})?.info(),!r.silent))for(let p of l)a.log(` - ${p}`);if(f.length&&(y(`Skipped ${f.length} ${l.length===1?"file":"files"}:`,{silent:r.silent})?.info(),!r.silent))for(let p of f)a.log(` - ${p}`);r.silent||a.break()}async function ae(e,t,r){r={overwrite:!1,silent:!1,isNewProject:!1,...r};let i=y("Checking registry.",{silent:r.silent})?.start(),n=await ot(e,t);if(!n)return i?.fail(),x(new Error("Failed to fetch components from registry."));i?.succeed(),await He(n.tailwind?.config,t,{silent:r.silent}),await lt(n.cssVars,t,{cleanupDefaultNextStyles:r.isNewProject,silent:r.silent}),await Z(n.dependencies,t,{silent:r.silent}),await ut(n.files,t,{overwrite:r.overwrite,silent:r.silent}),n.docs&&a.info(n.docs)}import Zr from"path";import{execa as ei}from"execa";import ve from"fs-extra";import ht from"prompts";async function ce(e){if(e={srcDir:!1,...e},!e.force){let{proceed:s}=await ht({type:"confirm",name:"proceed",message:`The path ${c.info(e.cwd)} does not contain a package.json file. Would you like to start a new ${c.info("Next.js")} project?`,initial:!0});if(!s)return{projectPath:null,projectName:null}}let t=await q(e.cwd,{withFallback:!0}),{name:r}=await ht({type:"text",name:"name",message:"What is your project named?",initial:"my-app",format:s=>s.trim(),validate:s=>s.length>128?"Name should be less than 128 characters.":!0}),i=`${e.cwd}/${r}`;try{await ve.access(e.cwd,ve.constants.W_OK)}catch{a.break(),a.error(`The path ${c.info(e.cwd)} is not writable.`),a.error(`It is likely you do not have write permissions for this folder or the path ${c.info(e.cwd)} does not exist.`),a.break(),process.exit(1)}ve.existsSync(Zr.resolve(e.cwd,r,"package.json"))&&(a.break(),a.error(`A project with the name ${c.info(r)} already exists.`),a.error("Please choose a different name and try again."),a.break(),process.exit(1));let n=y("Creating a new Next.js project. This may take a few minutes.").start(),o=["--tailwind","--eslint","--typescript","--app",e.srcDir?"--src-dir":"--no-src-dir","--no-import-alias",`--use-${t}`];try{await ei("npx",["create-next-app@14.2.16",i,"--silent",...o],{cwd:e.cwd})}catch{a.break(),a.error("Something went wrong creating a new Next.js project. Please try again."),process.exit(1)}return n?.succeed("Creating a new Next.js project."),{projectPath:i,projectName:r}}import{promises as yt}from"fs";import ti from"path";import{SyntaxKind as le}from"ts-morph";async function wt(e,t,r){if(!e)return;r={silent:!1,...r};let i=ti.relative(t.resolvedPaths.cwd,t.resolvedPaths.tailwindConfig),n=y(`Updating ${c.info(i)}`,{silent:r.silent}).start(),o=await yt.readFile(t.resolvedPaths.tailwindConfig,"utf8"),s=await ri(o,e,t);await yt.writeFile(t.resolvedPaths.tailwindConfig,s,"utf8"),n?.succeed()}async function ri(e,t,r){let i=await Q(e,r),n=i.getDescendantsOfKind(le.ObjectLiteralExpression).find(o=>o.getProperties().some(s=>s.isKind(le.PropertyAssignment)&&s.getName()==="content"));return n?(ii(n,t),i.getFullText()):e}async function ii(e,t){let r=Se(e),i=e.getProperty("content");if(!i){let n={name:"content",initializer:`[${r}${t.join(`${r}, ${r}`)}${r}]`};return e.addPropertyAssignment(n),e}if(i.isKind(le.PropertyAssignment)){let n=i.getInitializer();if(n?.isKind(le.ArrayLiteralExpression))for(let o of t){let s=`${r}${o}${r}`;n.getElements().map(l=>l.getText()).includes(s)||n.addElement(s)}return e}return e}import{Command as oi}from"commander";import ke from"prompts";import{z as v}from"zod";var si=v.object({cwd:v.string(),components:v.array(v.string()).optional(),yes:v.boolean(),defaults:v.boolean(),force:v.boolean(),silent:v.boolean(),isNewProject:v.boolean(),srcDir:v.boolean().optional()}),bt=new oi().name("init").description("initialize your project and install dependencies").argument("[components...]","the components to add or a url to the component.").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).action(async(e,t)=>{try{let r=si.parse({cwd:xt.resolve(t.cwd),isNewProject:!1,components:e,...t});await pe(r),a.log(`${c.success("Success!")} Project initialization completed.
22
- You may now add components.`),a.break()}catch(r){a.break(),x(r)}});async function pe(e){let t;if(e.skipPreflight)t=await E(e.cwd);else{let f=await Me(e);if(f.errors[I]){let{projectPath:d}=await ce(e);d||process.exit(1),e.cwd=d,e.isNewProject=!0}t=f.projectInfo}let r=await ze(e.cwd,t),i=r?await ci(r,e):await ai(await C(e.cwd));if(!e.yes){let{proceed:f}=await ke({type:"confirm",name:"proceed",message:`Write configuration to ${c.info("components.json")}. Proceed?`,initial:!0});f||process.exit(0)}let n=y("Writing components.json.").start(),o=xt.resolve(e.cwd,"components.json");await ni.writeFile(o,JSON.stringify(i,null,2),"utf8"),n.succeed();let s=await M(e.cwd,i),l=["index",...e.components||[]];return await ae(l,s,{overwrite:!0,silent:e.silent,isNewProject:e.isNewProject||t?.framework.name==="next-app"}),e.isNewProject&&e.srcDir&&await wt(["./src/**/*.{js,ts,jsx,tsx,mdx}"],s,{silent:e.silent}),s}async function ai(e=null){let[t,r]=await Promise.all([Ie(),Ce()]);a.info("");let i=await ke([{type:"toggle",name:"typescript",message:`Would you like to use ${c.info("TypeScript")} (recommended)?`,initial:e?.tsx??!0,active:"yes",inactive:"no"},{type:"select",name:"style",message:`Which ${c.info("style")} would you like to use?`,choices:t.map(n=>({title:n.label,value:n.name}))},{type:"select",name:"tailwindBaseColor",message:`Which color would you like to use as the ${c.info("base color")}?`,choices:r.map(n=>({title:n.label,value:n.name}))},{type:"text",name:"tailwindCss",message:`Where is your ${c.info("global CSS")} file?`,initial:e?.tailwind.css??De},{type:"toggle",name:"tailwindCssVariables",message:`Would you like to use ${c.info("CSS variables")} for theming?`,initial:e?.tailwind.cssVariables??!0,active:"yes",inactive:"no"},{type:"text",name:"tailwindPrefix",message:`Are you using a custom ${c.info("tailwind prefix eg. tw-")}? (Leave blank if not)`,initial:""},{type:"text",name:"tailwindConfig",message:`Where is your ${c.info("tailwind.config.js")} located?`,initial:e?.tailwind.config??_e},{type:"text",name:"components",message:`Configure the import alias for ${c.info("components")}:`,initial:e?.aliases.components??Le},{type:"text",name:"utils",message:`Configure the import alias for ${c.info("utils")}:`,initial:e?.aliases.utils??Fe},{type:"toggle",name:"rsc",message:`Are you using ${c.info("React Server Components")}?`,initial:e?.rsc??!0,active:"yes",inactive:"no"}]);return K.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 ci(e,t){let r=e.style,i=e.tailwind.baseColor,n=e.tailwind.cssVariables;if(!t.defaults){let[o,s]=await Promise.all([Ie(),Ce()]),l=await ke([{type:"select",name:"style",message:`Which ${c.info("style")} would you like to use?`,choices:o.map(f=>({title:f.label,value:f.name})),initial:o.findIndex(f=>f.name===r)},{type:"select",name:"tailwindBaseColor",message:`Which color would you like to use as the ${c.info("base color")}?`,choices:s.map(f=>({title:f.label,value:f.name}))},{type:"toggle",name:"tailwindCssVariables",message:`Would you like to use ${c.info("CSS variables")} for theming?`,initial:e?.tailwind.cssVariables,active:"yes",inactive:"no"}]);r=l.style,i=l.tailwindBaseColor,n=l.tailwindCssVariables}return K.parse({$schema:e?.$schema,style:r,tailwind:{...e?.tailwind,baseColor:i,cssVariables:n},rsc:e?.rsc,tsx:e?.tsx,aliases:e?.aliases,iconLibrary:e?.iconLibrary})}import St from"path";import Te from"fs-extra";async function It(e){let t={};if(!Te.existsSync(e.cwd)||!Te.existsSync(St.resolve(e.cwd,"package.json")))return t[I]=!0,{errors:t,config:null};if(!Te.existsSync(St.resolve(e.cwd,"components.json")))return t[j]=!0,{errors:t,config:null};try{let r=await C(e.cwd);return{errors:t,config:r}}catch{a.break(),a.error(`An invalid ${c.info("components.json")} file was found at ${c.info(e.cwd)}.
23
- Before you can add components, you must create a valid ${c.info("components.json")} file by running the ${c.info("init")} command.`),a.error(`Learn more at ${c.info("https://ui.shadcn.com/docs/components-json")}.`),a.break(),process.exit(1)}}import Ct from"fs/promises";import li from"path";async function Rt(e,t){let r=li.join(t.resolvedPaths.cwd,"app/page.tsx");if(!(await Ct.stat(r)).isFile())return;let i=await tt(e,t.style);if(!i?.meta?.importSpecifier||!i?.meta?.moduleSpecifier)return;let n=`import { ${i?.meta?.importSpecifier} } from "${i.meta.moduleSpecifier}"
21
+ `);let s=await Nr([{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&&(o=s.flag)}i?.start(),await Lr(n,[n==="npm"?"install":"add",...n==="npm"&&o?[`--${o}`]:[],...e],{cwd:t.resolvedPaths.cwd}),i?.succeed()}function Ar(e){let t=Y(e.resolvedPaths.cwd);return t?.dependencies?.react?/^(?:\^|~)?19(?:\.\d+)*(?:-.*)?$/.test(t.dependencies.react):!1}import{existsSync as yt,promises as wt}from"fs";import L,{basename as ei}from"path";import{promises as Yr}from"fs";import{tmpdir as Hr}from"os";import ht from"path";import{SyntaxKind as Fr}from"ts-morph";var re=async({sourceFile:e,config:t,baseColor:r})=>(t.tailwind?.cssVariables||!r?.inlineColors||e.getDescendantsOfKind(Fr.StringLiteral).forEach(i=>{let n=i.getText();if(n){let o=_r(n.replace(/"/g,""),r.inlineColors);i.replaceWithText(`"${o.trim()}"`)}}),e);function je(e){if(!e.includes("/")&&!e.includes(":"))return[null,e,null];let t=[],[r,i]=e.split("/");if(!r.includes(":"))return[null,r,i];let n=r.split(":"),o=n.pop(),s=n.join(":");return t.push(s??null,o??null,i??null),t}var Dr=["bg-","text-","border-","ring-offset-","ring-"];function _r(e,t){e.includes(" border ")&&(e=e.replace(" border "," border border-border "));let r=e.split(" "),i=new Set,n=new Set;for(let o of r){let[s,c,f]=je(o),d=Dr.find(u=>c?.startsWith(u));if(!d){i.has(o)||i.add(o);continue}let p=c?.replace(d,"");if(p&&p in t.light){i.add([s,`${d}${t.light[p]}`].filter(Boolean).join(":")+(f?`/${f}`:"")),n.add(["dark",s,`${d}${t.dark[p]}`].filter(Boolean).join(":")+(f?`/${f}`:""));continue}i.has(o)||i.add(o)}return[...Array.from(i),...Array.from(n)].join(" ").trim()}var R={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"}};import{SyntaxKind as Kr}from"ts-morph";var gt="lucide",ie=async({sourceFile:e,config:t})=>{if(!t.iconLibrary||!(t.iconLibrary in R))return e;let r=await Z(),i=gt,n=t.iconLibrary;if(i===n)return e;let o=[];for(let s of e.getImportDeclarations()??[])if(s.getModuleSpecifier()?.getText()===`"${R[gt].import}"`){for(let c of s.getNamedImports()??[]){let f=c.getName(),d=r[f]?.[n];!d||o.includes(d)||(o.push(d),c.remove(),e.getDescendantsOfKind(Kr.JsxSelfClosingElement).filter(p=>p.getTagNameNode()?.getText()===f).forEach(p=>p.getTagNameNode()?.replaceWithText(d)))}s.getNamedImports()?.length===0&&s.remove()}if(o.length>0){let s=e.addImportDeclaration({moduleSpecifier:R[n]?.import,namedImports:o.map(c=>({name:c}))});zr(e)||s.replaceWithText(s.getText().replace(";",""))}return e};function zr(e){return e.getImportDeclarations()?.[0]?.getText().endsWith(";")??!1}var ne=async({sourceFile:e,config:t})=>{let r=e.getImportDeclarations();for(let i of r){let n=Mr(i.getModuleSpecifierValue(),t);i.setModuleSpecifier(n),n=="@/lib/utils"&&i.getNamedImports().find(c=>c.getName()==="cn")&&i.setModuleSpecifier(n.replace(/^@\/lib\/utils/,t.aliases.utils))}return e};function Mr(e,t){if(!e.startsWith("@/"))return e;if(!e.startsWith("@/registry/")){let r=t.aliases.components.split("/")[0];return e.replace(/^@\//,`${r}/`)}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)}import{transformFromAstSync as Wr}from"@babel/core";import{parse as Ur}from"@babel/parser";import Vr from"@babel/plugin-transform-typescript";import*as oe from"recast";var Br={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"]},ut=async({sourceFile:e,config:t})=>{let r=e.getFullText();if(t.tsx)return r;let i=oe.parse(r,{parser:{parse:o=>Ur(o,Br)}}),n=Wr(i,r,{cloneInputAst:!1,code:!1,ast:!0,plugins:[Vr],configFile:!1});if(!n||!n.ast)throw new Error("Failed to transform JSX");return oe.print(n.ast).code};import{SyntaxKind as Gr}from"ts-morph";var Jr=/^["']use client["']$/g,se=async({sourceFile:e,config:t})=>{if(t.rsc)return e;let r=e.getFirstChildByKind(Gr.ExpressionStatement);return r&&Jr.test(r.getText())&&r.remove(),e};import{Project as Qr,ScriptKind as Xr}from"ts-morph";import{SyntaxKind as w}from"ts-morph";var ae=async({sourceFile:e,config:t})=>(t.tailwind?.prefix&&(e.getDescendantsOfKind(w.CallExpression).filter(r=>r.getExpression().getText()==="cva").forEach(r=>{if(r.getArguments()[0]?.isKind(w.StringLiteral)){let i=r.getArguments()[0];i&&i.replaceWithText(`"${$(i.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`)}r.getArguments()[1]?.isKind(w.ObjectLiteralExpression)&&r.getArguments()[1]?.getDescendantsOfKind(w.PropertyAssignment).find(i=>i.getName()==="variants")?.getDescendantsOfKind(w.PropertyAssignment).forEach(i=>{i.getDescendantsOfKind(w.PropertyAssignment).forEach(n=>{let o=n.getInitializerIfKind(w.StringLiteral);o&&o?.replaceWithText(`"${$(o.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`)})})}),e.getDescendantsOfKind(w.JsxAttribute).forEach(r=>{if(r.getName()==="className"){if(r.getInitializer()?.isKind(w.StringLiteral)){let i=r.getInitializer();i&&i.replaceWithText(`"${$(i.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`)}if(r.getInitializer()?.isKind(w.JsxExpression)){let i=r.getInitializer()?.getDescendantsOfKind(w.CallExpression).find(n=>n.getExpression().getText()==="cn");i&&i.getArguments().forEach(n=>{(n.isKind(w.ConditionalExpression)||n.isKind(w.BinaryExpression))&&n.getChildrenOfKind(w.StringLiteral).forEach(o=>{o.replaceWithText(`"${$(o.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`)}),n.isKind(w.StringLiteral)&&n.replaceWithText(`"${$(n.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`)})}}r.getName()==="classNames"&&r.getInitializer()?.isKind(w.JsxExpression)&&r.getDescendantsOfKind(w.PropertyAssignment).forEach(i=>{if(i.getInitializer()?.isKind(w.CallExpression)){let n=i.getInitializerIfKind(w.CallExpression);n&&n.getArguments().forEach(o=>{o.isKind(w.ConditionalExpression)&&o.getChildrenOfKind(w.StringLiteral).forEach(s=>{s.replaceWithText(`"${$(s.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`)}),o.isKind(w.StringLiteral)&&o.replaceWithText(`"${$(o.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`)})}if(i.getInitializer()?.isKind(w.StringLiteral)&&i.getName()!=="variant"){let n=i.getInitializer();n&&n.replaceWithText(`"${$(n.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`)}})})),e);function $(e,t=""){let r=e.split(" "),i=[];for(let n of r){let[o,s,c]=je(n);o?c?i.push(`${o}:${t}${s}/${c}`):i.push(`${o}:${t}${s}`):c?i.push(`${t}${s}/${c}`):i.push(`${t}${s}`)}return i.join(" ")}var qr=new Qr({compilerOptions:{}});async function Zr(e){let t=await Yr.mkdtemp(ht.join(Hr(),"shadcn-"));return ht.join(t,e)}async function le(e,t=[ne,se,re,ae,ie]){let r=await Zr(e.filename),i=qr.createSourceFile(r,e.raw,{scriptKind:Xr.TSX});for(let n of t)await n({sourceFile:i,...e});return e.transformJsx?await ut({sourceFile:i,...e}):i.getText()}import ti from"prompts";function ri(e,t,r){return r.startsWith("~/")?L.join(t.resolvedPaths.cwd,r.replace("~/","")):e?.isSrcDir?L.join(t.resolvedPaths.cwd,"src",r):L.join(t.resolvedPaths.cwd,r)}async function xt(e,t,r){if(!e?.length)return;r={overwrite:!1,force:!1,silent:!1,...r};let i=y("Updating files.",{silent:r.silent})?.start(),[n,o]=await Promise.all([k(t.resolvedPaths.cwd),G(t.tailwind.baseColor)]),s=[],c=[],f=[];for(let p of e){if(!p.content)continue;let u=lt(p,t),b=ei(p.path),S=L.join(u,b);p.target&&(S=ri(n,t,p.target),u=L.dirname(S)),t.tsx||(S=S.replace(/\.tsx?$/,ue=>ue===".tsx"?".jsx":".js"));let N=yt(S);if(N&&!r.overwrite){i.stop();let{overwrite:ue}=await ti({type:"confirm",name:"overwrite",message:`The file ${l.info(b)} already exists. Would you like to overwrite?`,initial:!1});if(!ue){f.push(L.relative(t.resolvedPaths.cwd,S));continue}i?.start()}yt(u)||await wt.mkdir(u,{recursive:!0});let A=await le({filename:p.path,raw:p.content,config:t,baseColor:o,transformJsx:!t.tsx},[ne,se,re,ae,ie]);await wt.writeFile(S,A,"utf-8"),N?c.push(L.relative(t.resolvedPaths.cwd,S)):s.push(L.relative(t.resolvedPaths.cwd,S))}if(!(s.length||c.length)&&!f.length&&i?.info("No files updated."),s.length){if(i?.succeed(`Created ${s.length} ${s.length===1?"file":"files"}:`),!r.silent)for(let p of s)a.log(` - ${p}`)}else i?.stop();if(c.length&&(y(`Updated ${c.length} ${c.length===1?"file":"files"}:`,{silent:r.silent})?.info(),!r.silent))for(let p of c)a.log(` - ${p}`);if(f.length&&(y(`Skipped ${f.length} ${c.length===1?"file":"files"}:`,{silent:r.silent})?.info(),!r.silent))for(let p of f)a.log(` - ${p}`);r.silent||a.break()}async function ce(e,t,r){r={overwrite:!1,silent:!1,isNewProject:!1,...r};let i=y("Checking registry.",{silent:r.silent})?.start(),n=await ct(e,t);if(!n)return i?.fail(),x(new Error("Failed to fetch components from registry."));i?.succeed(),await et(n.tailwind?.config,t,{silent:r.silent}),await dt(n.cssVars,t,{cleanupDefaultNextStyles:r.isNewProject,silent:r.silent}),await te(n.dependencies,t,{silent:r.silent}),await xt(n.files,t,{overwrite:r.overwrite,silent:r.silent}),n.docs&&a.info(n.docs)}import ii from"path";import{execa as ni}from"execa";import Oe from"fs-extra";import bt from"prompts";async function pe(e){if(e={srcDir:!1,...e},!e.force){let{proceed:s}=await bt({type:"confirm",name:"proceed",message:`The path ${l.info(e.cwd)} does not contain a package.json file. Would you like to start a new ${l.info("Next.js")} project?`,initial:!0});if(!s)return{projectPath:null,projectName:null}}let t=await ee(e.cwd,{withFallback:!0}),{name:r}=await bt({type:"text",name:"name",message:"What is your project named?",initial:"my-app",format:s=>s.trim(),validate:s=>s.length>128?"Name should be less than 128 characters.":!0}),i=`${e.cwd}/${r}`;try{await Oe.access(e.cwd,Oe.constants.W_OK)}catch{a.break(),a.error(`The path ${l.info(e.cwd)} is not writable.`),a.error(`It is likely you do not have write permissions for this folder or the path ${l.info(e.cwd)} does not exist.`),a.break(),process.exit(1)}Oe.existsSync(ii.resolve(e.cwd,r,"package.json"))&&(a.break(),a.error(`A project with the name ${l.info(r)} already exists.`),a.error("Please choose a different name and try again."),a.break(),process.exit(1));let n=y("Creating a new Next.js project. This may take a few minutes.").start(),o=["--tailwind","--eslint","--typescript","--app",e.srcDir?"--src-dir":"--no-src-dir","--no-import-alias",`--use-${t}`];try{await ni("npx",["create-next-app@14.2.16",i,"--silent",...o],{cwd:e.cwd})}catch{a.break(),a.error("Something went wrong creating a new Next.js project. Please try again."),process.exit(1)}return n?.succeed("Creating a new Next.js project."),{projectPath:i,projectName:r}}import{promises as St}from"fs";import oi from"path";import{SyntaxKind as me}from"ts-morph";async function It(e,t,r){if(!e)return;r={silent:!1,...r};let i=oi.relative(t.resolvedPaths.cwd,t.resolvedPaths.tailwindConfig),n=y(`Updating ${l.info(i)}`,{silent:r.silent}).start(),o=await St.readFile(t.resolvedPaths.tailwindConfig,"utf8"),s=await si(o,e,t);await St.writeFile(t.resolvedPaths.tailwindConfig,s,"utf8"),n?.succeed()}async function si(e,t,r){let i=await X(e,r),n=i.getDescendantsOfKind(me.ObjectLiteralExpression).find(o=>o.getProperties().some(s=>s.isKind(me.PropertyAssignment)&&s.getName()==="content"));return n?(ai(n,t),i.getFullText()):e}async function ai(e,t){let r=Ce(e),i=e.getProperty("content");if(!i){let n={name:"content",initializer:`[${r}${t.join(`${r}, ${r}`)}${r}]`};return e.addPropertyAssignment(n),e}if(i.isKind(me.PropertyAssignment)){let n=i.getInitializer();if(n?.isKind(me.ArrayLiteralExpression))for(let o of t){let s=`${r}${o}${r}`;n.getElements().map(c=>c.getText()).includes(s)||n.addElement(s)}return e}return e}import{Command as ci}from"commander";import $e from"prompts";import{z as P}from"zod";var pi=P.object({cwd:P.string(),components:P.array(P.string()).optional(),yes:P.boolean(),defaults:P.boolean(),force:P.boolean(),silent:P.boolean(),isNewProject:P.boolean(),srcDir:P.boolean().optional()}),Rt=new ci().name("init").description("initialize your project and install dependencies").argument("[components...]","the components to add or a url to the component.").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).action(async(e,t)=>{try{let r=pi.parse({cwd:Ct.resolve(t.cwd),isNewProject:!1,components:e,...t});await fe(r),a.log(`${l.success("Success!")} Project initialization completed.
22
+ You may now add components.`),a.break()}catch(r){a.break(),x(r)}});async function fe(e){let t;if(e.skipPreflight)t=await k(e.cwd);else{let f=await Ge(e);if(f.errors[I]){let{projectPath:d}=await pe(e);d||process.exit(1),e.cwd=d,e.isNewProject=!0}t=f.projectInfo}let r=await Ve(e.cwd,t),i=r?await fi(r,e):await mi(await C(e.cwd));if(!e.yes){let{proceed:f}=await $e({type:"confirm",name:"proceed",message:`Write configuration to ${l.info("components.json")}. Proceed?`,initial:!0});f||process.exit(0)}let n=y("Writing components.json.").start(),o=Ct.resolve(e.cwd,"components.json");await li.writeFile(o,JSON.stringify(i,null,2),"utf8"),n.succeed();let s=await W(e.cwd,i),c=["index",...e.components||[]];return await ce(c,s,{overwrite:!0,silent:e.silent,isNewProject:e.isNewProject||t?.framework.name==="next-app"}),e.isNewProject&&e.srcDir&&await It(["./src/**/*.{js,ts,jsx,tsx,mdx}"],s,{silent:e.silent}),s}async function mi(e=null){let[t,r]=await Promise.all([Ee(),Te()]);a.info("");let i=await $e([{type:"toggle",name:"typescript",message:`Would you like to use ${l.info("TypeScript")} (recommended)?`,initial:e?.tsx??!0,active:"yes",inactive:"no"},{type:"select",name:"style",message:`Which ${l.info("style")} would you like to use?`,choices:t.map(n=>({title:n.label,value:n.name}))},{type:"select",name:"tailwindBaseColor",message:`Which color would you like to use as the ${l.info("base color")}?`,choices:r.map(n=>({title:n.label,value:n.name}))},{type:"text",name:"tailwindCss",message:`Where is your ${l.info("global CSS")} file?`,initial:e?.tailwind.css??We},{type:"toggle",name:"tailwindCssVariables",message:`Would you like to use ${l.info("CSS variables")} for theming?`,initial:e?.tailwind.cssVariables??!0,active:"yes",inactive:"no"},{type:"text",name:"tailwindPrefix",message:`Are you using a custom ${l.info("tailwind prefix eg. tw-")}? (Leave blank if not)`,initial:""},{type:"text",name:"tailwindConfig",message:`Where is your ${l.info("tailwind.config.js")} located?`,initial:e?.tailwind.config??Ue},{type:"text",name:"components",message:`Configure the import alias for ${l.info("components")}:`,initial:e?.aliases.components??ze},{type:"text",name:"utils",message:`Configure the import alias for ${l.info("utils")}:`,initial:e?.aliases.utils??Me},{type:"toggle",name:"rsc",message:`Are you using ${l.info("React Server Components")}?`,initial:e?.rsc??!0,active:"yes",inactive:"no"}]);return M.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 fi(e,t){let r=e.style,i=e.tailwind.baseColor,n=e.tailwind.cssVariables;if(!t.defaults){let[o,s]=await Promise.all([Ee(),Te()]),c=await $e([{type:"select",name:"style",message:`Which ${l.info("style")} would you like to use?`,choices:o.map(f=>({title:f.label,value:f.name})),initial:o.findIndex(f=>f.name===r)},{type:"select",name:"tailwindBaseColor",message:`Which color would you like to use as the ${l.info("base color")}?`,choices:s.map(f=>({title:f.label,value:f.name}))},{type:"toggle",name:"tailwindCssVariables",message:`Would you like to use ${l.info("CSS variables")} for theming?`,initial:e?.tailwind.cssVariables,active:"yes",inactive:"no"}]);r=c.style,i=c.tailwindBaseColor,n=c.tailwindCssVariables}return M.parse({$schema:e?.$schema,style:r,tailwind:{...e?.tailwind,baseColor:i,cssVariables:n},rsc:e?.rsc,tsx:e?.tsx,aliases:e?.aliases,iconLibrary:e?.iconLibrary})}import vt from"path";import Le from"fs-extra";async function Pt(e){let t={};if(!Le.existsSync(e.cwd)||!Le.existsSync(vt.resolve(e.cwd,"package.json")))return t[I]=!0,{errors:t,config:null};if(!Le.existsSync(vt.resolve(e.cwd,"components.json")))return t[j]=!0,{errors:t,config:null};try{let r=await C(e.cwd);return{errors:t,config:r}}catch{a.break(),a.error(`An invalid ${l.info("components.json")} file was found at ${l.info(e.cwd)}.
23
+ Before you can add components, you must create a valid ${l.info("components.json")} file by running the ${l.info("init")} command.`),a.error(`Learn more at ${l.info("https://ui.shadcn.com/docs/components-json")}.`),a.break(),process.exit(1)}}import Et from"fs/promises";import di from"path";async function Tt(e,t){let r=di.join(t.resolvedPaths.cwd,"app/page.tsx");if(!(await Et.stat(r)).isFile())return;let i=await ot(e,t.style);if(!i?.meta?.importSpecifier||!i?.meta?.moduleSpecifier)return;let n=`import { ${i?.meta?.importSpecifier} } from "${i.meta.moduleSpecifier}"
24
24
 
25
25
  export default function Page() {
26
26
  return <${i?.meta?.importSpecifier} />
27
- }`;await Ct.writeFile(r,n,"utf8")}import{Command as mi}from"commander";import Ee from"prompts";import{z as P}from"zod";var fi=P.object({components:P.array(P.string()).optional(),yes:P.boolean(),overwrite:P.boolean(),cwd:P.string(),all:P.boolean(),path:P.string().optional(),silent:P.boolean(),srcDir:P.boolean().optional()}),Pt=new mi().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).action(async(e,t)=>{try{let r=fi.parse({components:e,cwd:pi.resolve(t.cwd),...t}),i=r.components?.some(l=>l.includes("theme-"));if(!r.yes&&i){a.break();let{confirm:l}=await Ee({type:"confirm",name:"confirm",message:c.warn(`You are about to install a new theme.
28
- Existing CSS variables will be overwritten. Continue?`)});l||(a.break(),a.log("Theme installation cancelled."),a.break(),process.exit(1))}r.components?.length||(r.components=await di(r));let{errors:n,config:o}=await It(r);if(n[j]){let{proceed:l}=await Ee({type:"confirm",name:"proceed",message:`You need to create a ${c.info("components.json")} file to add components. Proceed?`,initial:!0});l||(a.break(),process.exit(1)),o=await pe({cwd:r.cwd,yes:!0,force:!0,defaults:!1,skipPreflight:!1,silent:!0,isNewProject:!1,srcDir:r.srcDir})}let s=!1;if(n[I]){let{projectPath:l}=await ce({cwd:r.cwd,force:r.overwrite,srcDir:r.srcDir});l||(a.break(),process.exit(1)),r.cwd=l,o=await pe({cwd:r.cwd,yes:!0,force:!0,defaults:!1,skipPreflight:!0,silent:!0,isNewProject:!0,srcDir:r.srcDir}),s=r.components?.length===1&&!!r.components[0].match(/\/chat\/b\//)}if(!o)throw new Error(`Failed to read config at ${c.info(r.cwd)}.`);await ae(r.components,o,r),s&&await Rt(r.components[0],o)}catch(r){a.break(),x(r)}});async function di(e){let t=await V();if(!t)return a.break(),x(new Error("Failed to fetch registry index.")),[];if(e.all)return t.map(n=>n.name);if(e.components?.length)return e.components;let{components:r}=await Ee({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(n=>n.type==="registry:ui").map(n=>({title:n.name,value:n.name,selected:e.all?!0:e.components?.includes(n.name)}))});r?.length||(a.warn("No components selected. Exiting."),a.info(""),process.exit(1));let i=P.array(P.string()).safeParse(r);return i.success?i.data:(a.error(""),x(new Error("Something went wrong. Please try again.")),[])}import{existsSync as je,promises as gi}from"fs";import $e from"path";import{Command as ui}from"commander";import{diffLines as hi}from"diff";import{z as G}from"zod";var yi=G.object({component:G.string().optional(),yes:G.boolean(),cwd:G.string(),path:G.string().optional()}),kt=new ui().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=yi.parse({component:e,...t}),i=$e.resolve(r.cwd);je(i)||(a.error(`The path ${i} does not exist. Please try again.`),process.exit(1));let n=await C(i);n||(a.warn(`Configuration is missing. Please run ${c.success("init")} to create a components.json file.`),process.exit(1));let o=await V();if(o||(x(new Error("Failed to fetch registry index.")),process.exit(1)),!r.component){let f=n.resolvedPaths.components,d=o.filter(g=>{for(let b of g.files??[]){let S=$e.resolve(f,typeof b=="string"?b:b.path);if(je(S))return!0}return!1}),p=[];for(let g of d){let b=await vt(g,n);b.length&&p.push({name:g.name,changes:b})}p.length||(a.info("No updates found."),process.exit(0)),a.info("The following components have updates available:");for(let g of p){a.info(`- ${g.name}`);for(let b of g.changes)a.info(` - ${b.filePath}`)}a.break(),a.info(`Run ${c.success("diff <component>")} to see the changes.`),process.exit(0)}let s=o.find(f=>f.name===r.component);s||(a.error(`The component ${c.success(r.component)} does not exist.`),process.exit(1));let l=await vt(s,n);l.length||(a.info(`No updates found for ${r.component}.`),process.exit(0));for(let f of l)a.info(`- ${f.filePath}`),await wi(f.patch),a.info("")}catch(r){x(r)}});async function vt(e,t){let r=await rt(t.style,[e]),i=await B(t.tailwind.baseColor);if(!r)return[];let n=[];for(let o of r){let s=await it(t,o);if(s)for(let l of o.files??[]){let f=$e.resolve(s,typeof l=="string"?l:l.path);if(!je(f))continue;let d=await gi.readFile(f,"utf8");if(typeof l=="string"||!l.content)continue;let p=await se({filename:l.path,raw:l.content,config:t,baseColor:i}),g=hi(p,d);g.length>1&&n.push({filePath:f,patch:g})}}return n}async function wi(e){e.forEach(t=>{if(t)return t.added?process.stdout.write(c.success(t.value)):t.removed?process.stdout.write(c.error(t.value)):process.stdout.write(t.value)})}import{Command as xi}from"commander";var Tt=new xi().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=>{a.info("> project info"),console.log(await E(e.cwd)),a.break(),a.info("> components.json"),console.log(await C(e.cwd))});import ki from"path";import{randomBytes as bi}from"crypto";import{promises as Oe}from"fs";import{tmpdir as Si}from"os";import me from"path";import Ii from"fast-glob";import Et from"prompts";import{Project as Ci,ScriptKind as Ri,SyntaxKind as Pi}from"ts-morph";async function jt(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([Ii("**/*.{js,ts,jsx,tsx}",{cwd:t}),X()]);if(Object.keys(i).length===0)throw new Error("Something went wrong fetching the registry icons.");let n=Object.entries(R).map(([p,g])=>({title:g.name,value:p})),o=await Et([{type:"select",name:"sourceLibrary",message:`Which icon library would you like to ${c.info("migrate from")}?`,choices:n},{type:"select",name:"targetLibrary",message:`Which icon library would you like to ${c.info("migrate to")}?`,choices:n}]);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 R&&o.targetLibrary in R))throw new Error("Invalid icon library. Please choose a valid icon library.");let s=R[o.sourceLibrary],l=R[o.targetLibrary],{confirm:f}=await Et({type:"confirm",name:"confirm",initial:!0,message:`We will migrate ${c.info(r.length)} files in ${c.info(`./${me.relative(e.resolvedPaths.cwd,t)}`)} from ${c.info(s.name)} to ${c.info(l.name)}. Continue?`});f||(a.info("Migration cancelled."),process.exit(0)),l.package&&await Z([l.package],e,{silent:!1});let d=y("Migrating icons...")?.start();await Promise.all(r.map(async p=>{d.text=`Migrating ${p}...`;let g=me.join(t,p),b=await Oe.readFile(g,"utf-8"),S=await vi(b,o.sourceLibrary,o.targetLibrary,i);await Oe.writeFile(g,S)})),d.succeed("Migration complete.")}async function vi(e,t,r,i){let n=R[t]?.import,o=R[r]?.import,s=await Oe.mkdtemp(me.join(Si(),"shadcn-")),l=new Ci({compilerOptions:{}}),f=me.join(s,`shadcn-icons-${bi(4).toString("hex")}.tsx`),d=l.createSourceFile(f,e,{scriptKind:Ri.TSX}),p=[];for(let g of d.getImportDeclarations()??[])if(g.getModuleSpecifier()?.getText()===`"${n}"`){for(let b of g.getNamedImports()??[]){let S=b.getName(),A=Object.values(i).find(L=>L[t]===S)?.[r];!A||p.includes(A)||(p.push(A),b.remove(),d.getDescendantsOfKind(Pi.JsxSelfClosingElement).filter(L=>L.getTagNameNode()?.getText()===S).forEach(L=>L.getTagNameNode()?.replaceWithText(A)))}g.getNamedImports()?.length===0&&g.remove()}return p.length>0&&d.addImportDeclaration({moduleSpecifier:o,namedImports:p.map(g=>({name:g}))}),await d.getText()}import $t from"path";import Ne from"fs-extra";async function Ot(e){let t={};if(!Ne.existsSync(e.cwd)||!Ne.existsSync($t.resolve(e.cwd,"package.json")))return t[I]=!0,{errors:t,config:null};if(!Ne.existsSync($t.resolve(e.cwd,"components.json")))return t[j]=!0,{errors:t,config:null};try{let r=await C(e.cwd);return{errors:t,config:r}}catch{a.break(),a.error(`An invalid ${c.info("components.json")} file was found at ${c.info(e.cwd)}.
29
- Before you can run a migration, you must create a valid ${c.info("components.json")} file by running the ${c.info("init")} command.`),a.error(`Learn more at ${c.info("https://ui.shadcn.com/docs/components-json")}.`),a.break(),process.exit(1)}}import{Command as Ti}from"commander";import{z as fe}from"zod";var Nt=[{name:"icons",description:"migrate your ui components to a different icon library."}],Ei=fe.object({cwd:fe.string(),list:fe.boolean(),migration:fe.string().refine(e=>e&&Nt.some(t=>t.name===e),{message:"You must specify a valid migration. Run `shadcn migrate --list` to see available migrations."}).optional()}),At=new Ti().name("migrate").description("run a migration.").argument("[migration]","the migration to run.").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).option("-l, --list","list all migrations.",!1).action(async(e,t)=>{try{let r=Ei.parse({cwd:ki.resolve(t.cwd),migration:e,list:t.list});if(r.list||!r.migration){a.info("Available migrations:");for(let o of Nt)a.info(`- ${o.name}: ${o.description}`);return}if(!r.migration)throw new Error("You must specify a migration. Run `shadcn migrate --list` to see available migrations.");let{errors:i,config:n}=await Ot(r);if(i[I]||i[j])throw new Error("No `components.json` file found. Ensure you are at the root of your project.");if(!n)throw new Error("Something went wrong reading your `components.json` file. Please ensure you have a valid `components.json` file.");r.migration==="icons"&&await jt(n)}catch(r){a.break(),x(r)}});import{Command as $i}from"commander";var Lt={name:"shadcn",version:"2.1.6",description:"Add components to your apps.",publishConfig:{access:"public"},license:"MIT",author:{name:"shadcn",url:"https://twitter.com/shadcn"},repository:{type:"git",url:"https://github.com/shadcn/ui.git",directory:"packages/shadcn"},files:["dist"],keywords:["components","ui","tailwind","radix-ui","shadcn"],type:"module",exports:"./dist/index.js",bin:"./dist/index.js",scripts:{dev:"tsup --watch",build:"tsup",typecheck:"tsc --noEmit",clean:"rimraf dist && rimraf components","start:dev":"cross-env REGISTRY_URL=http://localhost:3333/r node dist/index.js","start:prod":"cross-env REGISTRY_URL=https://ui.shadcn.com/r node dist/index.js",start:"node dist/index.js","format:write":'prettier --write "**/*.{ts,tsx,mdx}" --cache',"format:check":'prettier --check "**/*.{ts,tsx,mdx}" --cache',release:"changeset version","pub:beta":"pnpm build && pnpm publish --no-git-checks --access public --tag beta","pub:next":"pnpm build && pnpm publish --no-git-checks --access public --tag next","pub:release":"pnpm build && pnpm publish --access public",test:"vitest run","test:dev":"REGISTRY_URL=http://localhost:3333/r vitest run"},dependencies:{"@antfu/ni":"^0.21.4","@babel/core":"^7.22.1","@babel/parser":"^7.22.6","@babel/plugin-transform-typescript":"^7.22.5",commander:"^10.0.0",cosmiconfig:"^8.1.3",deepmerge:"^4.3.1",diff:"^5.1.0",execa:"^7.0.0","fast-glob":"^3.3.2","fs-extra":"^11.1.0","https-proxy-agent":"^6.2.0",kleur:"^4.1.5","lodash.template":"^4.5.0","node-fetch":"^3.3.0",ora:"^6.1.2",postcss:"^8.4.24",prompts:"^2.4.2",recast:"^0.23.2","stringify-object":"^5.0.0","ts-morph":"^18.0.0","tsconfig-paths":"^4.2.0",zod:"^3.20.2"},devDependencies:{"@types/babel__core":"^7.20.1","@types/diff":"^5.0.3","@types/fs-extra":"^11.0.1","@types/lodash.template":"^4.5.1","@types/prompts":"^2.4.2","@types/stringify-object":"^4.0.5",rimraf:"^6.0.1",tsup:"^6.6.3","type-fest":"^3.8.0",typescript:"^4.9.3"}};process.on("SIGINT",()=>process.exit(0));process.on("SIGTERM",()=>process.exit(0));async function Oi(){let e=new $i().name("shadcn").description("add components and dependencies to your project").version(Lt.version||"1.0.0","-v, --version","display the version number");e.addCommand(bt).addCommand(Pt).addCommand(kt).addCommand(At).addCommand(Tt),e.parse()}Oi();
27
+ }`;await Et.writeFile(r,n,"utf8")}import{Command as ui}from"commander";import Ne from"prompts";import{z as v}from"zod";var hi=v.object({components:v.array(v.string()).optional(),yes:v.boolean(),overwrite:v.boolean(),cwd:v.string(),all:v.boolean(),path:v.string().optional(),silent:v.boolean(),srcDir:v.boolean().optional()}),kt=new ui().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).action(async(e,t)=>{try{let r=hi.parse({components:e,cwd:gi.resolve(t.cwd),...t}),i=r.components?.some(c=>c.includes("theme-"));if(!r.yes&&i){a.break();let{confirm:c}=await Ne({type:"confirm",name:"confirm",message:l.warn(`You are about to install a new theme.
28
+ Existing CSS variables will be overwritten. Continue?`)});c||(a.break(),a.log("Theme installation cancelled."),a.break(),process.exit(1))}r.components?.length||(r.components=await yi(r));let{errors:n,config:o}=await Pt(r);if(n[j]){let{proceed:c}=await Ne({type:"confirm",name:"proceed",message:`You need to create a ${l.info("components.json")} file to add components. Proceed?`,initial:!0});c||(a.break(),process.exit(1)),o=await fe({cwd:r.cwd,yes:!0,force:!0,defaults:!1,skipPreflight:!1,silent:!0,isNewProject:!1,srcDir:r.srcDir})}let s=!1;if(n[I]){let{projectPath:c}=await pe({cwd:r.cwd,force:r.overwrite,srcDir:r.srcDir});c||(a.break(),process.exit(1)),r.cwd=c,o=await fe({cwd:r.cwd,yes:!0,force:!0,defaults:!1,skipPreflight:!0,silent:!0,isNewProject:!0,srcDir:r.srcDir}),s=r.components?.length===1&&!!r.components[0].match(/\/chat\/b\//)}if(!o)throw new Error(`Failed to read config at ${l.info(r.cwd)}.`);await ce(r.components,o,r),s&&await Tt(r.components[0],o)}catch(r){a.break(),x(r)}});async function yi(e){let t=await B();if(!t)return a.break(),x(new Error("Failed to fetch registry index.")),[];if(e.all)return t.map(n=>n.name);if(e.components?.length)return e.components;let{components:r}=await Ne({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(n=>n.type==="registry:ui").map(n=>({title:n.name,value:n.name,selected:e.all?!0:e.components?.includes(n.name)}))});r?.length||(a.warn("No components selected. Exiting."),a.info(""),process.exit(1));let i=v.array(v.string()).safeParse(r);return i.success?i.data:(a.error(""),x(new Error("Something went wrong. Please try again.")),[])}import{existsSync as Ae,promises as wi}from"fs";import Fe from"path";import{Command as xi}from"commander";import{diffLines as bi}from"diff";import{z as J}from"zod";var Si=J.object({component:J.string().optional(),yes:J.boolean(),cwd:J.string(),path:J.string().optional()}),Ot=new xi().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=Si.parse({component:e,...t}),i=Fe.resolve(r.cwd);Ae(i)||(a.error(`The path ${i} does not exist. Please try again.`),process.exit(1));let n=await C(i);n||(a.warn(`Configuration is missing. Please run ${l.success("init")} to create a components.json file.`),process.exit(1));let o=await B();if(o||(x(new Error("Failed to fetch registry index.")),process.exit(1)),!r.component){let f=n.resolvedPaths.components,d=o.filter(u=>{for(let b of u.files??[]){let S=Fe.resolve(f,typeof b=="string"?b:b.path);if(Ae(S))return!0}return!1}),p=[];for(let u of d){let b=await jt(u,n);b.length&&p.push({name:u.name,changes:b})}p.length||(a.info("No updates found."),process.exit(0)),a.info("The following components have updates available:");for(let u of p){a.info(`- ${u.name}`);for(let b of u.changes)a.info(` - ${b.filePath}`)}a.break(),a.info(`Run ${l.success("diff <component>")} to see the changes.`),process.exit(0)}let s=o.find(f=>f.name===r.component);s||(a.error(`The component ${l.success(r.component)} does not exist.`),process.exit(1));let c=await jt(s,n);c.length||(a.info(`No updates found for ${r.component}.`),process.exit(0));for(let f of c)a.info(`- ${f.filePath}`),await Ii(f.patch),a.info("")}catch(r){x(r)}});async function jt(e,t){let r=await st(t.style,[e]),i=await G(t.tailwind.baseColor);if(!r)return[];let n=[];for(let o of r){let s=await at(t,o);if(s)for(let c of o.files??[]){let f=Fe.resolve(s,typeof c=="string"?c:c.path);if(!Ae(f))continue;let d=await wi.readFile(f,"utf8");if(typeof c=="string"||!c.content)continue;let p=await le({filename:c.path,raw:c.content,config:t,baseColor:i}),u=bi(p,d);u.length>1&&n.push({filePath:f,patch:u})}}return n}async function Ii(e){e.forEach(t=>{if(t)return t.added?process.stdout.write(l.success(t.value)):t.removed?process.stdout.write(l.error(t.value)):process.stdout.write(t.value)})}import{Command as Ci}from"commander";var $t=new Ci().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=>{a.info("> project info"),console.log(await k(e.cwd)),a.break(),a.info("> components.json"),console.log(await C(e.cwd))});import Oi from"path";import{randomBytes as Ri}from"crypto";import{promises as De}from"fs";import{tmpdir as vi}from"os";import de from"path";import Pi from"fast-glob";import Lt from"prompts";import{Project as Ei,ScriptKind as Ti,SyntaxKind as ki}from"ts-morph";async function Nt(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([Pi("**/*.{js,ts,jsx,tsx}",{cwd:t}),Z()]);if(Object.keys(i).length===0)throw new Error("Something went wrong fetching the registry icons.");let n=Object.entries(R).map(([p,u])=>({title:u.name,value:p})),o=await Lt([{type:"select",name:"sourceLibrary",message:`Which icon library would you like to ${l.info("migrate from")}?`,choices:n},{type:"select",name:"targetLibrary",message:`Which icon library would you like to ${l.info("migrate to")}?`,choices:n}]);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 R&&o.targetLibrary in R))throw new Error("Invalid icon library. Please choose a valid icon library.");let s=R[o.sourceLibrary],c=R[o.targetLibrary],{confirm:f}=await Lt({type:"confirm",name:"confirm",initial:!0,message:`We will migrate ${l.info(r.length)} files in ${l.info(`./${de.relative(e.resolvedPaths.cwd,t)}`)} from ${l.info(s.name)} to ${l.info(c.name)}. Continue?`});f||(a.info("Migration cancelled."),process.exit(0)),c.package&&await te([c.package],e,{silent:!1});let d=y("Migrating icons...")?.start();await Promise.all(r.map(async p=>{d.text=`Migrating ${p}...`;let u=de.join(t,p),b=await De.readFile(u,"utf-8"),S=await ji(b,o.sourceLibrary,o.targetLibrary,i);await De.writeFile(u,S)})),d.succeed("Migration complete.")}async function ji(e,t,r,i){let n=R[t]?.import,o=R[r]?.import,s=await De.mkdtemp(de.join(vi(),"shadcn-")),c=new Ei({compilerOptions:{}}),f=de.join(s,`shadcn-icons-${Ri(4).toString("hex")}.tsx`),d=c.createSourceFile(f,e,{scriptKind:Ti.TSX}),p=[];for(let u of d.getImportDeclarations()??[])if(u.getModuleSpecifier()?.getText()===`"${n}"`){for(let b of u.getNamedImports()??[]){let S=b.getName(),N=Object.values(i).find(A=>A[t]===S)?.[r];!N||p.includes(N)||(p.push(N),b.remove(),d.getDescendantsOfKind(ki.JsxSelfClosingElement).filter(A=>A.getTagNameNode()?.getText()===S).forEach(A=>A.getTagNameNode()?.replaceWithText(N)))}u.getNamedImports()?.length===0&&u.remove()}return p.length>0&&d.addImportDeclaration({moduleSpecifier:o,namedImports:p.map(u=>({name:u}))}),await d.getText()}import At from"path";import _e from"fs-extra";async function Ft(e){let t={};if(!_e.existsSync(e.cwd)||!_e.existsSync(At.resolve(e.cwd,"package.json")))return t[I]=!0,{errors:t,config:null};if(!_e.existsSync(At.resolve(e.cwd,"components.json")))return t[j]=!0,{errors:t,config:null};try{let r=await C(e.cwd);return{errors:t,config:r}}catch{a.break(),a.error(`An invalid ${l.info("components.json")} file was found at ${l.info(e.cwd)}.
29
+ Before you can run a migration, you must create a valid ${l.info("components.json")} file by running the ${l.info("init")} command.`),a.error(`Learn more at ${l.info("https://ui.shadcn.com/docs/components-json")}.`),a.break(),process.exit(1)}}import{Command as $i}from"commander";import{z as ge}from"zod";var Dt=[{name:"icons",description:"migrate your ui components to a different icon library."}],Li=ge.object({cwd:ge.string(),list:ge.boolean(),migration:ge.string().refine(e=>e&&Dt.some(t=>t.name===e),{message:"You must specify a valid migration. Run `shadcn migrate --list` to see available migrations."}).optional()}),_t=new $i().name("migrate").description("run a migration.").argument("[migration]","the migration to run.").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).option("-l, --list","list all migrations.",!1).action(async(e,t)=>{try{let r=Li.parse({cwd:Oi.resolve(t.cwd),migration:e,list:t.list});if(r.list||!r.migration){a.info("Available migrations:");for(let o of Dt)a.info(`- ${o.name}: ${o.description}`);return}if(!r.migration)throw new Error("You must specify a migration. Run `shadcn migrate --list` to see available migrations.");let{errors:i,config:n}=await Ft(r);if(i[I]||i[j])throw new Error("No `components.json` file found. Ensure you are at the root of your project.");if(!n)throw new Error("Something went wrong reading your `components.json` file. Please ensure you have a valid `components.json` file.");r.migration==="icons"&&await Nt(n)}catch(r){a.break(),x(r)}});import{Command as Ai}from"commander";var Kt={name:"shadcn",version:"2.1.7",description:"Add components to your apps.",publishConfig:{access:"public"},license:"MIT",author:{name:"shadcn",url:"https://twitter.com/shadcn"},repository:{type:"git",url:"https://github.com/shadcn/ui.git",directory:"packages/shadcn"},files:["dist"],keywords:["components","ui","tailwind","radix-ui","shadcn"],type:"module",exports:"./dist/index.js",bin:"./dist/index.js",scripts:{dev:"tsup --watch",build:"tsup",typecheck:"tsc --noEmit",clean:"rimraf dist && rimraf components","start:dev":"cross-env REGISTRY_URL=http://localhost:3333/r node dist/index.js","start:prod":"cross-env REGISTRY_URL=https://ui.shadcn.com/r node dist/index.js",start:"node dist/index.js","format:write":'prettier --write "**/*.{ts,tsx,mdx}" --cache',"format:check":'prettier --check "**/*.{ts,tsx,mdx}" --cache',release:"changeset version","pub:beta":"pnpm build && pnpm publish --no-git-checks --access public --tag beta","pub:next":"pnpm build && pnpm publish --no-git-checks --access public --tag next","pub:release":"pnpm build && pnpm publish --access public",test:"vitest run","test:dev":"REGISTRY_URL=http://localhost:3333/r vitest run"},dependencies:{"@antfu/ni":"^0.21.4","@babel/core":"^7.22.1","@babel/parser":"^7.22.6","@babel/plugin-transform-typescript":"^7.22.5",commander:"^10.0.0",cosmiconfig:"^8.1.3",deepmerge:"^4.3.1",diff:"^5.1.0",execa:"^7.0.0","fast-glob":"^3.3.2","fs-extra":"^11.1.0","https-proxy-agent":"^6.2.0",kleur:"^4.1.5","lodash.template":"^4.5.0","node-fetch":"^3.3.0",ora:"^6.1.2",postcss:"^8.4.24",prompts:"^2.4.2",recast:"^0.23.2","stringify-object":"^5.0.0","ts-morph":"^18.0.0","tsconfig-paths":"^4.2.0",zod:"^3.20.2"},devDependencies:{"@types/babel__core":"^7.20.1","@types/diff":"^5.0.3","@types/fs-extra":"^11.0.1","@types/lodash.template":"^4.5.1","@types/prompts":"^2.4.2","@types/stringify-object":"^4.0.5",rimraf:"^6.0.1",tsup:"^6.6.3","type-fest":"^3.8.0",typescript:"^4.9.3"}};process.on("SIGINT",()=>process.exit(0));process.on("SIGTERM",()=>process.exit(0));async function Fi(){let e=new Ai().name("shadcn").description("add components and dependencies to your project").version(Kt.version||"1.0.0","-v, --version","display the version number");e.addCommand(Rt).addCommand(kt).addCommand(Ot).addCommand(_t).addCommand($t),e.parse()}Fi();
30
30
  //# sourceMappingURL=index.js.map