@foundrykit/cli 2.0.4 → 2.0.5

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foundrykit/cli",
3
- "version": "2.0.4",
3
+ "version": "2.0.5",
4
4
  "type": "module",
5
5
  "private": false,
6
6
  "main": "./dist/index.js",
@@ -25,7 +25,7 @@
25
25
  "glob": "^10.3.10",
26
26
  "inquirer": "^9.2.15",
27
27
  "node-fetch": "^3.3.0",
28
- "@foundrykit/types": "2.0.0"
28
+ "@foundrykit/types": "2.0.1"
29
29
  },
30
30
  "devDependencies": {
31
31
  "@types/node": "^20.19.9",
@@ -35,8 +35,8 @@
35
35
  "tsup": "^8.0.0",
36
36
  "typescript": "^5.9.2",
37
37
  "vitest": "^1.2.0",
38
- "@foundrykit/typescript-config": "1.0.5",
39
- "@foundrykit/eslint-config": "1.0.5"
38
+ "@foundrykit/eslint-config": "1.0.5",
39
+ "@foundrykit/typescript-config": "1.0.5"
40
40
  },
41
41
  "scripts": {
42
42
  "build": "tsup",
@@ -432,7 +432,9 @@ export async function handlePackageDependencies(
432
432
  /**
433
433
  * Check which packages are missing from the project
434
434
  */
435
- export async function getMissingPackages(packages: string[]): Promise<string[]> {
435
+ export async function getMissingPackages(
436
+ packages: string[]
437
+ ): Promise<string[]> {
436
438
  const packageJsonPath = path.join(process.cwd(), 'package.json');
437
439
 
438
440
  try {
@@ -507,134 +509,297 @@ export async function loadConfig(): Promise<Config> {
507
509
  /**
508
510
  * Transform imports in file content based on config
509
511
  */
510
- export function transformImportsForConfig(content: string, config: Config): string {
512
+ export function transformImportsForConfig(
513
+ content: string,
514
+ config: Config
515
+ ): string {
511
516
  let transformed = content;
512
517
 
513
- // Ensure config.paths exists with fallbacks
514
- const paths =
515
- config?.paths && config?.aliases
516
- ? {
517
- primitives: `components/${config.paths.primitives.split('/').pop()}`,
518
- components: `components/${config.paths.components.split('/').pop()}`,
519
- blocks: `components/${config.paths.blocks.split('/').pop()}`,
520
- animations: `components/${config.paths.animations.split('/').pop()}`,
521
- utils: `lib/${config.paths.utils.split('/').pop()}`,
522
- }
523
- : {
524
- primitives: 'components/primitives',
525
- components: 'components',
526
- blocks: 'components/blocks',
527
- animations: 'components/animations',
528
- utils: 'lib/utils',
529
- };
530
-
531
- // Transform imports using regex to capture component names and build proper paths
532
- // Handle @/components/primitives imports
533
- transformed = transformed.replace(
534
- /import\s+{([^}]+)}\s+from\s+["']@\/components\/primitives["']/g,
535
- (match, imports) => {
536
- const componentNames = imports.split(',').map(
537
- (imp: string) =>
538
- imp
539
- ?.trim()
540
- .split(/\s+as\s+/)[0]
541
- ?.trim() || ''
542
- );
518
+ const importPaths = getConfiguredImportPaths(config);
519
+
520
+ transformed = transformRegistryBarrelImports(
521
+ transformed,
522
+ ['@foundrykit/primitives', '@/components/primitives', '@/components/ui'],
523
+ importPaths.primitives,
524
+ config,
525
+ 'primitives'
526
+ );
543
527
 
544
- const primitivesPath = paths.primitives
545
- .replace(/^\.\//, '')
546
- .replace(/\/$/, '');
528
+ transformed = transformRegistryBarrelImports(
529
+ transformed,
530
+ ['@foundrykit/components', '@/components/components'],
531
+ importPaths.components,
532
+ config,
533
+ 'components'
534
+ );
547
535
 
548
- return `import {${imports}} from "@/${primitivesPath}/${componentNames[0].toLowerCase()}"`;
549
- }
536
+ transformed = transformRegistryBarrelImports(
537
+ transformed,
538
+ ['@foundrykit/blocks', '@/components/blocks'],
539
+ importPaths.blocks,
540
+ config,
541
+ 'blocks'
542
+ );
543
+
544
+ transformed = transformRegistryBarrelImports(
545
+ transformed,
546
+ ['@foundrykit/animation', '@/components/animations'],
547
+ importPaths.animations,
548
+ config,
549
+ 'animations'
550
550
  );
551
551
 
552
- // Handle @/components/ui imports (legacy, maps to primitives)
553
- transformed = transformed.replace(
554
- /import\s+{([^}]+)}\s+from\s+["']@\/components\/ui["']/g,
555
- (match, imports) => {
556
- const componentNames = imports.split(',').map(
557
- (imp: string) =>
558
- imp
559
- ?.trim()
560
- .split(/\s+as\s+/)[0]
561
- ?.trim() || ''
552
+ // Handle utils imports
553
+ transformed = transformed
554
+ .replace(/@foundrykit\/utils/g, importPaths.utils)
555
+ .replace(/@\/lib\/utils/g, importPaths.utils);
556
+
557
+ return transformed;
558
+ }
559
+
560
+ function getConfiguredImportPaths(
561
+ config: Config
562
+ ): Record<ComponentCategory | 'utils', string> {
563
+ const paths = config?.paths || {
564
+ primitives: 'components/primitives',
565
+ components: 'components',
566
+ blocks: 'components/blocks',
567
+ animations: 'components/animations',
568
+ utils: 'lib/utils',
569
+ };
570
+
571
+ return {
572
+ primitives: resolveImportBasePath(paths.primitives, config),
573
+ components: resolveImportBasePath(paths.components, config),
574
+ blocks: resolveImportBasePath(paths.blocks, config),
575
+ animations: resolveImportBasePath(paths.animations, config),
576
+ utils: resolveImportBasePath(paths.utils, config).replace(
577
+ /\.(ts|js)x?$/,
578
+ ''
579
+ ),
580
+ };
581
+ }
582
+
583
+ function resolveImportBasePath(filePath: string, config: Config): string {
584
+ const normalizedPath = normalizeConfigPath(filePath).replace(
585
+ /\.(ts|js)x?$/,
586
+ ''
587
+ );
588
+ const aliases = config?.aliases ?? {};
589
+
590
+ const aliasMatches = Object.entries(aliases)
591
+ .map(([alias, target]) => ({
592
+ alias,
593
+ target: normalizeConfigPath(target),
594
+ }))
595
+ .filter(({ target }) => {
596
+ return (
597
+ normalizedPath === target ||
598
+ (target !== '' && normalizedPath.startsWith(`${target}/`)) ||
599
+ target === ''
562
600
  );
601
+ })
602
+ .sort((a, b) => b.target.length - a.target.length);
603
+
604
+ const bestMatch = aliasMatches[0];
605
+ if (bestMatch) {
606
+ const relativePath =
607
+ bestMatch.target === ''
608
+ ? normalizedPath
609
+ : normalizedPath.slice(bestMatch.target.length).replace(/^\//, '');
610
+ return joinImportPath(bestMatch.alias, relativePath);
611
+ }
563
612
 
564
- const primitivesPath = paths.primitives
565
- .replace(/^\.\//, '')
566
- .replace(/\/$/, '');
613
+ return joinImportPath('@', normalizedPath);
614
+ }
567
615
 
568
- return `import {${imports}} from "@/${primitivesPath}/${componentNames[0].toLowerCase()}"`;
569
- }
616
+ function normalizeConfigPath(filePath: string): string {
617
+ return filePath
618
+ .replace(/\\/g, '/')
619
+ .replace(/^\.\//, '')
620
+ .replace(/^\.\/?$/, '')
621
+ .replace(/\/$/, '');
622
+ }
623
+
624
+ function joinImportPath(basePath: string, childPath: string): string {
625
+ const normalizedBase = basePath.replace(/\/$/, '');
626
+ const normalizedChild = childPath.replace(/^\//, '').replace(/\/$/, '');
627
+
628
+ if (!normalizedChild) {
629
+ return normalizedBase;
630
+ }
631
+
632
+ return `${normalizedBase}/${normalizedChild}`;
633
+ }
634
+
635
+ function transformRegistryBarrelImports(
636
+ content: string,
637
+ sources: string[],
638
+ destinationBasePath: string,
639
+ config: Config,
640
+ category: ComponentCategory
641
+ ): string {
642
+ const sourcePattern = sources
643
+ .map(source => source.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
644
+ .join('|');
645
+ const importPattern = new RegExp(
646
+ `import\\s+{([^}]+)}\\s+from\\s+["'](${sourcePattern})["'];?`,
647
+ 'g'
570
648
  );
571
649
 
572
- // Handle @/components/components imports
573
- transformed = transformed.replace(
574
- /import\s+{([^}]+)}\s+from\s+["']@\/components\/components["']/g,
575
- (match, imports) => {
576
- const componentNames = imports.split(',').map(
577
- (imp: string) =>
578
- imp
579
- ?.trim()
580
- .split(/\s+as\s+/)[0]
581
- ?.trim() || ''
582
- );
650
+ return content.replace(importPattern, (match, imports: string) => {
651
+ const groupedImports = groupImportsByComponent(imports, config, category);
583
652
 
584
- const componentsPath = paths.components
585
- .replace(/^\.\//, '')
586
- .replace(/\/$/, '');
653
+ return Array.from(groupedImports.entries())
654
+ .map(([componentPath, specifiers]) => {
655
+ return `import { ${specifiers.join(', ')} } from "${destinationBasePath}/${componentPath}";`;
656
+ })
657
+ .join('\n');
658
+ });
659
+ }
587
660
 
588
- return `import {${imports}} from "@/${componentsPath}/${componentNames[0].toLowerCase()}"`;
589
- }
661
+ function groupImportsByComponent(
662
+ imports: string,
663
+ config: Config,
664
+ category: ComponentCategory
665
+ ): Map<string, string[]> {
666
+ const groupedImports = new Map<string, string[]>();
667
+ const exportMap = getInstalledComponentExportMap(config, category);
668
+ const specifiers = imports
669
+ .split(',')
670
+ .map(specifier => specifier.trim())
671
+ .filter(Boolean);
672
+ const exportNames = specifiers.map(getExportNameFromSpecifier);
673
+
674
+ for (const specifier of specifiers) {
675
+ const componentPath = getComponentPathForSpecifier(
676
+ specifier,
677
+ exportNames,
678
+ exportMap
679
+ );
680
+ const existing = groupedImports.get(componentPath) ?? [];
681
+ existing.push(specifier);
682
+ groupedImports.set(componentPath, existing);
683
+ }
684
+
685
+ return groupedImports;
686
+ }
687
+
688
+ function getComponentPathForSpecifier(
689
+ specifier: string,
690
+ importExportNames: string[],
691
+ exportMap: Map<string, string>
692
+ ): string {
693
+ const exportName = getExportNameFromSpecifier(specifier);
694
+
695
+ const mappedPath = exportMap.get(exportName);
696
+ if (mappedPath) {
697
+ return mappedPath;
698
+ }
699
+
700
+ const siblingOwnerName = importExportNames
701
+ .filter(name => name !== exportName)
702
+ .sort((a, b) => a.length - b.length)
703
+ .find(name => exportName.toLowerCase().startsWith(name.toLowerCase()));
704
+
705
+ if (siblingOwnerName) {
706
+ return exportMap.get(siblingOwnerName) ?? toKebabCase(siblingOwnerName);
707
+ }
708
+
709
+ const variantsOwnerName = exportName.replace(/Variants$/, '');
710
+ if (variantsOwnerName !== exportName) {
711
+ return exportMap.get(variantsOwnerName) ?? toKebabCase(variantsOwnerName);
712
+ }
713
+
714
+ return toKebabCase(exportName);
715
+ }
716
+
717
+ function getExportNameFromSpecifier(specifier: string): string {
718
+ return (
719
+ specifier
720
+ .replace(/^type\s+/, '')
721
+ .split(/\s+as\s+/)[0]
722
+ ?.trim() || specifier
590
723
  );
724
+ }
591
725
 
592
- // Handle @/components/blocks imports
593
- transformed = transformed.replace(
594
- /import\s+{([^}]+)}\s+from\s+["']@\/components\/blocks["']/g,
595
- (match, imports) => {
596
- const componentNames = imports.split(',').map(
597
- (imp: string) =>
598
- imp
599
- ?.trim()
600
- .split(/\s+as\s+/)[0]
601
- ?.trim() || ''
602
- );
726
+ function getInstalledComponentExportMap(
727
+ config: Config,
728
+ category: ComponentCategory
729
+ ): Map<string, string> {
730
+ const exportMap = new Map<string, string>();
731
+ const categoryPath = config.paths?.[category];
732
+ if (!categoryPath) {
733
+ return exportMap;
734
+ }
603
735
 
604
- const blocksPath = paths.blocks.replace(/^\.\//, '').replace(/\/$/, '');
736
+ const absoluteCategoryPath = path.resolve(
737
+ process.cwd(),
738
+ normalizeConfigPath(categoryPath)
739
+ );
605
740
 
606
- return `import {${imports}} from "@/${blocksPath}/${componentNames[0].toLowerCase()}"`;
741
+ if (!fs.existsSync(absoluteCategoryPath)) {
742
+ return exportMap;
743
+ }
744
+
745
+ for (const entry of fs.readdirSync(absoluteCategoryPath, {
746
+ withFileTypes: true,
747
+ })) {
748
+ if (!entry.isDirectory()) continue;
749
+
750
+ const componentPath = entry.name;
751
+ const componentDir = path.join(absoluteCategoryPath, componentPath);
752
+ const entryFiles = ['index.tsx', 'index.ts', 'index.jsx', 'index.js']
753
+ .map(fileName => path.join(componentDir, fileName))
754
+ .filter(filePath => fs.existsSync(filePath));
755
+
756
+ for (const filePath of entryFiles) {
757
+ const content = fs.readFileSync(filePath, 'utf-8');
758
+ for (const exportName of parseExportNames(content)) {
759
+ exportMap.set(exportName, componentPath);
760
+ }
607
761
  }
608
- );
762
+ }
609
763
 
610
- // Handle @/components/animations imports
611
- transformed = transformed.replace(
612
- /import\s+{([^}]+)}\s+from\s+["']@\/components\/animations["']/g,
613
- (match, imports) => {
614
- const componentNames = imports.split(',').map(
615
- (imp: string) =>
616
- imp
617
- ?.trim()
618
- .split(/\s+as\s+/)[0]
619
- ?.trim() || ''
620
- );
764
+ return exportMap;
765
+ }
621
766
 
622
- const animationsPath = paths.animations
623
- .replace(/^\.\//, '')
624
- .replace(/\/$/, '');
767
+ function parseExportNames(content: string): string[] {
768
+ const exportNames = new Set<string>();
769
+ const namedExportPattern = /export\s*{\s*([^}]+)\s*}/g;
770
+ const declarationExportPattern =
771
+ /export\s+(?:declare\s+)?(?:const|let|var|function|class|interface|type|enum)\s+([A-Za-z_$][\w$]*)/g;
772
+
773
+ for (const match of content.matchAll(namedExportPattern)) {
774
+ const exports = match[1] ?? '';
775
+ for (const rawExport of exports.split(',')) {
776
+ const exportName = rawExport
777
+ .trim()
778
+ .replace(/^type\s+/, '')
779
+ .split(/\s+as\s+/)
780
+ .pop()
781
+ ?.trim();
782
+
783
+ if (exportName) {
784
+ exportNames.add(exportName);
785
+ }
786
+ }
787
+ }
625
788
 
626
- return `import {${imports}} from "@/${animationsPath}/${componentNames[0].toLowerCase()}"`;
789
+ for (const match of content.matchAll(declarationExportPattern)) {
790
+ if (match[1]) {
791
+ exportNames.add(match[1]);
627
792
  }
628
- );
793
+ }
629
794
 
630
- // Handle utils imports
631
- const utilsPath = paths.utils
632
- .replace(/^\.\//, '')
633
- .replace(/\/$/, '')
634
- .replace(/\.(ts|js)$/, '');
635
- transformed = transformed.replace(/@\/lib\/utils/g, `@/${utilsPath}`);
795
+ return Array.from(exportNames);
796
+ }
636
797
 
637
- return transformed;
798
+ function toKebabCase(value: string): string {
799
+ return value
800
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
801
+ .replace(/([A-Z]+)([A-Z][a-z])/g, '$1-$2')
802
+ .toLowerCase();
638
803
  }
639
804
 
640
805
  /**
@@ -643,7 +808,7 @@ export function transformImportsForConfig(content: string, config: Config): stri
643
808
  export function resolveComponentPath(
644
809
  originalPath: string,
645
810
  category: ComponentCategory,
646
- config: any
811
+ config: Config
647
812
  ): string {
648
813
  // Ensure config.paths exists with fallbacks
649
814
  const paths = config?.paths || {
@@ -692,7 +857,10 @@ export function resolveComponentPath(
692
857
  /**
693
858
  * Get import path for a component
694
859
  */
695
- export function getImportPath(componentData: ComponentData, config: any): string {
860
+ export function getImportPath(
861
+ componentData: ComponentData,
862
+ config: Config
863
+ ): string {
696
864
  // Ensure config.paths exists with fallbacks
697
865
  const paths = config?.paths || {
698
866
  primitives: 'components/primitives',
@@ -703,28 +871,17 @@ export function getImportPath(componentData: ComponentData, config: any): string
703
871
  };
704
872
 
705
873
  const componentName = path.basename(
706
- componentData.files[0]?.path || '',
707
- '.tsx'
874
+ path.dirname(componentData.files[0]?.path || '')
708
875
  );
709
876
 
710
877
  if (componentData.category === 'primitives') {
711
- const primitivesPath = paths.primitives
712
- .replace(/^\.\//, '')
713
- .replace(/\/$/, '');
714
- return `@/${primitivesPath}/${componentName}`;
878
+ return `${resolveImportBasePath(paths.primitives, config)}/${componentName}`;
715
879
  } else if (componentData.category === 'components') {
716
- const componentsPath = paths.components
717
- .replace(/^\.\//, '')
718
- .replace(/\/$/, '');
719
- return `@/${componentsPath}/${componentName}`;
880
+ return `${resolveImportBasePath(paths.components, config)}/${componentName}`;
720
881
  } else if (componentData.category === 'blocks') {
721
- const blocksPath = paths.blocks.replace(/^\.\//, '').replace(/\/$/, '');
722
- return `@/${blocksPath}/${componentName}`;
882
+ return `${resolveImportBasePath(paths.blocks, config)}/${componentName}`;
723
883
  } else if (componentData.category === 'animations') {
724
- const animationsPath = paths.animations
725
- .replace(/^\.\//, '')
726
- .replace(/\/$/, '');
727
- return `@/${animationsPath}/${componentName}`;
884
+ return `${resolveImportBasePath(paths.animations, config)}/${componentName}`;
728
885
  }
729
886
 
730
887
  return `@/components/${componentName}`;
@@ -7,6 +7,10 @@ import fs from 'fs-extra';
7
7
  import path from 'path';
8
8
  import os from 'os';
9
9
  import { RegistryService } from '../src/lib/registry.js';
10
+ import {
11
+ getImportPath,
12
+ transformImportsForConfig,
13
+ } from '../src/commands/add.js';
10
14
  import type { ComponentData } from '@foundrykit/types';
11
15
 
12
16
  describe('Dependency Resolution', () => {
@@ -286,4 +290,127 @@ describe('Dependency Resolution', () => {
286
290
  expect(failed).toEqual(['non-existent']);
287
291
  });
288
292
  });
293
+
294
+ describe('Configured Import Rewriting', () => {
295
+ const marketingConfig = {
296
+ version: '1.0.16',
297
+ registry: 'https://foundry.umiflow.com',
298
+ paths: {
299
+ utils: './src/lib/utils.ts',
300
+ primitives: './src/components/marketing/primitives',
301
+ components: './src/components/marketing/ui',
302
+ blocks: './src/components/marketing/blocks',
303
+ hooks: './src/hooks',
304
+ animations: './src/components/marketing/animations',
305
+ },
306
+ packageManager: 'pnpm',
307
+ typescript: true,
308
+ framework: 'next',
309
+ tailwind: {
310
+ css: './src/app/(frontend)/globals.css',
311
+ },
312
+ aliases: {
313
+ '@': './src',
314
+ '@/components': './src/components/marketing',
315
+ '@/lib': './src/lib',
316
+ '@/hooks': './src/hooks',
317
+ },
318
+ };
319
+
320
+ it('should preserve configured component aliases when rewriting primitive imports', () => {
321
+ const source = `import { Input } from "@foundrykit/primitives";
322
+ import { Button } from "@foundrykit/primitives";
323
+ import { Separator } from "@foundrykit/primitives";
324
+ import { Badge } from "@foundrykit/primitives";
325
+ import { ScrollArea } from "@foundrykit/primitives";
326
+ import { cn } from "@foundrykit/utils";`;
327
+
328
+ const transformed = transformImportsForConfig(source, marketingConfig);
329
+
330
+ expect(transformed).toContain(
331
+ 'import { Input } from "@/components/primitives/input";'
332
+ );
333
+ expect(transformed).toContain(
334
+ 'import { Button } from "@/components/primitives/button";'
335
+ );
336
+ expect(transformed).toContain(
337
+ 'import { Separator } from "@/components/primitives/separator";'
338
+ );
339
+ expect(transformed).toContain(
340
+ 'import { Badge } from "@/components/primitives/badge";'
341
+ );
342
+ expect(transformed).toContain(
343
+ 'import { ScrollArea } from "@/components/primitives/scroll-area";'
344
+ );
345
+ expect(transformed).toContain('import { cn } from "@/lib/utils";');
346
+ expect(transformed).not.toContain('@/components/primitives/scrollarea');
347
+ expect(transformed).not.toContain('@/src/components');
348
+ });
349
+
350
+ it('should keep related primitive exports grouped on their component path', () => {
351
+ const source =
352
+ 'import { Button, buttonVariants, Sheet, SheetContent } from "@/components/primitives";';
353
+
354
+ const transformed = transformImportsForConfig(source, marketingConfig);
355
+
356
+ expect(transformed).toBe(
357
+ 'import { Button, buttonVariants } from "@/components/primitives/button";\n' +
358
+ 'import { Sheet, SheetContent } from "@/components/primitives/sheet";'
359
+ );
360
+ });
361
+
362
+ it('should discover component paths from installed exports', async () => {
363
+ const absoluteMarketingConfig = {
364
+ ...marketingConfig,
365
+ paths: {
366
+ ...marketingConfig.paths,
367
+ primitives: path.join(testDir, 'src/components/marketing/primitives'),
368
+ },
369
+ aliases: {
370
+ ...marketingConfig.aliases,
371
+ '@': path.join(testDir, 'src'),
372
+ '@/components': path.join(testDir, 'src/components/marketing'),
373
+ '@/lib': path.join(testDir, 'src/lib'),
374
+ '@/hooks': path.join(testDir, 'src/hooks'),
375
+ },
376
+ };
377
+
378
+ await fs.outputFile(
379
+ path.join(
380
+ testDir,
381
+ 'src/components/marketing/primitives/fancy-picker/index.tsx'
382
+ ),
383
+ 'export { FancyPicker, FancyPickerItem, fancyPickerVariants };'
384
+ );
385
+
386
+ const transformed = transformImportsForConfig(
387
+ 'import { FancyPickerItem, fancyPickerVariants } from "@foundrykit/primitives";',
388
+ absoluteMarketingConfig
389
+ );
390
+
391
+ expect(transformed).toBe(
392
+ 'import { FancyPickerItem, fancyPickerVariants } from "@/components/primitives/fancy-picker";'
393
+ );
394
+ });
395
+
396
+ it('should build usage imports from the component directory, not index.tsx', () => {
397
+ const componentData: ComponentData = {
398
+ id: 'advanced-search-bar',
399
+ name: 'Advanced Search Bar',
400
+ category: 'components',
401
+ description: 'Search component',
402
+ files: [
403
+ {
404
+ path: 'components/ui/advanced-search-bar/index.tsx',
405
+ type: 'component',
406
+ content: '',
407
+ },
408
+ ],
409
+ };
410
+
411
+ expect(getImportPath(componentData, marketingConfig)).toBe(
412
+ '@/components/ui/advanced-search-bar'
413
+ );
414
+ });
415
+ });
289
416
  });