create-shadcn-js 1.0.0 → 1.2.0
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 +118 -31
- package/SECURITY.md +25 -0
- package/package.json +15 -5
- package/src/index.js +28 -40
- package/src/options.js +53 -0
- package/src/prompts.js +30 -2
- package/src/scaffold.js +106 -19
- package/src/shadcn.js +380 -29
- package/src/templates/app.js +17 -6
- package/src/templates/configs.js +116 -7
- package/src/templates/indexCss.js +83 -0
- package/src/utils.js +263 -22
package/src/scaffold.js
CHANGED
|
@@ -2,17 +2,66 @@ import fs from "fs-extra"
|
|
|
2
2
|
import path from "node:path"
|
|
3
3
|
import * as p from "@clack/prompts"
|
|
4
4
|
import pc from "picocolors"
|
|
5
|
-
import {
|
|
5
|
+
import {
|
|
6
|
+
getCreateViteCommand,
|
|
7
|
+
getPackageManagerCommands,
|
|
8
|
+
getShadcnAddCommand,
|
|
9
|
+
runCommandOutput,
|
|
10
|
+
validateProjectName,
|
|
11
|
+
} from "./utils.js"
|
|
6
12
|
import {
|
|
7
13
|
getJsConfig,
|
|
8
14
|
getViteConfig,
|
|
9
15
|
getTailwindConfigV3,
|
|
10
16
|
getPostcssConfigV3,
|
|
17
|
+
getComponentsJsonV3,
|
|
18
|
+
getShadcnUtilsJs,
|
|
11
19
|
getIndexHtml,
|
|
12
20
|
} from "./templates/configs.js"
|
|
13
21
|
import { getIndexCss } from "./templates/indexCss.js"
|
|
14
22
|
import { getAppJsx } from "./templates/app.js"
|
|
15
23
|
|
|
24
|
+
export const TAILWIND_V4_DEPS = ["tailwindcss@4", "@tailwindcss/vite@4"]
|
|
25
|
+
|
|
26
|
+
// Tailwind v3 is a legacy path: shadcn@2.3.0 is the last CLI that emits v3
|
|
27
|
+
// components, and its install step only runs non-interactively on React 18.
|
|
28
|
+
export const TAILWIND_V3_DEPS = [
|
|
29
|
+
"tailwindcss@3.4.17",
|
|
30
|
+
"postcss@8",
|
|
31
|
+
"autoprefixer@10",
|
|
32
|
+
"tailwindcss-animate@1.0.7",
|
|
33
|
+
]
|
|
34
|
+
export const REACT_V3_DEPS = ["react@18.3.1", "react-dom@18.3.1"]
|
|
35
|
+
export const REACT_V3_DEV_DEPS = ["@types/react@18", "@types/react-dom@18"]
|
|
36
|
+
export const SHADCN_V3_RUNTIME_DEPS = [
|
|
37
|
+
"class-variance-authority@0.7.1",
|
|
38
|
+
"clsx@2",
|
|
39
|
+
// tailwind-merge v3 targets Tailwind v4; v2.6.0 is the Tailwind v3 line.
|
|
40
|
+
"tailwind-merge@2.6.0",
|
|
41
|
+
"lucide-react@1",
|
|
42
|
+
"@radix-ui/react-slot@1",
|
|
43
|
+
]
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Refuses targets that would empty the current working directory or a
|
|
47
|
+
* filesystem root. Exported for tests; scaffoldProject always calls it before
|
|
48
|
+
* touching the filesystem.
|
|
49
|
+
* @param {string} targetDir
|
|
50
|
+
* @param {string} [cwd]
|
|
51
|
+
*/
|
|
52
|
+
export function assertSafeScaffoldTarget(targetDir, cwd = process.cwd()) {
|
|
53
|
+
const resolvedTargetDir = path.resolve(targetDir)
|
|
54
|
+
const resolvedCwd = path.resolve(cwd)
|
|
55
|
+
if (
|
|
56
|
+
resolvedTargetDir === resolvedCwd ||
|
|
57
|
+
resolvedTargetDir === path.parse(resolvedTargetDir).root
|
|
58
|
+
) {
|
|
59
|
+
throw new Error(
|
|
60
|
+
`Refusing to scaffold into "${resolvedTargetDir}". Choose a project subdirectory instead.`
|
|
61
|
+
)
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
16
65
|
/**
|
|
17
66
|
* Scaffolds the base Vite + React (JavaScript) project.
|
|
18
67
|
* @param {object} options
|
|
@@ -25,6 +74,18 @@ export async function scaffoldProject({
|
|
|
25
74
|
}) {
|
|
26
75
|
const spinner = p.spinner()
|
|
27
76
|
|
|
77
|
+
const parentDir = path.dirname(targetDir)
|
|
78
|
+
const folderName = path.basename(targetDir)
|
|
79
|
+
|
|
80
|
+
const validation = validateProjectName(folderName)
|
|
81
|
+
if (typeof validation === "string") {
|
|
82
|
+
throw new Error(validation)
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// The scaffolder empties the target directory. Never do that to the current
|
|
86
|
+
// working directory or a filesystem root, even if called as a library.
|
|
87
|
+
assertSafeScaffoldTarget(targetDir)
|
|
88
|
+
|
|
28
89
|
// 1. Prepare directory
|
|
29
90
|
if (fs.existsSync(targetDir)) {
|
|
30
91
|
fs.emptyDirSync(targetDir)
|
|
@@ -32,26 +93,23 @@ export async function scaffoldProject({
|
|
|
32
93
|
fs.ensureDirSync(targetDir)
|
|
33
94
|
}
|
|
34
95
|
|
|
96
|
+
const pmCmds = getPackageManagerCommands(packageManager)
|
|
97
|
+
|
|
35
98
|
// 2. Scaffold Vite React JavaScript template
|
|
36
99
|
spinner.start("Scaffolding Vite React JavaScript project...")
|
|
37
100
|
try {
|
|
38
|
-
|
|
39
|
-
const
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
runCommandOutput(
|
|
43
|
-
"npx",
|
|
44
|
-
["--yes", "create-vite@latest", folderName, "--template", "react", "-y"],
|
|
45
|
-
{ cwd: parentDir }
|
|
101
|
+
// Run create-vite with the same package manager the project will use.
|
|
102
|
+
const [createBin, createArgs] = getCreateViteCommand(
|
|
103
|
+
packageManager,
|
|
104
|
+
folderName
|
|
46
105
|
)
|
|
106
|
+
runCommandOutput(createBin, createArgs, { cwd: parentDir })
|
|
47
107
|
spinner.stop(`${pc.green("✔")} Vite project scaffolded successfully.`)
|
|
48
108
|
} catch (error) {
|
|
49
109
|
spinner.stop(`${pc.red("✖")} Failed to scaffold Vite project.`)
|
|
50
110
|
throw error
|
|
51
111
|
}
|
|
52
112
|
|
|
53
|
-
const pmCmds = getPackageManagerCommands(packageManager)
|
|
54
|
-
|
|
55
113
|
// 3. Install base dependencies
|
|
56
114
|
spinner.start(`Installing project dependencies with ${pc.cyan(packageManager)}...`)
|
|
57
115
|
try {
|
|
@@ -63,16 +121,29 @@ export async function scaffoldProject({
|
|
|
63
121
|
throw error
|
|
64
122
|
}
|
|
65
123
|
|
|
66
|
-
// 4. Install Tailwind CSS dependencies
|
|
67
|
-
const
|
|
68
|
-
|
|
69
|
-
? ["tailwindcss", "@tailwindcss/vite"]
|
|
70
|
-
: ["tailwindcss", "postcss", "autoprefixer"]
|
|
124
|
+
// 4. Install Tailwind CSS (and legacy v3 runtime) dependencies
|
|
125
|
+
const isV3 = tailwindVersion === "v3"
|
|
126
|
+
const tailwindDeps = isV3 ? TAILWIND_V3_DEPS : TAILWIND_V4_DEPS
|
|
71
127
|
|
|
72
128
|
spinner.start(`Installing Tailwind CSS (${tailwindVersion}) dependencies...`)
|
|
73
129
|
try {
|
|
74
130
|
const [addBin, addArgs] = pmCmds.add(tailwindDeps, false)
|
|
75
131
|
runCommandOutput(addBin, addArgs, { cwd: targetDir })
|
|
132
|
+
|
|
133
|
+
if (isV3) {
|
|
134
|
+
// shadcn@2.3.0 prompts (and can hang in CI) when npm sees React 19.
|
|
135
|
+
// Tailwind v3 projects are pinned to React 18, the version that CLI
|
|
136
|
+
// and its v3 registry were built for.
|
|
137
|
+
const [reactBin, reactArgs] = pmCmds.add(REACT_V3_DEPS, false)
|
|
138
|
+
runCommandOutput(reactBin, reactArgs, { cwd: targetDir })
|
|
139
|
+
|
|
140
|
+
const [typesBin, typesArgs] = pmCmds.add(REACT_V3_DEV_DEPS, true)
|
|
141
|
+
runCommandOutput(typesBin, typesArgs, { cwd: targetDir })
|
|
142
|
+
|
|
143
|
+
const [runtimeBin, runtimeArgs] = pmCmds.add(SHADCN_V3_RUNTIME_DEPS, false)
|
|
144
|
+
runCommandOutput(runtimeBin, runtimeArgs, { cwd: targetDir })
|
|
145
|
+
}
|
|
146
|
+
|
|
76
147
|
spinner.stop(`${pc.green("✔")} Tailwind CSS (${tailwindVersion}) installed.`)
|
|
77
148
|
} catch (error) {
|
|
78
149
|
spinner.stop(`${pc.red("✖")} Failed to install Tailwind CSS dependencies.`)
|
|
@@ -92,8 +163,10 @@ export async function scaffoldProject({
|
|
|
92
163
|
"utf-8"
|
|
93
164
|
)
|
|
94
165
|
|
|
95
|
-
// For Tailwind v3, write config
|
|
96
|
-
|
|
166
|
+
// For Tailwind v3, write the legacy CLI config, theme, and JS cn helper.
|
|
167
|
+
// shadcn init is skipped entirely for v3 because shadcn@2.3.0 writes
|
|
168
|
+
// v4-flavoured (oklch) CSS variables that break a v3 theme.
|
|
169
|
+
if (isV3) {
|
|
97
170
|
fs.writeFileSync(
|
|
98
171
|
path.join(targetDir, "tailwind.config.js"),
|
|
99
172
|
getTailwindConfigV3(),
|
|
@@ -104,6 +177,17 @@ export async function scaffoldProject({
|
|
|
104
177
|
getPostcssConfigV3(),
|
|
105
178
|
"utf-8"
|
|
106
179
|
)
|
|
180
|
+
fs.writeFileSync(
|
|
181
|
+
path.join(targetDir, "components.json"),
|
|
182
|
+
getComponentsJsonV3(),
|
|
183
|
+
"utf-8"
|
|
184
|
+
)
|
|
185
|
+
fs.ensureDirSync(path.join(targetDir, "src", "lib"))
|
|
186
|
+
fs.writeFileSync(
|
|
187
|
+
path.join(targetDir, "src", "lib", "utils.js"),
|
|
188
|
+
getShadcnUtilsJs(),
|
|
189
|
+
"utf-8"
|
|
190
|
+
)
|
|
107
191
|
}
|
|
108
192
|
|
|
109
193
|
// Write src/index.css
|
|
@@ -136,7 +220,10 @@ export async function scaffoldProject({
|
|
|
136
220
|
// Write clean initial App.jsx
|
|
137
221
|
fs.writeFileSync(
|
|
138
222
|
path.join(targetDir, "src", "App.jsx"),
|
|
139
|
-
getAppJsx({
|
|
223
|
+
getAppJsx({
|
|
224
|
+
hasButton: false,
|
|
225
|
+
addCommand: getShadcnAddCommand(packageManager, tailwindVersion),
|
|
226
|
+
}),
|
|
140
227
|
"utf-8"
|
|
141
228
|
)
|
|
142
229
|
|
package/src/shadcn.js
CHANGED
|
@@ -2,22 +2,344 @@ import fs from "fs-extra"
|
|
|
2
2
|
import path from "node:path"
|
|
3
3
|
import * as p from "@clack/prompts"
|
|
4
4
|
import pc from "picocolors"
|
|
5
|
-
import {
|
|
5
|
+
import {
|
|
6
|
+
getPackageManagerCommands,
|
|
7
|
+
getShadcnAddCommand,
|
|
8
|
+
getShadcnCliPackage,
|
|
9
|
+
runCommandSync,
|
|
10
|
+
runCommandOutput,
|
|
11
|
+
sanitizeDependencies,
|
|
12
|
+
} from "./utils.js"
|
|
6
13
|
import { getAppJsx } from "./templates/app.js"
|
|
7
14
|
|
|
15
|
+
/**
|
|
16
|
+
* Reads components.json, returning null when it is missing or invalid.
|
|
17
|
+
* @param {string} targetDir
|
|
18
|
+
* @returns {object | null}
|
|
19
|
+
*/
|
|
20
|
+
function readComponentsJson(targetDir) {
|
|
21
|
+
const configPath = path.join(targetDir, "components.json")
|
|
22
|
+
if (!fs.existsSync(configPath)) return null
|
|
23
|
+
try {
|
|
24
|
+
return fs.readJsonSync(configPath)
|
|
25
|
+
} catch {
|
|
26
|
+
return null
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Resolves a project-relative path while keeping it inside the project root.
|
|
32
|
+
* @param {string} targetDir
|
|
33
|
+
* @param {string} relativePath
|
|
34
|
+
* @returns {string | null}
|
|
35
|
+
*/
|
|
36
|
+
function resolveProjectFile(targetDir, relativePath) {
|
|
37
|
+
if (typeof relativePath !== "string" || relativePath.length === 0) return null
|
|
38
|
+
const root = path.resolve(targetDir)
|
|
39
|
+
const resolved = path.resolve(root, relativePath)
|
|
40
|
+
if (!resolved.startsWith(root + path.sep)) return null
|
|
41
|
+
return resolved
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* @param {string} filePath
|
|
46
|
+
* @returns {boolean} True when the path exists and is a regular file.
|
|
47
|
+
*/
|
|
48
|
+
function isExistingFile(filePath) {
|
|
49
|
+
try {
|
|
50
|
+
return fs.statSync(filePath).isFile()
|
|
51
|
+
} catch {
|
|
52
|
+
return false
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Validates the required shape of components.json. A parseable file is not
|
|
58
|
+
* necessarily a usable one: an interrupted init can leave `{}` or a config
|
|
59
|
+
* without aliases behind.
|
|
60
|
+
* @param {unknown} config
|
|
61
|
+
* @returns {string | null} A human-readable problem, or null when valid.
|
|
62
|
+
*/
|
|
63
|
+
function validateConfigShape(config) {
|
|
64
|
+
if (!config || typeof config !== "object" || Array.isArray(config)) {
|
|
65
|
+
return "expected a JSON object"
|
|
66
|
+
}
|
|
67
|
+
if (typeof config.style !== "string" || config.style.length === 0) {
|
|
68
|
+
return 'missing "style"'
|
|
69
|
+
}
|
|
70
|
+
if (
|
|
71
|
+
!config.tailwind ||
|
|
72
|
+
typeof config.tailwind !== "object" ||
|
|
73
|
+
Array.isArray(config.tailwind)
|
|
74
|
+
) {
|
|
75
|
+
return 'missing "tailwind" configuration'
|
|
76
|
+
}
|
|
77
|
+
if (
|
|
78
|
+
typeof config.tailwind.css !== "string" ||
|
|
79
|
+
config.tailwind.css.length === 0
|
|
80
|
+
) {
|
|
81
|
+
return 'missing "tailwind.css"'
|
|
82
|
+
}
|
|
83
|
+
if (
|
|
84
|
+
!config.aliases ||
|
|
85
|
+
typeof config.aliases !== "object" ||
|
|
86
|
+
Array.isArray(config.aliases)
|
|
87
|
+
) {
|
|
88
|
+
return 'missing "aliases"'
|
|
89
|
+
}
|
|
90
|
+
for (const key of ["components", "utils", "ui"]) {
|
|
91
|
+
if (
|
|
92
|
+
typeof config.aliases[key] !== "string" ||
|
|
93
|
+
!config.aliases[key].startsWith("@/")
|
|
94
|
+
) {
|
|
95
|
+
return `invalid "aliases.${key}"`
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
return null
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Resolves the utils alias from components.json to a file inside src/.
|
|
103
|
+
* @param {string} targetDir
|
|
104
|
+
* @param {object} config
|
|
105
|
+
* @returns {{ jsPath: string, tsPath: string } | null}
|
|
106
|
+
*/
|
|
107
|
+
function resolveUtilsPaths(targetDir, config) {
|
|
108
|
+
const alias = config?.aliases?.utils
|
|
109
|
+
if (typeof alias !== "string" || !alias.startsWith("@/")) return null
|
|
110
|
+
|
|
111
|
+
const relative = alias.slice(2).replace(/\.(?:js|jsx|ts|tsx)$/, "")
|
|
112
|
+
const srcDir = path.resolve(targetDir, "src")
|
|
113
|
+
const basePath = path.resolve(srcDir, relative)
|
|
114
|
+
|
|
115
|
+
// Never write into (or outside) the src root itself: the utils alias must
|
|
116
|
+
// name a file inside src/, even if a hand-edited or registry-supplied
|
|
117
|
+
// components.json contains a traversal alias such as "@/lib/..".
|
|
118
|
+
if (!basePath.startsWith(srcDir + path.sep)) {
|
|
119
|
+
return null
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
return {
|
|
123
|
+
jsPath: `${basePath}.js`,
|
|
124
|
+
tsPath: `${basePath}.ts`,
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Verifies that the stylesheet actually received shadcn's theme variables.
|
|
130
|
+
* components.json and the CSS file can both exist after an interrupted init
|
|
131
|
+
* while the stylesheet still only imports Tailwind, which would build but
|
|
132
|
+
* render components with no theme colors. Configs that explicitly disable
|
|
133
|
+
* CSS variables intentionally use inline colors instead.
|
|
134
|
+
* @param {string} cssPath
|
|
135
|
+
* @param {object} config
|
|
136
|
+
*/
|
|
137
|
+
function validateThemeTokens(cssPath, config) {
|
|
138
|
+
if (config?.tailwind?.cssVariables === false) return
|
|
139
|
+
|
|
140
|
+
// Ignore comments so a commented-out token cannot satisfy the check, and
|
|
141
|
+
// require a value so alias lines like `--color-background: var(...)` in
|
|
142
|
+
// `@theme inline` do not masquerade as the real `:root` definition.
|
|
143
|
+
const css = fs.readFileSync(cssPath, "utf-8").replace(/\/\*[\s\S]*?\*\//g, "")
|
|
144
|
+
const missing = ["--background", "--primary"].filter(
|
|
145
|
+
(token) => !new RegExp(`${token}\\s*:\\s*[^;{}]+`).test(css)
|
|
146
|
+
)
|
|
147
|
+
if (missing.length > 0) {
|
|
148
|
+
throw new Error(
|
|
149
|
+
`shadcn/ui initialization did not finish: "${config.tailwind.css}" is missing theme variables (${missing.join(
|
|
150
|
+
", "
|
|
151
|
+
)}). Check your network connection and run the command again.`
|
|
152
|
+
)
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/**
|
|
157
|
+
* Verifies that the cn() helper only imports packages declared by the
|
|
158
|
+
* project. An init that wrote config files but failed while installing
|
|
159
|
+
* dependencies would otherwise be reported as successful.
|
|
160
|
+
* @param {string} targetDir
|
|
161
|
+
* @param {string} utilsPath
|
|
162
|
+
*/
|
|
163
|
+
function validateUtilsDependencies(targetDir, utilsPath) {
|
|
164
|
+
const packageJsonPath = path.join(targetDir, "package.json")
|
|
165
|
+
if (!fs.existsSync(packageJsonPath)) return
|
|
166
|
+
|
|
167
|
+
let pkg
|
|
168
|
+
try {
|
|
169
|
+
pkg = fs.readJsonSync(packageJsonPath)
|
|
170
|
+
} catch {
|
|
171
|
+
return
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const declared = {
|
|
175
|
+
...(pkg?.dependencies || {}),
|
|
176
|
+
...(pkg?.devDependencies || {}),
|
|
177
|
+
}
|
|
178
|
+
const utils = fs.readFileSync(utilsPath, "utf-8")
|
|
179
|
+
const required = []
|
|
180
|
+
if (/from\s+["']cn["']/.test(utils)) required.push("cn")
|
|
181
|
+
if (/from\s+["']clsx["']/.test(utils)) required.push("clsx")
|
|
182
|
+
if (/from\s+["']tailwind-merge["']/.test(utils)) required.push("tailwind-merge")
|
|
183
|
+
|
|
184
|
+
const missing = required.filter((name) => !declared[name])
|
|
185
|
+
if (missing.length > 0) {
|
|
186
|
+
throw new Error(
|
|
187
|
+
`shadcn/ui initialization did not finish: package.json is missing ${missing.join(
|
|
188
|
+
", "
|
|
189
|
+
)}. Check your network connection and run the command again.`
|
|
190
|
+
)
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/**
|
|
195
|
+
* shadcn@latest detects the project language, but a stale detection (or a
|
|
196
|
+
* preset created for TypeScript) can still leave a utils.ts behind. Make the
|
|
197
|
+
* project consistently JavaScript before any components are added.
|
|
198
|
+
* @param {string} targetDir
|
|
199
|
+
* @param {object} config
|
|
200
|
+
* @returns {string} Path to the JavaScript utils file.
|
|
201
|
+
*/
|
|
202
|
+
function ensureJavaScriptUtils(targetDir, config) {
|
|
203
|
+
const paths = resolveUtilsPaths(targetDir, config)
|
|
204
|
+
if (!paths) {
|
|
205
|
+
throw new Error(
|
|
206
|
+
'shadcn/ui initialization produced an invalid "aliases.utils" path. ' +
|
|
207
|
+
"Check your components.json and run the command again."
|
|
208
|
+
)
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
if (fs.existsSync(paths.jsPath)) {
|
|
212
|
+
if (fs.existsSync(paths.tsPath)) fs.removeSync(paths.tsPath)
|
|
213
|
+
return paths.jsPath
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
let content = `export { cn } from "cn"\n`
|
|
217
|
+
if (fs.existsSync(paths.tsPath)) {
|
|
218
|
+
const tsContent = fs.readFileSync(paths.tsPath, "utf-8")
|
|
219
|
+
// shadcn 4's utils.ts is already valid JavaScript apart from the
|
|
220
|
+
// extension. Older output imports clsx/tailwind-merge directly.
|
|
221
|
+
if (!/from\s+["']cn["']/.test(tsContent)) {
|
|
222
|
+
content = `import { clsx } from "clsx"\nimport { twMerge } from "tailwind-merge"\n\nexport function cn(...inputs) {\n return twMerge(clsx(inputs))\n}\n`
|
|
223
|
+
}
|
|
224
|
+
fs.removeSync(paths.tsPath)
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
fs.ensureDirSync(path.dirname(paths.jsPath))
|
|
228
|
+
fs.writeFileSync(paths.jsPath, content, "utf-8")
|
|
229
|
+
return paths.jsPath
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Forces components.json into JavaScript mode and verifies that the shadcn
|
|
234
|
+
* CLI actually finished writing a usable config.
|
|
235
|
+
*
|
|
236
|
+
* Exported for tests; it is intentionally side-effect only on the targetDir.
|
|
237
|
+
* @param {string} targetDir
|
|
238
|
+
* @returns {object}
|
|
239
|
+
*/
|
|
240
|
+
export function finalizeShadcnConfig(targetDir) {
|
|
241
|
+
const configPath = path.join(targetDir, "components.json")
|
|
242
|
+
const config = readComponentsJson(targetDir)
|
|
243
|
+
|
|
244
|
+
if (!config) {
|
|
245
|
+
throw new Error(
|
|
246
|
+
"shadcn/ui initialization did not finish: components.json is missing or invalid. " +
|
|
247
|
+
"Check your network connection and run the command again."
|
|
248
|
+
)
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
const shapeProblem = validateConfigShape(config)
|
|
252
|
+
if (shapeProblem) {
|
|
253
|
+
throw new Error(
|
|
254
|
+
`shadcn/ui initialization produced an invalid components.json (${shapeProblem}). ` +
|
|
255
|
+
"Check your network connection and run the command again."
|
|
256
|
+
)
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
const cssPath = resolveProjectFile(targetDir, config.tailwind.css)
|
|
260
|
+
if (!cssPath || !isExistingFile(cssPath)) {
|
|
261
|
+
throw new Error(
|
|
262
|
+
`shadcn/ui initialization did not finish: "${config.tailwind.css}" is missing. ` +
|
|
263
|
+
"Check your network connection and run the command again."
|
|
264
|
+
)
|
|
265
|
+
}
|
|
266
|
+
validateThemeTokens(cssPath, config)
|
|
267
|
+
|
|
268
|
+
if (
|
|
269
|
+
typeof config.tailwind.config === "string" &&
|
|
270
|
+
config.tailwind.config.length > 0
|
|
271
|
+
) {
|
|
272
|
+
const tailwindConfigPath = resolveProjectFile(
|
|
273
|
+
targetDir,
|
|
274
|
+
config.tailwind.config
|
|
275
|
+
)
|
|
276
|
+
if (!tailwindConfigPath || !isExistingFile(tailwindConfigPath)) {
|
|
277
|
+
throw new Error(
|
|
278
|
+
`shadcn/ui initialization did not finish: "${config.tailwind.config}" is missing. ` +
|
|
279
|
+
"Check your network connection and run the command again."
|
|
280
|
+
)
|
|
281
|
+
}
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
let changed = false
|
|
285
|
+
if (config.tsx !== false) {
|
|
286
|
+
config.tsx = false
|
|
287
|
+
changed = true
|
|
288
|
+
}
|
|
289
|
+
// This scaffolder only targets client-side Vite projects.
|
|
290
|
+
if (config.rsc !== false) {
|
|
291
|
+
config.rsc = false
|
|
292
|
+
changed = true
|
|
293
|
+
}
|
|
294
|
+
if (changed) {
|
|
295
|
+
fs.writeJsonSync(configPath, config, { spaces: 2 })
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
const utilsPath = ensureJavaScriptUtils(targetDir, config)
|
|
299
|
+
if (!fs.existsSync(utilsPath)) {
|
|
300
|
+
throw new Error(
|
|
301
|
+
"shadcn/ui initialization did not finish: src/lib/utils.js could not be created."
|
|
302
|
+
)
|
|
303
|
+
}
|
|
304
|
+
validateUtilsDependencies(targetDir, utilsPath)
|
|
305
|
+
|
|
306
|
+
return config
|
|
307
|
+
}
|
|
308
|
+
|
|
8
309
|
/**
|
|
9
310
|
* Initializes shadcn/ui in the scaffolded project.
|
|
311
|
+
*
|
|
312
|
+
* Tailwind v4 uses the official shadcn 4.x CLI. Tailwind v3 uses the legacy
|
|
313
|
+
* 2.3.0 CLI (the last release with v3 components); the scaffold has already
|
|
314
|
+
* written v3-compatible config, so no legacy init is run.
|
|
315
|
+
*
|
|
10
316
|
* @param {object} options
|
|
11
317
|
*/
|
|
12
318
|
export async function initShadcn({
|
|
13
319
|
targetDir,
|
|
14
320
|
packageManager,
|
|
321
|
+
tailwindVersion = "v4",
|
|
15
322
|
initMode = "interactive",
|
|
16
323
|
nonInteractive = false,
|
|
17
324
|
base,
|
|
18
325
|
preset,
|
|
19
326
|
}) {
|
|
20
327
|
const pmCmds = getPackageManagerCommands(packageManager)
|
|
328
|
+
const cliPackage = getShadcnCliPackage(tailwindVersion)
|
|
329
|
+
|
|
330
|
+
if (tailwindVersion === "v3") {
|
|
331
|
+
if (base || preset) {
|
|
332
|
+
p.log.warn(
|
|
333
|
+
pc.yellow(
|
|
334
|
+
"Tailwind v3 uses the legacy shadcn CLI with Radix + new-york defaults; --base and --preset are ignored."
|
|
335
|
+
)
|
|
336
|
+
)
|
|
337
|
+
}
|
|
338
|
+
p.log.step(`${pc.cyan("◆")} Writing legacy Tailwind v3 shadcn configuration...`)
|
|
339
|
+
finalizeShadcnConfig(targetDir)
|
|
340
|
+
p.log.success(`${pc.green("✔")} shadcn/ui (v3) configuration ready.`)
|
|
341
|
+
return
|
|
342
|
+
}
|
|
21
343
|
|
|
22
344
|
if (initMode === "interactive" && !nonInteractive) {
|
|
23
345
|
p.log.step(`${pc.cyan("◆")} Launching official shadcn/ui CLI...`)
|
|
@@ -25,17 +347,26 @@ export async function initShadcn({
|
|
|
25
347
|
pc.dim(" Select your component library, preset, and styles below:\n")
|
|
26
348
|
)
|
|
27
349
|
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
if (preset) initArgs.push("-p", preset)
|
|
350
|
+
const initArgs = ["init", "--no-monorepo"]
|
|
351
|
+
if (base) initArgs.push("-b", base)
|
|
352
|
+
if (preset) initArgs.push("-p", preset)
|
|
32
353
|
|
|
354
|
+
try {
|
|
33
355
|
// Run shadcn init interactively with inherited stdio
|
|
34
|
-
const [runnerBin, runnerArgs] = pmCmds.dlx(
|
|
356
|
+
const [runnerBin, runnerArgs] = pmCmds.dlx(cliPackage, initArgs)
|
|
35
357
|
runCommandSync(runnerBin, runnerArgs, { cwd: targetDir })
|
|
36
358
|
} catch (error) {
|
|
359
|
+
// The CLI can exit non-zero after writing a valid config (for example
|
|
360
|
+
// when the user answers "no" to an optional prompt). Only continue when
|
|
361
|
+
// the config is actually usable.
|
|
362
|
+
if (!readComponentsJson(targetDir)) {
|
|
363
|
+
throw new Error(
|
|
364
|
+
`shadcn/ui init failed: ${error.message}\n` +
|
|
365
|
+
`Run "npx ${cliPackage} init" inside the project to finish setup.`
|
|
366
|
+
)
|
|
367
|
+
}
|
|
37
368
|
p.log.warn(
|
|
38
|
-
pc.yellow("
|
|
369
|
+
pc.yellow("shadcn/ui exited early, but a valid components.json was written.")
|
|
39
370
|
)
|
|
40
371
|
}
|
|
41
372
|
} else {
|
|
@@ -43,9 +374,11 @@ export async function initShadcn({
|
|
|
43
374
|
const selectedBase = base || "radix"
|
|
44
375
|
const selectedPreset = preset || "nova"
|
|
45
376
|
const spinner = p.spinner()
|
|
46
|
-
spinner.start(
|
|
377
|
+
spinner.start(
|
|
378
|
+
`Initializing shadcn/ui with ${selectedBase} library & ${selectedPreset} preset...`
|
|
379
|
+
)
|
|
47
380
|
try {
|
|
48
|
-
const [runnerBin, runnerArgs] = pmCmds.dlx(
|
|
381
|
+
const [runnerBin, runnerArgs] = pmCmds.dlx(cliPackage, [
|
|
49
382
|
"init",
|
|
50
383
|
"--no-monorepo",
|
|
51
384
|
"-b",
|
|
@@ -55,51 +388,69 @@ export async function initShadcn({
|
|
|
55
388
|
"-y",
|
|
56
389
|
])
|
|
57
390
|
runCommandOutput(runnerBin, runnerArgs, { cwd: targetDir })
|
|
58
|
-
spinner.stop(`${pc.green("✔")} shadcn/ui initialized.`)
|
|
59
391
|
} catch (error) {
|
|
60
|
-
spinner.stop(`${pc.red("✖")} Failed to initialize shadcn/ui
|
|
61
|
-
throw
|
|
392
|
+
spinner.stop(`${pc.red("✖")} Failed to initialize shadcn/ui.`)
|
|
393
|
+
throw new Error(
|
|
394
|
+
`shadcn/ui init failed: ${error.message}\n` +
|
|
395
|
+
`You can retry with: npx ${cliPackage} init -b ${selectedBase} -p ${selectedPreset} -y`
|
|
396
|
+
)
|
|
62
397
|
}
|
|
398
|
+
spinner.stop(`${pc.green("✔")} shadcn/ui initialized.`)
|
|
63
399
|
}
|
|
64
400
|
|
|
65
|
-
|
|
66
|
-
const componentsJsonPath = path.join(targetDir, "components.json")
|
|
67
|
-
if (fs.existsSync(componentsJsonPath)) {
|
|
68
|
-
try {
|
|
69
|
-
const compJson = fs.readJsonSync(componentsJsonPath)
|
|
70
|
-
if (compJson.tsx !== false) {
|
|
71
|
-
compJson.tsx = false
|
|
72
|
-
fs.writeJsonSync(componentsJsonPath, compJson, { spaces: 2 })
|
|
73
|
-
}
|
|
74
|
-
} catch {
|
|
75
|
-
// Ignore JSON parse errors if file is being written
|
|
76
|
-
}
|
|
77
|
-
}
|
|
401
|
+
finalizeShadcnConfig(targetDir)
|
|
78
402
|
}
|
|
79
403
|
|
|
80
404
|
/**
|
|
81
405
|
* Adds default components to the project.
|
|
82
406
|
* @param {object} options
|
|
83
407
|
*/
|
|
84
|
-
export async function addComponents({
|
|
408
|
+
export async function addComponents({
|
|
409
|
+
targetDir,
|
|
410
|
+
packageManager,
|
|
411
|
+
tailwindVersion = "v4",
|
|
412
|
+
components = ["button"],
|
|
413
|
+
}) {
|
|
85
414
|
if (!components || components.length === 0) return
|
|
86
415
|
|
|
416
|
+
if (!readComponentsJson(targetDir)) {
|
|
417
|
+
throw new Error(
|
|
418
|
+
"Cannot add components because components.json is missing. " +
|
|
419
|
+
"Re-run the shadcn init step (or run it manually inside the project)."
|
|
420
|
+
)
|
|
421
|
+
}
|
|
422
|
+
|
|
87
423
|
const spinner = p.spinner()
|
|
88
424
|
spinner.start(`Adding shadcn component(s): ${pc.cyan(components.join(", "))}...`)
|
|
89
425
|
|
|
90
426
|
const pmCmds = getPackageManagerCommands(packageManager)
|
|
427
|
+
const cliPackage = getShadcnCliPackage(tailwindVersion)
|
|
428
|
+
const addCommand = getShadcnAddCommand(packageManager, tailwindVersion)
|
|
429
|
+
|
|
91
430
|
try {
|
|
92
|
-
const
|
|
431
|
+
const safeComponents = sanitizeDependencies(components)
|
|
432
|
+
const [runnerBin, runnerArgs] = pmCmds.dlx(cliPackage, [
|
|
433
|
+
"add",
|
|
434
|
+
...safeComponents,
|
|
435
|
+
"-y",
|
|
436
|
+
])
|
|
93
437
|
runCommandOutput(runnerBin, runnerArgs, { cwd: targetDir })
|
|
94
438
|
spinner.stop(`${pc.green("✔")} Added component(s): ${pc.cyan(components.join(", "))}`)
|
|
95
439
|
|
|
96
440
|
// Update App.jsx with interactive component showcase
|
|
97
441
|
const hasButton = components.includes("button")
|
|
98
442
|
const appJsxPath = path.join(targetDir, "src", "App.jsx")
|
|
99
|
-
fs.writeFileSync(
|
|
443
|
+
fs.writeFileSync(
|
|
444
|
+
appJsxPath,
|
|
445
|
+
getAppJsx({ hasButton, addCommand }),
|
|
446
|
+
"utf-8"
|
|
447
|
+
)
|
|
100
448
|
} catch (error) {
|
|
101
449
|
spinner.stop(
|
|
102
|
-
`${pc.yellow("⚠")} Could not automatically add ${components.join(", ")}. You can add it later via: ${pc.cyan(
|
|
450
|
+
`${pc.yellow("⚠")} Could not automatically add ${components.join(", ")}. You can add it later via: ${pc.cyan(
|
|
451
|
+
addCommand.replace(" <component>", ` ${components.join(" ")}`)
|
|
452
|
+
)}`
|
|
103
453
|
)
|
|
454
|
+
p.log.warn(pc.dim(` ${error.message}`))
|
|
104
455
|
}
|
|
105
456
|
}
|