@foundrykit/cli 2.0.11 → 3.0.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.
@@ -1,1065 +0,0 @@
1
- /**
2
- * Add command for FoundryKit CLI
3
- * Handles adding components to projects
4
- */
5
-
6
- import { Command } from 'commander';
7
- import chalk from 'chalk';
8
- import fs from 'fs-extra';
9
- import path from 'path';
10
- import inquirer from 'inquirer';
11
- import { exec } from 'child_process';
12
- import { promisify } from 'util';
13
- import type {
14
- ComponentMeta,
15
- ComponentData,
16
- ComponentCategory,
17
- Config,
18
- } from '@foundrykit/types';
19
- import { getRegistry } from '../lib/registry.js';
20
- import { CLI_VERSION, REGISTRY_CATEGORY_ORDER } from '../lib/constants.js';
21
-
22
- const execAsync = promisify(exec);
23
-
24
- interface AddOptions {
25
- withAnimation?: boolean;
26
- path?: string;
27
- overwrite?: boolean;
28
- force?: boolean;
29
- }
30
-
31
- export type { AddOptions };
32
-
33
- export function addCommand() {
34
- return new Command('add')
35
- .description('Add a component or block to your project')
36
- .argument('[id]', 'Component or block ID (optional for interactive mode)')
37
- .option('--with-animation', 'Include animation variants')
38
- .option('-p, --path <path>', 'Custom installation path')
39
- .option('-o, --overwrite', 'Overwrite existing files')
40
- .action(async (id: string | undefined, options: AddOptions) => {
41
- try {
42
- // If no ID provided, show interactive selector
43
- if (!id) {
44
- const selectedIds = await selectComponentsInteractively();
45
- if (selectedIds.length === 0) {
46
- console.log(chalk.yellow('No components selected.'));
47
- return;
48
- }
49
-
50
- // Add each selected component
51
- for (const componentId of selectedIds) {
52
- await addSingleComponent(componentId, options);
53
- }
54
- } else {
55
- // Add single component
56
- await addSingleComponent(id, options);
57
- }
58
- } catch (error) {
59
- console.error(chalk.red('❌ Failed to add component:'));
60
- console.error(
61
- chalk.red(error instanceof Error ? error.message : String(error))
62
- );
63
- process.exit(1);
64
- }
65
- });
66
- }
67
-
68
- /**
69
- * Interactive component selection
70
- */
71
- async function selectComponentsInteractively(): Promise<string[]> {
72
- console.log(chalk.blue('📦 Select components to add:'));
73
- console.log(
74
- chalk.gray(' Use arrow keys to navigate, space to select, a to toggle all')
75
- );
76
- console.log(chalk.gray(' Press enter when done\n'));
77
-
78
- const registry = getRegistry();
79
-
80
- try {
81
- // Fetch all available components from registry
82
- console.log(chalk.gray('Fetching components from registry...'));
83
- const allComponents = await registry.getComponents();
84
-
85
- if (allComponents.length === 0) {
86
- console.log(chalk.yellow('No components available in the registry.'));
87
- return [];
88
- }
89
-
90
- // Group components by category
91
- const groupedChoices = createGroupedChoices(allComponents);
92
-
93
- const { selectedComponents } = await inquirer.prompt([
94
- {
95
- type: 'checkbox',
96
- name: 'selectedComponents',
97
- message: 'Which components would you like to add?',
98
- choices: groupedChoices,
99
- pageSize: 20,
100
- loop: false,
101
- },
102
- ]);
103
-
104
- return selectedComponents;
105
- } catch (error) {
106
- console.error(chalk.red('Failed to fetch components from registry:'));
107
- console.error(
108
- chalk.red(error instanceof Error ? error.message : String(error))
109
- );
110
- throw error;
111
- }
112
- }
113
-
114
- /**
115
- * Create grouped choices for the interactive selector
116
- */
117
- function createGroupedChoices(components: ComponentMeta[]) {
118
- const knownCategories = new Set<ComponentCategory>(
119
- REGISTRY_CATEGORY_ORDER as readonly ComponentCategory[]
120
- );
121
- const categories: ComponentCategory[] = [
122
- ...(REGISTRY_CATEGORY_ORDER as readonly ComponentCategory[]),
123
- ...components
124
- .map(component => component.category)
125
- .filter(category => !knownCategories.has(category)),
126
- ];
127
-
128
- const choices: any[] = [];
129
-
130
- for (const category of categories) {
131
- const categoryComponents = components.filter(c => c.category === category);
132
-
133
- if (categoryComponents.length === 0) continue;
134
-
135
- // Add category separator
136
- choices.push({
137
- name: chalk.bold.cyan(`─── ${category.toUpperCase()} ───`),
138
- disabled: true,
139
- value: `separator-${category}`,
140
- });
141
-
142
- // Add components in this category
143
- for (const component of categoryComponents) {
144
- choices.push({
145
- name: `${component.name} - ${chalk.gray(component.description)}`,
146
- value: component.id,
147
- short: component.name,
148
- });
149
- }
150
- }
151
-
152
- return choices;
153
- }
154
-
155
- /**
156
- * Add a single component to the project
157
- */
158
- export async function addSingleComponent(
159
- id: string,
160
- options: AddOptions
161
- ): Promise<void> {
162
- console.log(chalk.blue(`\n📦 Adding ${id} to your project...`));
163
-
164
- // Validate project is initialized
165
- await validateProject();
166
-
167
- const registry = getRegistry();
168
-
169
- try {
170
- // Fetch component data from registry
171
- const componentData = await registry.getComponent(id, options.force);
172
-
173
- // Check for existing files
174
- if (
175
- !options.overwrite &&
176
- (await hasConflictingFiles(componentData, options))
177
- ) {
178
- const { shouldContinue } = await inquirer.prompt([
179
- {
180
- type: 'confirm',
181
- name: 'shouldContinue',
182
- message: `Some files for ${componentData.name} already exist. Overwrite?`,
183
- default: false,
184
- },
185
- ]);
186
-
187
- if (!shouldContinue) {
188
- console.log(chalk.yellow(`⏭️ Skipping ${componentData.name}.`));
189
- return;
190
- }
191
- }
192
-
193
- // Install registry dependencies first
194
- if (componentData.registryDependencies?.length) {
195
- console.log(chalk.blue('📦 Installing required dependencies...'));
196
- for (const dep of componentData.registryDependencies) {
197
- try {
198
- // Fetch dependency from registry
199
- const depData = await registry.getComponent(dep);
200
-
201
- // Handle package dependencies (hooks, types) differently
202
- if (['hooks', 'types'].includes(dep)) {
203
- console.log(chalk.green(` ✓ ${dep} package is available`));
204
- continue;
205
- }
206
-
207
- // Check if dependency files already exist
208
- const hasExisting = await hasConflictingFiles(depData, options);
209
-
210
- if (!hasExisting) {
211
- await installComponentFiles(depData, options);
212
- console.log(chalk.green(` ✓ Installed ${dep}`));
213
- } else {
214
- console.log(chalk.gray(` ⏭ ${dep} already exists`));
215
- }
216
- } catch (error) {
217
- // If dependency fetch fails, log warning but continue
218
- console.log(
219
- chalk.yellow(
220
- ` ⚠ Could not install dependency "${dep}": ${
221
- error instanceof Error ? error.message : 'Unknown error'
222
- }`
223
- )
224
- );
225
- }
226
- }
227
- }
228
-
229
- // Install the component files
230
- await installComponentFiles(componentData, options);
231
-
232
- // Track the installed component in config
233
- await trackInstalledComponent(componentData);
234
-
235
- console.log(chalk.green(`✅ ${componentData.name} added successfully!`));
236
-
237
- // Show usage example
238
- showUsageExample(componentData);
239
-
240
- // Handle package dependencies
241
- await handlePackageDependencies(componentData, options);
242
- } catch (error) {
243
- console.error(chalk.red(`Failed to add ${id}:`));
244
- throw error;
245
- }
246
- }
247
-
248
- /**
249
- * Update config version to match CLI version
250
- */
251
- export async function updateConfigVersion(): Promise<void> {
252
- const configPath = path.join(process.cwd(), 'foundrykit.config.json');
253
- if (fs.existsSync(configPath)) {
254
- const config = await fs.readJson(configPath);
255
- if (config.version !== CLI_VERSION) {
256
- config.version = CLI_VERSION;
257
- await fs.writeJson(configPath, config, { spaces: 2 });
258
- }
259
- }
260
- }
261
-
262
- /**
263
- * Validate that the project is properly initialized
264
- */
265
- export async function validateProject(): Promise<void> {
266
- const packageJsonPath = path.join(process.cwd(), 'package.json');
267
-
268
- if (!fs.existsSync(packageJsonPath)) {
269
- throw new Error(
270
- 'No package.json found. Please run this command in a project root.'
271
- );
272
- }
273
-
274
- // Check for configuration file
275
- const configPath = path.join(process.cwd(), 'foundrykit.config.json');
276
- if (!fs.existsSync(configPath)) {
277
- throw new Error('FoundryKit not initialized. Run "foundrykit init" first.');
278
- }
279
-
280
- // Update config version if needed
281
- await updateConfigVersion();
282
- }
283
-
284
- /**
285
- * Check if component files already exist
286
- */
287
- export async function hasConflictingFiles(
288
- componentData: ComponentData,
289
- options: AddOptions
290
- ): Promise<boolean> {
291
- const config = await loadConfig();
292
- const basePath = options.path || process.cwd();
293
-
294
- for (const file of componentData.files) {
295
- // Special handling for utils to ensure it always goes to the right place
296
- let resolvedPath: string;
297
- if (componentData.id === 'utils' || file.path === 'lib/utils.ts') {
298
- resolvedPath = config.paths.utils || 'lib/utils.ts';
299
- } else {
300
- resolvedPath = resolveComponentPath(
301
- file.path,
302
- componentData.category,
303
- config
304
- );
305
- }
306
- const filePath = path.join(basePath, resolvedPath);
307
- if (fs.existsSync(filePath)) {
308
- return true;
309
- }
310
- }
311
-
312
- return false;
313
- }
314
-
315
- /**
316
- * Install component files to the project
317
- */
318
- export async function installComponentFiles(
319
- componentData: ComponentData,
320
- options: AddOptions
321
- ): Promise<void> {
322
- const config = await loadConfig();
323
- const basePath = options.path || process.cwd();
324
-
325
- if (componentData.files.length === 0) {
326
- return;
327
- }
328
-
329
- console.log(chalk.blue('📝 Installing component files...'));
330
-
331
- for (const file of componentData.files) {
332
- // Special handling for utils to ensure it always goes to the right place
333
- let resolvedPath: string;
334
- if (componentData.id === 'utils' || file.path === 'lib/utils.ts') {
335
- resolvedPath = config.paths.utils || 'lib/utils.ts';
336
- } else {
337
- resolvedPath = resolveComponentPath(
338
- file.path,
339
- componentData.category,
340
- config
341
- );
342
- }
343
-
344
- const filePath = path.join(basePath, resolvedPath);
345
-
346
- // Ensure directory exists
347
- await fs.ensureDir(path.dirname(filePath));
348
-
349
- // Check if file has content before writing
350
- if (!file.content || file.content.trim() === '') {
351
- console.log(
352
- chalk.yellow(` ⚠ Skipping ${resolvedPath} - no content available`)
353
- );
354
- continue;
355
- }
356
-
357
- // Transform imports based on config
358
- const transformedContent = transformImportsForConfig(file.content, config);
359
-
360
- // Write the file
361
- await fs.writeFile(filePath, transformedContent);
362
- console.log(chalk.gray(` ✓ Created ${resolvedPath}`));
363
- }
364
-
365
- // Update config version after successful installation
366
- await updateConfigVersion();
367
- }
368
-
369
- /**
370
- * Record an installed component in foundrykit.config.json
371
- */
372
- export async function trackInstalledComponent(
373
- componentData: ComponentData
374
- ): Promise<void> {
375
- const configPath = path.join(process.cwd(), 'foundrykit.config.json');
376
- if (!fs.existsSync(configPath)) return;
377
-
378
- const config = await fs.readJson(configPath);
379
- config.installedComponents = config.installedComponents ?? {};
380
- config.installedComponents[componentData.id] = {
381
- id: componentData.id,
382
- version: componentData.version ?? null,
383
- installedAt: new Date().toISOString(),
384
- };
385
- await fs.writeJson(configPath, config, { spaces: 2 });
386
- }
387
-
388
- /**
389
- * Handle package dependencies - check and auto-install if needed
390
- */
391
- export async function handlePackageDependencies(
392
- componentData: ComponentData,
393
- options: AddOptions = {}
394
- ): Promise<void> {
395
- // Only use the package dependencies specified by the component
396
- const allDependencies = new Set<string>();
397
-
398
- if (componentData.packageDependencies?.length) {
399
- componentData.packageDependencies.forEach(dep => allDependencies.add(dep));
400
- }
401
-
402
- if (allDependencies.size === 0) {
403
- return;
404
- }
405
-
406
- const dependencies = Array.from(allDependencies);
407
- const forcePackageUpdate =
408
- componentData.files.length === 0 && (options.force || options.overwrite);
409
- const missingPackages = forcePackageUpdate
410
- ? dependencies
411
- : await getMissingPackages(dependencies);
412
-
413
- if (missingPackages.length === 0) {
414
- console.log(chalk.green('✅ All required packages are already installed'));
415
- return;
416
- }
417
-
418
- const packagesToInstall = missingPackages.map(pkg =>
419
- forcePackageUpdate
420
- ? getPackageInstallSpec(pkg, componentData.version)
421
- : pkg
422
- );
423
-
424
- console.log(
425
- chalk.yellow(
426
- forcePackageUpdate
427
- ? '\n📦 Updating required packages...'
428
- : '\n📦 Installing required packages...'
429
- )
430
- );
431
- console.log(chalk.gray(` ${packagesToInstall.join(', ')}`));
432
-
433
- // Try to detect package manager
434
- const packageManager = await detectPackageManager();
435
-
436
- try {
437
- const installCommand = `${packageManager} add ${packagesToInstall.join(' ')}`;
438
- console.log(chalk.blue(` Running: ${installCommand}`));
439
-
440
- const { stdout, stderr } = await execAsync(installCommand);
441
-
442
- if (stderr && !stderr.includes('warning')) {
443
- console.error(chalk.yellow(` Warning: ${stderr}`));
444
- }
445
-
446
- console.log(chalk.green('✅ Packages installed successfully'));
447
- } catch (error) {
448
- console.log(chalk.yellow('\n⚠️ Could not install packages automatically'));
449
- console.log(chalk.gray(' Please install them manually:'));
450
- console.log(
451
- chalk.cyan(` ${packageManager} add ${packagesToInstall.join(' ')}`)
452
- );
453
- }
454
- }
455
-
456
- function getPackageInstallSpec(packageName: string, version?: string): string {
457
- if (!packageName.startsWith('@foundrykit/')) {
458
- return packageName;
459
- }
460
-
461
- return `${packageName}@${version ?? 'latest'}`;
462
- }
463
-
464
- /**
465
- * Check which packages are missing from the project
466
- */
467
- export async function getMissingPackages(
468
- packages: string[]
469
- ): Promise<string[]> {
470
- const packageJsonPath = path.join(process.cwd(), 'package.json');
471
-
472
- try {
473
- const packageJson = await fs.readJson(packageJsonPath);
474
- const installedPackages = {
475
- ...packageJson.dependencies,
476
- ...packageJson.devDependencies,
477
- };
478
-
479
- return packages.filter(pkg => !installedPackages[pkg]);
480
- } catch (error) {
481
- // If we can't read package.json, assume all packages are missing
482
- return packages;
483
- }
484
- }
485
-
486
- /**
487
- * Detect which package manager is being used
488
- */
489
- export async function detectPackageManager(): Promise<string> {
490
- // Check for lock files
491
- if (await fs.pathExists(path.join(process.cwd(), 'pnpm-lock.yaml'))) {
492
- return 'pnpm';
493
- }
494
- if (await fs.pathExists(path.join(process.cwd(), 'yarn.lock'))) {
495
- return 'yarn';
496
- }
497
- if (await fs.pathExists(path.join(process.cwd(), 'package-lock.json'))) {
498
- return 'npm';
499
- }
500
- if (await fs.pathExists(path.join(process.cwd(), 'bun.lockb'))) {
501
- return 'bun';
502
- }
503
-
504
- // Default to pnpm as it's what FoundryKit uses
505
- return 'pnpm';
506
- }
507
-
508
- /**
509
- * Show usage example for the installed component
510
- */
511
- export async function showUsageExample(
512
- componentData: ComponentData
513
- ): Promise<void> {
514
- const config = await loadConfig();
515
- console.log(chalk.cyan('\n💡 Usage:'));
516
-
517
- if (componentData.files.length === 0) {
518
- const packageName = componentData.packageDependencies?.find(dep =>
519
- dep.startsWith('@foundrykit/')
520
- );
521
- if (packageName) {
522
- console.log(chalk.gray(`import { ... } from "${packageName}"`));
523
- }
524
- return;
525
- }
526
-
527
- const componentName = componentData.name.replace(/\s+/g, '');
528
- const importPath = getImportPath(componentData, config);
529
-
530
- console.log(chalk.gray(`import { ${componentName} } from "${importPath}"`));
531
-
532
- // Show usage example if provided in component data
533
- if (componentData.usageExample) {
534
- console.log(chalk.gray(`\n${componentData.usageExample}`));
535
- }
536
- }
537
-
538
- /**
539
- * Load FoundryKit configuration
540
- */
541
- export async function loadConfig(): Promise<Config> {
542
- const configPath = path.join(process.cwd(), 'foundrykit.config.json');
543
- if (!fs.existsSync(configPath)) {
544
- throw new Error(
545
- 'Configuration file not found. Run "foundrykit init" first.'
546
- );
547
- }
548
- return fs.readJson(configPath);
549
- }
550
-
551
- /**
552
- * Transform imports in file content based on config
553
- */
554
- export function transformImportsForConfig(
555
- content: string,
556
- config: Config
557
- ): string {
558
- let transformed = content;
559
-
560
- const importPaths = getConfiguredImportPaths(config);
561
-
562
- transformed = transformRegistryBarrelImports(
563
- transformed,
564
- ['@foundrykit/primitives', '@/components/primitives', '@/components/ui'],
565
- importPaths.primitives,
566
- config,
567
- 'primitives'
568
- );
569
-
570
- transformed = transformRegistryBarrelImports(
571
- transformed,
572
- ['@foundrykit/components', '@/components/components'],
573
- importPaths.components,
574
- config,
575
- 'components'
576
- );
577
-
578
- transformed = transformRegistryBarrelImports(
579
- transformed,
580
- ['@foundrykit/blocks', '@/components/blocks'],
581
- importPaths.blocks,
582
- config,
583
- 'blocks'
584
- );
585
-
586
- transformed = transformRegistryBarrelImports(
587
- transformed,
588
- ['@foundrykit/animation', '@/components/animations'],
589
- importPaths.animations,
590
- config,
591
- 'animations'
592
- );
593
-
594
- transformed = transformRegistryBarrelImports(
595
- transformed,
596
- ['@foundrykit/maps', '@/components/maps'],
597
- importPaths.maps,
598
- config,
599
- 'maps'
600
- );
601
-
602
- transformed = transformRegistryBarrelImports(
603
- transformed,
604
- ['@foundrykit/hooks', '@/hooks'],
605
- importPaths.hooks,
606
- config,
607
- 'hooks'
608
- );
609
-
610
- // Handle utils imports
611
- transformed = transformed
612
- .replace(/@foundrykit\/utils/g, importPaths.utils)
613
- .replace(/@\/lib\/utils/g, importPaths.utils);
614
-
615
- return transformed;
616
- }
617
-
618
- function getConfiguredImportPaths(
619
- config: Config
620
- ): Record<ComponentCategory | 'utils', string> {
621
- const paths = config?.paths || {
622
- primitives: 'components/primitives',
623
- components: 'components',
624
- blocks: 'components/blocks',
625
- animations: 'components/animations',
626
- hooks: 'hooks',
627
- maps: 'components/maps',
628
- utils: 'lib/utils',
629
- };
630
-
631
- return {
632
- primitives: resolveImportBasePath(paths.primitives, config, {
633
- preferRootAlias: true,
634
- }),
635
- components: resolveImportBasePath(paths.components, config, {
636
- preferRootAlias: true,
637
- }),
638
- blocks: resolveImportBasePath(paths.blocks, config, {
639
- preferRootAlias: true,
640
- }),
641
- animations: resolveImportBasePath(paths.animations, config, {
642
- preferRootAlias: true,
643
- }),
644
- maps: resolveImportBasePath(
645
- paths.maps ?? joinImportPath(paths.components, 'maps'),
646
- config,
647
- {
648
- preferRootAlias: true,
649
- }
650
- ),
651
- hooks: resolveImportBasePath(paths.hooks ?? 'hooks', config, {
652
- preferRootAlias: true,
653
- }),
654
- packages: resolveImportBasePath(paths.components, config, {
655
- preferRootAlias: true,
656
- }),
657
- utils: resolveImportBasePath(paths.utils, config).replace(
658
- /\.(ts|js)x?$/,
659
- ''
660
- ),
661
- };
662
- }
663
-
664
- function resolveImportBasePath(
665
- filePath: string,
666
- config: Config,
667
- options: { preferRootAlias?: boolean } = {}
668
- ): string {
669
- if (isPackageImportSpecifier(filePath)) {
670
- return filePath.replace(/\/$/, '');
671
- }
672
-
673
- const normalizedPath = normalizeConfigPath(filePath).replace(
674
- /\.(ts|js)x?$/,
675
- ''
676
- );
677
- const aliases = config?.aliases ?? {};
678
-
679
- if (options.preferRootAlias && aliases['@']) {
680
- const rootTarget = normalizeConfigPath(aliases['@']);
681
- const matchesRoot =
682
- normalizedPath === rootTarget ||
683
- (rootTarget !== '' && normalizedPath.startsWith(`${rootTarget}/`)) ||
684
- rootTarget === '';
685
-
686
- if (matchesRoot) {
687
- const relativePath =
688
- rootTarget === ''
689
- ? normalizedPath
690
- : normalizedPath.slice(rootTarget.length).replace(/^\//, '');
691
- return joinImportPath('@', relativePath);
692
- }
693
- }
694
-
695
- const aliasMatches = Object.entries(aliases)
696
- .map(([alias, target]) => ({
697
- alias,
698
- target: normalizeConfigPath(target),
699
- }))
700
- .filter(({ target }) => {
701
- return (
702
- normalizedPath === target ||
703
- (target !== '' && normalizedPath.startsWith(`${target}/`)) ||
704
- target === ''
705
- );
706
- })
707
- .sort((a, b) => b.target.length - a.target.length);
708
-
709
- const bestMatch = aliasMatches[0];
710
- if (bestMatch) {
711
- const relativePath =
712
- bestMatch.target === ''
713
- ? normalizedPath
714
- : normalizedPath.slice(bestMatch.target.length).replace(/^\//, '');
715
- return joinImportPath(bestMatch.alias, relativePath);
716
- }
717
-
718
- return joinImportPath('@', normalizedPath);
719
- }
720
-
721
- function normalizeConfigPath(filePath: string): string {
722
- return filePath
723
- .replace(/\\/g, '/')
724
- .replace(/^\.\//, '')
725
- .replace(/^\.\/?$/, '')
726
- .replace(/\/$/, '');
727
- }
728
-
729
- function isPackageImportSpecifier(importPath: string): boolean {
730
- return importPath.startsWith('@') && !importPath.startsWith('@/');
731
- }
732
-
733
- function joinImportPath(basePath: string, childPath: string): string {
734
- const normalizedBase = basePath.replace(/\/$/, '');
735
- const normalizedChild = childPath.replace(/^\//, '').replace(/\/$/, '');
736
-
737
- if (!normalizedChild) {
738
- return normalizedBase;
739
- }
740
-
741
- return `${normalizedBase}/${normalizedChild}`;
742
- }
743
-
744
- function transformRegistryBarrelImports(
745
- content: string,
746
- sources: string[],
747
- destinationBasePath: string,
748
- config: Config,
749
- category: ComponentCategory
750
- ): string {
751
- const sourcePattern = sources
752
- .map(source => source.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
753
- .join('|');
754
- const importPattern = new RegExp(
755
- `import\\s+{([^}]+)}\\s+from\\s+["'](${sourcePattern})["'];?`,
756
- 'g'
757
- );
758
-
759
- return content.replace(
760
- importPattern,
761
- (match, imports: string, source: string) => {
762
- if (isPackageImportSpecifier(destinationBasePath)) {
763
- return match.replace(source, destinationBasePath);
764
- }
765
-
766
- const groupedImports = groupImportsByComponent(imports, config, category);
767
-
768
- return Array.from(groupedImports.entries())
769
- .map(([componentPath, specifiers]) => {
770
- return `import { ${specifiers.join(', ')} } from "${destinationBasePath}/${componentPath}";`;
771
- })
772
- .join('\n');
773
- }
774
- );
775
- }
776
-
777
- function groupImportsByComponent(
778
- imports: string,
779
- config: Config,
780
- category: ComponentCategory
781
- ): Map<string, string[]> {
782
- const groupedImports = new Map<string, string[]>();
783
- const exportMap = getInstalledComponentExportMap(config, category);
784
- const specifiers = imports
785
- .split(',')
786
- .map(specifier => specifier.trim())
787
- .filter(Boolean);
788
- const exportNames = specifiers.map(getExportNameFromSpecifier);
789
-
790
- for (const specifier of specifiers) {
791
- const componentPath = getComponentPathForSpecifier(
792
- specifier,
793
- exportNames,
794
- exportMap
795
- );
796
- const existing = groupedImports.get(componentPath) ?? [];
797
- existing.push(specifier);
798
- groupedImports.set(componentPath, existing);
799
- }
800
-
801
- return groupedImports;
802
- }
803
-
804
- function getComponentPathForSpecifier(
805
- specifier: string,
806
- importExportNames: string[],
807
- exportMap: Map<string, string>
808
- ): string {
809
- const exportName = getExportNameFromSpecifier(specifier);
810
-
811
- const mappedPath = exportMap.get(exportName);
812
- if (mappedPath) {
813
- return mappedPath;
814
- }
815
-
816
- const siblingOwnerName = importExportNames
817
- .filter(name => name !== exportName)
818
- .sort((a, b) => a.length - b.length)
819
- .find(name => exportName.toLowerCase().startsWith(name.toLowerCase()));
820
-
821
- if (siblingOwnerName) {
822
- return exportMap.get(siblingOwnerName) ?? toKebabCase(siblingOwnerName);
823
- }
824
-
825
- const variantsOwnerName = exportName.replace(/Variants$/, '');
826
- if (variantsOwnerName !== exportName) {
827
- return exportMap.get(variantsOwnerName) ?? toKebabCase(variantsOwnerName);
828
- }
829
-
830
- return toKebabCase(exportName);
831
- }
832
-
833
- function getExportNameFromSpecifier(specifier: string): string {
834
- return (
835
- specifier
836
- .replace(/^type\s+/, '')
837
- .split(/\s+as\s+/)[0]
838
- ?.trim() || specifier
839
- );
840
- }
841
-
842
- function getInstalledComponentExportMap(
843
- config: Config,
844
- category: ComponentCategory
845
- ): Map<string, string> {
846
- const exportMap = new Map<string, string>();
847
- const categoryPath = getConfiguredCategoryPath(config, category);
848
- if (!categoryPath) {
849
- return exportMap;
850
- }
851
-
852
- const absoluteCategoryPath = path.resolve(
853
- process.cwd(),
854
- normalizeConfigPath(categoryPath)
855
- );
856
-
857
- if (!fs.existsSync(absoluteCategoryPath)) {
858
- return exportMap;
859
- }
860
-
861
- for (const entry of fs.readdirSync(absoluteCategoryPath, {
862
- withFileTypes: true,
863
- })) {
864
- if (!entry.isDirectory()) continue;
865
-
866
- const componentPath = entry.name;
867
- const componentDir = path.join(absoluteCategoryPath, componentPath);
868
- const entryFiles = ['index.tsx', 'index.ts', 'index.jsx', 'index.js']
869
- .map(fileName => path.join(componentDir, fileName))
870
- .filter(filePath => fs.existsSync(filePath));
871
-
872
- for (const filePath of entryFiles) {
873
- const content = fs.readFileSync(filePath, 'utf-8');
874
- for (const exportName of parseExportNames(content)) {
875
- exportMap.set(exportName, componentPath);
876
- }
877
- }
878
- }
879
-
880
- return exportMap;
881
- }
882
-
883
- function parseExportNames(content: string): string[] {
884
- const exportNames = new Set<string>();
885
- const namedExportPattern = /export\s*{\s*([^}]+)\s*}/g;
886
- const declarationExportPattern =
887
- /export\s+(?:declare\s+)?(?:const|let|var|function|class|interface|type|enum)\s+([A-Za-z_$][\w$]*)/g;
888
-
889
- for (const match of content.matchAll(namedExportPattern)) {
890
- const exports = match[1] ?? '';
891
- for (const rawExport of exports.split(',')) {
892
- const exportName = rawExport
893
- .trim()
894
- .replace(/^type\s+/, '')
895
- .split(/\s+as\s+/)
896
- .pop()
897
- ?.trim();
898
-
899
- if (exportName) {
900
- exportNames.add(exportName);
901
- }
902
- }
903
- }
904
-
905
- for (const match of content.matchAll(declarationExportPattern)) {
906
- if (match[1]) {
907
- exportNames.add(match[1]);
908
- }
909
- }
910
-
911
- return Array.from(exportNames);
912
- }
913
-
914
- function toKebabCase(value: string): string {
915
- return value
916
- .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
917
- .replace(/([A-Z]+)([A-Z][a-z])/g, '$1-$2')
918
- .toLowerCase();
919
- }
920
-
921
- /**
922
- * Resolve component path based on category and configuration
923
- */
924
- export function resolveComponentPath(
925
- originalPath: string,
926
- category: ComponentCategory,
927
- config: Config
928
- ): string {
929
- // Ensure config.paths exists with fallbacks
930
- const paths = config?.paths || {
931
- primitives: 'components/primitives',
932
- components: 'components',
933
- blocks: 'components/blocks',
934
- animations: 'components/animations',
935
- hooks: 'hooks',
936
- maps: 'components/maps',
937
- utils: 'lib/utils',
938
- };
939
-
940
- // Special handling for utils files - they should go directly to lib/utils.ts
941
- if (originalPath === 'lib/utils.ts') {
942
- return paths.utils || 'lib/utils.ts';
943
- }
944
-
945
- // Get the base path for the category from config
946
- const categoryPath =
947
- getConfiguredCategoryPath(config, category) || paths.components;
948
-
949
- // Extract just the filename from the original path
950
- const fileName = path.basename(originalPath);
951
- const componentName = path.dirname(originalPath).split('/').pop() || '';
952
-
953
- // Build the resolved path based on category
954
- if (category === 'primitives') {
955
- return path.join(categoryPath, componentName, fileName);
956
- } else if (category === 'components') {
957
- return path.join(paths.components, componentName, fileName);
958
- } else if (category === 'blocks') {
959
- return path.join(
960
- paths.blocks || path.join(paths.components, 'blocks'),
961
- componentName,
962
- fileName
963
- );
964
- } else if (category === 'animations') {
965
- return path.join(
966
- paths.animations || path.join(paths.components, 'animations'),
967
- componentName,
968
- fileName
969
- );
970
- } else if (category === 'maps') {
971
- return path.join(
972
- paths.maps || path.join(paths.components, 'maps'),
973
- componentName,
974
- fileName
975
- );
976
- } else if (category === 'hooks') {
977
- return path.join(paths.hooks || 'hooks', componentName, fileName);
978
- } else if (category === 'packages') {
979
- return path.join(paths.components, componentName, fileName);
980
- }
981
-
982
- // Default to original path if category not recognized
983
- return originalPath;
984
- }
985
-
986
- function getConfiguredCategoryPath(
987
- config: Config,
988
- category: ComponentCategory
989
- ): string | undefined {
990
- const paths = config.paths;
991
-
992
- switch (category) {
993
- case 'primitives':
994
- return paths.primitives;
995
- case 'components':
996
- return paths.components;
997
- case 'blocks':
998
- return paths.blocks;
999
- case 'animations':
1000
- return paths.animations;
1001
- case 'maps':
1002
- return paths.maps ?? path.join(paths.components, 'maps');
1003
- case 'hooks':
1004
- return paths.hooks ?? 'hooks';
1005
- case 'packages':
1006
- return paths.components;
1007
- default:
1008
- return undefined;
1009
- }
1010
- }
1011
-
1012
- /**
1013
- * Get import path for a component
1014
- */
1015
- export function getImportPath(
1016
- componentData: ComponentData,
1017
- config: Config
1018
- ): string {
1019
- // Ensure config.paths exists with fallbacks
1020
- const paths = config?.paths || {
1021
- primitives: 'components/primitives',
1022
- components: 'components',
1023
- blocks: 'components/blocks',
1024
- animations: 'components/animations',
1025
- hooks: 'hooks',
1026
- maps: 'components/maps',
1027
- utils: 'lib/utils',
1028
- };
1029
-
1030
- const componentName = path.basename(
1031
- path.dirname(componentData.files[0]?.path || '')
1032
- );
1033
-
1034
- if (componentData.category === 'primitives') {
1035
- return `${resolveImportBasePath(paths.primitives, config, {
1036
- preferRootAlias: true,
1037
- })}/${componentName}`;
1038
- } else if (componentData.category === 'components') {
1039
- return `${resolveImportBasePath(paths.components, config, {
1040
- preferRootAlias: true,
1041
- })}/${componentName}`;
1042
- } else if (componentData.category === 'blocks') {
1043
- return `${resolveImportBasePath(paths.blocks, config, {
1044
- preferRootAlias: true,
1045
- })}/${componentName}`;
1046
- } else if (componentData.category === 'animations') {
1047
- return `${resolveImportBasePath(paths.animations, config, {
1048
- preferRootAlias: true,
1049
- })}/${componentName}`;
1050
- } else if (componentData.category === 'maps') {
1051
- return `${resolveImportBasePath(
1052
- paths.maps || path.join(paths.components, 'maps'),
1053
- config,
1054
- {
1055
- preferRootAlias: true,
1056
- }
1057
- )}/${componentName}`;
1058
- } else if (componentData.category === 'hooks') {
1059
- return `${resolveImportBasePath(paths.hooks || 'hooks', config, {
1060
- preferRootAlias: true,
1061
- })}/${componentName}`;
1062
- }
1063
-
1064
- return `@/components/${componentName}`;
1065
- }