shadcn 0.0.0-beta.2f496b3 → 0.0.0-beta.422c8b4
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/README.md +5 -5
- package/dist/index.js +20 -15
- package/dist/index.js.map +1 -1
- package/package.json +5 -4
package/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# shadcn
|
|
1
|
+
# shadcn
|
|
2
2
|
|
|
3
3
|
A CLI for adding components to your project.
|
|
4
4
|
|
|
@@ -9,7 +9,7 @@ Use the `init` command to initialize dependencies for a new project.
|
|
|
9
9
|
The `init` command installs dependencies, adds the `cn` util, configures `tailwind.config.js`, and CSS variables for the project.
|
|
10
10
|
|
|
11
11
|
```bash
|
|
12
|
-
npx shadcn
|
|
12
|
+
npx shadcn init
|
|
13
13
|
```
|
|
14
14
|
|
|
15
15
|
## add
|
|
@@ -19,19 +19,19 @@ Use the `add` command to add components to your project.
|
|
|
19
19
|
The `add` command adds a component to your project and installs all required dependencies.
|
|
20
20
|
|
|
21
21
|
```bash
|
|
22
|
-
npx shadcn
|
|
22
|
+
npx shadcn add [component]
|
|
23
23
|
```
|
|
24
24
|
|
|
25
25
|
### Example
|
|
26
26
|
|
|
27
27
|
```bash
|
|
28
|
-
npx shadcn
|
|
28
|
+
npx shadcn add alert-dialog
|
|
29
29
|
```
|
|
30
30
|
|
|
31
31
|
You can also run the command without any arguments to view a list of all available components:
|
|
32
32
|
|
|
33
33
|
```bash
|
|
34
|
-
npx shadcn
|
|
34
|
+
npx shadcn add
|
|
35
35
|
```
|
|
36
36
|
|
|
37
37
|
## Documentation
|
package/dist/index.js
CHANGED
|
@@ -1,22 +1,27 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import
|
|
3
|
-
To start over, remove the ${l.info("components.json")} file and run ${l.info("init")} again.`),
|
|
2
|
+
import ni from"path";import{promises as qr}from"fs";import wt from"path";import _e from"path";var C="1";var k="3";var pe="5",me="6",$e="7";import fe from"path";var I={"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 _ from"path";import{cyan as Ft,green as At,red as Dt,yellow as Lt}from"kleur/colors";var l={error:Dt,warn:Lt,info:Ft,success:At};import{createMatchPath as _t}from"tsconfig-paths";async function T(e,t){return _t(t.absoluteBaseUrl,t.paths)(e,void 0,()=>!0,[".ts",".tsx"])}import{cosmiconfig as zt}from"cosmiconfig";import{loadConfig as Kt}from"tsconfig-paths";import{z as h}from"zod";var Oe="@/components",Ne="@/lib/utils",Fe="app/globals.css",Ae="tailwind.config.js";var Mt=zt("components",{searchPlaces:["components.json"]}),z=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()})}).strict(),Wt=z.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 v(e){let t=await Vt(e);return t?await K(e,t):null}async function K(e,t){let r=await Kt(e);if(r.resultType==="failed")throw new Error(`Failed to load ${t.tsx?"tsconfig":"jsconfig"}.json. ${r.message??""}`.trim());return Wt.parse({...t,resolvedPaths:{cwd:e,tailwindConfig:_.resolve(e,t.tailwind.config),tailwindCss:_.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):_.resolve(await T(t.aliases.components,r)??e,"ui"),lib:t.aliases.lib?await T(t.aliases.lib,r):_.resolve(await T(t.aliases.utils,r)??e,".."),hooks:t.aliases.hooks?await T(t.aliases.hooks,r):_.resolve(await T(t.aliases.components,r)??e,"..","hooks")}})}async function Vt(e){try{let t=await Mt.search(e);return t?z.parse(t.config):null}catch{let r=`${e}/components.json`;throw new Error(`Invalid configuration found in ${l.info(r)}.`)}}import Ut from"path";import Gt from"fs-extra";function De(e="",t=!0){let r=Ut.join(e,"package.json");return Gt.readJSONSync(r,{throws:t})}import J from"fast-glob";import de from"fs-extra";import{loadConfig as Bt}from"tsconfig-paths";var Y=["**/node_modules/**",".next","public","dist","build"];async function O(e){let[t,r,i,n,o,s,c]=await Promise.all([J.glob("**/{next,vite,astro}.config.*|gatsby-config.*|composer.json",{cwd:e,deep:3,ignore:Y}),de.pathExists(fe.resolve(e,"src")),Xt(e),Yt(e),Jt(e),Qt(e),De(e,!1)]),f=await de.pathExists(fe.resolve(e,`${r?"src/":""}app`)),d={framework:I.manual,isSrcDir:r,isRSC:!1,isTsx:i,tailwindConfigFile:n,tailwindCssFile:o,aliasPrefix:s};return t.find(m=>m.startsWith("next.config."))?.length?(d.framework=f?I["next-app"]:I["next-pages"],d.isRSC=f,d):t.find(m=>m.startsWith("astro.config."))?.length?(d.framework=I.astro,d):t.find(m=>m.startsWith("gatsby-config."))?.length?(d.framework=I.gatsby,d):t.find(m=>m.startsWith("composer.json"))?.length?(d.framework=I.laravel,d):Object.keys(c?.dependencies??{}).find(m=>m.startsWith("@remix-run/"))?(d.framework=I.remix,d):(t.find(m=>m.startsWith("vite.config."))?.length&&(d.framework=I.vite),d)}async function Jt(e){let t=await J.glob(["**/*.css","**/*.scss"],{cwd:e,deep:5,ignore:Y});if(!t.length)return null;for(let r of t)if((await de.readFile(fe.resolve(e,r),"utf8")).includes("@tailwind base"))return r;return null}async function Yt(e){let t=await J.glob("tailwind.config.*",{cwd:e,deep:3,ignore:Y});return t.length?t[0]:null}async function Qt(e){let t=await Bt(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 Xt(e){return(await J.glob("tsconfig.*",{cwd:e,deep:1,ignore:Y})).length>0}async function Le(e,t=null){let[r,i]=await Promise.all([v(e),t?Promise.resolve(t):O(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:""},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 K(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 Ht from"ora";function y(e,t){return Ht({text:e,isSilent:t?.silent})}import ge from"fs-extra";async function ze(e){let t={};if(!ge.existsSync(e.cwd)||!ge.existsSync(_e.resolve(e.cwd,"package.json")))return t[C]=!0,{errors:t,projectInfo:null};let r=y("Preflight checks.",{silent:e.silent}).start();ge.existsSync(_e.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 O(e.cwd);(!n||n?.framework.name==="manual")&&(t[$e]=!0,i?.fail(),a.break(),n?.framework.links.installation&&a.error(`We could not detect a supported framework at ${l.info(e.cwd)}.
|
|
4
4
|
Visit ${l.info(n?.framework.links.installation)} to manually configure your project.
|
|
5
|
-
Once configured, you can use the cli to add components.`),
|
|
6
|
-
`),
|
|
7
|
-
`),
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
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[pe]=!0,o?.fail()):o?.succeed();let s=y("Validating import alias.",{silent:e.silent}).start();return n?.aliasPrefix?s?.succeed():(t[me]=!0,s?.fail()),Object.keys(t).length>0&&(t[pe]&&(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[me]&&(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 qt}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 qt.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 mr from"path";import{z as p}from"zod";var Ke=p.enum(["registry:style","registry:lib","registry:example","registry:block","registry:component","registry:ui","registry:hook","registry:theme","registry:page"]),Me=p.object({path:p.string(),content:p.string().optional(),type:Ke,target:p.string().optional()}),Zt=p.object({config:p.object({content:p.array(p.string()).optional(),theme:p.record(p.string(),p.any()).optional(),plugins:p.array(p.string()).optional()}).optional()}),er=p.object({light:p.record(p.string(),p.string()).optional(),dark:p.record(p.string(),p.string()).optional()}),L=p.object({name:p.string(),type:Ke,description:p.string().optional(),dependencies:p.array(p.string()).optional(),devDependencies:p.array(p.string()).optional(),registryDependencies:p.array(p.string()).optional(),files:p.array(Me).optional(),tailwind:Zt.optional(),cssVars:er.optional(),meta:p.record(p.string(),p.any()).optional(),docs:p.string().optional()}),ue=p.array(L.extend({files:p.array(p.union([p.string(),Me])).optional()})),We=p.array(p.object({name:p.string(),label:p.string()})),Ve=p.record(p.string(),p.record(p.string(),p.string())),Ue=p.object({inlineColors:p.object({light:p.record(p.string(),p.string()),dark:p.record(p.string(),p.string())}),cssVars:p.object({light:p.record(p.string(),p.string()),dark:p.record(p.string(),p.string())}),inlineColorsTemplate:p.string(),cssVarsTemplate:p.string()}),Ge=L.pick({dependencies:!0,devDependencies:!0,files:!0,tailwind:!0,cssVars:!0,docs:!0});import{promises as he}from"fs";import{tmpdir as tr}from"os";import M from"path";import rr from"deepmerge";import ir from"stringify-object";import{Project as nr,QuoteKind as or,ScriptKind as Be,SyntaxKind as u}from"ts-morph";async function Je(e,t,r){if(!e)return;r={silent:!1,...r};let i=M.relative(t.resolvedPaths.cwd,t.resolvedPaths.tailwindConfig),n=y(`Updating ${l.info(i)}`,{silent:r.silent}).start(),o=await he.readFile(t.resolvedPaths.tailwindConfig,"utf8"),s=await sr(o,e,t);await he.writeFile(t.resolvedPaths.tailwindConfig,s,"utf8"),n?.succeed()}async function sr(e,t,r){let i=await Q(e,r),n=i.getDescendantsOfKind(u.ObjectLiteralExpression).find(s=>s.getProperties().some(c=>c.isKind(u.PropertyAssignment)&&c.getName()==="content"));if(!n)return e;let o=ye(n);return ar(n,{name:"darkMode",value:"class"},{quoteChar:o}),t.plugins?.forEach(s=>{cr(n,s)}),t.theme&&await lr(n,t.theme),i.getFullText()}function ar(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 lr(e,t){e.getProperty("theme")||e.addPropertyAssignment({name:"theme",initializer:"{}"}),Ye(e);let i=(e.getPropertyOrThrow("theme")?.asKindOrThrow(u.PropertyAssignment)).getInitializer();if(i?.isKind(u.ObjectLiteralExpression)){let n=i.getText(),o=await pr(n),s=rr(o,t),c=ir(s).replace(/\'\"/g,"'").replace(/\"\'/g,"'").replace(/\'\[/g,"[").replace(/\]\'/g,"]").replace(/\'\\\'/g,"'").replace(/\\\'/g,"'").replace(/\\\'\'/g,"'").replace(/\'\'/g,"'");i.replaceWithText(c)}Qe(e)}function cr(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 he.mkdtemp(M.join(tr(),"shadcn-")),i=t?.resolvedPaths?.tailwindConfig||"tailwind.config.ts",n=M.join(r,`shadcn-${M.basename(i)}`);return new nr({compilerOptions:{}}).createSourceFile(n,e,{scriptKind:M.extname(i)===".ts"?Be.TS:Be.JS})}function ye(e){return e.getFirstDescendantByKind(u.StringLiteral)?.getQuoteKind()===or.Single?"'":'"'}function Ye(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)&&Ye(o.asKindOrThrow(u.ObjectLiteralExpression))}}}function Qe(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)&&Qe(o)}}}async function pr(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 Xe(n)}throw new Error("Invalid input: not an object literal")}function Xe(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]=Xe(r.getInitializer()):t[i]=He(r.getInitializer())}return t}function He(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(He);default:return e.getText()}}function qe(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 W from"deepmerge";import{HttpsProxyAgent as fr}from"https-proxy-agent";import dr from"node-fetch";import{z as gr}from"zod";var ur=process.env.REGISTRY_URL??"https://ui.shadcn.com/r",hr=process.env.https_proxy?new fr(process.env.https_proxy):void 0;async function V(){try{let[e]=await E(["index.json"]);return ue.parse(e)}catch(e){a.error(`
|
|
6
|
+
`),x(e)}}async function we(){try{let[e]=await E(["styles/index.json"]);return We.parse(e)}catch(e){return a.error(`
|
|
7
|
+
`),x(e),[]}}async function Ze(){try{let[e]=await E(["icons/index.json"]);return Ve.parse(e)}catch(e){return x(e),{}}}async function et(e,t){try{let[r]=await E([be(e)?e:`styles/${t}/${e}.json`]);return L.parse(r)}catch(r){return a.break(),x(r),null}}async function xe(){return[{name:"neutral",label:"Neutral"},{name:"gray",label:"Gray"},{name:"zinc",label:"Zinc"},{name:"stone",label:"Stone"},{name:"slate",label:"Slate"}]}async function U(e){try{let[t]=await E([`colors/${e}.json`]);return Ue.parse(t)}catch(t){x(t)}}async function tt(e,t){try{let r=t.map(n=>`styles/${e}/${n.name}.json`),i=await E(r);return ue.parse(i)}catch(r){x(r)}}async function rt(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?mr.join(e.resolvedPaths[i],n):null}async function E(e){try{return await Promise.all(e.map(async r=>{let i=ot(r),n=await dr(i,{agent:hr});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 it(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 nt(e,t){try{if(!await V())return null;e.includes("index")&&e.unshift("index");let i=[];for(let m of e){let g=await yr(m,t);i.push(...g)}let n=Array.from(new Set(i)),o=await E(n),s=gr.array(L).parse(o);if(!s)return null;if(e.includes("index")&&t.tailwind.baseColor){let m=await wr(t.tailwind.baseColor,t);m&&s.unshift(m)}let c={};s.forEach(m=>{c=W(c,m.tailwind??{})});let f={};s.forEach(m=>{f=W(f,m.cssVars??{})});let d="";return s.forEach(m=>{m.docs&&(d+=`${m.docs}
|
|
13
|
+
`)}),Ge.parse({dependencies:W.all(s.map(m=>m.dependencies??[])),devDependencies:W.all(s.map(m=>m.devDependencies??[])),files:W.all(s.map(m=>m.files??[])),tailwind:c,cssVars:f,docs:d})}catch(r){return x(r),null}}async function yr(e,t){let r=new Set,i=[];async function n(o){let s=ot(be(o)?o:`styles/${t.style}/${o}.json`);if(!r.has(s)){r.add(s);try{let[c]=await E([s]),f=L.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 wr(e,t){let r=await U(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,...qe(r.cssVars.dark)},i.cssVars={light:{...r.cssVars.light,...i.cssVars.light},dark:{...r.cssVars.dark,...i.cssVars.dark}}),i}function ot(e){if(be(e)){let t=new URL(e);return t.pathname.match(/\/chat\/b\//)&&!t.pathname.endsWith("/json")&&(t.pathname=`${t.pathname}/json`),t.toString()}return`${ur}/${e}`}function be(e){try{return new URL(e),!0}catch{return!1}}import{promises as st}from"fs";import xr from"path";import N from"postcss";import br 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=xr.relative(t.resolvedPaths.cwd,i),o=y(`Updating ${l.info(n)}`,{silent:r.silent}).start(),s=await st.readFile(i,"utf8"),c=await Sr(s,e,t,{cleanupDefaultNextStyles:r.cleanupDefaultNextStyles});await st.writeFile(i,c,"utf8"),o.succeed()}async function Sr(e,t,r,i){i={cleanupDefaultNextStyles:!1,...i};let n=[Pr(t)];return i.cleanupDefaultNextStyles&&n.push(vr()),r.tailwind.cssVariables&&n.push(Cr()),(await N(n).process(e,{from:void 0})).css}function Cr(){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=N.atRule({name:"layer",params:"base",raws:{semicolon:!0,between:" ",before:`
|
|
14
|
+
`}}),e.append(r)),t.forEach(({selector:i,apply:n})=>{r?.nodes?.find(s=>s.type==="rule"&&s.selector===i)||r?.append(N.rule({selector:i,nodes:[N.atRule({name:"apply",params:n,raws:{semicolon:!0,before:`
|
|
11
15
|
`}})],raws:{semicolon:!0,between:" ",before:`
|
|
12
|
-
`}}))})}}}function
|
|
13
|
-
`,between:" "}}),t.append(r)),r!==void 0&&Object.entries(e).forEach(([i,n])=>{let
|
|
14
|
-
`}}),e.append(i)),Object.entries(r).forEach(([n,s])=>{let a=`--${n.replace(/^--/,"")}`,c=I.decl({prop:a,value:s,raws:{semicolon:!0}}),m=i?.nodes.find(f=>f.type==="decl"&&f.prop===a);m?m.replaceWith(c):i?.append(c)})}import{detect as ir}from"@antfu/ni";async function J(e,{withFallback:t}={withFallback:!1}){let r=await ir({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 nr}from"execa";async function He(e,t,r){if(e=Array.from(new Set(e)),!e?.length)return;r={silent:!1,...r};let i=h("Installing dependencies.",{silent:r.silent})?.start(),n=await J(t.resolvedPaths.cwd);await nr(n,[n==="npm"?"install":"add",...e],{cwd:t.resolvedPaths.cwd}),i?.succeed()}import{existsSync as Ze,promises as qe}from"fs";import j,{basename as br}from"path";import{promises as ur}from"fs";import{tmpdir as gr}from"os";import Xe from"path";import{SyntaxKind as sr}from"ts-morph";var Y=async({sourceFile:e,config:t,baseColor:r})=>(t.tailwind?.cssVariables||!r?.inlineColors||e.getDescendantsOfKind(sr.StringLiteral).forEach(i=>{let n=i.getText();if(n){let s=ar(n.replace(/"/g,""),r.inlineColors);i.replaceWithText(`"${s.trim()}"`)}}),e);function ue(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(":"),s=n.pop(),a=n.join(":");return t.push(a??null,s??null,i??null),t}var or=["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 s of r){let[a,c,m]=ue(s),f=or.find(d=>c?.startsWith(d));if(!f){i.has(s)||i.add(s);continue}let x=c?.replace(f,"");if(x&&x in t.light){i.add([a,`${f}${t.light[x]}`].filter(Boolean).join(":")+(m?`/${m}`:"")),n.add(["dark",a,`${f}${t.dark[x]}`].filter(Boolean).join(":")+(m?`/${m}`:""));continue}i.has(s)||i.add(s)}return[...Array.from(i),...Array.from(n)].join(" ").trim()}var H=async({sourceFile:e,config:t})=>{let r=e.getImportDeclarations();for(let i of r){let n=lr(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 lr(e,t){return e.startsWith("@/registry/")?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):e}import{transformFromAstSync as cr}from"@babel/core";import{parse as pr}from"@babel/parser";import mr from"@babel/plugin-transform-typescript";import*as Q from"recast";var fr={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"]},Qe=async({sourceFile:e,config:t})=>{let r=e.getFullText();if(t.tsx)return r;let i=Q.parse(r,{parser:{parse:s=>pr(s,fr)}}),n=cr(i,r,{cloneInputAst:!1,code:!1,ast:!0,plugins:[mr],configFile:!1});if(!n||!n.ast)throw new Error("Failed to transform JSX");return Q.print(n.ast).code};import{SyntaxKind as dr}from"ts-morph";var X=async({sourceFile:e,config:t})=>{if(t.rsc)return e;let r=e.getFirstChildByKind(dr.ExpressionStatement);return r?.getText()==='"use client"'&&r.remove(),e};import{Project as hr,ScriptKind as yr}from"ts-morph";import{SyntaxKind as y}from"ts-morph";var Z=async({sourceFile:e,config:t})=>(t.tailwind?.prefix&&(e.getDescendantsOfKind(y.CallExpression).filter(r=>r.getExpression().getText()==="cva").forEach(r=>{if(r.getArguments()[0]?.isKind(y.StringLiteral)){let i=r.getArguments()[0];i&&i.replaceWithText(`"${T(i.getText()?.replace(/"/g,""),t.tailwind.prefix)}"`)}r.getArguments()[1]?.isKind(y.ObjectLiteralExpression)&&r.getArguments()[1]?.getDescendantsOfKind(y.PropertyAssignment).find(i=>i.getName()==="variants")?.getDescendantsOfKind(y.PropertyAssignment).forEach(i=>{i.getDescendantsOfKind(y.PropertyAssignment).forEach(n=>{let s=n.getInitializerIfKind(y.StringLiteral);s&&s?.replaceWithText(`"${T(s.getText()?.replace(/"/g,""),t.tailwind.prefix)}"`)})})}),e.getDescendantsOfKind(y.JsxAttribute).forEach(r=>{if(r.getName()==="className"){if(r.getInitializer()?.isKind(y.StringLiteral)){let i=r.getInitializer();i&&i.replaceWithText(`"${T(i.getText()?.replace(/"/g,""),t.tailwind.prefix)}"`)}if(r.getInitializer()?.isKind(y.JsxExpression)){let i=r.getInitializer()?.getDescendantsOfKind(y.CallExpression).find(n=>n.getExpression().getText()==="cn");i&&i.getArguments().forEach(n=>{(n.isKind(y.ConditionalExpression)||n.isKind(y.BinaryExpression))&&n.getChildrenOfKind(y.StringLiteral).forEach(s=>{s.replaceWithText(`"${T(s.getText()?.replace(/"/g,""),t.tailwind.prefix)}"`)}),n.isKind(y.StringLiteral)&&n.replaceWithText(`"${T(n.getText()?.replace(/"/g,""),t.tailwind.prefix)}"`)})}}r.getName()==="classNames"&&r.getInitializer()?.isKind(y.JsxExpression)&&r.getDescendantsOfKind(y.PropertyAssignment).forEach(i=>{if(i.getInitializer()?.isKind(y.CallExpression)){let n=i.getInitializerIfKind(y.CallExpression);n&&n.getArguments().forEach(s=>{s.isKind(y.ConditionalExpression)&&s.getChildrenOfKind(y.StringLiteral).forEach(a=>{a.replaceWithText(`"${T(a.getText()?.replace(/"/g,""),t.tailwind.prefix)}"`)}),s.isKind(y.StringLiteral)&&s.replaceWithText(`"${T(s.getText()?.replace(/"/g,""),t.tailwind.prefix)}"`)})}if(i.getInitializer()?.isKind(y.StringLiteral)&&i.getName()!=="variant"){let n=i.getInitializer();n&&n.replaceWithText(`"${T(n.getText()?.replace(/"/g,""),t.tailwind.prefix)}"`)}})})),e);function T(e,t=""){let r=e.split(" "),i=[];for(let n of r){let[s,a,c]=ue(n);s?c?i.push(`${s}:${t}${a}/${c}`):i.push(`${s}:${t}${a}`):c?i.push(`${t}${a}/${c}`):i.push(`${t}${a}`)}return i.join(" ")}var wr=new hr({compilerOptions:{}});async function xr(e){let t=await ur.mkdtemp(Xe.join(gr(),"shadcn-"));return Xe.join(t,e)}async function q(e,t=[H,X,Y,Z]){let r=await xr(e.filename),i=wr.createSourceFile(r,e.raw,{scriptKind:yr.TSX});for(let n of t)n({sourceFile:i,...e});return e.transformJsx?await Qe({sourceFile:i,...e}):i.getText()}import Sr from"prompts";async function et(e,t,r){if(!e?.length)return;r={overwrite:!1,force:!1,silent:!1,...r};let i=h("Updating files.",{silent:r.silent})?.start(),n=await z(t.tailwind.baseColor),s=[],a=[],c=[];for(let f of e){if(!f.content)continue;let x=Ue(f,t),d=br(f.path),w=j.join(x,d);f.target&&(w=j.join(t.resolvedPaths.cwd,f.target),x=j.dirname(w)),t.tsx||(w=w.replace(/\.tsx?$/,ie=>ie===".tsx"?".jsx":".js"));let W=Ze(w);if(W&&!r.overwrite){i.stop();let{overwrite:ie}=await Sr({type:"confirm",name:"overwrite",message:`The file ${l.info(d)} already exists. Would you like to overwrite?`,initial:!1});if(!ie){c.push(j.relative(t.resolvedPaths.cwd,w));continue}i?.start()}Ze(x)||await qe.mkdir(x,{recursive:!0});let ft=await q({filename:f.path,raw:f.content,config:t,baseColor:n,transformJsx:!t.tsx},[H,X,Y,Z]);await qe.writeFile(w,ft,"utf-8"),W?a.push(j.relative(t.resolvedPaths.cwd,w)):s.push(j.relative(t.resolvedPaths.cwd,w))}if(!(s.length||a.length)&&!c.length&&i?.info("No files updated."),s.length){if(i?.succeed(`Created ${s.length} ${s.length===1?"file":"files"}:`),!r.silent)for(let f of s)o.log(` - ${f}`)}else i?.stop();if(a.length&&(h(`Updated ${a.length} ${a.length===1?"file":"files"}:`,{silent:r.silent})?.info(),!r.silent))for(let f of a)o.log(` - ${f}`);if(c.length&&(h(`Skipped ${c.length} ${a.length===1?"file":"files"}:`,{silent:r.silent})?.info(),!r.silent))for(let f of c)o.log(` - ${f}`);r.silent||o.break()}async function ee(e,t,r){r={overwrite:!1,silent:!1,isNewProject:!1,...r};let i=h("Checking registry.",{silent:r.silent})?.start(),n=await Ge(e,t);if(!n)return i?.fail(),b(new Error("Failed to fetch components from registry."));i?.succeed(),await Fe(n.tailwind?.config,t,{silent:r.silent}),await Ye(n.cssVars,t,{cleanupDefaultNextStyles:r.isNewProject,silent:r.silent}),await He(n.dependencies,t,{silent:r.silent}),await et(n.files,t,{overwrite:r.overwrite,silent:r.silent})}import Cr from"path";import{execa as Pr}from"execa";import ge from"fs-extra";import tt from"prompts";async function te(e){if(!e.force){let{proceed:a}=await tt({type:"confirm",name:"proceed",message:`The path ${l.info(e.cwd)} is empty. Would you like to start a new ${l.info("Next.js")} project?`,initial:!0});if(!a)return{projectPath:null,projectName:null}}let t=await J(e.cwd),{name:r}=await tt({type:"text",name:"name",message:"What is your project named?",initial:"my-app",format:a=>a.trim(),validate:a=>a.length>128?"Name should be less than 128 characters.":!0}),i=`${e.cwd}/${r}`;try{await ge.access(e.cwd,ge.constants.W_OK)}catch{o.break(),o.error(`The path ${l.info(e.cwd)} is not writable.`),o.error(`It is likely you do not have write permissions for this folder or the path ${l.info(e.cwd)} does not exist.`),o.break(),process.exit(1)}ge.existsSync(Cr.resolve(e.cwd,r,"package.json"))&&(o.break(),o.error(`A project with the name ${l.info(r)} already exists.`),o.error("Please choose a different name and try again."),o.break(),process.exit(1));let n=h("Creating a new Next.js project. This may take a few minutes.").start(),s=["--tailwind","--eslint","--typescript","--app","--no-src-dir","--no-import-alias",`--use-${t}`];try{await Pr("npx",["create-next-app@latest",i,"--silent",...s],{cwd:e.cwd})}catch{o.break(),o.error("Something went wront 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{Command as Rr}from"commander";import he from"prompts";import{z as k}from"zod";var Tr=k.object({cwd:k.string(),yes:k.boolean(),defaults:k.boolean(),force:k.boolean(),silent:k.boolean(),isNewProject:k.boolean()}),it=new Rr().name("init").description("initialize your project and install dependencies").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).action(async e=>{try{let t=Tr.parse({cwd:rt.resolve(e.cwd),isNewProject:!1,...e});await re(t),o.log(`${l.success("Success!")} Project initialization completed.
|
|
15
|
-
You may now add components.`),
|
|
16
|
-
Before you can add components, you must create a valid ${l.info("components.json")} file by running the ${l.info("init")} command.`),
|
|
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 br||(r=N.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}`;Rr(r,o,n)})}}}function at(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()),at(e);let r=e.nodes.find(i=>i.type==="atrule"&&i.params==="(prefers-color-scheme: dark)");r&&(at(r),r.nodes.length===0&&r.remove())}}}function Rr(e,t,r){let i=e.nodes?.find(n=>n.type==="rule"&&n.selector===t);i||Object.keys(r).length>0&&(i=N.rule({selector:t,raws:{between:" ",before:`
|
|
18
|
+
`}}),e.append(i)),Object.entries(r).forEach(([n,o])=>{let s=`--${n.replace(/^--/,"")}`,c=N.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 Ir}from"@antfu/ni";async function X(e,{withFallback:t}={withFallback:!1}){let r=await Ir({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 Tr}from"execa";async function ct(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 X(t.resolvedPaths.cwd);await Tr(n,[n==="npm"?"install":"add",...e],{cwd:t.resolvedPaths.cwd}),i?.succeed()}import{existsSync as ft,promises as dt}from"fs";import $,{basename as Ur}from"path";import{promises as _r}from"fs";import{tmpdir as zr}from"os";import mt from"path";import{SyntaxKind as kr}from"ts-morph";var H=async({sourceFile:e,config:t,baseColor:r})=>(t.tailwind?.cssVariables||!r?.inlineColors||e.getDescendantsOfKind(kr.StringLiteral).forEach(i=>{let n=i.getText();if(n){let o=jr(n.replace(/"/g,""),r.inlineColors);i.replaceWithText(`"${o.trim()}"`)}}),e);function Se(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 Er=["bg-","text-","border-","ring-offset-","ring-"];function jr(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]=Se(o),d=Er.find(g=>c?.startsWith(g));if(!d){i.has(o)||i.add(o);continue}let m=c?.replace(d,"");if(m&&m in t.light){i.add([s,`${d}${t.light[m]}`].filter(Boolean).join(":")+(f?`/${f}`:"")),n.add(["dark",s,`${d}${t.dark[m]}`].filter(Boolean).join(":")+(f?`/${f}`:""));continue}i.has(o)||i.add(o)}return[...Array.from(i),...Array.from(n)].join(" ").trim()}var q=async({sourceFile:e,config:t})=>{let r=e.getImportDeclarations();for(let i of r){let n=$r(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 $r(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 Or}from"@babel/core";import{parse as Nr}from"@babel/parser";import Fr from"@babel/plugin-transform-typescript";import*as Z from"recast";var Ar={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"]},pt=async({sourceFile:e,config:t})=>{let r=e.getFullText();if(t.tsx)return r;let i=Z.parse(r,{parser:{parse:o=>Nr(o,Ar)}}),n=Or(i,r,{cloneInputAst:!1,code:!1,ast:!0,plugins:[Fr],configFile:!1});if(!n||!n.ast)throw new Error("Failed to transform JSX");return Z.print(n.ast).code};import{SyntaxKind as Dr}from"ts-morph";var Lr=/^["']use client["']$/g,ee=async({sourceFile:e,config:t})=>{if(t.rsc)return e;let r=e.getFirstChildByKind(Dr.ExpressionStatement);return r&&Lr.test(r.getText())&&r.remove(),e};import{Project as Kr,ScriptKind as Mr}from"ts-morph";import{SyntaxKind as w}from"ts-morph";var te=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(`"${j(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(`"${j(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(`"${j(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(`"${j(o.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`)}),n.isKind(w.StringLiteral)&&n.replaceWithText(`"${j(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(`"${j(s.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`)}),o.isKind(w.StringLiteral)&&o.replaceWithText(`"${j(o.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`)})}if(i.getInitializer()?.isKind(w.StringLiteral)&&i.getName()!=="variant"){let n=i.getInitializer();n&&n.replaceWithText(`"${j(n.getText()?.replace(/"|'/g,""),t.tailwind.prefix)}"`)}})})),e);function j(e,t=""){let r=e.split(" "),i=[];for(let n of r){let[o,s,c]=Se(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 Wr=new Kr({compilerOptions:{}});async function Vr(e){let t=await _r.mkdtemp(mt.join(zr(),"shadcn-"));return mt.join(t,e)}async function re(e,t=[q,ee,H,te]){let r=await Vr(e.filename),i=Wr.createSourceFile(r,e.raw,{scriptKind:Mr.TSX});for(let n of t)n({sourceFile:i,...e});return e.transformJsx?await pt({sourceFile:i,...e}):i.getText()}import Gr from"prompts";function Br(e,t,r){return r.startsWith("~/")?$.join(t.resolvedPaths.cwd,r.replace("~/","")):e?.isSrcDir?$.join(t.resolvedPaths.cwd,"src",r):$.join(t.resolvedPaths.cwd,r)}async function gt(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([O(t.resolvedPaths.cwd),U(t.tailwind.baseColor)]),s=[],c=[],f=[];for(let m of e){if(!m.content)continue;let g=it(m,t),b=Ur(m.path),S=$.join(g,b);m.target&&(S=Br(n,t,m.target),g=$.dirname(S)),t.tsx||(S=S.replace(/\.tsx?$/,B=>B===".tsx"?".jsx":".js"));let A=ft(S);if(A&&!r.overwrite){i.stop();let{overwrite:B}=await Gr({type:"confirm",name:"overwrite",message:`The file ${l.info(b)} already exists. Would you like to overwrite?`,initial:!1});if(!B){f.push($.relative(t.resolvedPaths.cwd,S));continue}i?.start()}ft(g)||await dt.mkdir(g,{recursive:!0});let je=await re({filename:m.path,raw:m.content,config:t,baseColor:o,transformJsx:!t.tsx},[q,ee,H,te]);await dt.writeFile(S,je,"utf-8"),A?c.push($.relative(t.resolvedPaths.cwd,S)):s.push($.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 m of s)a.log(` - ${m}`)}else i?.stop();if(c.length&&(y(`Updated ${c.length} ${c.length===1?"file":"files"}:`,{silent:r.silent})?.info(),!r.silent))for(let m of c)a.log(` - ${m}`);if(f.length&&(y(`Skipped ${f.length} ${c.length===1?"file":"files"}:`,{silent:r.silent})?.info(),!r.silent))for(let m of f)a.log(` - ${m}`);r.silent||a.break()}async function ie(e,t,r){r={overwrite:!1,silent:!1,isNewProject:!1,...r};let i=y("Checking registry.",{silent:r.silent})?.start(),n=await nt(e,t);if(!n)return i?.fail(),x(new Error("Failed to fetch components from registry."));i?.succeed(),await Je(n.tailwind?.config,t,{silent:r.silent}),await lt(n.cssVars,t,{cleanupDefaultNextStyles:r.isNewProject,silent:r.silent}),await ct(n.dependencies,t,{silent:r.silent}),await gt(n.files,t,{overwrite:r.overwrite,silent:r.silent}),n.docs&&a.info(n.docs)}import Jr from"path";import{execa as Yr}from"execa";import Ce from"fs-extra";import ut from"prompts";async function ne(e){if(e={srcDir:!1,...e},!e.force){let{proceed:s}=await ut({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 X(e.cwd,{withFallback:!0}),{name:r}=await ut({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 Ce.access(e.cwd,Ce.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)}Ce.existsSync(Jr.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 Yr("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 ht}from"fs";import Qr from"path";import{SyntaxKind as oe}from"ts-morph";async function yt(e,t,r){if(!e)return;r={silent:!1,...r};let i=Qr.relative(t.resolvedPaths.cwd,t.resolvedPaths.tailwindConfig),n=y(`Updating ${l.info(i)}`,{silent:r.silent}).start(),o=await ht.readFile(t.resolvedPaths.tailwindConfig,"utf8"),s=await Xr(o,e,t);await ht.writeFile(t.resolvedPaths.tailwindConfig,s,"utf8"),n?.succeed()}async function Xr(e,t,r){let i=await Q(e,r),n=i.getDescendantsOfKind(oe.ObjectLiteralExpression).find(o=>o.getProperties().some(s=>s.isKind(oe.PropertyAssignment)&&s.getName()==="content"));return n?(Hr(n,t),i.getFullText()):e}async function Hr(e,t){let r=ye(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(oe.PropertyAssignment)){let n=i.getInitializer();if(n?.isKind(oe.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 Zr}from"commander";import Pe from"prompts";import{z as R}from"zod";var ei=R.object({cwd:R.string(),components:R.array(R.string()).optional(),yes:R.boolean(),defaults:R.boolean(),force:R.boolean(),silent:R.boolean(),isNewProject:R.boolean(),srcDir:R.boolean().optional()}),xt=new Zr().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=ei.parse({cwd:wt.resolve(t.cwd),isNewProject:!1,components:e,...t});await se(r),a.log(`${l.success("Success!")} Project initialization completed.
|
|
19
|
+
You may now add components.`),a.break()}catch(r){a.break(),x(r)}});async function se(e){let t;if(e.skipPreflight)t=await O(e.cwd);else{let f=await ze(e);if(f.errors[C]){let{projectPath:d}=await ne(e);d||process.exit(1),e.cwd=d,e.isNewProject=!0}t=f.projectInfo}let r=await Le(e.cwd,t),i=r?await ri(r,e):await ti(await v(e.cwd));if(!e.yes){let{proceed:f}=await Pe({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=wt.resolve(e.cwd,"components.json");await qr.writeFile(o,JSON.stringify(i,null,2),"utf8"),n.succeed();let s=await K(e.cwd,i),c=["index",...e.components||[]];return await ie(c,s,{overwrite:!0,silent:e.silent,isNewProject:e.isNewProject||t?.framework.name==="next-app"}),e.isNewProject&&e.srcDir&&await yt(["./src/**/*.{js,ts,jsx,tsx,mdx}"],s,{silent:e.silent}),s}async function ti(e=null){let[t,r]=await Promise.all([we(),xe()]);a.info("");let i=await Pe([{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??Fe},{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??Ae},{type:"text",name:"components",message:`Configure the import alias for ${l.info("components")}:`,initial:e?.aliases.components??Oe},{type:"text",name:"utils",message:`Configure the import alias for ${l.info("utils")}:`,initial:e?.aliases.utils??Ne},{type:"toggle",name:"rsc",message:`Are you using ${l.info("React Server Components")}?`,initial:e?.rsc??!0,active:"yes",inactive:"no"}]);return z.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 ri(e,t){let r=e.style,i=e.tailwind.baseColor,n=e.tailwind.cssVariables;if(!t.defaults){let[o,s]=await Promise.all([we(),xe()]),c=await Pe([{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 z.parse({$schema:e?.$schema,style:r,tailwind:{...e?.tailwind,baseColor:i,cssVariables:n},rsc:e?.rsc,tsx:e?.tsx,aliases:e?.aliases})}import bt from"path";import ve from"fs-extra";async function St(e){let t={};if(!ve.existsSync(e.cwd)||!ve.existsSync(bt.resolve(e.cwd,"package.json")))return t[C]=!0,{errors:t,config:null};if(!ve.existsSync(bt.resolve(e.cwd,"components.json")))return t[k]=!0,{errors:t,config:null};try{let r=await v(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)}.
|
|
20
|
+
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 Ct from"fs/promises";import ii from"path";async function Pt(e,t){let r=ii.join(t.resolvedPaths.cwd,"app/page.tsx");if(!(await Ct.stat(r)).isFile())return;let i=await et(e,t.style);if(!i?.meta?.importSpecifier||!i?.meta?.moduleSpecifier)return;let n=`import { ${i?.meta?.importSpecifier} } from "${i.meta.moduleSpecifier}"
|
|
17
21
|
|
|
18
22
|
export default function Page() {
|
|
19
23
|
return <${i?.meta?.importSpecifier} />
|
|
20
|
-
}`;await
|
|
21
|
-
Existing CSS variables will be overwritten. Continue?`)});c||(
|
|
24
|
+
}`;await Ct.writeFile(r,n,"utf8")}import{Command as oi}from"commander";import Re from"prompts";import{z as P}from"zod";var si=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()}),vt=new oi().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=si.parse({components:e,cwd:ni.resolve(t.cwd),...t}),i=r.components?.some(c=>c.includes("theme-"));if(!r.yes&&i){a.break();let{confirm:c}=await Re({type:"confirm",name:"confirm",message:l.warn(`You are about to install a new theme.
|
|
25
|
+
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 ai(r));let{errors:n,config:o}=await St(r);if(n[k]){let{proceed:c}=await Re({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 se({cwd:r.cwd,yes:!0,force:!0,defaults:!1,skipPreflight:!1,silent:!0,isNewProject:!1,srcDir:r.srcDir})}let s=!1;if(n[C]){let{projectPath:c}=await ne({cwd:r.cwd,force:r.overwrite,srcDir:r.srcDir});c||(a.break(),process.exit(1)),r.cwd=c,o=await se({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 ie(r.components,o,r),s&&await Pt(r.components[0],o)}catch(r){a.break(),x(r)}});async function ai(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 Re({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 Ie,promises as li}from"fs";import Te from"path";import{Command as ci}from"commander";import{diffLines as pi}from"diff";import{z as G}from"zod";var mi=G.object({component:G.string().optional(),yes:G.boolean(),cwd:G.string(),path:G.string().optional()}),It=new ci().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=mi.parse({component:e,...t}),i=Te.resolve(r.cwd);Ie(i)||(a.error(`The path ${i} does not exist. Please try again.`),process.exit(1));let n=await v(i);n||(a.warn(`Configuration is missing. Please run ${l.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=Te.resolve(f,typeof b=="string"?b:b.path);if(Ie(S))return!0}return!1}),m=[];for(let g of d){let b=await Rt(g,n);b.length&&m.push({name:g.name,changes:b})}m.length||(a.info("No updates found."),process.exit(0)),a.info("The following components have updates available:");for(let g of m){a.info(`- ${g.name}`);for(let b of g.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 Rt(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 fi(f.patch),a.info("")}catch(r){x(r)}});async function Rt(e,t){let r=await tt(t.style,[e]),i=await U(t.tailwind.baseColor);if(!r)return[];let n=[];for(let o of r){let s=await rt(t,o);if(s)for(let c of o.files??[]){let f=Te.resolve(s,typeof c=="string"?c:c.path);if(!Ie(f))continue;let d=await li.readFile(f,"utf8");if(typeof c=="string"||!c.content)continue;let m=await re({filename:c.path,raw:c.content,config:t,baseColor:i}),g=pi(m,d);g.length>1&&n.push({filePath:f,patch:g})}}return n}async function fi(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 bi from"path";import{randomBytes as di}from"crypto";import{promises as ke}from"fs";import{tmpdir as gi}from"os";import ae from"path";import ui from"fast-glob";import Tt from"prompts";import{Project as hi,ScriptKind as yi,SyntaxKind as wi}from"ts-morph";var F={lucide:"lucide-react",radix:"@radix-ui/react-icons"};async function kt(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([ui("**/*.{js,ts,jsx,tsx}",{cwd:t}),Ze()]);if(Object.keys(i).length===0)throw new Error("Something went wrong fetching the registry icons.");let n=Object.entries(F).map(([m,g])=>({title:g,value:m})),o=await Tt([{type:"select",name:"sourceLibrary",message:`Which icon library would you like to ${l.info("migrate from")}?`,choices:[...n].reverse(),initial:0},{type:"select",name:"targetLibrary",message:`Which icon library would you like to ${l.info("migrate to")}?`,choices:n,initial:0}]);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 F&&o.targetLibrary in F))throw new Error("Invalid icon library. Please choose a valid icon library.");let s=F[o.sourceLibrary],c=F[o.targetLibrary],{confirm:f}=await Tt({type:"confirm",name:"confirm",initial:!0,message:`We will migrate ${l.info(r.length)} files in ${l.info(`./${ae.relative(e.resolvedPaths.cwd,t)}`)} from ${l.info(s)} to ${l.info(c)}. Continue?`});f||(a.info("Migration cancelled."),process.exit(0));let d=y("Migrating icons...")?.start();await Promise.all(r.map(async m=>{d.text=`Migrating ${m}...`;let g=ae.join(t,m),b=await ke.readFile(g,"utf-8"),S=await xi(b,o.sourceLibrary,o.targetLibrary,i);await ke.writeFile(g,S)})),d.succeed("Migration complete.")}async function xi(e,t,r,i){let n=F[t],o=F[r],s=await ke.mkdtemp(ae.join(gi(),"shadcn-")),c=new hi({compilerOptions:{}}),f=ae.join(s,`shadcn-icons-${di(4).toString("hex")}.tsx`),d=c.createSourceFile(f,e,{scriptKind:yi.TSX}),m=[];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(ce=>ce[t]===S)?.[r];if(!A)continue;m.push(A),b.remove(),d.getDescendantsOfKind(wi.JsxSelfClosingElement).find(ce=>ce.getTagNameNode()?.getText()===S)?.getTagNameNode()?.replaceWithText(A)}g.getNamedImports()?.length===0&&g.remove()}return m.length>0&&d.addImportDeclaration({moduleSpecifier:o,namedImports:m.map(g=>({name:g}))}),await d.getText()}import Et from"path";import Ee from"fs-extra";async function jt(e){let t={};if(!Ee.existsSync(e.cwd)||!Ee.existsSync(Et.resolve(e.cwd,"package.json")))return t[C]=!0,{errors:t,config:null};if(!Ee.existsSync(Et.resolve(e.cwd,"components.json")))return t[k]=!0,{errors:t,config:null};try{let r=await v(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)}.
|
|
26
|
+
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 Si}from"commander";import{z as le}from"zod";var $t=[{name:"icons",description:"migrate your ui components to a different icon library."}],Ci=le.object({cwd:le.string(),list:le.boolean(),migration:le.string().refine(e=>e&&$t.some(t=>t.name===e),{message:"You must specify a valid migration. Run `shadcn migrate --list` to see available migrations."}).optional()}),Ot=new Si().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=Ci.parse({cwd:bi.resolve(t.cwd),migration:e,list:t.list});if(r.list||!r.migration){a.info("Available migrations:");for(let o of $t)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 jt(r);if(i[C]||i[k])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 kt(n)}catch(r){a.break(),x(r)}});import{Command as vi}from"commander";var Nt={name:"shadcn",version:"0.0.0-beta.422c8b4",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 Ri(){let e=new vi().name("shadcn").description("add components and dependencies to your project").version(Nt.version||"1.0.0","-v, --version","display the version number");e.addCommand(xt).addCommand(vt).addCommand(It).addCommand(Ot),e.parse()}Ri();
|
|
22
27
|
//# sourceMappingURL=index.js.map
|