@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,935 +0,0 @@
1
- import { Command } from 'commander';
2
- import chalk from 'chalk';
3
- import fs from 'fs-extra';
4
- import path from 'path';
5
- import inquirer from 'inquirer';
6
- import { exec } from 'child_process';
7
- import { promisify } from 'util';
8
- import { CLI_VERSION, DEFAULT_REGISTRY_URL } from '../lib/constants.js';
9
-
10
- interface InitOptions {
11
- force?: boolean;
12
- skipInstall?: boolean;
13
- skipPrompts?: boolean;
14
- }
15
-
16
- interface ProjectStructure {
17
- hasSrc: boolean;
18
- hasApp: boolean;
19
- hasComponents: boolean;
20
- hasLib: boolean;
21
- hasHooks: boolean;
22
- hasStyles: boolean;
23
- baseDir: string;
24
- framework: string;
25
- isTypeScript: boolean;
26
- packageManager: string;
27
- appPath?: string;
28
- componentsPath?: string;
29
- libPath?: string;
30
- hooksPath?: string;
31
- stylesPath?: string;
32
- }
33
-
34
- interface PathConfig {
35
- utils: string;
36
- primitives: string;
37
- components: string;
38
- blocks: string;
39
- hooks: string;
40
- maps: string;
41
- animations: string;
42
- styles: string;
43
- lib: string;
44
- }
45
-
46
- export function initCommand() {
47
- return new Command('init')
48
- .description('Initialize FoundryKit in your project')
49
- .option('-f, --force', 'overwrite existing files')
50
- .option('--skip-install', 'skip installing dependencies')
51
- .option('--skip-prompts', 'use default paths without prompting')
52
- .action(async (options: InitOptions) => {
53
- try {
54
- console.log(chalk.blue('🚀 Initializing FoundryKit...'));
55
-
56
- // Validate project
57
- await validateProject();
58
-
59
- // Check if already initialized
60
- if (!options.force && (await isFoundryKitInitialized())) {
61
- const { shouldContinue } = await inquirer.prompt([
62
- {
63
- type: 'confirm',
64
- name: 'shouldContinue',
65
- message: 'FoundryKit is already initialized. Continue anyway?',
66
- default: false,
67
- },
68
- ]);
69
-
70
- if (!shouldContinue) {
71
- console.log(chalk.yellow('❌ Initialization cancelled.'));
72
- return;
73
- }
74
- }
75
-
76
- // Detect project structure
77
- const projectStructure = await detectProjectStructure();
78
- console.log(
79
- chalk.gray(
80
- `Detected project structure: ${projectStructure.hasSrc ? 'src/' : 'root'} based`
81
- )
82
- );
83
-
84
- // Get path configuration (with prompts or defaults)
85
- const pathConfig = await getPathConfiguration(
86
- projectStructure,
87
- options.skipPrompts
88
- );
89
-
90
- // Install dependencies
91
- if (!options.skipInstall) {
92
- await installDependencies();
93
- }
94
-
95
- console.log(pathConfig);
96
-
97
- // Create configuration file with custom paths
98
- await createConfigFile(options, projectStructure, pathConfig);
99
-
100
- // Install utils with custom path
101
- await installUtils(pathConfig);
102
-
103
- // Setup CSS with Tailwind v4
104
- await setupTailwindV4(
105
- pathConfig,
106
- projectStructure,
107
- options.skipPrompts
108
- );
109
-
110
- // Create components directory with custom paths
111
- await createDirectories(pathConfig);
112
-
113
- // Create example files with custom paths
114
- await createExampleFiles(pathConfig, projectStructure);
115
-
116
- // Update package.json scripts
117
- await updatePackageScripts();
118
-
119
- console.log(chalk.green('\n✅ FoundryKit initialized successfully!'));
120
- console.log(chalk.cyan('\n📦 Next steps:'));
121
- console.log(
122
- chalk.gray(
123
- ' 1. Add a component: pnpm dlx @foundrykit/cli add hero-minimal'
124
- )
125
- );
126
- console.log(
127
- chalk.gray(
128
- ' 2. List available components: pnpm dlx @foundrykit/cli list'
129
- )
130
- );
131
- console.log(
132
- chalk.gray(
133
- ' 3. Check out the docs: https://foundry-docs.umiflow.com'
134
- )
135
- );
136
- } catch (error) {
137
- console.error(chalk.red('❌ Failed to initialize FoundryKit:'));
138
- console.error(
139
- chalk.red(error instanceof Error ? error.message : String(error))
140
- );
141
- process.exit(1);
142
- }
143
- });
144
- }
145
-
146
- async function validateProject(): Promise<void> {
147
- const packageJsonPath = path.join(process.cwd(), 'package.json');
148
-
149
- if (!fs.existsSync(packageJsonPath)) {
150
- throw new Error(
151
- 'No package.json found. Please run this command in a project directory.'
152
- );
153
- }
154
-
155
- const packageJson = await fs.readJson(packageJsonPath);
156
- const deps = {
157
- ...packageJson.dependencies,
158
- ...packageJson.devDependencies,
159
- };
160
-
161
- if (!deps.next) {
162
- throw new Error(
163
- 'Next.js not detected. FoundryKit currently requires Next.js.'
164
- );
165
- }
166
-
167
- console.log(chalk.green('✅ Next.js project detected'));
168
- }
169
-
170
- async function isFoundryKitInitialized(): Promise<boolean> {
171
- return fs.existsSync(path.join(process.cwd(), 'foundrykit.config.json'));
172
- }
173
-
174
- async function detectProjectStructure(): Promise<ProjectStructure> {
175
- const cwd = process.cwd();
176
-
177
- // Check for src directory
178
- const hasSrc = fs.existsSync(path.join(cwd, 'src'));
179
-
180
- // Determine base directory
181
- let baseDir = './';
182
- let appPath: string | undefined;
183
- let componentsPath: string | undefined;
184
- let libPath: string | undefined;
185
- let hooksPath: string | undefined;
186
- let stylesPath: string | undefined;
187
-
188
- if (hasSrc) {
189
- // Check if src contains app directory
190
- const srcHasApp = fs.existsSync(path.join(cwd, 'src/app'));
191
- if (srcHasApp) {
192
- baseDir = './src/';
193
- appPath = './src/app';
194
- } else {
195
- // Check if there's an app directory in root
196
- const rootHasApp = fs.existsSync(path.join(cwd, 'app'));
197
- if (rootHasApp) {
198
- // Mixed structure - app in root, other dirs might be in src
199
- appPath = './app';
200
- baseDir = './src/';
201
- }
202
- }
203
-
204
- // Check for existing directories in src
205
- if (fs.existsSync(path.join(cwd, 'src/components'))) {
206
- componentsPath = './src/components';
207
- }
208
- if (fs.existsSync(path.join(cwd, 'src/lib'))) {
209
- libPath = './src/lib';
210
- }
211
- if (fs.existsSync(path.join(cwd, 'src/hooks'))) {
212
- hooksPath = './src/hooks';
213
- }
214
- if (fs.existsSync(path.join(cwd, 'src/styles'))) {
215
- stylesPath = './src/styles';
216
- }
217
- } else {
218
- // No src directory - check for app directory in root
219
- const hasApp = fs.existsSync(path.join(cwd, 'app'));
220
- if (hasApp) {
221
- appPath = './app';
222
- }
223
-
224
- // Check for existing directories in root
225
- if (fs.existsSync(path.join(cwd, 'components'))) {
226
- componentsPath = './components';
227
- }
228
- if (fs.existsSync(path.join(cwd, 'lib'))) {
229
- libPath = './lib';
230
- }
231
- if (fs.existsSync(path.join(cwd, 'hooks'))) {
232
- hooksPath = './hooks';
233
- }
234
- if (fs.existsSync(path.join(cwd, 'styles'))) {
235
- stylesPath = './styles';
236
- }
237
- }
238
-
239
- // Detect TypeScript
240
- const isTypeScript = fs.existsSync(path.join(cwd, 'tsconfig.json'));
241
-
242
- // Detect package manager
243
- const packageManager = detectPackageManager();
244
-
245
- return {
246
- hasSrc,
247
- hasApp: !!appPath,
248
- hasComponents: !!componentsPath,
249
- hasLib: !!libPath,
250
- hasHooks: !!hooksPath,
251
- hasStyles: !!stylesPath,
252
- baseDir,
253
- framework: 'next',
254
- isTypeScript,
255
- packageManager,
256
- appPath,
257
- componentsPath,
258
- libPath,
259
- hooksPath,
260
- stylesPath,
261
- };
262
- }
263
-
264
- async function getPathConfiguration(
265
- structure: ProjectStructure,
266
- skipPrompts?: boolean
267
- ): Promise<PathConfig> {
268
- const ext = structure.isTypeScript ? '.ts' : '.js';
269
- const jsxExt = structure.isTypeScript ? '.tsx' : '.jsx';
270
-
271
- // Smart defaults based on existing structure
272
- const defaults: PathConfig = {
273
- utils: path.join(
274
- structure.libPath || path.join(structure.baseDir, 'lib'),
275
- `utils${ext}`
276
- ),
277
- primitives: path.join(
278
- structure.componentsPath || path.join(structure.baseDir, 'components'),
279
- 'primitives'
280
- ),
281
- components: path.join(
282
- structure.componentsPath || path.join(structure.baseDir, 'components'),
283
- 'ui'
284
- ),
285
- blocks: path.join(
286
- structure.componentsPath || path.join(structure.baseDir, 'components'),
287
- 'blocks'
288
- ),
289
- maps: path.join(
290
- structure.componentsPath || path.join(structure.baseDir, 'components'),
291
- 'maps'
292
- ),
293
- animations: path.join(
294
- structure.componentsPath || path.join(structure.baseDir, 'components'),
295
- 'animations'
296
- ),
297
- hooks: structure.hooksPath || path.join(structure.baseDir, 'hooks'),
298
- lib: structure.libPath || path.join(structure.baseDir, 'lib'),
299
- styles: path.join(structure.appPath || structure.baseDir, 'globals.css'),
300
- };
301
-
302
- // If app directory exists, look for existing globals.css
303
- if (structure.appPath) {
304
- const possibleStylePaths = [
305
- path.join(structure.appPath, 'globals.css'),
306
- path.join(structure.appPath, 'global.css'),
307
- path.join(structure.stylesPath || '', 'globals.css'),
308
- path.join(structure.stylesPath || '', 'global.css'),
309
- ];
310
-
311
- for (const stylePath of possibleStylePaths) {
312
- if (fs.existsSync(path.join(process.cwd(), stylePath))) {
313
- defaults.styles = stylePath;
314
- break;
315
- }
316
- }
317
- }
318
-
319
- if (skipPrompts) {
320
- console.log(
321
- chalk.gray('Using smart defaults based on project structure...')
322
- );
323
- return defaults;
324
- }
325
-
326
- console.log(chalk.blue('\n📂 Configure installation paths:'));
327
- console.log(
328
- chalk.gray('Press enter to use the default value shown in parentheses\n')
329
- );
330
-
331
- const answers = await inquirer.prompt([
332
- {
333
- type: 'input',
334
- name: 'utils',
335
- message: 'Utils file path:',
336
- default: defaults.utils,
337
- validate: (input: string) => {
338
- if (!input) return 'Path cannot be empty';
339
- return true;
340
- },
341
- },
342
- {
343
- type: 'input',
344
- name: 'components',
345
- message: 'Components directory:',
346
- default: defaults.components,
347
- },
348
- {
349
- type: 'input',
350
- name: 'primitives',
351
- message: 'Primitives directory:',
352
- default: defaults.primitives,
353
- },
354
- {
355
- type: 'input',
356
- name: 'blocks',
357
- message: 'Blocks directory:',
358
- default: defaults.blocks,
359
- },
360
- {
361
- type: 'input',
362
- name: 'hooks',
363
- message: 'Hooks directory:',
364
- default: defaults.hooks,
365
- },
366
- {
367
- type: 'input',
368
- name: 'maps',
369
- message: 'Maps directory:',
370
- default: defaults.maps,
371
- },
372
- {
373
- type: 'input',
374
- name: 'animations',
375
- message: 'Animations directory:',
376
- default: defaults.animations,
377
- },
378
- {
379
- type: 'input',
380
- name: 'styles',
381
- message: 'Global styles file:',
382
- default: defaults.styles,
383
- },
384
- {
385
- type: 'input',
386
- name: 'lib',
387
- message: 'Lib directory:',
388
- default: defaults.lib,
389
- },
390
- ]);
391
-
392
- return answers as PathConfig;
393
- }
394
-
395
- async function installDependencies(): Promise<void> {
396
- console.log(chalk.blue('📦 Installing dependencies...'));
397
-
398
- const packageManager = detectPackageManager();
399
- const execAsync = promisify(exec);
400
-
401
- const dependencies = [
402
- 'clsx',
403
- 'tailwind-merge',
404
- 'framer-motion',
405
- 'lucide-react',
406
- 'next-themes',
407
- 'cmdk',
408
- '@foundrykit/tailwind',
409
- '@radix-ui/react-dialog',
410
- '@radix-ui/react-dropdown-menu',
411
- '@radix-ui/react-label',
412
- '@radix-ui/react-popover',
413
- '@radix-ui/react-select',
414
- '@radix-ui/react-separator',
415
- '@radix-ui/react-slot',
416
- '@radix-ui/react-switch',
417
- '@radix-ui/react-tabs',
418
- '@radix-ui/react-tooltip',
419
- ];
420
-
421
- const devDependencies = ['tailwindcss', 'autoprefixer', 'postcss'];
422
-
423
- try {
424
- // Install regular dependencies
425
- const installCmd = packageManager === 'npm' ? 'install' : 'add';
426
- await execAsync(
427
- `${packageManager} ${installCmd} ${dependencies.join(' ')}`
428
- );
429
-
430
- // Install dev dependencies
431
- const devFlag = packageManager === 'npm' ? '--save-dev' : '-D';
432
- await execAsync(
433
- `${packageManager} ${installCmd} ${devFlag} ${devDependencies.join(' ')}`
434
- );
435
-
436
- console.log(chalk.green('✅ Dependencies installed'));
437
- } catch (error) {
438
- console.error(chalk.yellow('⚠️ Failed to install some dependencies'));
439
- console.error(chalk.gray('You may need to install them manually'));
440
- }
441
- }
442
-
443
- function detectPackageManager(): string {
444
- if (fs.existsSync(path.join(process.cwd(), 'pnpm-lock.yaml'))) return 'pnpm';
445
- if (fs.existsSync(path.join(process.cwd(), 'yarn.lock'))) return 'yarn';
446
- if (fs.existsSync(path.join(process.cwd(), 'bun.lockb'))) return 'bun';
447
- return 'npm';
448
- }
449
-
450
- async function setupTailwindV4(
451
- pathConfig: PathConfig,
452
- projectStructure: ProjectStructure,
453
- skipPrompts?: boolean
454
- ): Promise<void> {
455
- console.log(chalk.blue('🎨 Setting up Tailwind CSS v4...'));
456
-
457
- // First check if layout already imports FoundryKit styles
458
- const layoutPath = await findLayoutFile(projectStructure);
459
-
460
- if (layoutPath) {
461
- const layoutContent = await fs.readFile(layoutPath, 'utf-8');
462
-
463
- // Check if already importing FoundryKit styles directly
464
- if (layoutContent.includes('@foundrykit/tailwind/globals.css')) {
465
- if (skipPrompts) {
466
- console.log(
467
- chalk.green(
468
- '✅ Keeping existing import from @foundrykit/tailwind/globals.css'
469
- )
470
- );
471
- return;
472
- }
473
-
474
- const { importPreference } = await inquirer.prompt([
475
- {
476
- type: 'list',
477
- name: 'importPreference',
478
- message:
479
- 'FoundryKit styles are already imported directly. How would you like to proceed?',
480
- choices: [
481
- {
482
- name: 'Keep direct import from @foundrykit/tailwind/globals.css',
483
- value: 'direct',
484
- },
485
- {
486
- name: 'Switch to local globals.css file (recommended for customization)',
487
- value: 'local',
488
- },
489
- ],
490
- default: 'direct',
491
- },
492
- ]);
493
-
494
- if (importPreference === 'direct') {
495
- console.log(
496
- chalk.green(
497
- '✅ Keeping direct import from @foundrykit/tailwind/globals.css'
498
- )
499
- );
500
- return;
501
- }
502
-
503
- // User wants to switch to local globals.css
504
- await createOrUpdateGlobalsCss(pathConfig, projectStructure);
505
- await updateLayoutImport(layoutPath, pathConfig);
506
- return;
507
- }
508
-
509
- // Check if importing a local globals.css
510
- const globalsCssImportMatch = layoutContent.match(
511
- /import\s+['"]([^'"]*globals?\.css)['"]/
512
- );
513
-
514
- if (globalsCssImportMatch && globalsCssImportMatch[1]) {
515
- // Local globals.css is imported, update it
516
- const importPath = globalsCssImportMatch[1];
517
- const resolvedPath = resolveImportPath(layoutPath, importPath);
518
-
519
- if (fs.existsSync(resolvedPath)) {
520
- await updateExistingGlobalsCss(resolvedPath);
521
- console.log(
522
- chalk.green('✅ Updated existing globals.css with FoundryKit styles')
523
- );
524
- return;
525
- }
526
- }
527
- }
528
-
529
- // No existing setup found, use default preference or ask user
530
- let setupPreference = 'local';
531
-
532
- if (!skipPrompts) {
533
- const answer = await inquirer.prompt([
534
- {
535
- type: 'list',
536
- name: 'setupPreference',
537
- message: 'How would you like to import FoundryKit styles?',
538
- choices: [
539
- {
540
- name: 'Create/update a local globals.css file (recommended for customization)',
541
- value: 'local',
542
- },
543
- {
544
- name: 'Import directly from @foundrykit/tailwind/globals.css',
545
- value: 'direct',
546
- },
547
- ],
548
- default: 'local',
549
- },
550
- ]);
551
- setupPreference = answer.setupPreference;
552
- }
553
-
554
- if (setupPreference === 'direct') {
555
- await addDirectImportToLayout(layoutPath!, pathConfig);
556
- } else {
557
- await createOrUpdateGlobalsCss(pathConfig, projectStructure);
558
- if (layoutPath) {
559
- await updateLayoutImport(layoutPath, pathConfig);
560
- }
561
- }
562
-
563
- console.log(chalk.green('✅ Tailwind CSS v4 configured'));
564
- }
565
-
566
- async function createOrUpdateGlobalsCss(
567
- pathConfig: PathConfig,
568
- projectStructure: ProjectStructure
569
- ): Promise<void> {
570
- const globalsCssPath = path.join(process.cwd(), pathConfig.styles);
571
-
572
- // Check if file already exists
573
- if (fs.existsSync(globalsCssPath)) {
574
- await updateExistingGlobalsCss(globalsCssPath);
575
- } else {
576
- // Create new globals.css
577
- const cssContent = `/* Import FoundryKit's Tailwind CSS v4 styles */
578
- @import "@foundrykit/tailwind/globals.css";
579
-
580
- /* Your custom styles below */
581
- `;
582
-
583
- await fs.ensureDir(path.dirname(globalsCssPath));
584
- await fs.writeFile(globalsCssPath, cssContent);
585
- console.log(chalk.green(`✅ Created ${pathConfig.styles}`));
586
- }
587
- }
588
-
589
- async function updateExistingGlobalsCss(globalsCssPath: string): Promise<void> {
590
- const content = await fs.readFile(globalsCssPath, 'utf-8');
591
-
592
- // Check if already has FoundryKit import
593
- if (content.includes('@foundrykit/tailwind/globals.css')) {
594
- console.log(chalk.gray('globals.css already imports FoundryKit styles'));
595
- return;
596
- }
597
-
598
- // Check if it has @import "tailwindcss"
599
- if (content.includes('@import "tailwindcss"')) {
600
- // Replace the tailwindcss import with FoundryKit import but keep all other content
601
- const updatedContent = content.replace(
602
- '@import "tailwindcss"',
603
- `/* Import FoundryKit's Tailwind CSS v4 styles */\n@import "@foundrykit/tailwind/globals.css"`
604
- );
605
-
606
- await fs.writeFile(globalsCssPath, updatedContent);
607
- console.log(chalk.green('✅ Updated globals.css with FoundryKit styles'));
608
- } else {
609
- // Just prepend the FoundryKit import
610
- const updatedContent = `/* Import FoundryKit's Tailwind CSS v4 styles */
611
- @import "@foundrykit/tailwind/globals.css";
612
-
613
- /* Your custom styles below */
614
- ${content}`;
615
-
616
- await fs.writeFile(globalsCssPath, updatedContent);
617
- console.log(chalk.green('✅ Updated globals.css with FoundryKit styles'));
618
- }
619
- }
620
-
621
- async function findLayoutFile(
622
- projectStructure: ProjectStructure
623
- ): Promise<string | null> {
624
- const possiblePaths = [];
625
-
626
- if (projectStructure.appPath) {
627
- const ext = projectStructure.isTypeScript ? '.tsx' : '.jsx';
628
- possiblePaths.push(
629
- path.join(projectStructure.appPath, `layout${ext}`),
630
- path.join(projectStructure.appPath, `layout.js`)
631
- );
632
- }
633
-
634
- // Also check standard paths
635
- possiblePaths.push(
636
- 'app/layout.tsx',
637
- 'app/layout.jsx',
638
- 'app/layout.js',
639
- 'src/app/layout.tsx',
640
- 'src/app/layout.jsx',
641
- 'src/app/layout.js'
642
- );
643
-
644
- for (const layoutPath of possiblePaths) {
645
- const fullPath = path.join(process.cwd(), layoutPath);
646
- if (fs.existsSync(fullPath)) {
647
- return fullPath;
648
- }
649
- }
650
-
651
- return null;
652
- }
653
-
654
- async function updateLayoutImport(
655
- layoutPath: string,
656
- pathConfig: PathConfig
657
- ): Promise<void> {
658
- try {
659
- let content = await fs.readFile(layoutPath, 'utf-8');
660
-
661
- // Calculate relative import path from layout to styles
662
- const fromPath = path.dirname(layoutPath);
663
- const toPath = path.join(process.cwd(), pathConfig.styles);
664
- const relativePath = path.relative(fromPath, toPath).replace(/\\/g, '/');
665
- const importPath = relativePath.startsWith('.')
666
- ? relativePath
667
- : `./${relativePath}`;
668
-
669
- // Check for existing global CSS imports
670
- const globalImportRegex = /import\s+['"]([^'"]*globals?\.css)['"]/;
671
- const match = content.match(globalImportRegex);
672
-
673
- if (match) {
674
- // Replace existing import
675
- content = content.replace(globalImportRegex, `import '${importPath}'`);
676
- } else if (!content.includes(importPath)) {
677
- // Add new import after other imports
678
- const importStatement = `import '${importPath}';\n`;
679
- const importRegex = /^(import\s+.*?;\s*)+/m;
680
- const importMatch = content.match(importRegex);
681
-
682
- if (importMatch) {
683
- const lastImportIndex = importMatch.index! + importMatch[0].length;
684
- content =
685
- content.slice(0, lastImportIndex) +
686
- importStatement +
687
- content.slice(lastImportIndex);
688
- } else {
689
- content = importStatement + content;
690
- }
691
- }
692
-
693
- await fs.writeFile(layoutPath, content);
694
- console.log(
695
- chalk.gray(
696
- `Updated ${path.relative(process.cwd(), layoutPath)} with CSS import`
697
- )
698
- );
699
- } catch (error) {
700
- console.error(chalk.yellow('⚠️ Failed to update layout with CSS import'));
701
- }
702
- }
703
-
704
- async function addDirectImportToLayout(
705
- layoutPath: string,
706
- pathConfig: PathConfig
707
- ): Promise<void> {
708
- try {
709
- let content = await fs.readFile(layoutPath, 'utf-8');
710
- const importStatement = `import '@foundrykit/tailwind/globals.css';\n`;
711
-
712
- if (!content.includes('@foundrykit/tailwind/globals.css')) {
713
- // Add import at the top of the file after any existing imports
714
- const importRegex = /^(import\s+.*?;\s*)+/m;
715
- const match = content.match(importRegex);
716
-
717
- if (match) {
718
- // Add after existing imports
719
- const lastImportIndex = match.index! + match[0].length;
720
- content =
721
- content.slice(0, lastImportIndex) +
722
- importStatement +
723
- content.slice(lastImportIndex);
724
- } else {
725
- // Add at the very beginning
726
- content = importStatement + content;
727
- }
728
-
729
- await fs.writeFile(layoutPath, content);
730
- console.log(
731
- chalk.green('✅ Added direct import of FoundryKit styles to layout')
732
- );
733
- }
734
- } catch (error) {
735
- console.error(chalk.yellow('⚠️ Failed to add CSS import to layout'));
736
- }
737
- }
738
-
739
- function resolveImportPath(fromFile: string, importPath: string): string {
740
- if (importPath.startsWith('.')) {
741
- // Relative import
742
- return path.join(path.dirname(fromFile), importPath);
743
- } else if (importPath.startsWith('@/')) {
744
- // Alias import
745
- return path.join(process.cwd(), importPath.replace('@/', 'src/'));
746
- } else if (importPath.startsWith('/')) {
747
- // Absolute import from project root
748
- return path.join(process.cwd(), importPath);
749
- }
750
-
751
- // Default to relative from project root
752
- return path.join(process.cwd(), importPath);
753
- }
754
-
755
- async function createDirectories(pathConfig: PathConfig): Promise<void> {
756
- console.log(chalk.blue('📁 Creating component directories...'));
757
-
758
- const dirs = [
759
- pathConfig.primitives,
760
- pathConfig.components,
761
- pathConfig.blocks,
762
- pathConfig.maps,
763
- pathConfig.animations,
764
- pathConfig.hooks,
765
- pathConfig.lib,
766
- ];
767
-
768
- for (const dir of dirs) {
769
- const fullPath = path.join(process.cwd(), dir);
770
- await fs.ensureDir(fullPath);
771
- console.log(chalk.gray(`Created ${dir}`));
772
- }
773
-
774
- console.log(chalk.green('✅ Directories created'));
775
- }
776
-
777
- async function createExampleFiles(
778
- pathConfig: PathConfig,
779
- structure: ProjectStructure
780
- ): Promise<void> {
781
- console.log(chalk.blue('📝 Creating example files...'));
782
-
783
- // Create lib/utils.ts if it doesn't exist
784
- const utilsPath = path.join(process.cwd(), pathConfig.utils);
785
- const utilsContent = `import { type ClassValue, clsx } from 'clsx';
786
- import { twMerge } from 'tailwind-merge';
787
-
788
- export function cn(...inputs: ClassValue[]) {
789
- return twMerge(clsx(inputs));
790
- }
791
- `;
792
-
793
- await fs.ensureDir(path.dirname(utilsPath));
794
-
795
- if (!fs.existsSync(utilsPath)) {
796
- await fs.writeFile(utilsPath, utilsContent);
797
- console.log(chalk.gray(`Created ${pathConfig.utils}`));
798
- }
799
-
800
- // Create providers.tsx for Next.js projects
801
- const providersPath = path.join(
802
- process.cwd(),
803
- path.dirname(pathConfig.components),
804
- `theme-provider${structure.isTypeScript ? '.tsx' : '.jsx'}`
805
- );
806
-
807
- const providersContent = `
808
- 'use client';
809
-
810
- import type * as React from 'react';
811
- import { ThemeProvider as NextThemesProvider } from 'next-themes';
812
-
813
- export function ThemeProvider({ children }: { children: React.ReactNode }) {
814
- return (
815
- <NextThemesProvider
816
- attribute='class'
817
- defaultTheme='system'
818
- enableSystem
819
- disableTransitionOnChange
820
- enableColorScheme
821
- >
822
- {children}
823
- </NextThemesProvider>
824
- );
825
- }
826
-
827
- `;
828
-
829
- if (!fs.existsSync(providersPath)) {
830
- await fs.writeFile(providersPath, providersContent);
831
- console.log(
832
- chalk.gray(
833
- `Created theme-provider.${structure.isTypeScript ? 'tsx' : 'jsx'}`
834
- )
835
- );
836
- }
837
-
838
- console.log(chalk.green('✅ Example files created'));
839
- }
840
-
841
- async function updatePackageScripts(): Promise<void> {
842
- console.log(chalk.blue('📝 Updating package.json scripts...'));
843
-
844
- const packageJsonPath = path.join(process.cwd(), 'package.json');
845
- const packageJson = await fs.readJson(packageJsonPath);
846
-
847
- // Add foundrykit scripts
848
- packageJson.scripts = {
849
- ...packageJson.scripts,
850
- 'foundrykit:add': 'pnpm dlx @foundrykit/cli add',
851
- 'foundrykit:update': 'pnpm dlx @foundrykit/cli update',
852
- };
853
-
854
- await fs.writeJson(packageJsonPath, packageJson, { spaces: 2 });
855
- console.log(chalk.green('✅ Package scripts updated'));
856
- }
857
-
858
- async function createConfigFile(
859
- options: InitOptions,
860
- structure: ProjectStructure,
861
- pathConfig: PathConfig
862
- ): Promise<void> {
863
- console.log(chalk.blue('📝 Creating configuration file...'));
864
-
865
- const configPath = path.join(process.cwd(), 'foundrykit.config.json');
866
-
867
- if (fs.existsSync(configPath) && !options.force) {
868
- console.log(chalk.yellow('⚠️ Configuration file already exists'));
869
- return;
870
- }
871
-
872
- // Create configuration with custom paths
873
- // Normalize paths - ensure they start with ./ if they're relative
874
- const normalizePath = (p: string) => {
875
- if (p.startsWith('./') || p.startsWith('../') || path.isAbsolute(p)) {
876
- return p;
877
- }
878
- return `./${p}`;
879
- };
880
-
881
- const config = {
882
- version: CLI_VERSION,
883
- registry: DEFAULT_REGISTRY_URL,
884
- paths: {
885
- utils: normalizePath(pathConfig.utils),
886
- primitives: normalizePath(pathConfig.primitives),
887
- components: normalizePath(pathConfig.components),
888
- blocks: normalizePath(pathConfig.blocks),
889
- hooks: normalizePath(pathConfig.hooks),
890
- maps: normalizePath(pathConfig.maps),
891
- animations: normalizePath(pathConfig.animations),
892
- },
893
- packageManager: structure.packageManager,
894
- typescript: structure.isTypeScript,
895
- framework: structure.framework,
896
- tailwind: {
897
- css: normalizePath(pathConfig.styles),
898
- },
899
- aliases: {
900
- '@': normalizePath(structure.baseDir.replace(/\/$/, '') || '.'),
901
- '@/components': normalizePath(
902
- path.dirname(pathConfig.components).replace(/\/$/, '')
903
- ),
904
- '@/lib': normalizePath(pathConfig.lib.replace(/\/$/, '')),
905
- '@/hooks': normalizePath(pathConfig.hooks.replace(/\/$/, '')),
906
- },
907
- };
908
-
909
- await fs.writeJson(configPath, config, { spaces: 2 });
910
- console.log(chalk.green('✅ Created foundrykit.config.json'));
911
- }
912
-
913
- async function installUtils(pathConfig: PathConfig): Promise<void> {
914
- console.log(chalk.blue('📦 Installing utility functions...'));
915
-
916
- const utilsPath = path.join(process.cwd(), pathConfig.utils);
917
- const utilsContent = `import { type ClassValue, clsx } from 'clsx';
918
- import { twMerge } from 'tailwind-merge';
919
-
920
- export function cn(...inputs: ClassValue[]) {
921
- return twMerge(clsx(inputs));
922
- }
923
- `;
924
-
925
- // Ensure directory exists
926
- const utilsDir = path.dirname(utilsPath);
927
- await fs.ensureDir(utilsDir);
928
-
929
- if (!fs.existsSync(utilsPath)) {
930
- await fs.writeFile(utilsPath, utilsContent);
931
- console.log(chalk.green('✅ Utility functions installed'));
932
- } else {
933
- console.log(chalk.gray('Utils file already exists, skipping...'));
934
- }
935
- }