@foundrykit/cli 0.1.2 → 1.0.1

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.
@@ -182,11 +182,76 @@ async function addSingleComponent(
182
182
  if (componentData.registryDependencies?.length) {
183
183
  console.log(chalk.blue('šŸ“¦ Installing required dependencies...'));
184
184
  for (const dep of componentData.registryDependencies) {
185
- // Check if dependency is already installed
186
- const depData = await registry.getComponent(dep);
187
- if (!(await hasConflictingFiles(depData, options))) {
188
- await installComponentFiles(depData, options);
189
- console.log(chalk.green(` āœ“ Installed ${dep}`));
185
+ try {
186
+ // Special handling for utility dependencies
187
+ if (dep === 'utils') {
188
+ // Check if utils already exists
189
+ const utilsPath = path.join(
190
+ options.path || process.cwd(),
191
+ 'lib/utils.ts'
192
+ );
193
+ if (!fs.existsSync(utilsPath)) {
194
+ // Create a basic utils file if it doesn't exist
195
+ await fs.ensureDir(path.dirname(utilsPath));
196
+ await fs.writeFile(
197
+ utilsPath,
198
+ `import { type ClassValue, clsx } from "clsx"
199
+ import { twMerge } from "tailwind-merge"
200
+
201
+ export function cn(...inputs: ClassValue[]) {
202
+ return twMerge(clsx(inputs))
203
+ }
204
+ `
205
+ );
206
+ console.log(chalk.green(` āœ“ Created ${dep} file`));
207
+ } else {
208
+ console.log(chalk.gray(` ā­ ${dep} already exists`));
209
+ }
210
+ } else {
211
+ // Try to fetch as a regular component
212
+ const depData = await registry.getComponent(dep);
213
+ if (!(await hasConflictingFiles(depData, options))) {
214
+ await installComponentFiles(depData, options);
215
+ console.log(chalk.green(` āœ“ Installed ${dep}`));
216
+ } else {
217
+ console.log(chalk.gray(` ā­ ${dep} already exists`));
218
+ }
219
+ }
220
+ } catch (error) {
221
+ // If dependency fetch fails, log warning but continue
222
+ console.log(
223
+ chalk.yellow(
224
+ ` ⚠ Could not install dependency "${dep}": ${
225
+ error instanceof Error ? error.message : 'Unknown error'
226
+ }`
227
+ )
228
+ );
229
+
230
+ // For utils specifically, create it if missing
231
+ if (
232
+ dep === 'utils' &&
233
+ error instanceof Error &&
234
+ error.message.includes('not found')
235
+ ) {
236
+ const utilsPath = path.join(
237
+ options.path || process.cwd(),
238
+ 'lib/utils.ts'
239
+ );
240
+ if (!fs.existsSync(utilsPath)) {
241
+ await fs.ensureDir(path.dirname(utilsPath));
242
+ await fs.writeFile(
243
+ utilsPath,
244
+ `import { type ClassValue, clsx } from "clsx"
245
+ import { twMerge } from "tailwind-merge"
246
+
247
+ export function cn(...inputs: ClassValue[]) {
248
+ return twMerge(clsx(inputs))
249
+ }
250
+ `
251
+ );
252
+ console.log(chalk.green(` āœ“ Created ${dep} file`));
253
+ }
254
+ }
190
255
  }
191
256
  }
192
257
  }
@@ -210,6 +275,15 @@ async function addSingleComponent(
210
275
  chalk.cyan(` pnpm add ${componentData.packageDependencies.join(' ')}`)
211
276
  );
212
277
  }
278
+
279
+ // Additional dependencies for utils
280
+ if (componentData.registryDependencies?.includes('utils')) {
281
+ const utilsDeps = ['clsx', 'tailwind-merge'];
282
+ console.log(chalk.yellow('\nšŸ“¦ Required packages for utils:'));
283
+ console.log(chalk.gray(` ${utilsDeps.join(', ')}`));
284
+ console.log(chalk.gray(' Install them with:'));
285
+ console.log(chalk.cyan(` pnpm add ${utilsDeps.join(' ')}`));
286
+ }
213
287
  } catch (error) {
214
288
  console.error(chalk.red(`Failed to add ${id}:`));
215
289
  throw error;
package/src/index.ts CHANGED
@@ -1,18 +1,28 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  import { Command } from 'commander';
4
+ import { readFileSync } from 'fs';
5
+ import { fileURLToPath } from 'url';
6
+ import { dirname, join } from 'path';
4
7
  import { initCommand } from './commands/init.js';
5
8
  import { listCommand } from './commands/list.js';
6
9
  import { addCommand } from './commands/add.js';
7
10
  import { updateCommand } from './commands/update.js';
8
11
  import { doctorCommand } from './commands/doctor.js';
9
12
 
13
+ // Get package.json version
14
+ const __filename = fileURLToPath(import.meta.url);
15
+ const __dirname = dirname(__filename);
16
+ const packageJson = JSON.parse(
17
+ readFileSync(join(__dirname, '..', 'package.json'), 'utf-8')
18
+ );
19
+
10
20
  const program = new Command();
11
21
 
12
22
  program
13
23
  .name('foundrykit')
14
24
  .description('FoundryKit CLI - Component library management tool')
15
- .version('0.1.0');
25
+ .version(packageJson.version);
16
26
 
17
27
  // Add commands
18
28
  program.addCommand(initCommand());
@@ -93,6 +93,12 @@ export class RegistryService {
93
93
  */
94
94
  async getComponent(id: string): Promise<ComponentData> {
95
95
  try {
96
+ // Special handling for common utility dependencies
97
+ if (id === 'utils') {
98
+ console.log(chalk.gray(`Creating utils dependency...`));
99
+ return this.createUtilsComponent();
100
+ }
101
+
96
102
  const url = `${this.config.registryUrl}/registry/${id}`;
97
103
  console.log(chalk.gray(`Fetching component: ${url}`));
98
104
 
@@ -100,6 +106,15 @@ export class RegistryService {
100
106
 
101
107
  if (!response.ok) {
102
108
  if (response.status === 404) {
109
+ // Check if it's a known special dependency
110
+ if (this.isSpecialDependency(id)) {
111
+ console.log(
112
+ chalk.yellow(
113
+ `Special dependency "${id}" will be handled separately`
114
+ )
115
+ );
116
+ return this.createSpecialDependency(id);
117
+ }
103
118
  throw new Error(`Component "${id}" not found in registry`);
104
119
  }
105
120
  throw new Error(
@@ -121,6 +136,12 @@ export class RegistryService {
121
136
  return cache.componentData[id];
122
137
  }
123
138
 
139
+ // Check if it's a special dependency that we can handle locally
140
+ if (this.isSpecialDependency(id)) {
141
+ console.log(chalk.yellow(`Creating local version of "${id}"`));
142
+ return this.createSpecialDependency(id);
143
+ }
144
+
124
145
  // No cached data, throw error
125
146
  throw new Error(
126
147
  `Failed to fetch component "${id}": ${error instanceof Error ? error.message : 'Unknown error'}\n` +
@@ -130,6 +151,56 @@ export class RegistryService {
130
151
  }
131
152
  }
132
153
 
154
+ /**
155
+ * Check if a dependency is a special/utility dependency
156
+ */
157
+ private isSpecialDependency(id: string): boolean {
158
+ const specialDeps = ['utils', 'lib', 'helpers', 'cn'];
159
+ return specialDeps.includes(id);
160
+ }
161
+
162
+ /**
163
+ * Create a special dependency component
164
+ */
165
+ private createSpecialDependency(id: string): ComponentData {
166
+ switch (id) {
167
+ case 'utils':
168
+ case 'lib':
169
+ case 'helpers':
170
+ case 'cn':
171
+ return this.createUtilsComponent();
172
+ default:
173
+ throw new Error(`Unknown special dependency: ${id}`);
174
+ }
175
+ }
176
+
177
+ /**
178
+ * Create a utils component with the cn function
179
+ */
180
+ private createUtilsComponent(): ComponentData {
181
+ return {
182
+ id: 'utils',
183
+ name: 'Utils',
184
+ category: 'primitives',
185
+ description: 'Utility functions for className merging',
186
+ tags: ['utility', 'helper'],
187
+ packageDependencies: ['clsx', 'tailwind-merge'],
188
+ files: [
189
+ {
190
+ path: 'lib/utils.ts',
191
+ type: 'util',
192
+ content: `import { type ClassValue, clsx } from 'clsx';
193
+ import { twMerge } from 'tailwind-merge';
194
+
195
+ export function cn(...inputs: ClassValue[]) {
196
+ return twMerge(clsx(inputs));
197
+ }
198
+ `,
199
+ },
200
+ ],
201
+ };
202
+ }
203
+
133
204
  /**
134
205
  * Update the local cache with new component list
135
206
  */
@@ -0,0 +1,289 @@
1
+ /**
2
+ * Tests for dependency resolution in the CLI
3
+ */
4
+
5
+ import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
6
+ import fs from 'fs-extra';
7
+ import path from 'path';
8
+ import os from 'os';
9
+ import { RegistryService } from '../src/lib/registry';
10
+ import type { ComponentData } from '@foundrykit/types';
11
+
12
+ describe('Dependency Resolution', () => {
13
+ let testDir: string;
14
+ let registry: RegistryService;
15
+
16
+ beforeEach(async () => {
17
+ // Create a temporary test directory
18
+ testDir = path.join(os.tmpdir(), 'foundrykit-test-' + Date.now());
19
+ await fs.ensureDir(testDir);
20
+
21
+ // Create a registry instance with test config
22
+ registry = new RegistryService({
23
+ registryUrl: 'https://test.registry.com',
24
+ cacheDir: path.join(testDir, '.cache'),
25
+ cacheMaxAge: 1000 * 60 * 60,
26
+ });
27
+
28
+ // Mock fetch
29
+ global.fetch = vi.fn();
30
+ });
31
+
32
+ afterEach(async () => {
33
+ // Clean up test directory
34
+ if (await fs.pathExists(testDir)) {
35
+ await fs.remove(testDir);
36
+ }
37
+ vi.restoreAllMocks();
38
+ });
39
+
40
+ describe('Special Dependencies', () => {
41
+ it('should create utils dependency locally without fetching', async () => {
42
+ const component = await registry.getComponent('utils');
43
+
44
+ expect(component).toBeDefined();
45
+ expect(component.id).toBe('utils');
46
+ expect(component.files).toHaveLength(1);
47
+ expect(component.files[0].path).toBe('lib/utils.ts');
48
+ expect(component.files[0].content).toContain('cn');
49
+ expect(component.files[0].content).toContain('clsx');
50
+ expect(component.files[0].content).toContain('twMerge');
51
+ });
52
+
53
+ it('should handle lib alias for utils', async () => {
54
+ const component = await registry.getComponent('lib');
55
+
56
+ expect(component).toBeDefined();
57
+ expect(component.id).toBe('utils');
58
+ expect(component.files[0].path).toBe('lib/utils.ts');
59
+ });
60
+
61
+ it('should handle helpers alias for utils', async () => {
62
+ const component = await registry.getComponent('helpers');
63
+
64
+ expect(component).toBeDefined();
65
+ expect(component.id).toBe('utils');
66
+ expect(component.files[0].path).toBe('lib/utils.ts');
67
+ });
68
+
69
+ it('should handle cn alias for utils', async () => {
70
+ const component = await registry.getComponent('cn');
71
+
72
+ expect(component).toBeDefined();
73
+ expect(component.id).toBe('utils');
74
+ expect(component.files[0].path).toBe('lib/utils.ts');
75
+ });
76
+ });
77
+
78
+ describe('Registry Component Fetching', () => {
79
+ it('should fetch regular components from registry', async () => {
80
+ const mockComponent: ComponentData = {
81
+ id: 'button',
82
+ name: 'Button',
83
+ category: 'components',
84
+ description: 'A button component',
85
+ files: [
86
+ {
87
+ path: 'components/ui/button.tsx',
88
+ type: 'component',
89
+ content: 'export function Button() { return <button />; }',
90
+ },
91
+ ],
92
+ };
93
+
94
+ (global.fetch as any).mockResolvedValueOnce({
95
+ ok: true,
96
+ json: async () => mockComponent,
97
+ });
98
+
99
+ const component = await registry.getComponent('button');
100
+
101
+ expect(component).toEqual(mockComponent);
102
+ expect(global.fetch).toHaveBeenCalledWith(
103
+ 'https://test.registry.com/registry/button'
104
+ );
105
+ });
106
+
107
+ it('should handle 404 errors for non-existent components', async () => {
108
+ (global.fetch as any).mockResolvedValueOnce({
109
+ ok: false,
110
+ status: 404,
111
+ statusText: 'Not Found',
112
+ });
113
+
114
+ await expect(registry.getComponent('non-existent')).rejects.toThrow(
115
+ 'Component "non-existent" not found in registry'
116
+ );
117
+ });
118
+
119
+ it('should handle network errors gracefully', async () => {
120
+ (global.fetch as any).mockRejectedValueOnce(new Error('Network error'));
121
+
122
+ await expect(registry.getComponent('button')).rejects.toThrow(
123
+ 'Failed to fetch component "button"'
124
+ );
125
+ });
126
+ });
127
+
128
+ describe('Cache Management', () => {
129
+ it('should cache fetched components', async () => {
130
+ const mockComponent: ComponentData = {
131
+ id: 'card',
132
+ name: 'Card',
133
+ category: 'components',
134
+ description: 'A card component',
135
+ files: [
136
+ {
137
+ path: 'components/ui/card.tsx',
138
+ type: 'component',
139
+ content: 'export function Card() { return <div />; }',
140
+ },
141
+ ],
142
+ };
143
+
144
+ (global.fetch as any).mockResolvedValueOnce({
145
+ ok: true,
146
+ json: async () => mockComponent,
147
+ });
148
+
149
+ // First fetch - should call API
150
+ await registry.getComponent('card');
151
+ expect(global.fetch).toHaveBeenCalledTimes(1);
152
+
153
+ // Second fetch - should use cache
154
+ (global.fetch as any).mockRejectedValueOnce(new Error('Network error'));
155
+ const cached = await registry.getComponent('card');
156
+
157
+ expect(cached).toEqual(mockComponent);
158
+ });
159
+
160
+ it('should clear cache when requested', async () => {
161
+ const cacheFile = path.join(testDir, '.cache', 'registry.json');
162
+
163
+ // Create a cache file
164
+ await fs.ensureDir(path.dirname(cacheFile));
165
+ await fs.writeJson(cacheFile, { test: 'data' });
166
+
167
+ await registry.clearCache();
168
+
169
+ expect(await fs.pathExists(cacheFile)).toBe(false);
170
+ });
171
+
172
+ it('should provide cache statistics', async () => {
173
+ const stats = await registry.getCacheStats();
174
+
175
+ expect(stats).toHaveProperty('exists');
176
+ expect(stats).toHaveProperty('size');
177
+ expect(stats).toHaveProperty('lastUpdated');
178
+ expect(stats).toHaveProperty('componentCount');
179
+ });
180
+ });
181
+
182
+ describe('Component Installation', () => {
183
+ it('should not overwrite existing utils file', async () => {
184
+ const utilsPath = path.join(testDir, 'lib', 'utils.ts');
185
+ const customContent = '// Custom utils implementation';
186
+
187
+ await fs.ensureDir(path.dirname(utilsPath));
188
+ await fs.writeFile(utilsPath, customContent);
189
+
190
+ // Simulate checking for existing file
191
+ const exists = await fs.pathExists(utilsPath);
192
+ expect(exists).toBe(true);
193
+
194
+ const content = await fs.readFile(utilsPath, 'utf-8');
195
+ expect(content).toBe(customContent);
196
+ });
197
+
198
+ it('should create utils file if it does not exist', async () => {
199
+ const utilsPath = path.join(testDir, 'lib', 'utils.ts');
200
+
201
+ expect(await fs.pathExists(utilsPath)).toBe(false);
202
+
203
+ // Get utils component
204
+ const utils = await registry.getComponent('utils');
205
+
206
+ // Simulate installation
207
+ await fs.ensureDir(path.dirname(utilsPath));
208
+ await fs.writeFile(utilsPath, utils.files[0].content);
209
+
210
+ expect(await fs.pathExists(utilsPath)).toBe(true);
211
+
212
+ const content = await fs.readFile(utilsPath, 'utf-8');
213
+ expect(content).toContain('cn');
214
+ expect(content).toContain('clsx');
215
+ });
216
+ });
217
+
218
+ describe('Dependency Chain Resolution', () => {
219
+ it('should resolve multiple dependencies in order', async () => {
220
+ const dependencies = ['utils', 'button', 'card'];
221
+ const resolved: string[] = [];
222
+
223
+ for (const dep of dependencies) {
224
+ if (dep === 'utils') {
225
+ const component = await registry.getComponent(dep);
226
+ expect(component.id).toBe('utils');
227
+ resolved.push(dep);
228
+ } else {
229
+ // Mock registry fetch for other components
230
+ (global.fetch as any).mockResolvedValueOnce({
231
+ ok: true,
232
+ json: async () => ({
233
+ id: dep,
234
+ name: dep.charAt(0).toUpperCase() + dep.slice(1),
235
+ category: 'components',
236
+ description: `A ${dep} component`,
237
+ files: [],
238
+ }),
239
+ });
240
+
241
+ const component = await registry.getComponent(dep);
242
+ expect(component.id).toBe(dep);
243
+ resolved.push(dep);
244
+ }
245
+ }
246
+
247
+ expect(resolved).toEqual(dependencies);
248
+ });
249
+
250
+ it('should continue installation when a dependency fails', async () => {
251
+ const dependencies = ['utils', 'non-existent', 'button'];
252
+ const resolved: string[] = [];
253
+ const failed: string[] = [];
254
+
255
+ for (const dep of dependencies) {
256
+ try {
257
+ if (dep === 'utils') {
258
+ await registry.getComponent(dep);
259
+ resolved.push(dep);
260
+ } else if (dep === 'non-existent') {
261
+ (global.fetch as any).mockResolvedValueOnce({
262
+ ok: false,
263
+ status: 404,
264
+ });
265
+ await registry.getComponent(dep);
266
+ } else {
267
+ (global.fetch as any).mockResolvedValueOnce({
268
+ ok: true,
269
+ json: async () => ({
270
+ id: dep,
271
+ name: 'Button',
272
+ category: 'components',
273
+ description: 'A button',
274
+ files: [],
275
+ }),
276
+ });
277
+ await registry.getComponent(dep);
278
+ resolved.push(dep);
279
+ }
280
+ } catch (error) {
281
+ failed.push(dep);
282
+ }
283
+ }
284
+
285
+ expect(resolved).toEqual(['utils', 'button']);
286
+ expect(failed).toEqual(['non-existent']);
287
+ });
288
+ });
289
+ });