components-differ 1.2.1 → 1.2.3

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.
@@ -0,0 +1,73 @@
1
+ import path from "node:path";
2
+ function fixAlias(alias) {
3
+ return alias.replace("@", ".");
4
+ }
5
+ export function parseFilePath(wasInSrcDir, config, filePath, content) {
6
+ const normalizedPath = filePath.replace(/^\.\//, "");
7
+ const extension = path.extname(normalizedPath);
8
+ const baseName = path.basename(normalizedPath);
9
+ const styleExtensions = new Set([
10
+ ".css",
11
+ ".scss",
12
+ ".sass",
13
+ ".less",
14
+ ".pcss",
15
+ ]);
16
+ const fileExtensions = new Set([
17
+ ".json",
18
+ ".yaml",
19
+ ".yml",
20
+ ".md",
21
+ ".mdx",
22
+ ".txt",
23
+ ]);
24
+ const themePattern = /(\/|^)(theme|.*-theme)(\.[a-z0-9]+)?$/i;
25
+ const sanitizedTargetPath = normalizedPath.replace(/^src\//, "");
26
+ const defaultTarget = wasInSrcDir ? filePath : `~/${normalizedPath}`;
27
+ const out = {
28
+ path: filePath,
29
+ content,
30
+ type: "registry:example",
31
+ target: defaultTarget,
32
+ };
33
+ if (filePath.startsWith(fixAlias(config.ui))) {
34
+ out.type = "registry:ui";
35
+ out.target = undefined;
36
+ }
37
+ else if (filePath.startsWith(fixAlias(config.components))) {
38
+ out.type = "registry:block";
39
+ out.target = undefined;
40
+ }
41
+ else if (filePath.startsWith(fixAlias(config.hooks))) {
42
+ out.type = "registry:hook";
43
+ out.target = undefined;
44
+ }
45
+ else if (filePath.startsWith(fixAlias(config.lib))) {
46
+ out.type = "registry:lib";
47
+ out.target = undefined;
48
+ }
49
+ else if (normalizedPath.startsWith("app/")) {
50
+ out.type = "registry:page";
51
+ out.target = `./${sanitizedTargetPath}`;
52
+ }
53
+ else if (themePattern.test(normalizedPath)) {
54
+ out.type = "registry:theme";
55
+ out.target = undefined;
56
+ }
57
+ else if (styleExtensions.has(extension)) {
58
+ out.type = "registry:style";
59
+ }
60
+ else if (baseName.startsWith(".env") || fileExtensions.has(extension)) {
61
+ out.type = "registry:file";
62
+ out.target = `~/${sanitizedTargetPath}`;
63
+ }
64
+ else if (extension === ".tsx" || extension === ".jsx") {
65
+ out.type = "registry:component";
66
+ out.target = undefined;
67
+ }
68
+ else {
69
+ out.type = "registry:file";
70
+ out.target = `./${sanitizedTargetPath}`;
71
+ }
72
+ return out;
73
+ }
@@ -0,0 +1,50 @@
1
+ import { spawnSync } from "node:child_process";
2
+ function run(command, args = []) {
3
+ const full = [command, ...args].join(" ");
4
+ console.log(`\n$ ${full}`);
5
+ const result = spawnSync(command, args, {
6
+ stdio: "inherit",
7
+ shell: process.platform === "win32",
8
+ });
9
+ if (result.status !== 0) {
10
+ console.error(`\nCommand failed: ${full}`);
11
+ process.exit(result.status === null ? 1 : result.status);
12
+ }
13
+ }
14
+ function getVersionBumpFromArgs() {
15
+ const type = process.argv[2] ?? "patch";
16
+ if (!["patch", "minor", "major"].includes(type)) {
17
+ console.error(`Invalid version bump "${type}". Use one of: patch, minor, major.`);
18
+ process.exit(1);
19
+ }
20
+ return type;
21
+ }
22
+ function ensureCleanGit() {
23
+ const result = spawnSync("git", ["status", "--porcelain"], {
24
+ encoding: "utf8",
25
+ });
26
+ if (result.status !== 0) {
27
+ console.error("Failed to check git status.");
28
+ process.exit(1);
29
+ }
30
+ if ((result.stdout ?? "").trim().length > 0) {
31
+ console.error("Git working tree is not clean. Commit or stash your changes before releasing.");
32
+ process.exit(1);
33
+ }
34
+ }
35
+ async function main() {
36
+ const bump = getVersionBumpFromArgs();
37
+ console.log("Ensuring clean git working tree...");
38
+ ensureCleanGit();
39
+ console.log("\nBuilding project...");
40
+ run("npm", ["run", "build"]);
41
+ console.log(`\nBumping version (${bump})...`);
42
+ run("npm", ["version", bump]);
43
+ console.log("\nPublishing to npm...");
44
+ run("npm", ["publish"]);
45
+ console.log("\nRelease complete.");
46
+ }
47
+ main().catch((err) => {
48
+ console.error(err);
49
+ process.exit(1);
50
+ });
@@ -0,0 +1,103 @@
1
+ import path from "node:path";
2
+ import { extractPathSpecifiers } from "./extract-imports.js";
3
+ const EXTENSIONS = [".tsx", ".ts", ".jsx", ".js", ".mts", ".mjs", ".cts", ".cjs"];
4
+ const INDEX_NAMES = ["index.tsx", "index.ts", "index.jsx", "index.js"];
5
+ /** Build [aliasPrefix, pathPrefix] pairs, longest first. pathPrefix is project-relative (e.g. src/lib when isSrcDir). */
6
+ function getAliasEntries(config) {
7
+ const entries = [];
8
+ const prefix = config.isSrcDir ? "src/" : "";
9
+ const keys = ["components", "utils", "ui", "lib", "hooks"];
10
+ for (const k of keys) {
11
+ const v = config[k];
12
+ if (typeof v === "string" && v.startsWith("@/")) {
13
+ const pathPart = v.replace(/^@\//, "").replace(/\/$/, "");
14
+ entries.push([v.replace(/\/$/, ""), prefix + pathPart]);
15
+ }
16
+ }
17
+ entries.push(["@", config.isSrcDir ? "src" : ""]);
18
+ entries.sort((a, b) => b[0].length - a[0].length);
19
+ return entries;
20
+ }
21
+ /**
22
+ * Resolve a path-like import specifier to a project-relative file path.
23
+ * Tries common extensions and /index.*. Returns the first path that exists in projectPaths.
24
+ */
25
+ function resolveSpecifier(specifier, fromFilePath, aliasEntries, projectPaths, rootFallback) {
26
+ const normalizedFrom = fromFilePath.replace(/\\/g, "/");
27
+ const fromDir = path.dirname(normalizedFrom).replace(/\\/g, "/");
28
+ let candidate;
29
+ if (specifier.startsWith(".") || specifier.startsWith("/")) {
30
+ candidate = path.normalize(path.join(fromDir, specifier)).replace(/\\/g, "/");
31
+ }
32
+ else {
33
+ // Alias: @/components/Button -> components/Button
34
+ let matched = false;
35
+ for (const [aliasPrefix, pathPrefix] of aliasEntries) {
36
+ const prefix = aliasPrefix === "@" ? "@/" : aliasPrefix.endsWith("/") ? aliasPrefix : aliasPrefix + "/";
37
+ if (specifier === aliasPrefix || specifier.startsWith(prefix)) {
38
+ const suffix = specifier.slice(prefix.length).replace(/^\//, "");
39
+ candidate = path.normalize(path.join(pathPrefix, suffix)).replace(/\\/g, "/");
40
+ matched = true;
41
+ break;
42
+ }
43
+ }
44
+ if (!matched) {
45
+ const suffix = specifier.replace(/^@\//, "").replace(/^~\//, "");
46
+ candidate = path.normalize(path.join(rootFallback, suffix)).replace(/\\/g, "/");
47
+ }
48
+ }
49
+ if (!candidate)
50
+ return null;
51
+ if (projectPaths.has(candidate))
52
+ return candidate;
53
+ for (const ext of EXTENSIONS) {
54
+ const p = candidate.endsWith(ext) ? candidate : candidate + ext;
55
+ if (projectPaths.has(p))
56
+ return p;
57
+ }
58
+ for (const name of INDEX_NAMES) {
59
+ const p = candidate.endsWith("/") ? candidate + name : candidate + "/" + name;
60
+ if (projectPaths.has(p))
61
+ return p;
62
+ }
63
+ return null;
64
+ }
65
+ /**
66
+ * Expand the list of included files by recursively adding any project file
67
+ * that is imported (via relative or alias path) by an already-included file.
68
+ * Uses TypeScript/JS import syntax only.
69
+ */
70
+ export function expandIncludedFiles(includedFiles, allProjectFiles, config) {
71
+ const projectPathToFile = new Map();
72
+ for (const f of allProjectFiles) {
73
+ const key = f.path.replace(/\\/g, "/");
74
+ projectPathToFile.set(key, f);
75
+ }
76
+ const projectPaths = new Set(projectPathToFile.keys());
77
+ const aliasEntries = getAliasEntries(config);
78
+ const rootFallback = config.isSrcDir ? "src" : "";
79
+ const includedPaths = new Set();
80
+ for (const f of includedFiles) {
81
+ includedPaths.add(f.path.replace(/\\/g, "/"));
82
+ }
83
+ let added = true;
84
+ while (added) {
85
+ added = false;
86
+ for (const file of [...includedFiles]) {
87
+ const content = file.content;
88
+ const fromPath = file.path.replace(/\\/g, "/");
89
+ for (const spec of extractPathSpecifiers(content)) {
90
+ const resolved = resolveSpecifier(spec, fromPath, aliasEntries, projectPaths, rootFallback);
91
+ if (resolved && !includedPaths.has(resolved)) {
92
+ const scanned = projectPathToFile.get(resolved);
93
+ if (scanned) {
94
+ includedFiles.push(scanned);
95
+ includedPaths.add(resolved);
96
+ added = true;
97
+ }
98
+ }
99
+ }
100
+ }
101
+ }
102
+ return includedFiles;
103
+ }
package/package.json CHANGED
@@ -1,52 +1,23 @@
1
1
  {
2
2
  "name": "components-differ",
3
- "version": "1.2.1",
4
- "description": "Simple CLI to create Shadcn components from project",
3
+ "version": "1.2.3",
4
+ "description": "CLI to generate shadcn registry items from git diffs",
5
+ "license": "ISC",
5
6
  "type": "module",
6
- "main": "dist/index.mjs",
7
- "bin": "dist/index.mjs",
8
- "exports": {
9
- ".": "./dist/index.mjs"
7
+ "main": "dist/index.js",
8
+ "bin": {
9
+ "components-differ": "dist/index.js"
10
10
  },
11
- "files": [
12
- "dist"
13
- ],
14
- "directories": {
15
- "test": "tests"
11
+ "scripts": {
12
+ "build": "tsc",
13
+ "release": "npm run build && node dist/release.js"
16
14
  },
17
15
  "dependencies": {
18
- "commander": "^12.1.0",
19
- "ignore": "^6.0.2"
16
+ "commander": "13.1.0",
17
+ "ignore": "7.0.4"
20
18
  },
21
19
  "devDependencies": {
22
- "vitest": "^2.1.1"
23
- },
24
- "publishConfig": {
25
- "access": "public"
26
- },
27
- "engines": {
28
- "node": ">=18"
29
- },
30
- "repository": {
31
- "type": "git",
32
- "url": "git+https://github.com/componentshost/components-differ.git"
33
- },
34
- "keywords": [
35
- "components",
36
- "shadcn",
37
- "differ",
38
- "react",
39
- "vite"
40
- ],
41
- "author": "Izet Molla",
42
- "license": "MIT",
43
- "bugs": {
44
- "url": "https://github.com/componentshost/components-differ/issues"
45
- },
46
- "homepage": "https://github.com/componentshost/components-differ#readme",
47
- "scripts": {
48
- "build": "node ./scripts/build.mjs",
49
- "release": "pnpm run prepublishOnly && pnpm publish --access public",
50
- "test": "vitest run"
20
+ "typescript": "5.9.3",
21
+ "@types/node": "25.3.0"
51
22
  }
52
- }
23
+ }
@@ -0,0 +1,170 @@
1
+ import path from "node:path";
2
+ import fs from "node:fs";
3
+
4
+ const WHITELISTED_COMPONENTS = [
5
+ "accordion",
6
+ "alert",
7
+ "alert-dialog",
8
+ "aspect-ratio",
9
+ "avatar",
10
+ "badge",
11
+ "breadcrumb",
12
+ "button",
13
+ "button-group",
14
+ "calendar",
15
+ "card",
16
+ "carousel",
17
+ "chart",
18
+ "checkbox",
19
+ "collapsible",
20
+ "combobox",
21
+ "command",
22
+ "context-menu",
23
+ "data-table",
24
+ "date-picker",
25
+ "dialog",
26
+ "drawer",
27
+ "dropdown-menu",
28
+ "empty",
29
+ "field",
30
+ "form",
31
+ "hover-card",
32
+ "input",
33
+ "input-group",
34
+ "input-otp",
35
+ "item",
36
+ "kbd",
37
+ "label",
38
+ "menubar",
39
+ "native-select",
40
+ "navigation-menu",
41
+ "pagination",
42
+ "popover",
43
+ "progress",
44
+ "radio-group",
45
+ "resizable",
46
+ "scroll-area",
47
+ "select",
48
+ "separator",
49
+ "sheet",
50
+ "sidebar",
51
+ "skeleton",
52
+ "slider",
53
+ "sonner",
54
+ "spinner",
55
+ "switch",
56
+ "table",
57
+ "tabs",
58
+ "textarea",
59
+ "toast",
60
+ "toggle",
61
+ "toggle-group",
62
+ "tooltip",
63
+ "typography",
64
+ ] as const;
65
+
66
+ type WhitelistedComponent = (typeof WHITELISTED_COMPONENTS)[number];
67
+
68
+ export interface ComponentsConfig {
69
+ components: string;
70
+ utils: string;
71
+ ui: string;
72
+ lib: string;
73
+ hooks: string;
74
+ registries?: Record<string, unknown>;
75
+ isSrcDir?: boolean;
76
+ }
77
+
78
+ function findComponentsJson(startDir: string): string | null {
79
+ let currentDir = startDir;
80
+
81
+ while (true) {
82
+ const manifestPath = path.join(currentDir, "components.json");
83
+ if (fs.existsSync(manifestPath)) {
84
+ return manifestPath;
85
+ }
86
+
87
+ const parentDir = path.dirname(currentDir);
88
+ if (parentDir === currentDir) {
89
+ break;
90
+ }
91
+ currentDir = parentDir;
92
+ }
93
+
94
+ return null;
95
+ }
96
+
97
+ export function findComponentFiles(
98
+ config: ComponentsConfig,
99
+ originalFiles: { path: string }[],
100
+ ): string[] {
101
+ const registryDependencies: string[] = [];
102
+ const compDir = config.ui.replace("@/", config.isSrcDir ? "src/" : "");
103
+
104
+ const registriesConfig = config.registries ?? {};
105
+ const registryNamespaces = Object.keys(registriesConfig);
106
+ const defaultNamespace =
107
+ registryNamespaces.find((name) => name === "@shadcn") ??
108
+ registryNamespaces[0] ??
109
+ null;
110
+
111
+ for (const { path: filePath } of originalFiles) {
112
+ if (filePath.startsWith(compDir)) {
113
+ const fileExtension = path.extname(filePath);
114
+ const fileName = path.basename(filePath, fileExtension) as WhitelistedComponent;
115
+ if (
116
+ (fileExtension === ".tsx" || fileExtension === ".jsx") &&
117
+ WHITELISTED_COMPONENTS.includes(fileName)
118
+ ) {
119
+ const baseName = path.basename(filePath, fileExtension);
120
+ const dependencyName = defaultNamespace
121
+ ? `${defaultNamespace}/${baseName}`
122
+ : baseName;
123
+ registryDependencies.push(dependencyName);
124
+ }
125
+ }
126
+ }
127
+
128
+ return registryDependencies;
129
+ }
130
+
131
+ export function readComponentsManifest(dir: string): ComponentsConfig {
132
+ const manifestPath = findComponentsJson(dir);
133
+
134
+ if (!manifestPath) {
135
+ console.error("Components manifest (components.json) not found");
136
+ process.exit(1);
137
+ }
138
+
139
+ const json = JSON.parse(fs.readFileSync(manifestPath, "utf-8")) as {
140
+ aliases: Omit<ComponentsConfig, "registries" | "isSrcDir">;
141
+ registries?: ComponentsConfig["registries"];
142
+ };
143
+
144
+ return {
145
+ ...json.aliases,
146
+ registries: json.registries ?? {},
147
+ };
148
+ }
149
+
150
+ export function getAliasedPaths(config: ComponentsConfig): string[] {
151
+ return [
152
+ config.components.replace("@/", ""),
153
+ config.utils.replace("@/", ""),
154
+ config.ui.replace("@/", ""),
155
+ config.lib.replace("@/", ""),
156
+ config.hooks.replace("@/", ""),
157
+ ];
158
+ }
159
+
160
+ export function isBuiltinComponent(
161
+ config: ComponentsConfig,
162
+ filePath: string,
163
+ ): boolean {
164
+ if (filePath.startsWith(config.ui.replace("@/", ""))) {
165
+ const component = path.basename(filePath, path.extname(filePath));
166
+ return (WHITELISTED_COMPONENTS as readonly string[]).includes(component);
167
+ }
168
+ return false;
169
+ }
170
+
@@ -0,0 +1,156 @@
1
+ import {
2
+ findComponentFiles,
3
+ getAliasedPaths,
4
+ isBuiltinComponent,
5
+ type ComponentsConfig,
6
+ } from "./components.js";
7
+ import { parseFilePath, type ParsedFile } from "./parse-file-path.js";
8
+ import { extractImportedPackages } from "./extract-imports.js";
9
+ import type { ScannedFile } from "./git.js";
10
+
11
+ interface CreateDiffOptions {
12
+ name: string;
13
+ config: ComponentsConfig & { isSrcDir?: boolean };
14
+ alteredFiles: ScannedFile[];
15
+ specificFiles: Record<string, string>;
16
+ currentFiles: ScannedFile[];
17
+ currentPackageJson: string;
18
+ }
19
+
20
+ export interface RegistryDiffOutput {
21
+ name: string;
22
+ type: "registry:block";
23
+ dependencies: string[];
24
+ devDependencies: string[];
25
+ registryDependencies: string[];
26
+ files: ParsedFile[];
27
+ tailwind: Record<string, unknown>;
28
+ cssVars: Record<string, unknown>;
29
+ meta: Record<string, unknown>;
30
+ }
31
+
32
+ function addFile(
33
+ output: RegistryDiffOutput,
34
+ config: ComponentsConfig,
35
+ inSrcDir: boolean,
36
+ relativeFilePath: string,
37
+ content: string,
38
+ ): void {
39
+ if (!isBuiltinComponent(config, relativeFilePath)) {
40
+ output.files.push(
41
+ parseFilePath(inSrcDir, config, `./${relativeFilePath}`, content),
42
+ );
43
+ }
44
+ }
45
+
46
+ function addDependencies(
47
+ output: RegistryDiffOutput,
48
+ _initialPackageContents: string,
49
+ currentPackageContents: string,
50
+ usedPackages: Set<string>,
51
+ ): void {
52
+ const currentPackageJson = JSON.parse(currentPackageContents) as {
53
+ dependencies?: Record<string, string>;
54
+ devDependencies?: Record<string, string>;
55
+ };
56
+
57
+ const currentDependencies = currentPackageJson.dependencies ?? {};
58
+ const currentDevDependencies = currentPackageJson.devDependencies ?? {};
59
+
60
+ const shadcnNamespaces = new Set(
61
+ output.registryDependencies
62
+ .map((dep) => dep.split("/")[0])
63
+ .filter((ns) => ns === "@shadcn"),
64
+ );
65
+
66
+ const shouldKeepDep = (dep: string): boolean => {
67
+ if (!usedPackages.has(dep)) return false;
68
+ if (!shadcnNamespaces.size) return true;
69
+
70
+ if (dep === "shadcn/ui") return false;
71
+
72
+ for (const ns of shadcnNamespaces) {
73
+ if (dep === ns || dep === `${ns}/ui`) {
74
+ return false;
75
+ }
76
+ }
77
+
78
+ return true;
79
+ };
80
+
81
+ // Only include packages that are actually imported in the registry item files
82
+ // (and exist in package.json so we know dep vs devDep). No other deps.
83
+ output.dependencies = Object.keys(currentDependencies).filter(shouldKeepDep);
84
+ output.devDependencies = Object.keys(currentDevDependencies).filter(shouldKeepDep);
85
+ }
86
+
87
+ function scanWithSrcDir(
88
+ output: RegistryDiffOutput,
89
+ config: ComponentsConfig,
90
+ alteredFiles: ScannedFile[],
91
+ ): void {
92
+ for (const { path, content } of alteredFiles) {
93
+ if (path.startsWith("src/")) {
94
+ addFile(output, config, true, path.replace("src/", ""), content);
95
+ } else {
96
+ addFile(output, config, false, path, content);
97
+ }
98
+ }
99
+ }
100
+
101
+ function isInAppDir(filePath: string): boolean {
102
+ return filePath.startsWith("app/");
103
+ }
104
+
105
+ function scanWithoutSrcDir(
106
+ output: RegistryDiffOutput,
107
+ config: ComponentsConfig,
108
+ alteredFiles: ScannedFile[],
109
+ ): void {
110
+ const aliasedPaths = getAliasedPaths(config);
111
+
112
+ for (const { path, content } of alteredFiles) {
113
+ const inSrcDir = aliasedPaths.includes(path) || isInAppDir(path);
114
+ addFile(output, config, inSrcDir, path, content);
115
+ }
116
+ }
117
+
118
+ export function createDiff({
119
+ name,
120
+ config,
121
+ alteredFiles,
122
+ specificFiles,
123
+ currentFiles,
124
+ currentPackageJson,
125
+ }: CreateDiffOptions): RegistryDiffOutput {
126
+ const output: RegistryDiffOutput = {
127
+ name,
128
+ type: "registry:block",
129
+ dependencies: [],
130
+ devDependencies: [],
131
+ registryDependencies: [],
132
+ files: [],
133
+ tailwind: {},
134
+ cssVars: {},
135
+ meta: {},
136
+ };
137
+
138
+ if (config.isSrcDir) {
139
+ scanWithSrcDir(output, config, alteredFiles);
140
+ } else {
141
+ scanWithoutSrcDir(output, config, alteredFiles);
142
+ }
143
+
144
+ output.registryDependencies = findComponentFiles(config, currentFiles);
145
+
146
+ const usedPackages = extractImportedPackages(alteredFiles);
147
+ addDependencies(
148
+ output,
149
+ specificFiles["./package.json"],
150
+ currentPackageJson,
151
+ usedPackages,
152
+ );
153
+
154
+ return output;
155
+ }
156
+