@foundrykit/cli 1.0.0 → 1.0.2

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.
@@ -8,6 +8,8 @@ import chalk from 'chalk';
8
8
  import fs from 'fs-extra';
9
9
  import path from 'path';
10
10
  import inquirer from 'inquirer';
11
+ import { exec } from 'child_process';
12
+ import { promisify } from 'util';
11
13
  import type {
12
14
  ComponentMeta,
13
15
  ComponentData,
@@ -15,6 +17,8 @@ import type {
15
17
  } from '@foundrykit/types';
16
18
  import { getRegistry } from '../lib/registry.js';
17
19
 
20
+ const execAsync = promisify(exec);
21
+
18
22
  interface AddOptions {
19
23
  withAnimation?: boolean;
20
24
  path?: string;
@@ -182,11 +186,28 @@ async function addSingleComponent(
182
186
  if (componentData.registryDependencies?.length) {
183
187
  console.log(chalk.blue('📦 Installing required dependencies...'));
184
188
  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}`));
189
+ try {
190
+ // Fetch dependency from registry
191
+ const depData = await registry.getComponent(dep);
192
+
193
+ // Check if dependency files already exist
194
+ const hasExisting = await hasConflictingFiles(depData, options);
195
+
196
+ if (!hasExisting) {
197
+ await installComponentFiles(depData, options);
198
+ console.log(chalk.green(` ✓ Installed ${dep}`));
199
+ } else {
200
+ console.log(chalk.gray(` ⏭ ${dep} already exists`));
201
+ }
202
+ } catch (error) {
203
+ // If dependency fetch fails, log warning but continue
204
+ console.log(
205
+ chalk.yellow(
206
+ ` ⚠ Could not install dependency "${dep}": ${
207
+ error instanceof Error ? error.message : 'Unknown error'
208
+ }`
209
+ )
210
+ );
190
211
  }
191
212
  }
192
213
  }
@@ -199,17 +220,8 @@ async function addSingleComponent(
199
220
  // Show usage example
200
221
  showUsageExample(componentData);
201
222
 
202
- // Show package dependencies if any
203
- if (componentData.packageDependencies?.length) {
204
- console.log(chalk.yellow('\n📦 Required npm packages:'));
205
- console.log(
206
- chalk.gray(` ${componentData.packageDependencies.join(', ')}`)
207
- );
208
- console.log(chalk.gray(' Install them with:'));
209
- console.log(
210
- chalk.cyan(` pnpm add ${componentData.packageDependencies.join(' ')}`)
211
- );
212
- }
223
+ // Handle package dependencies
224
+ await handlePackageDependencies(componentData);
213
225
  } catch (error) {
214
226
  console.error(chalk.red(`Failed to add ${id}:`));
215
227
  throw error;
@@ -287,6 +299,110 @@ async function installComponentFiles(
287
299
  }
288
300
  }
289
301
 
302
+ /**
303
+ * Handle package dependencies - check and auto-install if needed
304
+ */
305
+ async function handlePackageDependencies(
306
+ componentData: ComponentData
307
+ ): Promise<void> {
308
+ const allDependencies = new Set<string>();
309
+
310
+ // Add component's package dependencies
311
+ if (componentData.packageDependencies?.length) {
312
+ componentData.packageDependencies.forEach(dep => allDependencies.add(dep));
313
+ }
314
+
315
+ // Add utils dependencies if utils is a dependency
316
+ if (componentData.registryDependencies?.includes('utils')) {
317
+ allDependencies.add('clsx');
318
+ allDependencies.add('tailwind-merge');
319
+ }
320
+
321
+ // Add class-variance-authority for button
322
+ if (componentData.id === 'button') {
323
+ allDependencies.add('class-variance-authority');
324
+ }
325
+
326
+ if (allDependencies.size === 0) {
327
+ return;
328
+ }
329
+
330
+ // Check which packages are already installed
331
+ const missingPackages = await getMissingPackages(Array.from(allDependencies));
332
+
333
+ if (missingPackages.length === 0) {
334
+ console.log(chalk.green('✅ All required packages are already installed'));
335
+ return;
336
+ }
337
+
338
+ console.log(chalk.yellow('\n📦 Installing required packages...'));
339
+ console.log(chalk.gray(` ${missingPackages.join(', ')}`));
340
+
341
+ // Try to detect package manager
342
+ const packageManager = await detectPackageManager();
343
+
344
+ try {
345
+ const installCommand = `${packageManager} add ${missingPackages.join(' ')}`;
346
+ console.log(chalk.blue(` Running: ${installCommand}`));
347
+
348
+ const { stdout, stderr } = await execAsync(installCommand);
349
+
350
+ if (stderr && !stderr.includes('warning')) {
351
+ console.error(chalk.yellow(` Warning: ${stderr}`));
352
+ }
353
+
354
+ console.log(chalk.green('✅ Packages installed successfully'));
355
+ } catch (error) {
356
+ console.log(chalk.yellow('\n⚠️ Could not install packages automatically'));
357
+ console.log(chalk.gray(' Please install them manually:'));
358
+ console.log(
359
+ chalk.cyan(` ${packageManager} add ${missingPackages.join(' ')}`)
360
+ );
361
+ }
362
+ }
363
+
364
+ /**
365
+ * Check which packages are missing from the project
366
+ */
367
+ async function getMissingPackages(packages: string[]): Promise<string[]> {
368
+ const packageJsonPath = path.join(process.cwd(), 'package.json');
369
+
370
+ try {
371
+ const packageJson = await fs.readJson(packageJsonPath);
372
+ const installedPackages = {
373
+ ...packageJson.dependencies,
374
+ ...packageJson.devDependencies,
375
+ };
376
+
377
+ return packages.filter(pkg => !installedPackages[pkg]);
378
+ } catch (error) {
379
+ // If we can't read package.json, assume all packages are missing
380
+ return packages;
381
+ }
382
+ }
383
+
384
+ /**
385
+ * Detect which package manager is being used
386
+ */
387
+ async function detectPackageManager(): Promise<string> {
388
+ // Check for lock files
389
+ if (await fs.pathExists(path.join(process.cwd(), 'pnpm-lock.yaml'))) {
390
+ return 'pnpm';
391
+ }
392
+ if (await fs.pathExists(path.join(process.cwd(), 'yarn.lock'))) {
393
+ return 'yarn';
394
+ }
395
+ if (await fs.pathExists(path.join(process.cwd(), 'package-lock.json'))) {
396
+ return 'npm';
397
+ }
398
+ if (await fs.pathExists(path.join(process.cwd(), 'bun.lockb'))) {
399
+ return 'bun';
400
+ }
401
+
402
+ // Default to pnpm as it's what FoundryKit uses
403
+ return 'pnpm';
404
+ }
405
+
290
406
  /**
291
407
  * Show usage example for the installed component
292
408
  */
@@ -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
+ });