@foundrykit/cli 0.1.1 → 1.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.
package/dist/index.js CHANGED
@@ -2,6 +2,9 @@
2
2
 
3
3
  // src/index.ts
4
4
  import { Command as Command6 } from "commander";
5
+ import { readFileSync } from "fs";
6
+ import { fileURLToPath } from "url";
7
+ import { dirname, join } from "path";
5
8
 
6
9
  // src/commands/init.ts
7
10
  import { Command } from "commander";
@@ -32,7 +35,7 @@ function initCommand() {
32
35
  if (!options.skipInstall) {
33
36
  await installDependencies();
34
37
  }
35
- await setupTailwindConfig();
38
+ await setupTailwindV4();
36
39
  await createDirectories();
37
40
  await createExampleFiles();
38
41
  await updatePackageScripts();
@@ -65,10 +68,10 @@ async function validateNextJsProject() {
65
68
  "No package.json found. Please run this command in a Next.js project root."
66
69
  );
67
70
  }
68
- const packageJson = await fs.readJson(packageJsonPath);
71
+ const packageJson2 = await fs.readJson(packageJsonPath);
69
72
  const dependencies = {
70
- ...packageJson.dependencies,
71
- ...packageJson.devDependencies
73
+ ...packageJson2.dependencies,
74
+ ...packageJson2.devDependencies
72
75
  };
73
76
  if (!dependencies.next) {
74
77
  throw new Error(
@@ -78,28 +81,36 @@ async function validateNextJsProject() {
78
81
  console.log(chalk.green("\u2705 Next.js project detected"));
79
82
  }
80
83
  async function isFoundryKitInitialized() {
81
- const tailwindConfigPath = path.join(process.cwd(), "tailwind.config.js");
82
- const tailwindConfigTsPath = path.join(process.cwd(), "tailwind.config.ts");
83
- if (fs.existsSync(tailwindConfigPath)) {
84
- const config = await fs.readFile(tailwindConfigPath, "utf-8");
85
- return config.includes("@foundrykit/tailwind-config");
86
- }
87
- if (fs.existsSync(tailwindConfigTsPath)) {
88
- const config = await fs.readFile(tailwindConfigTsPath, "utf-8");
89
- return config.includes("@foundrykit/tailwind-config");
84
+ const packageJsonPath = path.join(process.cwd(), "package.json");
85
+ if (fs.existsSync(packageJsonPath)) {
86
+ const packageJson2 = await fs.readJson(packageJsonPath);
87
+ const dependencies = {
88
+ ...packageJson2.dependencies,
89
+ ...packageJson2.devDependencies
90
+ };
91
+ return Object.keys(dependencies).some(
92
+ (dep) => dep.startsWith("@foundrykit/")
93
+ );
90
94
  }
91
95
  return false;
92
96
  }
93
97
  async function installDependencies() {
94
98
  console.log(chalk.blue("\u{1F4E6} Installing FoundryKit dependencies..."));
99
+ const isWorkspace = await checkIfWorkspace();
100
+ if (isWorkspace) {
101
+ console.log(
102
+ chalk.yellow("\u26A0\uFE0F Workspace detected - skipping dependency installation")
103
+ );
104
+ console.log(chalk.gray("Dependencies are already available via workspace"));
105
+ return;
106
+ }
95
107
  const dependencies = [
96
108
  "@foundrykit/primitives",
97
109
  "@foundrykit/components",
98
110
  "@foundrykit/blocks",
99
111
  "@foundrykit/hooks",
100
112
  "@foundrykit/animation",
101
- "@foundrykit/tokens",
102
- "@foundrykit/tailwind-config"
113
+ "@foundrykit/tailwind"
103
114
  ];
104
115
  try {
105
116
  const packageManager = detectPackageManager();
@@ -113,34 +124,268 @@ async function installDependencies() {
113
124
  );
114
125
  }
115
126
  }
127
+ async function checkIfWorkspace() {
128
+ try {
129
+ const pnpmWorkspacePath = path.join(
130
+ process.cwd(),
131
+ "../../pnpm-workspace.yaml"
132
+ );
133
+ if (fs.existsSync(pnpmWorkspacePath)) {
134
+ return true;
135
+ }
136
+ const packageJsonPath = path.join(process.cwd(), "package.json");
137
+ if (fs.existsSync(packageJsonPath)) {
138
+ const packageJson2 = await fs.readJson(packageJsonPath);
139
+ const allDeps = {
140
+ ...packageJson2.dependencies,
141
+ ...packageJson2.devDependencies
142
+ };
143
+ const foundryKitPackages = Object.keys(allDeps).filter(
144
+ (key) => key.startsWith("@foundrykit/")
145
+ );
146
+ for (const pkg of foundryKitPackages) {
147
+ if (allDeps[pkg]?.includes("workspace:")) {
148
+ return true;
149
+ }
150
+ }
151
+ }
152
+ return false;
153
+ } catch {
154
+ return false;
155
+ }
156
+ }
116
157
  function detectPackageManager() {
117
158
  if (fs.existsSync("pnpm-lock.yaml")) return "pnpm";
118
159
  if (fs.existsSync("yarn.lock")) return "yarn";
119
160
  return "npm";
120
161
  }
121
- async function setupTailwindConfig() {
122
- console.log(chalk.blue("\u2699\uFE0F Setting up Tailwind configuration..."));
123
- const configPath = path.join(process.cwd(), "tailwind.config.ts");
124
- const configContent = `import type { Config } from 'tailwindcss';
125
- import { withFoundryKit } from '@foundrykit/tailwind-config';
162
+ async function setupTailwindV4() {
163
+ console.log(chalk.blue("\u2699\uFE0F Setting up Tailwind CSS v4..."));
164
+ const layoutInfo = await findLayoutFile();
165
+ if (layoutInfo) {
166
+ const layoutContent = await fs.readFile(layoutInfo.path, "utf-8");
167
+ if (layoutContent.includes("@foundrykit/tailwind/globals.css")) {
168
+ const { importPreference } = await inquirer.prompt([
169
+ {
170
+ type: "list",
171
+ name: "importPreference",
172
+ message: "FoundryKit styles are already imported directly. How would you like to proceed?",
173
+ choices: [
174
+ {
175
+ name: "Keep direct import from @foundrykit/tailwind/globals.css",
176
+ value: "direct"
177
+ },
178
+ {
179
+ name: "Switch to local globals.css file (recommended for customization)",
180
+ value: "local"
181
+ }
182
+ ],
183
+ default: "direct"
184
+ }
185
+ ]);
186
+ if (importPreference === "direct") {
187
+ console.log(
188
+ chalk.green(
189
+ "\u2705 Keeping direct import from @foundrykit/tailwind/globals.css"
190
+ )
191
+ );
192
+ return;
193
+ }
194
+ await createLocalGlobalsAndUpdateLayout(layoutInfo.path, layoutContent);
195
+ return;
196
+ }
197
+ const globalsCssImportMatch = layoutContent.match(
198
+ /import\s+['"]([^'"]*globals\.css)['"]/
199
+ );
200
+ if (globalsCssImportMatch && globalsCssImportMatch[1]) {
201
+ const importPath = globalsCssImportMatch[1];
202
+ const resolvedPath = importPath.startsWith(".") ? path.join(path.dirname(layoutInfo.path), importPath) : path.join(process.cwd(), importPath.replace(/^@\//, "app/"));
203
+ if (fs.existsSync(resolvedPath)) {
204
+ const globalsCssContent = await fs.readFile(resolvedPath, "utf-8");
205
+ if (globalsCssContent.includes("@foundrykit/tailwind/globals.css")) {
206
+ console.log(chalk.green("\u2705 FoundryKit styles already configured"));
207
+ return;
208
+ }
209
+ const updatedContent = `/* Import FoundryKit's Tailwind CSS v4 styles */
210
+ @import "@foundrykit/tailwind/globals.css";
126
211
 
127
- const config: Config = withFoundryKit({
128
- content: [
129
- './pages/**/*.{js,ts,jsx,tsx,mdx}',
130
- './components/**/*.{js,ts,jsx,tsx,mdx}',
131
- './app/**/*.{js,ts,jsx,tsx,mdx}',
132
- './src/**/*.{js,ts,jsx,tsx,mdx}',
133
- ],
134
- theme: {
135
- extend: {},
136
- },
137
- plugins: [],
138
- });
212
+ /* Your custom styles below */
213
+ ${globalsCssContent}`;
214
+ await fs.writeFile(resolvedPath, updatedContent);
215
+ console.log(
216
+ chalk.green("\u2705 Updated existing globals.css with FoundryKit styles")
217
+ );
218
+ return;
219
+ }
220
+ }
221
+ }
222
+ const { setupPreference } = await inquirer.prompt([
223
+ {
224
+ type: "list",
225
+ name: "setupPreference",
226
+ message: "How would you like to import FoundryKit styles?",
227
+ choices: [
228
+ {
229
+ name: "Create a local globals.css file (recommended for customization)",
230
+ value: "local"
231
+ },
232
+ {
233
+ name: "Import directly from @foundrykit/tailwind/globals.css",
234
+ value: "direct"
235
+ }
236
+ ],
237
+ default: "local"
238
+ }
239
+ ]);
240
+ if (setupPreference === "direct") {
241
+ await addDirectImportToLayout();
242
+ } else {
243
+ await createLocalGlobalsAndUpdateLayout();
244
+ }
245
+ }
246
+ async function createLocalGlobalsAndUpdateLayout(existingLayoutPath, existingLayoutContent) {
247
+ const possiblePaths = [
248
+ "app/globals.css",
249
+ "src/app/globals.css",
250
+ "styles/globals.css",
251
+ "src/styles/globals.css"
252
+ ];
253
+ let globalCssPath = null;
254
+ for (const p of possiblePaths) {
255
+ const fullPath = path.join(process.cwd(), p);
256
+ if (fs.existsSync(fullPath)) {
257
+ globalCssPath = fullPath;
258
+ break;
259
+ }
260
+ }
261
+ if (!globalCssPath) {
262
+ globalCssPath = path.join(process.cwd(), "app/globals.css");
263
+ await fs.ensureDir(path.dirname(globalCssPath));
264
+ }
265
+ const existingContent = fs.existsSync(globalCssPath) ? await fs.readFile(globalCssPath, "utf-8") : "";
266
+ if (!existingContent.includes("@foundrykit/tailwind/globals.css")) {
267
+ const cssContent = `/* Import FoundryKit's Tailwind CSS v4 styles */
268
+ @import "@foundrykit/tailwind/globals.css";
139
269
 
140
- export default config;
141
- `;
142
- await fs.writeFile(configPath, configContent);
143
- console.log(chalk.green("\u2705 Tailwind config created"));
270
+ /* Your custom styles below */
271
+ ${existingContent}`;
272
+ await fs.writeFile(globalCssPath, cssContent);
273
+ console.log(
274
+ chalk.green("\u2705 Created/updated globals.css with FoundryKit styles")
275
+ );
276
+ }
277
+ if (existingLayoutPath && existingLayoutContent) {
278
+ const layoutDir = path.dirname(existingLayoutPath);
279
+ const cssRelativePath = path.relative(layoutDir, globalCssPath).replace(/\\/g, "/");
280
+ const importPath = cssRelativePath.startsWith(".") ? cssRelativePath : `./${cssRelativePath}`;
281
+ const updatedContent = existingLayoutContent.replace(
282
+ /@foundrykit\/tailwind\/globals\.css/g,
283
+ importPath
284
+ );
285
+ await fs.writeFile(existingLayoutPath, updatedContent);
286
+ console.log(chalk.green("\u2705 Updated layout to use local globals.css"));
287
+ } else {
288
+ await updateLayoutImport(globalCssPath);
289
+ }
290
+ }
291
+ async function addDirectImportToLayout() {
292
+ const layoutInfo = await findLayoutFile();
293
+ if (!layoutInfo) {
294
+ console.log(
295
+ chalk.yellow(
296
+ "\u26A0\uFE0F No layout file found. Please add this import to your layout manually:"
297
+ )
298
+ );
299
+ console.log(chalk.gray(` import '@foundrykit/tailwind/globals.css';`));
300
+ return;
301
+ }
302
+ const layoutContent = await fs.readFile(layoutInfo.path, "utf-8");
303
+ if (layoutContent.includes("@foundrykit/tailwind/globals.css")) {
304
+ console.log(
305
+ chalk.gray("Layout already imports FoundryKit styles directly")
306
+ );
307
+ return;
308
+ }
309
+ const importStatement = `import '@foundrykit/tailwind/globals.css';`;
310
+ const importRegex = /^import\s+.*$/gm;
311
+ const imports = layoutContent.match(importRegex);
312
+ let updatedContent;
313
+ if (imports && imports.length > 0) {
314
+ const lastImport = imports[imports.length - 1];
315
+ const lastImportIndex = layoutContent.lastIndexOf(lastImport);
316
+ const insertPosition = lastImportIndex + lastImport.length;
317
+ updatedContent = layoutContent.slice(0, insertPosition) + "\n" + importStatement + layoutContent.slice(insertPosition);
318
+ } else {
319
+ updatedContent = importStatement + "\n" + layoutContent;
320
+ }
321
+ await fs.writeFile(layoutInfo.path, updatedContent);
322
+ console.log(
323
+ chalk.green("\u2705 Added direct import of FoundryKit styles to layout")
324
+ );
325
+ }
326
+ async function findLayoutFile() {
327
+ const layoutPaths = [
328
+ "app/layout.tsx",
329
+ "app/layout.jsx",
330
+ "app/layout.js",
331
+ "src/app/layout.tsx",
332
+ "src/app/layout.jsx",
333
+ "src/app/layout.js"
334
+ ];
335
+ for (const p of layoutPaths) {
336
+ const fullPath = path.join(process.cwd(), p);
337
+ if (fs.existsSync(fullPath)) {
338
+ return { path: fullPath };
339
+ }
340
+ }
341
+ return null;
342
+ }
343
+ async function updateLayoutImport(globalCssPath) {
344
+ const layoutInfo = await findLayoutFile();
345
+ if (!layoutInfo) {
346
+ console.log(
347
+ chalk.yellow(
348
+ "\u26A0\uFE0F No layout file found. Please import globals.css manually in your layout."
349
+ )
350
+ );
351
+ return;
352
+ }
353
+ const layoutContent = await fs.readFile(layoutInfo.path, "utf-8");
354
+ if (layoutContent.match(/import\s+['"][^'"]*globals\.css['"]/)) {
355
+ console.log(chalk.gray("Layout already has a globals.css import"));
356
+ return;
357
+ }
358
+ if (layoutContent.includes("@foundrykit/tailwind/globals.css")) {
359
+ const layoutDir2 = path.dirname(layoutInfo.path);
360
+ const cssRelativePath2 = path.relative(layoutDir2, globalCssPath).replace(/\\/g, "/");
361
+ const importPath2 = cssRelativePath2.startsWith(".") ? cssRelativePath2 : `./${cssRelativePath2}`;
362
+ const updatedContent2 = layoutContent.replace(
363
+ /@foundrykit\/tailwind\/globals\.css/g,
364
+ importPath2
365
+ );
366
+ await fs.writeFile(layoutInfo.path, updatedContent2);
367
+ console.log(
368
+ chalk.green("\u2705 Updated layout import to use local globals.css")
369
+ );
370
+ return;
371
+ }
372
+ const layoutDir = path.dirname(layoutInfo.path);
373
+ const cssRelativePath = path.relative(layoutDir, globalCssPath).replace(/\\/g, "/");
374
+ const importPath = cssRelativePath.startsWith(".") ? cssRelativePath : `./${cssRelativePath}`;
375
+ const importStatement = `import '${importPath}';`;
376
+ const importRegex = /^import\s+.*$/gm;
377
+ const imports = layoutContent.match(importRegex);
378
+ let updatedContent;
379
+ if (imports && imports.length > 0) {
380
+ const lastImport = imports[imports.length - 1];
381
+ const lastImportIndex = layoutContent.lastIndexOf(lastImport);
382
+ const insertPosition = lastImportIndex + lastImport.length;
383
+ updatedContent = layoutContent.slice(0, insertPosition) + "\n" + importStatement + layoutContent.slice(insertPosition);
384
+ } else {
385
+ updatedContent = importStatement + "\n" + layoutContent;
386
+ }
387
+ await fs.writeFile(layoutInfo.path, updatedContent);
388
+ console.log(chalk.green("\u2705 Layout file updated with globals.css import"));
144
389
  }
145
390
  async function createDirectories() {
146
391
  console.log(chalk.blue("\u{1F4C1} Creating component directories..."));
@@ -160,526 +405,529 @@ export function cn(...inputs: ClassValue[]) {
160
405
  return twMerge(clsx(inputs));
161
406
  }
162
407
  `;
163
- await fs.writeFile(utilsPath, utilsContent);
164
- const globalsCssPath = path.join(process.cwd(), "app/globals.css");
165
- const srcGlobalsCssPath = path.join(process.cwd(), "src/app/globals.css");
166
- const globalsCssContent = `@import "tailwindcss";
167
-
168
- @layer base {
169
- :root {
170
- --background: 0 0% 100%;
171
- --foreground: 222.2 84% 4.9%;
172
- --card: 0 0% 100%;
173
- --card-foreground: 222.2 84% 4.9%;
174
- --popover: 0 0% 100%;
175
- --popover-foreground: 222.2 84% 4.9%;
176
- --primary: 222.2 47.4% 11.2%;
177
- --primary-foreground: 210 40% 98%;
178
- --secondary: 210 40% 96%;
179
- --secondary-foreground: 222.2 84% 4.9%;
180
- --muted: 210 40% 96%;
181
- --muted-foreground: 215.4 16.3% 46.9%;
182
- --accent: 210 40% 96%;
183
- --accent-foreground: 222.2 84% 4.9%;
184
- --destructive: 0 84.2% 60.2%;
185
- --destructive-foreground: 210 40% 98%;
186
- --border: 214.3 31.8% 91.4%;
187
- --input: 214.3 31.8% 91.4%;
188
- --ring: 222.2 84% 4.9%;
189
- --radius: 0.5rem;
408
+ if (!fs.existsSync(utilsPath)) {
409
+ await fs.writeFile(utilsPath, utilsContent);
410
+ console.log(chalk.gray("Created lib/utils.ts"));
190
411
  }
412
+ const providersPath = path.join(process.cwd(), "components/providers.tsx");
413
+ const providersContent = `'use client';
191
414
 
192
- .dark {
193
- --background: 222.2 84% 4.9%;
194
- --foreground: 210 40% 98%;
195
- --card: 222.2 84% 4.9%;
196
- --card-foreground: 210 40% 98%;
197
- --popover: 222.2 84% 4.9%;
198
- --popover-foreground: 210 40% 98%;
199
- --primary: 210 40% 98%;
200
- --primary-foreground: 222.2 47.4% 11.2%;
201
- --secondary: 217.2 32.6% 17.5%;
202
- --secondary-foreground: 210 40% 98%;
203
- --muted: 217.2 32.6% 17.5%;
204
- --muted-foreground: 215 20.2% 65.1%;
205
- --accent: 217.2 32.6% 17.5%;
206
- --accent-foreground: 210 40% 98%;
207
- --destructive: 0 62.8% 30.6%;
208
- --destructive-foreground: 210 40% 98%;
209
- --border: 217.2 32.6% 17.5%;
210
- --input: 217.2 32.6% 17.5%;
211
- --ring: 212.7 26.8% 83.9%;
212
- }
213
- }
415
+ import { ThemeProvider } from 'next-themes';
214
416
 
215
- @layer base {
216
- body {
217
- @apply bg-background text-foreground;
218
- }
417
+ export function Providers({ children }: { children: React.ReactNode }) {
418
+ return (
419
+ <ThemeProvider attribute="class" defaultTheme="system" enableSystem>
420
+ {children}
421
+ </ThemeProvider>
422
+ );
219
423
  }
220
424
  `;
221
- if (fs.existsSync(globalsCssPath)) {
222
- const existing = await fs.readFile(globalsCssPath, "utf-8");
223
- if (!existing.includes("--background")) {
224
- await fs.writeFile(globalsCssPath, globalsCssContent);
225
- }
226
- } else if (fs.existsSync(srcGlobalsCssPath)) {
227
- const existing = await fs.readFile(srcGlobalsCssPath, "utf-8");
228
- if (!existing.includes("--background")) {
229
- await fs.writeFile(srcGlobalsCssPath, globalsCssContent);
230
- }
231
- } else {
232
- await fs.ensureDir(path.join(process.cwd(), "app"));
233
- await fs.writeFile(globalsCssPath, globalsCssContent);
425
+ if (!fs.existsSync(providersPath)) {
426
+ await fs.writeFile(providersPath, providersContent);
427
+ console.log(chalk.gray("Created components/providers.tsx"));
234
428
  }
235
429
  console.log(chalk.green("\u2705 Example files created"));
236
430
  }
237
431
  async function updatePackageScripts() {
238
432
  console.log(chalk.blue("\u{1F4CB} Updating package.json scripts..."));
239
433
  const packageJsonPath = path.join(process.cwd(), "package.json");
240
- const packageJson = await fs.readJson(packageJsonPath);
241
- if (!packageJson.scripts) {
242
- packageJson.scripts = {};
434
+ const packageJson2 = await fs.readJson(packageJsonPath);
435
+ if (!packageJson2.scripts) {
436
+ packageJson2.scripts = {};
243
437
  }
244
- if (!packageJson.scripts["foundrykit"]) {
245
- packageJson.scripts["foundrykit"] = "foundrykit";
438
+ if (!packageJson2.scripts["foundrykit"]) {
439
+ packageJson2.scripts["foundrykit"] = "foundrykit";
246
440
  }
247
- if (!packageJson.scripts["fk"]) {
248
- packageJson.scripts["fk"] = "foundrykit";
441
+ if (!packageJson2.scripts["fk"]) {
442
+ packageJson2.scripts["fk"] = "foundrykit";
249
443
  }
250
- await fs.writeJson(packageJsonPath, packageJson, { spaces: 2 });
444
+ await fs.writeJson(packageJsonPath, packageJson2, { spaces: 2 });
251
445
  console.log(chalk.green("\u2705 Package scripts updated"));
252
446
  }
253
447
 
254
448
  // src/commands/list.ts
255
449
  import { Command as Command2 } from "commander";
450
+ import chalk3 from "chalk";
451
+
452
+ // src/lib/registry.ts
453
+ import fs2 from "fs-extra";
454
+ import path2 from "path";
455
+ import os from "os";
256
456
  import chalk2 from "chalk";
257
- import fetch from "node-fetch";
457
+ var DEFAULT_CONFIG = {
458
+ registryUrl: process.env.FOUNDRYKIT_REGISTRY_URL || "https://foundry.umiflow.com",
459
+ cacheDir: path2.join(os.homedir(), ".foundrykit", "cache"),
460
+ cacheMaxAge: 1e3 * 60 * 60 * 24
461
+ // 24 hours
462
+ };
463
+ var RegistryService = class {
464
+ config;
465
+ cacheFile;
466
+ constructor(config) {
467
+ this.config = { ...DEFAULT_CONFIG, ...config };
468
+ this.cacheFile = path2.join(this.config.cacheDir, "registry.json");
469
+ }
470
+ /**
471
+ * Fetch all components from the registry
472
+ */
473
+ async getComponents(category, search) {
474
+ try {
475
+ const params = new URLSearchParams();
476
+ if (category) params.append("category", category);
477
+ if (search) params.append("search", search);
478
+ const url = `${this.config.registryUrl}/registry${params.toString() ? "?" + params.toString() : ""}`;
479
+ console.log(chalk2.gray(`Fetching from: ${url}`));
480
+ const response = await fetch(url);
481
+ if (!response.ok) {
482
+ throw new Error(
483
+ `Registry returned ${response.status}: ${response.statusText}`
484
+ );
485
+ }
486
+ const components = await response.json();
487
+ await this.updateCache(components);
488
+ return components;
489
+ } catch (error) {
490
+ const cache = await this.loadCache();
491
+ if (cache && this.isCacheValid(cache)) {
492
+ console.log(chalk2.yellow("Using cached registry data"));
493
+ return this.filterComponents(cache.components, category, search);
494
+ }
495
+ throw new Error(
496
+ `Failed to connect to registry: ${error instanceof Error ? error.message : "Unknown error"}
497
+ Registry URL: ${this.config.registryUrl}
498
+ Try again later or check your internet connection.`
499
+ );
500
+ }
501
+ }
502
+ /**
503
+ * Fetch a specific component by ID
504
+ */
505
+ async getComponent(id) {
506
+ try {
507
+ const url = `${this.config.registryUrl}/registry/${id}`;
508
+ console.log(chalk2.gray(`Fetching component: ${url}`));
509
+ const response = await fetch(url);
510
+ if (!response.ok) {
511
+ if (response.status === 404) {
512
+ throw new Error(`Component "${id}" not found in registry`);
513
+ }
514
+ throw new Error(
515
+ `Registry returned ${response.status}: ${response.statusText}`
516
+ );
517
+ }
518
+ const component = await response.json();
519
+ await this.cacheComponent(component);
520
+ return component;
521
+ } catch (error) {
522
+ const cache = await this.loadCache();
523
+ if (cache?.componentData?.[id]) {
524
+ console.log(chalk2.yellow(`Using cached data for component: ${id}`));
525
+ return cache.componentData[id];
526
+ }
527
+ throw new Error(
528
+ `Failed to fetch component "${id}": ${error instanceof Error ? error.message : "Unknown error"}
529
+ Registry URL: ${this.config.registryUrl}
530
+ Try again later or check your internet connection.`
531
+ );
532
+ }
533
+ }
534
+ /**
535
+ * Update the local cache with new component list
536
+ */
537
+ async updateCache(components) {
538
+ try {
539
+ const cache = await this.loadCache();
540
+ const newCache = {
541
+ version: "1.0.0",
542
+ lastUpdated: (/* @__PURE__ */ new Date()).toISOString(),
543
+ components,
544
+ componentData: cache?.componentData || {}
545
+ };
546
+ await fs2.ensureDir(this.config.cacheDir);
547
+ await fs2.writeJson(this.cacheFile, newCache, { spaces: 2 });
548
+ } catch (error) {
549
+ console.log(chalk2.gray("Failed to update cache"));
550
+ }
551
+ }
552
+ /**
553
+ * Cache a specific component
554
+ */
555
+ async cacheComponent(component) {
556
+ try {
557
+ const cache = await this.loadCache();
558
+ if (!cache) return;
559
+ cache.componentData[component.id] = component;
560
+ cache.lastUpdated = (/* @__PURE__ */ new Date()).toISOString();
561
+ await fs2.writeJson(this.cacheFile, cache, { spaces: 2 });
562
+ } catch (error) {
563
+ console.log(chalk2.gray("Failed to cache component"));
564
+ }
565
+ }
566
+ /**
567
+ * Load the local cache
568
+ */
569
+ async loadCache() {
570
+ try {
571
+ if (await fs2.pathExists(this.cacheFile)) {
572
+ return await fs2.readJson(this.cacheFile);
573
+ }
574
+ } catch (error) {
575
+ console.log(chalk2.gray("Failed to load cache"));
576
+ }
577
+ return null;
578
+ }
579
+ /**
580
+ * Check if cache is still valid
581
+ */
582
+ isCacheValid(cache) {
583
+ const lastUpdated = new Date(cache.lastUpdated).getTime();
584
+ const now = Date.now();
585
+ return now - lastUpdated < this.config.cacheMaxAge;
586
+ }
587
+ /**
588
+ * Filter components by category and search
589
+ */
590
+ filterComponents(components, category, search) {
591
+ let filtered = components;
592
+ if (category) {
593
+ filtered = filtered.filter((c) => c.category === category);
594
+ }
595
+ if (search) {
596
+ const searchLower = search.toLowerCase();
597
+ filtered = filtered.filter(
598
+ (c) => c.name.toLowerCase().includes(searchLower) || c.description.toLowerCase().includes(searchLower) || c.id.toLowerCase().includes(searchLower) || c.tags?.some((tag) => tag.toLowerCase().includes(searchLower))
599
+ );
600
+ }
601
+ return filtered;
602
+ }
603
+ /**
604
+ * Clear the local cache
605
+ */
606
+ async clearCache() {
607
+ try {
608
+ if (await fs2.pathExists(this.cacheFile)) {
609
+ await fs2.remove(this.cacheFile);
610
+ console.log(chalk2.green("Cache cleared successfully"));
611
+ }
612
+ } catch (error) {
613
+ throw new Error(
614
+ `Failed to clear cache: ${error instanceof Error ? error.message : "Unknown error"}`
615
+ );
616
+ }
617
+ }
618
+ /**
619
+ * Get cache statistics
620
+ */
621
+ async getCacheStats() {
622
+ try {
623
+ if (await fs2.pathExists(this.cacheFile)) {
624
+ const cache = await this.loadCache();
625
+ const stats = await fs2.stat(this.cacheFile);
626
+ return {
627
+ exists: true,
628
+ size: stats.size,
629
+ lastUpdated: cache?.lastUpdated || null,
630
+ componentCount: cache?.components.length || 0
631
+ };
632
+ }
633
+ } catch (error) {
634
+ }
635
+ return {
636
+ exists: false,
637
+ size: 0,
638
+ lastUpdated: null,
639
+ componentCount: 0
640
+ };
641
+ }
642
+ };
643
+ var registryInstance = null;
644
+ function getRegistry(config) {
645
+ if (!registryInstance) {
646
+ registryInstance = new RegistryService(config);
647
+ }
648
+ return registryInstance;
649
+ }
650
+
651
+ // src/commands/list.ts
258
652
  function listCommand() {
259
653
  return new Command2("list").description("List all available FoundryKit components and blocks").option(
260
654
  "-c, --category <category>",
261
- "filter by category (primitives, components, blocks)"
655
+ "filter by category (primitives, components, blocks, animations)"
262
656
  ).option("-s, --search <term>", "search components by name or description").action(async (options) => {
263
657
  try {
264
- console.log(chalk2.blue("\u{1F4E6} Available FoundryKit components:"));
265
- const registry = await getRegistry();
266
- let categories = [
267
- "primitives",
268
- "components",
269
- "blocks"
270
- ];
658
+ console.log(chalk3.blue("\u{1F4E6} Available FoundryKit components:"));
659
+ const registry = getRegistry();
271
660
  if (options.category) {
272
- if (!["primitives", "components", "blocks"].includes(options.category)) {
273
- console.error(chalk2.red(`Invalid category: ${options.category}`));
661
+ const validCategories = [
662
+ "primitives",
663
+ "components",
664
+ "blocks",
665
+ "animations"
666
+ ];
667
+ if (!validCategories.includes(options.category)) {
668
+ console.error(chalk3.red(`Invalid category: ${options.category}`));
274
669
  console.log(
275
- chalk2.gray("Available categories: primitives, components, blocks")
670
+ chalk3.gray(`Valid categories: ${validCategories.join(", ")}`)
276
671
  );
277
- return;
672
+ process.exit(1);
278
673
  }
279
- categories = [
280
- options.category
281
- ];
282
674
  }
283
- for (const category of categories) {
284
- const items = registry[category];
285
- const filteredItems = options.search ? items.filter(
286
- (item) => item.name.toLowerCase().includes(options.search.toLowerCase()) || item.description.toLowerCase().includes(options.search.toLowerCase())
287
- ) : items;
288
- if (filteredItems.length === 0) continue;
289
- console.log(`
290
- ${chalk2.cyan.bold(category.toUpperCase())}`);
291
- console.log(chalk2.gray("\u2500".repeat(40)));
292
- for (const item of filteredItems) {
293
- console.log(`${chalk2.green("\u25CF")} ${chalk2.bold(item.name)}`);
294
- console.log(` ${chalk2.gray(item.description)}`);
295
- if (item.tags && item.tags.length > 0) {
296
- console.log(
297
- ` ${chalk2.blue(item.tags.map((tag) => `#${tag}`).join(" "))}`
298
- );
299
- }
300
- console.log();
675
+ console.log(chalk3.gray("Fetching from registry..."));
676
+ const components = await registry.getComponents(
677
+ options.category,
678
+ options.search
679
+ );
680
+ if (components.length === 0) {
681
+ console.log(
682
+ chalk3.yellow("\nNo components found matching your criteria.")
683
+ );
684
+ if (options.search) {
685
+ console.log(chalk3.gray(`Search term: "${options.search}"`));
686
+ }
687
+ if (options.category) {
688
+ console.log(chalk3.gray(`Category: ${options.category}`));
301
689
  }
690
+ return;
302
691
  }
303
- console.log(chalk2.cyan("\n\u{1F4A1} Usage:"));
304
- console.log(chalk2.gray(" foundrykit add <component-name>"));
305
- console.log(chalk2.gray(" foundrykit add button --with-animation"));
692
+ displayComponents(components);
693
+ console.log(chalk3.cyan("\n\u{1F4A1} Usage:"));
694
+ console.log(
695
+ chalk3.gray(" foundrykit add # Interactive mode")
696
+ );
697
+ console.log(
698
+ chalk3.gray(" foundrykit add <id> # Add specific component")
699
+ );
700
+ console.log(chalk3.gray(" foundrykit add button # Example"));
306
701
  } catch (error) {
307
- console.error(chalk2.red("\u274C Failed to fetch component registry:"));
702
+ console.error(chalk3.red("\u274C Failed to fetch component registry:"));
308
703
  console.error(
309
- chalk2.red(error instanceof Error ? error.message : String(error))
704
+ chalk3.red(error instanceof Error ? error.message : String(error))
310
705
  );
311
- console.log(chalk2.yellow("\n\u{1F4CB} Using local registry:"));
312
- displayLocalRegistry(options);
706
+ process.exit(1);
313
707
  }
314
708
  });
315
709
  }
316
- async function getRegistry() {
317
- try {
318
- const response = await fetch("http://localhost:3001/api/components");
319
- if (response.ok) {
320
- const data = await response.json();
321
- return data;
322
- }
323
- } catch (error) {
324
- }
325
- return getLocalRegistry();
326
- }
327
- function getLocalRegistry() {
328
- return {
329
- primitives: [
330
- {
331
- name: "button",
332
- description: "Displays a button or a component that looks like a button.",
333
- category: "primitives",
334
- tags: ["form", "interactive"]
335
- },
336
- {
337
- name: "input",
338
- description: "Displays a form input field or a component that looks like an input.",
339
- category: "primitives",
340
- tags: ["form"]
341
- },
342
- {
343
- name: "badge",
344
- description: "Displays a badge or a component that looks like a badge.",
345
- category: "primitives",
346
- tags: ["status", "label"]
347
- },
348
- {
349
- name: "card",
350
- description: "Displays a card with header, content, and footer.",
351
- category: "primitives",
352
- tags: ["layout", "container"]
353
- },
354
- {
355
- name: "avatar",
356
- description: "An image element with a fallback for representing the user.",
357
- category: "primitives",
358
- tags: ["user", "profile"]
359
- }
360
- ],
361
- components: [
362
- {
363
- name: "search-bar",
364
- description: "A search input with suggestions and keyboard navigation.",
365
- category: "components",
366
- dependencies: ["input", "popover"],
367
- tags: ["search", "form"]
368
- },
369
- {
370
- name: "combobox",
371
- description: "Combines a text input with a listbox, allowing users to filter a list.",
372
- category: "components",
373
- dependencies: ["input", "popover", "command"],
374
- tags: ["form", "selection"]
375
- },
376
- {
377
- name: "date-picker",
378
- description: "A date picker component with calendar popup.",
379
- category: "components",
380
- dependencies: ["input", "popover", "calendar"],
381
- tags: ["form", "date"]
710
+ function displayComponents(components) {
711
+ const grouped = components.reduce(
712
+ (acc, component) => {
713
+ if (!acc[component.category]) {
714
+ acc[component.category] = [];
382
715
  }
383
- ],
384
- blocks: [
385
- {
386
- name: "hero-minimal",
387
- description: "A minimal hero section with heading, description, and CTA button.",
388
- category: "blocks",
389
- dependencies: ["button"],
390
- tags: ["landing", "marketing"]
391
- },
392
- {
393
- name: "hero-with-image",
394
- description: "A hero section with background image and content overlay.",
395
- category: "blocks",
396
- dependencies: ["button"],
397
- tags: ["landing", "marketing", "image"]
398
- },
399
- {
400
- name: "pricing",
401
- description: "A pricing section with multiple tiers and feature comparison.",
402
- category: "blocks",
403
- dependencies: ["card", "button", "badge"],
404
- tags: ["pricing", "marketing"]
405
- },
406
- {
407
- name: "testimonials",
408
- description: "A testimonials section with customer quotes and avatars.",
409
- category: "blocks",
410
- dependencies: ["avatar", "card"],
411
- tags: ["social-proof", "marketing"]
412
- }
413
- ]
414
- };
415
- }
416
- function displayLocalRegistry(options) {
417
- const registry = getLocalRegistry();
418
- let categories = [
716
+ acc[component.category].push(component);
717
+ return acc;
718
+ },
719
+ {}
720
+ );
721
+ const categoryOrder = [
419
722
  "primitives",
420
723
  "components",
421
- "blocks"
724
+ "blocks",
725
+ "animations"
422
726
  ];
423
- if (options.category) {
424
- categories = [options.category];
425
- }
426
- for (const category of categories) {
427
- const items = registry[category];
428
- const filteredItems = options.search ? items.filter(
429
- (item) => item.name.toLowerCase().includes(options.search.toLowerCase()) || item.description.toLowerCase().includes(options.search.toLowerCase())
430
- ) : items;
431
- if (filteredItems.length === 0) continue;
727
+ for (const category of categoryOrder) {
728
+ const items = grouped[category];
729
+ if (!items || items.length === 0) continue;
432
730
  console.log(`
433
- ${chalk2.cyan.bold(category.toUpperCase())}`);
434
- console.log(chalk2.gray("\u2500".repeat(40)));
435
- for (const item of filteredItems) {
436
- console.log(`${chalk2.green("\u25CF")} ${chalk2.bold(item.name)}`);
437
- console.log(` ${chalk2.gray(item.description)}`);
731
+ ${chalk3.cyan.bold(category.toUpperCase())}`);
732
+ console.log(chalk3.gray("\u2500".repeat(40)));
733
+ for (const item of items) {
734
+ console.log(
735
+ `${chalk3.green("\u25CF")} ${chalk3.bold(item.name)} ${chalk3.gray(
736
+ `(${item.id})`
737
+ )}`
738
+ );
739
+ console.log(` ${chalk3.gray(item.description)}`);
438
740
  if (item.tags && item.tags.length > 0) {
439
741
  console.log(
440
- ` ${chalk2.blue(item.tags.map((tag) => `#${tag}`).join(" "))}`
742
+ ` ${chalk3.blue(item.tags.map((tag) => `#${tag}`).join(" "))}`
743
+ );
744
+ }
745
+ if (item.registryDependencies && item.registryDependencies.length > 0) {
746
+ console.log(
747
+ ` ${chalk3.yellow("Requires:")} ${item.registryDependencies.join(
748
+ ", "
749
+ )}`
750
+ );
751
+ }
752
+ if (item.packageDependencies && item.packageDependencies.length > 0) {
753
+ console.log(
754
+ ` ${chalk3.magenta("NPM packages:")} ${item.packageDependencies.join(
755
+ ", "
756
+ )}`
441
757
  );
442
758
  }
443
759
  console.log();
444
760
  }
445
761
  }
762
+ const total = components.length;
763
+ const byCategory = Object.entries(grouped).map(([cat, items]) => `${items.length} ${cat}`).join(", ");
764
+ console.log(chalk3.gray("\u2500".repeat(40)));
765
+ console.log(chalk3.gray(`Total: ${total} components (${byCategory})`));
446
766
  }
447
767
 
448
768
  // src/commands/add.ts
449
769
  import { Command as Command3 } from "commander";
450
- import chalk3 from "chalk";
451
- import fs2 from "fs-extra";
452
- import path2 from "path";
453
- import fetch2 from "node-fetch";
770
+ import chalk4 from "chalk";
771
+ import fs3 from "fs-extra";
772
+ import path3 from "path";
454
773
  import inquirer2 from "inquirer";
455
774
  function addCommand() {
456
- return new Command3("add").description("Add a component or block to your project").argument("<id>", "Component or block ID").option("--with-animation", "Include animation variants").option("--path <path>", "Custom installation path").option("--force", "Force overwrite existing files").action(async (id, options) => {
775
+ return new Command3("add").description("Add a component or block to your project").argument("[id]", "Component or block ID (optional for interactive mode)").option("--with-animation", "Include animation variants").option("-p, --path <path>", "Custom installation path").option("-o, --overwrite", "Overwrite existing files").action(async (id, options) => {
457
776
  try {
458
- console.log(chalk3.blue(`\u{1F4E6} Adding ${id} to your project...`));
459
- await validateFoundryKitProject();
460
- const componentData = await getComponentData(id);
461
- if (!componentData) {
462
- console.error(chalk3.red(`\u274C Component "${id}" not found.`));
463
- console.log(
464
- chalk3.gray('\nUse "foundrykit list" to see available components.')
465
- );
466
- return;
467
- }
468
- if (!options.force && await hasConflictingFiles(componentData, options)) {
469
- const { shouldContinue } = await inquirer2.prompt([
470
- {
471
- type: "confirm",
472
- name: "shouldContinue",
473
- message: "Some files already exist. Continue and overwrite?",
474
- default: false
475
- }
476
- ]);
477
- if (!shouldContinue) {
478
- console.log(chalk3.yellow("\u274C Installation cancelled."));
777
+ if (!id) {
778
+ const selectedIds = await selectComponentsInteractively();
779
+ if (selectedIds.length === 0) {
780
+ console.log(chalk4.yellow("No components selected."));
479
781
  return;
480
782
  }
481
- }
482
- if (componentData.registryDependencies && componentData.registryDependencies.length > 0) {
483
- console.log(chalk3.blue("\u{1F4E6} Installing required components..."));
484
- for (const dep of componentData.registryDependencies) {
485
- await addComponent(dep, { ...options, force: true });
783
+ for (const componentId of selectedIds) {
784
+ await addSingleComponent(componentId, options);
486
785
  }
786
+ } else {
787
+ await addSingleComponent(id, options);
487
788
  }
488
- await installComponentFiles(componentData, options);
489
- await updateImports(componentData);
490
- console.log(
491
- chalk3.green(`
492
- \u2705 ${componentData.name} added successfully!`)
493
- );
494
- showUsageExample(componentData);
495
789
  } catch (error) {
496
- console.error(chalk3.red("\u274C Failed to add component:"));
790
+ console.error(chalk4.red("\u274C Failed to add component:"));
497
791
  console.error(
498
- chalk3.red(error instanceof Error ? error.message : String(error))
792
+ chalk4.red(error instanceof Error ? error.message : String(error))
499
793
  );
500
794
  process.exit(1);
501
795
  }
502
796
  });
503
797
  }
504
- async function validateFoundryKitProject() {
505
- const tailwindConfigPath = path2.join(process.cwd(), "tailwind.config.ts");
506
- const tailwindConfigJsPath = path2.join(process.cwd(), "tailwind.config.js");
507
- if (!fs2.existsSync(tailwindConfigPath) && !fs2.existsSync(tailwindConfigJsPath)) {
508
- throw new Error('FoundryKit not initialized. Run "foundrykit init" first.');
509
- }
510
- const configPath = fs2.existsSync(tailwindConfigPath) ? tailwindConfigPath : tailwindConfigJsPath;
511
- const config = await fs2.readFile(configPath, "utf-8");
512
- if (!config.includes("@foundrykit/tailwind-config")) {
513
- throw new Error(
514
- 'FoundryKit not properly configured. Run "foundrykit init" first.'
515
- );
516
- }
517
- }
518
- async function getComponentData(id) {
798
+ async function selectComponentsInteractively() {
799
+ console.log(chalk4.blue("\u{1F4E6} Select components to add:"));
800
+ console.log(
801
+ chalk4.gray(" Use arrow keys to navigate, space to select, a to toggle all")
802
+ );
803
+ console.log(chalk4.gray(" Press enter when done\n"));
804
+ const registry = getRegistry();
519
805
  try {
520
- const response = await fetch2(`http://localhost:3001/api/components/${id}`);
521
- if (response.ok) {
522
- const data = await response.json();
523
- return data;
806
+ console.log(chalk4.gray("Fetching components from registry..."));
807
+ const allComponents = await registry.getComponents();
808
+ if (allComponents.length === 0) {
809
+ console.log(chalk4.yellow("No components available in the registry."));
810
+ return [];
524
811
  }
812
+ const groupedChoices = createGroupedChoices(allComponents);
813
+ const { selectedComponents } = await inquirer2.prompt([
814
+ {
815
+ type: "checkbox",
816
+ name: "selectedComponents",
817
+ message: "Which components would you like to add?",
818
+ choices: groupedChoices,
819
+ pageSize: 20,
820
+ loop: false
821
+ }
822
+ ]);
823
+ return selectedComponents;
525
824
  } catch (error) {
825
+ console.error(chalk4.red("Failed to fetch components from registry:"));
826
+ console.error(
827
+ chalk4.red(error instanceof Error ? error.message : String(error))
828
+ );
829
+ throw error;
526
830
  }
527
- return getLocalComponentData(id);
528
831
  }
529
- function getLocalComponentData(id) {
530
- const components = {
531
- button: {
532
- name: "Button",
533
- category: "primitives",
534
- description: "A button component with multiple variants.",
535
- files: [
536
- {
537
- path: "components/ui/button.tsx",
538
- type: "component",
539
- content: `import * as React from "react"
540
- import { Slot } from "@radix-ui/react-slot"
541
- import { cva, type VariantProps } from "class-variance-authority"
542
-
543
- import { cn } from "@/lib/utils"
544
-
545
- const buttonVariants = cva(
546
- "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
547
- {
548
- variants: {
549
- variant: {
550
- default:
551
- "bg-primary text-primary-foreground shadow hover:bg-primary/90",
552
- destructive:
553
- "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
554
- outline:
555
- "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
556
- secondary:
557
- "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
558
- ghost: "hover:bg-accent hover:text-accent-foreground",
559
- link: "text-primary underline-offset-4 hover:underline",
560
- },
561
- size: {
562
- default: "h-9 px-4 py-2",
563
- sm: "h-8 rounded-md px-3 text-xs",
564
- lg: "h-10 rounded-md px-8",
565
- icon: "h-9 w-9",
566
- },
567
- },
568
- defaultVariants: {
569
- variant: "default",
570
- size: "default",
571
- },
832
+ function createGroupedChoices(components) {
833
+ const categories = [
834
+ "primitives",
835
+ "components",
836
+ "blocks",
837
+ "animations"
838
+ ];
839
+ const choices = [];
840
+ for (const category of categories) {
841
+ const categoryComponents = components.filter((c) => c.category === category);
842
+ if (categoryComponents.length === 0) continue;
843
+ choices.push({
844
+ name: chalk4.bold.cyan(`\u2500\u2500\u2500 ${category.toUpperCase()} \u2500\u2500\u2500`),
845
+ disabled: true,
846
+ value: `separator-${category}`
847
+ });
848
+ for (const component of categoryComponents) {
849
+ choices.push({
850
+ name: `${component.name} - ${chalk4.gray(component.description)}`,
851
+ value: component.id,
852
+ short: component.name
853
+ });
854
+ }
572
855
  }
573
- )
574
-
575
- export interface ButtonProps
576
- extends React.ButtonHTMLAttributes<HTMLButtonElement>,
577
- VariantProps<typeof buttonVariants> {
578
- asChild?: boolean
856
+ return choices;
579
857
  }
580
-
581
- const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
582
- ({ className, variant, size, asChild = false, ...props }, ref) => {
583
- const Comp = asChild ? Slot : "button"
584
- return (
585
- <Comp
586
- className={cn(buttonVariants({ variant, size, className }))}
587
- ref={ref}
588
- {...props}
589
- />
590
- )
591
- }
592
- )
593
- Button.displayName = "Button"
594
-
595
- export { Button, buttonVariants }
596
- `
597
- }
598
- ]
599
- },
600
- input: {
601
- name: "Input",
602
- category: "primitives",
603
- description: "A form input component.",
604
- files: [
858
+ async function addSingleComponent(id, options) {
859
+ console.log(chalk4.blue(`
860
+ \u{1F4E6} Adding ${id} to your project...`));
861
+ await validateProject();
862
+ const registry = getRegistry();
863
+ try {
864
+ const componentData = await registry.getComponent(id);
865
+ if (!options.overwrite && await hasConflictingFiles(componentData, options)) {
866
+ const { shouldContinue } = await inquirer2.prompt([
605
867
  {
606
- path: "components/ui/input.tsx",
607
- type: "component",
608
- content: `import * as React from "react"
609
-
610
- import { cn } from "@/lib/utils"
611
-
612
- export interface InputProps
613
- extends React.InputHTMLAttributes<HTMLInputElement> {}
614
-
615
- const Input = React.forwardRef<HTMLInputElement, InputProps>(
616
- ({ className, type, ...props }, ref) => {
617
- return (
618
- <input
619
- type={type}
620
- className={cn(
621
- "flex h-9 w-full rounded-md border border-input bg-transparent px-3 py-1 text-sm shadow-sm transition-colors file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:cursor-not-allowed disabled:opacity-50",
622
- className
623
- )}
624
- ref={ref}
625
- {...props}
626
- />
627
- )
628
- }
629
- )
630
- Input.displayName = "Input"
631
-
632
- export { Input }
633
- `
868
+ type: "confirm",
869
+ name: "shouldContinue",
870
+ message: `Some files for ${componentData.name} already exist. Overwrite?`,
871
+ default: false
634
872
  }
635
- ]
636
- },
637
- "hero-minimal": {
638
- name: "Hero Minimal",
639
- category: "blocks",
640
- description: "A minimal hero section with heading, description, and CTA.",
641
- registryDependencies: ["button"],
642
- files: [
643
- {
644
- path: "components/blocks/hero-minimal.tsx",
645
- type: "component",
646
- content: `import { Button } from "@/components/ui/button"
647
-
648
- export function HeroMinimal() {
649
- return (
650
- <section className="w-full py-12 md:py-24 lg:py-32">
651
- <div className="container px-4 md:px-6">
652
- <div className="flex flex-col items-center space-y-4 text-center">
653
- <div className="space-y-2">
654
- <h1 className="text-3xl font-bold tracking-tighter sm:text-4xl md:text-5xl lg:text-6xl/none">
655
- Welcome to FoundryKit
656
- </h1>
657
- <p className="mx-auto max-w-[700px] text-gray-500 md:text-xl dark:text-gray-400">
658
- Build beautiful, accessible React components with our comprehensive design system.
659
- Fast, flexible, and ready for production.
660
- </p>
661
- </div>
662
- <div className="space-x-4">
663
- <Button>Get Started</Button>
664
- <Button variant="outline">Learn More</Button>
665
- </div>
666
- </div>
667
- </div>
668
- </section>
669
- )
670
- }
671
- `
873
+ ]);
874
+ if (!shouldContinue) {
875
+ console.log(chalk4.yellow(`\u23ED\uFE0F Skipping ${componentData.name}.`));
876
+ return;
877
+ }
878
+ }
879
+ if (componentData.registryDependencies?.length) {
880
+ console.log(chalk4.blue("\u{1F4E6} Installing required dependencies..."));
881
+ for (const dep of componentData.registryDependencies) {
882
+ const depData = await registry.getComponent(dep);
883
+ if (!await hasConflictingFiles(depData, options)) {
884
+ await installComponentFiles(depData, options);
885
+ console.log(chalk4.green(` \u2713 Installed ${dep}`));
672
886
  }
673
- ]
887
+ }
674
888
  }
889
+ await installComponentFiles(componentData, options);
890
+ console.log(chalk4.green(`\u2705 ${componentData.name} added successfully!`));
891
+ showUsageExample(componentData);
892
+ if (componentData.packageDependencies?.length) {
893
+ console.log(chalk4.yellow("\n\u{1F4E6} Required npm packages:"));
894
+ console.log(
895
+ chalk4.gray(` ${componentData.packageDependencies.join(", ")}`)
896
+ );
897
+ console.log(chalk4.gray(" Install them with:"));
898
+ console.log(
899
+ chalk4.cyan(` pnpm add ${componentData.packageDependencies.join(" ")}`)
900
+ );
901
+ }
902
+ } catch (error) {
903
+ console.error(chalk4.red(`Failed to add ${id}:`));
904
+ throw error;
905
+ }
906
+ }
907
+ async function validateProject() {
908
+ const packageJsonPath = path3.join(process.cwd(), "package.json");
909
+ if (!fs3.existsSync(packageJsonPath)) {
910
+ throw new Error(
911
+ "No package.json found. Please run this command in a project root."
912
+ );
913
+ }
914
+ const packageJson2 = await fs3.readJson(packageJsonPath);
915
+ const dependencies = {
916
+ ...packageJson2.dependencies,
917
+ ...packageJson2.devDependencies
675
918
  };
676
- return components[id] || null;
919
+ const hasFoundryKit = Object.keys(dependencies).some(
920
+ (dep) => dep.startsWith("@foundrykit/")
921
+ );
922
+ if (!hasFoundryKit && !dependencies.next) {
923
+ throw new Error('FoundryKit not initialized. Run "foundrykit init" first.');
924
+ }
677
925
  }
678
926
  async function hasConflictingFiles(componentData, options) {
679
927
  const basePath = options.path || process.cwd();
680
928
  for (const file of componentData.files) {
681
- const filePath = path2.join(basePath, file.path);
682
- if (fs2.existsSync(filePath)) {
929
+ const filePath = path3.join(basePath, file.path);
930
+ if (fs3.existsSync(filePath)) {
683
931
  return true;
684
932
  }
685
933
  }
@@ -687,71 +935,85 @@ async function hasConflictingFiles(componentData, options) {
687
935
  }
688
936
  async function installComponentFiles(componentData, options) {
689
937
  const basePath = options.path || process.cwd();
690
- console.log(chalk3.blue("\u{1F4DD} Installing component files..."));
938
+ console.log(chalk4.blue("\u{1F4DD} Installing component files..."));
691
939
  for (const file of componentData.files) {
692
- const filePath = path2.join(basePath, file.path);
693
- await fs2.ensureDir(path2.dirname(filePath));
694
- await fs2.writeFile(filePath, file.content);
695
- console.log(chalk3.green(` \u2713 ${file.path}`));
696
- }
697
- }
698
- async function updateImports(componentData) {
699
- }
700
- async function addComponent(id, options) {
701
- const componentData = await getComponentData(id);
702
- if (!componentData) {
703
- throw new Error(`Dependency component "${id}" not found.`);
940
+ const filePath = path3.join(basePath, file.path);
941
+ await fs3.ensureDir(path3.dirname(filePath));
942
+ await fs3.writeFile(filePath, file.content);
943
+ console.log(chalk4.green(` \u2713 ${file.path}`));
704
944
  }
705
- await installComponentFiles(componentData, options);
706
945
  }
707
946
  function showUsageExample(componentData) {
708
- console.log(chalk3.cyan("\n\u{1F4A1} Usage:"));
709
- if (componentData.category === "primitives") {
947
+ console.log(chalk4.cyan("\n\u{1F4A1} Usage:"));
948
+ const componentName = componentData.name.replace(/\s+/g, "");
949
+ if (componentData.category === "primitives" || componentData.category === "components") {
710
950
  console.log(
711
- chalk3.gray(
712
- `import { ${componentData.name} } from "@/components/ui/${componentData.name.toLowerCase()}"`
951
+ chalk4.gray(
952
+ `import { ${componentName} } from "@/components/ui/${componentData.id}"`
713
953
  )
714
954
  );
715
955
  } else if (componentData.category === "blocks") {
716
956
  console.log(
717
- chalk3.gray(
718
- `import { ${componentData.name.replace(/\s+/g, "")} } from "@/components/blocks/${componentData.name.toLowerCase().replace(/\s+/g, "-")}"`
957
+ chalk4.gray(
958
+ `import { ${componentName} } from "@/components/blocks/${componentData.id}"`
959
+ )
960
+ );
961
+ } else if (componentData.category === "animations") {
962
+ console.log(
963
+ chalk4.gray(
964
+ `import { ${componentName} } from "@/components/animations/${componentData.id}"`
719
965
  )
720
966
  );
721
967
  }
722
- if (componentData.name === "Button") {
723
- console.log(chalk3.gray("\n<Button>Click me</Button>"));
724
- console.log(chalk3.gray('<Button variant="outline">Outline</Button>'));
725
- } else if (componentData.name === "Input") {
726
- console.log(chalk3.gray('\n<Input placeholder="Enter text..." />'));
727
- } else if (componentData.name === "Hero Minimal") {
728
- console.log(chalk3.gray("\n<HeroMinimal />"));
968
+ if (componentData.id === "button") {
969
+ console.log(chalk4.gray("\n<Button>Click me</Button>"));
970
+ console.log(chalk4.gray('<Button variant="outline">Outline</Button>'));
971
+ } else if (componentData.id === "input") {
972
+ console.log(chalk4.gray('\n<Input placeholder="Enter text..." />'));
973
+ } else if (componentData.id.includes("hero")) {
974
+ console.log(chalk4.gray(`
975
+ <${componentName} />`));
976
+ } else if (componentData.id === "card") {
977
+ console.log(chalk4.gray("\n<Card>"));
978
+ console.log(chalk4.gray(" <CardHeader>"));
979
+ console.log(chalk4.gray(" <CardTitle>Title</CardTitle>"));
980
+ console.log(
981
+ chalk4.gray(" <CardDescription>Description</CardDescription>")
982
+ );
983
+ console.log(chalk4.gray(" </CardHeader>"));
984
+ console.log(chalk4.gray(" <CardContent>Content</CardContent>"));
985
+ console.log(chalk4.gray("</Card>"));
729
986
  }
730
987
  }
731
988
 
732
989
  // src/commands/update.ts
733
990
  import { Command as Command4 } from "commander";
734
- import chalk4 from "chalk";
991
+ import chalk5 from "chalk";
735
992
  function updateCommand() {
736
993
  return new Command4("update").description("Update an existing component or block").argument("<id>", "Component or block ID").action(async (id) => {
737
- console.log(chalk4.blue(`\u{1F504} Updating ${id}...`));
738
- console.log(chalk4.green(`\u2705 ${id} updated successfully!`));
994
+ console.log(chalk5.blue(`\u{1F504} Updating ${id}...`));
995
+ console.log(chalk5.green(`\u2705 ${id} updated successfully!`));
739
996
  });
740
997
  }
741
998
 
742
999
  // src/commands/doctor.ts
743
1000
  import { Command as Command5 } from "commander";
744
- import chalk5 from "chalk";
1001
+ import chalk6 from "chalk";
745
1002
  function doctorCommand() {
746
1003
  return new Command5("doctor").description("Check project health and configuration").action(async () => {
747
- console.log(chalk5.blue("\u{1F50D} Checking project health..."));
748
- console.log(chalk5.green("\u2705 All checks passed!"));
1004
+ console.log(chalk6.blue("\u{1F50D} Checking project health..."));
1005
+ console.log(chalk6.green("\u2705 All checks passed!"));
749
1006
  });
750
1007
  }
751
1008
 
752
1009
  // src/index.ts
1010
+ var __filename = fileURLToPath(import.meta.url);
1011
+ var __dirname = dirname(__filename);
1012
+ var packageJson = JSON.parse(
1013
+ readFileSync(join(__dirname, "..", "package.json"), "utf-8")
1014
+ );
753
1015
  var program = new Command6();
754
- program.name("foundrykit").description("FoundryKit CLI - Component library management tool").version("0.1.0");
1016
+ program.name("foundrykit").description("FoundryKit CLI - Component library management tool").version(packageJson.version);
755
1017
  program.addCommand(initCommand());
756
1018
  program.addCommand(listCommand());
757
1019
  program.addCommand(addCommand());