shadcn CLI Support Workflows
Overview
This area contains the shared support code that shadcn CLI commands use before they mutate a project, plus the helpers that model what would be changed, migrate existing installations, scaffold starter projects, and expose public support data. The command entrypoints live outside this doc, but they rely on covered files for reusable behavior.
Preflight checks live in packages/shadcn/src/preflights/**. preflight-init.ts validates that cwd contains a package.json, refuses to overwrite an existing components.json unless forced, calls getProjectInfo() to identify the framework and Tailwind CSS setup, and verifies an import alias before init continues. It treats Tailwind v3 and v4 differently: v3 requires both a Tailwind config file and CSS file, while v4 only requires the CSS file. preflight-add.ts, preflight-migrate.ts, and preflight-apply.ts all enforce the same basic project contract (package.json plus components.json) and then load the resolved CLI config with getConfig(). preflight-add.ts and preflight-apply.ts also detect monorepo roots and print target-specific guidance with getMonorepoTargets() before exiting. preflight-build.ts and preflight-registry.ts resolve the registry input/output paths, ensure the registry file exists, and create the output directory; the registry variant also requires a valid components.json.
Migrations live in packages/shadcn/src/migrations/** and operate directly on the user project. migrate-cn.ts re-exports the cn migration in migrations/…/index.ts; that migration resolves files with migrations/…/files.ts, transforms source text through a ts-morph in-memory project in migrations/…/transform.ts, installs cn, writes changed files, and optionally removes old clsx, tailwind-merge, or cnfast dependencies when the run is not scoped to a path. Its transformer supports JS/TS/JSX/TSX, plus script regions in Vue/Svelte and Astro frontmatter/script regions, and reports unsupported cases instead of silently rewriting them. migrate-icons.ts migrates JSX icon imports/usages between icon libraries, using packages/…/templates.ts to parse each library's import and usage templates, registry icon mappings from getRegistryIcons(), and ts-morph to remove old imports, rewrite JSX, add target-library imports, and update components.json when the migration is project-wide. migrate-radix.ts rewrites @radix-ui/react-* imports into the consolidated radix-ui package, handles Slot aliasing as SlotPrimitive, and updates package.json/dependencies after scanning files. migrate-base-color.ts reads the configured Tailwind CSS file with PostCSS, compares current CSS variables against registry base color values, calls updateCssVars() only for variables that still match the source color, and updates components.json with the new tailwind.baseColor. migrate-rtl.ts sets rtl: true in components.json, applies the registry RTL transformer to UI files or a requested path/glob, and warns about components such as sidebar.tsx, pagination.tsx, and calendar.tsx that may require manual follow-up.
Dry-run support is concentrated in packages/…/dry-run.ts and dry-run-formatter.ts. dryRunComponents() resolves the registry tree read-only with resolveRegistryTree(), deduplicates dependencies and dev dependencies, optionally massages fonts, and then predicts file, CSS, environment variable, font, and docs changes. File prediction mirrors the real registry update pipeline: it resolves target paths, honors config.tsx, transforms registry content through import/RSC/CSS-vars/Tailwind-prefix/icon/menu/asChild/RTL/font/cleanup transformers, rewrites resolved imports against planned paths, and marks each file as create, overwrite, or skip by comparing with the existing file. CSS prediction applies transformCssVars() and transformCss() to the configured Tailwind CSS path without writing it. dry-run-formatter.ts renders that result as summary, focused --diff, or focused --view output; it suppresses formatting-only diffs and uses full-context CSS diffs so variable updates stay understandable.
Project creation and scaffolding support starts in packages/…/create-project.ts and packages/shadcn/src/templates/**. createProject() picks a template from templates/index.ts, prompts for template and project name unless forced, selects Next.js for remote /chat/b/ components, checks write permissions and existing project names, then calls the template scaffold. templates/create-template.ts defines the template contract, resolves monorepo overrides, downloads template folders from SHADCN_GITHUB_URL (or copies SHADCN_TEMPLATE_DIR for local development), adapts pnpm workspace templates for npm/yarn/bun, runs package installation with package-manager-specific flags, writes the project name into package.json, and attempts a best-effort initial git commit. next.ts, vite.ts, start.ts, react-router.ts, and astro.ts register framework-specific starter page files and monorepo variants. laravel.ts is intentionally a scaffold-only template that exits after instructing users to create a Laravel React app first. Non-Next monorepo initialization is shared in templates/monorepo.ts; it updates both packages/…/components.json and apps/…/components.json, applies registry components to packages/ui, manually installs fontsource CSS/dependencies, and installs icon packages in both workspaces. The Next monorepo path in templates/next.ts is similar, but handles fonts through the app workspace with Next font helpers while applying CSS variables in packages/ui.
Preset support is split between browser-safe exports and CLI-specific resolution. packages/…/index.ts re-exports preset constants and encode/decode helpers from the registry package for client-side use. preset/defaults.ts defines named default presets such as nova, vega, maia, and sera. preset/presets.ts builds URLs for the hosted preset builder and init endpoint, prompts for the component library base and preset choice, opens the builder for custom presets, and resolves a registry base config from an init URL using a shadow config. preset/resolve.ts derives a preset code from an existing project by reading components.json values, parsing Tailwind CSS with PostCSS for theme/chart/radius/font CSS variables, optionally reading Next font usage from app/layout or pages/_app, and falling back to the style defaults when values cannot be detected.
Styles and shared CSS are handled by packages/shadcn/src/styles/**, colors.ts, and tailwind.css. styles/create-style-map.ts parses CSS rules with PostCSS and selector-parser, extracts @apply classes from selectors whose subject class starts with cn-, and returns a validated map from cn-* style tokens to Tailwind classes. styles/transform.ts runs style transformers against a temporary TSX source file, and styles/transform-style-map.ts inlines mapped classes into cva() calls, JSX className, object className properties, and mergeProps() calls while preserving allowlisted cn-* classes that are still used as selectors or runtime hooks. colors.ts contains Tailwind color family/scale data plus findTailwindColorFamily(), which normalizes OKLCH values and recognizes legacy HSL aliases for preset resolution. tailwind.css is the installable Tailwind v4 support stylesheet: it defines shared keyframes, custom variants for data attributes/orientation/disabled state, no-scrollbar, scroll-fade utilities including RTL-aware inline masks, and shimmer utilities with reduced-motion fallbacks.
Registry/schema/icons exports under packages/…/index.ts, schema/index.ts, and icons/index.ts are public compatibility surfaces over @shadcn/registry internals. icons/templates.ts is the local parser used by icon migrations and consumers: import templates are parsed line-by-line, and usage templates are parsed with a hand-written linear scanner to avoid regex backtracking. Registry network helpers in utils/registry-api.ts fetch styles, icons, or deprecated style trees and run CLI-specific handleError() on failure. utils/registries.ts ensures registry namespaces referenced by requested components are available in config by resolving namespace dependencies, merging package.json-declared registries only in memory, discovering registries from the registry index, and persisting only discovered registry URLs back to components.json.
Other utilities cover error handling, backups, aliases, compatibility transformers, and tests. utils/handle-error.ts prints registry/Zod/general errors and suggests re-running with the previous minor CLI version before exiting. utils/file-helper.ts implements .bak backups around tasks and restores them on thrown errors or process exit. utils/alias.ts derives ui, lib, hooks, and utils aliases from a components alias while preserving existing aliases during re-init. utils/index.ts, utils/…/source-file.ts, and utils/…/transform-render.ts bridge older ts-morph SourceFile transformers with the registry's text-transformer pipeline and implement the base-style render prop rewrite. utils/…/update-tailwind-content.ts edits a Tailwind config object to append missing content globs without duplicating existing entries. utils/update-app-index.ts can replace a Next app app/page.tsx with a registry item's example import. packages/…/index.ts exposes getFixturesDir() and withTempDir() so tests can locate shared fixtures and clean up temporary projects.
Coupling
- If a preflight changes its error keys or exit behavior in packages/…/*.ts, also update callers that interpret packages/…/errors.ts; these helpers return numeric-string error records for recoverable missing-project/config cases but call
process.exit(1)for invalid configs and unsupported interactive guidance. - If registry file installation changes in
@shadcn/registry/internal/updaters/update-files, mirror the transformation order in packages/…/dry-run.ts; dry runs manually reproduce the real transform/import-rewrite pipeline and will mislead users if it drifts from the write path. - If icon library metadata changes, verify both packages/…/templates.ts and packages/…/migrate-icons.ts; migrations derive module specifiers, wrapper components, default attributes, and skipped-use rules from the
importandusagetemplate strings rather than from executable library code. - If a new starter template is added in packages/…/*.ts, register it in packages/…/index.ts and decide whether it needs monorepo init behavior from packages/…/monorepo.ts; otherwise
createProject()cannot prompt for it andgetTemplateForFramework()cannot map detected frameworks to it. - If preset dimensions are added or renamed in the registry preset API, update packages/…/defaults.ts, URL serialization in packages/…/presets.ts, and project inference in packages/…/resolve.ts; the resolver emits fallback fields when it cannot detect a value, but the init URL builder must still include every required dimension.
- If Tailwind color values or preset theme families change, update packages/…/colors.ts alongside packages/…/resolve.ts; preset inference maps raw CSS variable values back to theme/chart families through the normalized color table.
- If
cn-*style hooks are added to installed CSS, update the allowlist in packages/…/transform-style-map.ts when those class names must remain in generated code; the transformer removes non-allowlistedcn-*classes after inlining style-map classes. - If config registry discovery rules change in registry internals, verify packages/…/registries.ts; it intentionally writes only registries discovered from the index to components.json, while package.json registries remain in-memory to avoid mutating project config with package-local declarations.
Risks
- packages/…/migrate-radix.ts uses regex-based import rewriting plus line-based
Slotreplacement. Imports orSlotreferences in patterns outside those regexes can be left unchanged or rewritten incorrectly, which can produce mixed@radix-ui/react-*andradix-uiusage after migration. - packages/…/migrate-icons.ts only rewrites icon imports that can be mapped through registry icon names and only supports JSX usages matching the parsed source usage template. Unsupported references are skipped and reported; if users ignore the report, the project can end up with both source and target icon libraries installed/imported.
- packages/…/dry-run.ts duplicates real install logic instead of invoking the write path. A transformer order or path-resolution change outside this file can make
--dry-run,--diff, or--viewshow content that differs from an actualshadcn addrun. - packages/…/create-template.ts shells out to
gitand the selected package manager during scaffolding. If sparse checkout, install flags, workspace adaptation, or package-manager version detection fail,handleError()exits the process and the partially created project directory may remain for the user to clean up. - packages/…/file-helper.ts backs up by renaming the original file to
<path>.bak. If a.bakfile already exists or the process is interrupted after backup cleanup listeners are removed, the original file can be unavailable until manually restored.