create-shadcn-js 0.0.0-stage → 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/src/prompts.js ADDED
@@ -0,0 +1,197 @@
1
+ import * as p from "@clack/prompts"
2
+ import pc from "picocolors"
3
+ import fs from "fs-extra"
4
+ import path from "node:path"
5
+ import { detectPackageManager, validateProjectName } from "./utils.js"
6
+
7
+ /**
8
+ * Handles all interactive CLI prompts using @clack/prompts.
9
+ * @param {object} cliOptions
10
+ * @param {{ version?: string }} [metadata]
11
+ * @returns {Promise<object>}
12
+ */
13
+ export async function runInteractivePrompts(cliOptions = {}, { version } = {}) {
14
+ // run() validates first, but callers can reach this function directly.
15
+ if (cliOptions.name) {
16
+ const valid = validateProjectName(cliOptions.name)
17
+ if (typeof valid === "string") {
18
+ throw new Error(`Invalid project name: ${valid}`)
19
+ }
20
+ }
21
+
22
+ const versionLabel = version ? `v${version}` : ""
23
+ p.intro(
24
+ `${pc.bgCyan(pc.black(" create-shadcn-js "))}${
25
+ versionLabel ? ` ${pc.dim(versionLabel)}` : ""
26
+ }`
27
+ )
28
+
29
+ // 1. Project name / directory
30
+ let projectName = cliOptions.name
31
+ if (!projectName) {
32
+ const defaultName = "my-shadcn-app"
33
+ const response = await p.text({
34
+ message: "What is your project named?",
35
+ placeholder: defaultName,
36
+ defaultValue: defaultName,
37
+ validate: (value) => {
38
+ const val = value.trim() || defaultName
39
+ const res = validateProjectName(val)
40
+ return typeof res === "string" ? res : undefined
41
+ },
42
+ })
43
+
44
+ if (p.isCancel(response)) {
45
+ p.cancel("Operation cancelled by user.")
46
+ process.exit(0)
47
+ }
48
+ projectName = response.trim() || defaultName
49
+ }
50
+
51
+ const targetDir = path.resolve(process.cwd(), projectName)
52
+
53
+ // Check if directory exists and is not empty
54
+ if (fs.existsSync(targetDir) && fs.readdirSync(targetDir).length > 0) {
55
+ if (!cliOptions.force) {
56
+ // --yes promises a non-interactive run. Never delete a non-empty
57
+ // directory in that mode without an explicit --force.
58
+ if (cliOptions.yes) {
59
+ throw new Error(
60
+ `Target directory "${projectName}" is not empty. ` +
61
+ `Re-run with --force to overwrite it, or choose a different project name.`
62
+ )
63
+ }
64
+
65
+ const overwrite = await p.confirm({
66
+ message: `Target directory "${projectName}" is not empty. Remove existing files and continue?`,
67
+ initialValue: false,
68
+ })
69
+
70
+ if (p.isCancel(overwrite) || !overwrite) {
71
+ p.cancel("Setup aborted. Please choose an empty directory or rename your project.")
72
+ process.exit(0)
73
+ }
74
+ }
75
+ }
76
+
77
+ // 2. Package manager selection
78
+ let packageManager = cliOptions.pm
79
+ if (!packageManager) {
80
+ const detectedPm = detectPackageManager()
81
+ const pmResponse = await p.select({
82
+ message: "Which package manager do you want to use?",
83
+ initialValue: detectedPm,
84
+ options: [
85
+ { value: "npm", label: "npm", hint: detectedPm === "npm" ? "detected" : undefined },
86
+ { value: "pnpm", label: "pnpm", hint: detectedPm === "pnpm" ? "detected" : undefined },
87
+ { value: "bun", label: "bun", hint: detectedPm === "bun" ? "detected" : undefined },
88
+ { value: "yarn", label: "yarn", hint: detectedPm === "yarn" ? "detected" : undefined },
89
+ ],
90
+ })
91
+
92
+ if (p.isCancel(pmResponse)) {
93
+ p.cancel("Operation cancelled by user.")
94
+ process.exit(0)
95
+ }
96
+ packageManager = pmResponse
97
+ }
98
+
99
+ // 3. Tailwind CSS version selection
100
+ let tailwindVersion = cliOptions.tailwind
101
+ if (!tailwindVersion) {
102
+ const twResponse = await p.select({
103
+ message: "Which Tailwind CSS version would you like to use?",
104
+ initialValue: "v4",
105
+ options: [
106
+ {
107
+ value: "v4",
108
+ label: "Tailwind CSS v4",
109
+ hint: "Recommended: Vite plugin, CSS-first, zero config",
110
+ },
111
+ {
112
+ value: "v3",
113
+ label: "Tailwind CSS v3",
114
+ hint: "Classic: tailwind.config.js & postcss.config.js",
115
+ },
116
+ ],
117
+ })
118
+
119
+ if (p.isCancel(twResponse)) {
120
+ p.cancel("Operation cancelled by user.")
121
+ process.exit(0)
122
+ }
123
+ tailwindVersion = twResponse
124
+ }
125
+
126
+ // 4. shadcn/ui initialization mode
127
+ // Tailwind v3 uses the legacy shadcn CLI with a fixed new-york theme, so
128
+ // there is no interactive library/preset choice to make.
129
+ let initMode = cliOptions.mode
130
+ if (!initMode && tailwindVersion === "v3") {
131
+ initMode = "quickstart"
132
+ }
133
+ if (!initMode) {
134
+ const modeResponse = await p.select({
135
+ message: "How would you like to configure shadcn/ui?",
136
+ initialValue: "interactive",
137
+ options: [
138
+ {
139
+ value: "interactive",
140
+ label: "Interactive shadcn CLI",
141
+ hint: "Select component library (Radix/Base), style presets, and colors directly in shadcn CLI",
142
+ },
143
+ {
144
+ value: "quickstart",
145
+ label: "Quickstart Preset",
146
+ hint: "Auto-configured with Radix UI + Nova style (Lucide icons)",
147
+ },
148
+ ],
149
+ })
150
+
151
+ if (p.isCancel(modeResponse)) {
152
+ p.cancel("Operation cancelled by user.")
153
+ process.exit(0)
154
+ }
155
+ initMode = modeResponse
156
+ }
157
+
158
+ // 5. Sample components
159
+ let addSampleComponents = cliOptions.sampleComponents
160
+ if (addSampleComponents === undefined) {
161
+ const sampleResponse = await p.confirm({
162
+ message: "Would you like to install the starter Button component and interactive showcase demo?",
163
+ initialValue: true,
164
+ })
165
+
166
+ if (p.isCancel(sampleResponse)) {
167
+ p.cancel("Operation cancelled by user.")
168
+ process.exit(0)
169
+ }
170
+ addSampleComponents = sampleResponse
171
+ }
172
+
173
+ // 6. Git initialization
174
+ let initGit = cliOptions.git
175
+ if (initGit === undefined) {
176
+ const gitResponse = await p.confirm({
177
+ message: "Initialize a new Git repository?",
178
+ initialValue: true,
179
+ })
180
+
181
+ if (p.isCancel(gitResponse)) {
182
+ p.cancel("Operation cancelled by user.")
183
+ process.exit(0)
184
+ }
185
+ initGit = gitResponse
186
+ }
187
+
188
+ return {
189
+ projectName,
190
+ targetDir,
191
+ packageManager,
192
+ tailwindVersion,
193
+ initMode,
194
+ addSampleComponents,
195
+ initGit,
196
+ }
197
+ }
@@ -0,0 +1,235 @@
1
+ import fs from "fs-extra"
2
+ import path from "node:path"
3
+ import * as p from "@clack/prompts"
4
+ import pc from "picocolors"
5
+ import {
6
+ getCreateViteCommand,
7
+ getPackageManagerCommands,
8
+ getShadcnAddCommand,
9
+ runCommandOutput,
10
+ validateProjectName,
11
+ } from "./utils.js"
12
+ import {
13
+ getJsConfig,
14
+ getViteConfig,
15
+ getTailwindConfigV3,
16
+ getPostcssConfigV3,
17
+ getComponentsJsonV3,
18
+ getShadcnUtilsJs,
19
+ getIndexHtml,
20
+ } from "./templates/configs.js"
21
+ import { getIndexCss } from "./templates/indexCss.js"
22
+ import { getAppJsx } from "./templates/app.js"
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
+
65
+ /**
66
+ * Scaffolds the base Vite + React (JavaScript) project.
67
+ * @param {object} options
68
+ */
69
+ export async function scaffoldProject({
70
+ projectName,
71
+ targetDir,
72
+ packageManager,
73
+ tailwindVersion,
74
+ }) {
75
+ const spinner = p.spinner()
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
+
89
+ // 1. Prepare directory
90
+ if (fs.existsSync(targetDir)) {
91
+ fs.emptyDirSync(targetDir)
92
+ } else {
93
+ fs.ensureDirSync(targetDir)
94
+ }
95
+
96
+ const pmCmds = getPackageManagerCommands(packageManager)
97
+
98
+ // 2. Scaffold Vite React JavaScript template
99
+ spinner.start("Scaffolding Vite React JavaScript project...")
100
+ try {
101
+ // Run create-vite with the same package manager the project will use.
102
+ const [createBin, createArgs] = getCreateViteCommand(
103
+ packageManager,
104
+ folderName
105
+ )
106
+ runCommandOutput(createBin, createArgs, { cwd: parentDir })
107
+ spinner.stop(`${pc.green("✔")} Vite project scaffolded successfully.`)
108
+ } catch (error) {
109
+ spinner.stop(`${pc.red("✖")} Failed to scaffold Vite project.`)
110
+ throw error
111
+ }
112
+
113
+ // 3. Install base dependencies
114
+ spinner.start(`Installing project dependencies with ${pc.cyan(packageManager)}...`)
115
+ try {
116
+ const [installBin, installArgs] = pmCmds.install
117
+ runCommandOutput(installBin, installArgs, { cwd: targetDir })
118
+ spinner.stop(`${pc.green("✔")} Dependencies installed.`)
119
+ } catch (error) {
120
+ spinner.stop(`${pc.red("✖")} Failed to install dependencies.`)
121
+ throw error
122
+ }
123
+
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
127
+
128
+ spinner.start(`Installing Tailwind CSS (${tailwindVersion}) dependencies...`)
129
+ try {
130
+ const [addBin, addArgs] = pmCmds.add(tailwindDeps, false)
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
+
147
+ spinner.stop(`${pc.green("✔")} Tailwind CSS (${tailwindVersion}) installed.`)
148
+ } catch (error) {
149
+ spinner.stop(`${pc.red("✖")} Failed to install Tailwind CSS dependencies.`)
150
+ throw error
151
+ }
152
+
153
+ // 5. Configure project files
154
+ spinner.start("Configuring path aliases and build configurations...")
155
+ try {
156
+ // Write jsconfig.json
157
+ fs.writeFileSync(path.join(targetDir, "jsconfig.json"), getJsConfig(), "utf-8")
158
+
159
+ // Write vite.config.js
160
+ fs.writeFileSync(
161
+ path.join(targetDir, "vite.config.js"),
162
+ getViteConfig(tailwindVersion),
163
+ "utf-8"
164
+ )
165
+
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) {
170
+ fs.writeFileSync(
171
+ path.join(targetDir, "tailwind.config.js"),
172
+ getTailwindConfigV3(),
173
+ "utf-8"
174
+ )
175
+ fs.writeFileSync(
176
+ path.join(targetDir, "postcss.config.js"),
177
+ getPostcssConfigV3(),
178
+ "utf-8"
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
+ )
191
+ }
192
+
193
+ // Write src/index.css
194
+ fs.writeFileSync(
195
+ path.join(targetDir, "src", "index.css"),
196
+ getIndexCss(tailwindVersion),
197
+ "utf-8"
198
+ )
199
+
200
+ // Remove src/App.css if present to avoid conflicting default styles
201
+ const appCssPath = path.join(targetDir, "src", "App.css")
202
+ if (fs.existsSync(appCssPath)) {
203
+ fs.removeSync(appCssPath)
204
+ }
205
+
206
+ // Remove App.css import from App.jsx or main.jsx if it exists
207
+ const mainJsxPath = path.join(targetDir, "src", "main.jsx")
208
+ if (fs.existsSync(mainJsxPath)) {
209
+ let mainContent = fs.readFileSync(mainJsxPath, "utf-8")
210
+ mainContent = mainContent.replace(/import\s+['"]\.\/App\.css['"];?\n?/, "")
211
+ fs.writeFileSync(mainJsxPath, mainContent, "utf-8")
212
+ }
213
+
214
+ // Update index.html title
215
+ const indexHtmlPath = path.join(targetDir, "index.html")
216
+ if (fs.existsSync(indexHtmlPath)) {
217
+ fs.writeFileSync(indexHtmlPath, getIndexHtml(projectName), "utf-8")
218
+ }
219
+
220
+ // Write clean initial App.jsx
221
+ fs.writeFileSync(
222
+ path.join(targetDir, "src", "App.jsx"),
223
+ getAppJsx({
224
+ hasButton: false,
225
+ addCommand: getShadcnAddCommand(packageManager, tailwindVersion),
226
+ }),
227
+ "utf-8"
228
+ )
229
+
230
+ spinner.stop(`${pc.green("✔")} Project configurations applied.`)
231
+ } catch (error) {
232
+ spinner.stop(`${pc.red("✖")} Failed to write configuration files.`)
233
+ throw error
234
+ }
235
+ }