@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/cli.js ADDED
@@ -0,0 +1,1023 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import { Command as Command6 } from "commander";
5
+ import { readFileSync } from "fs";
6
+ import { fileURLToPath } from "url";
7
+ import { dirname, join } from "path";
8
+
9
+ // src/commands/init.ts
10
+ import { Command } from "commander";
11
+ import chalk from "chalk";
12
+ import fs from "fs-extra";
13
+ import path from "path";
14
+ import { execSync } from "child_process";
15
+ import inquirer from "inquirer";
16
+ function initCommand() {
17
+ return new Command("init").description("Initialize FoundryKit in your Next.js project").option("-f, --force", "overwrite existing files").option("--skip-install", "skip installing dependencies").action(async (options) => {
18
+ try {
19
+ console.log(chalk.blue("\u{1F680} Initializing FoundryKit..."));
20
+ await validateNextJsProject();
21
+ if (!options.force && await isFoundryKitInitialized()) {
22
+ const { shouldContinue } = await inquirer.prompt([
23
+ {
24
+ type: "confirm",
25
+ name: "shouldContinue",
26
+ message: "FoundryKit is already initialized. Continue anyway?",
27
+ default: false
28
+ }
29
+ ]);
30
+ if (!shouldContinue) {
31
+ console.log(chalk.yellow("\u274C Initialization cancelled."));
32
+ return;
33
+ }
34
+ }
35
+ if (!options.skipInstall) {
36
+ await installDependencies();
37
+ }
38
+ await setupTailwindV4();
39
+ await createDirectories();
40
+ await createExampleFiles();
41
+ await updatePackageScripts();
42
+ console.log(chalk.green("\n\u2705 FoundryKit initialized successfully!"));
43
+ console.log(chalk.cyan("\n\u{1F4E6} Next steps:"));
44
+ console.log(
45
+ chalk.gray(
46
+ " 1. Add a component: npx @foundrykit/cli add hero-minimal"
47
+ )
48
+ );
49
+ console.log(
50
+ chalk.gray(" 2. List available components: npx @foundrykit/cli list")
51
+ );
52
+ console.log(
53
+ chalk.gray(" 3. Check out the docs: https://foundrykit.dev")
54
+ );
55
+ } catch (error) {
56
+ console.error(chalk.red("\u274C Failed to initialize FoundryKit:"));
57
+ console.error(
58
+ chalk.red(error instanceof Error ? error.message : String(error))
59
+ );
60
+ process.exit(1);
61
+ }
62
+ });
63
+ }
64
+ async function validateNextJsProject() {
65
+ const packageJsonPath = path.join(process.cwd(), "package.json");
66
+ if (!fs.existsSync(packageJsonPath)) {
67
+ throw new Error(
68
+ "No package.json found. Please run this command in a Next.js project root."
69
+ );
70
+ }
71
+ const packageJson2 = await fs.readJson(packageJsonPath);
72
+ const dependencies = {
73
+ ...packageJson2.dependencies,
74
+ ...packageJson2.devDependencies
75
+ };
76
+ if (!dependencies.next) {
77
+ throw new Error(
78
+ "Next.js not detected. This command should be run in a Next.js project."
79
+ );
80
+ }
81
+ console.log(chalk.green("\u2705 Next.js project detected"));
82
+ }
83
+ async function isFoundryKitInitialized() {
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
+ );
94
+ }
95
+ return false;
96
+ }
97
+ async function installDependencies() {
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
+ }
107
+ const dependencies = [
108
+ "@foundrykit/primitives",
109
+ "@foundrykit/components",
110
+ "@foundrykit/blocks",
111
+ "@foundrykit/hooks",
112
+ "@foundrykit/animation",
113
+ "@foundrykit/tailwind"
114
+ ];
115
+ try {
116
+ const packageManager = detectPackageManager();
117
+ console.log(chalk.gray(`Using ${packageManager}...`));
118
+ const installCmd = packageManager === "npm" ? `npm install ${dependencies.join(" ")}` : packageManager === "yarn" ? `yarn add ${dependencies.join(" ")}` : `pnpm add ${dependencies.join(" ")}`;
119
+ execSync(installCmd, { stdio: "inherit" });
120
+ console.log(chalk.green("\u2705 Dependencies installed"));
121
+ } catch (error) {
122
+ throw new Error(
123
+ "Failed to install dependencies. Please install them manually."
124
+ );
125
+ }
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
+ }
157
+ function detectPackageManager() {
158
+ if (fs.existsSync("pnpm-lock.yaml")) return "pnpm";
159
+ if (fs.existsSync("yarn.lock")) return "yarn";
160
+ return "npm";
161
+ }
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";
211
+
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";
269
+
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"));
389
+ }
390
+ async function createDirectories() {
391
+ console.log(chalk.blue("\u{1F4C1} Creating component directories..."));
392
+ const dirs = ["components/ui", "components/blocks", "lib", "hooks"];
393
+ for (const dir of dirs) {
394
+ await fs.ensureDir(path.join(process.cwd(), dir));
395
+ }
396
+ console.log(chalk.green("\u2705 Directories created"));
397
+ }
398
+ async function createExampleFiles() {
399
+ console.log(chalk.blue("\u{1F4DD} Creating example files..."));
400
+ const utilsPath = path.join(process.cwd(), "lib/utils.ts");
401
+ const utilsContent = `import { type ClassValue, clsx } from 'clsx';
402
+ import { twMerge } from 'tailwind-merge';
403
+
404
+ export function cn(...inputs: ClassValue[]) {
405
+ return twMerge(clsx(inputs));
406
+ }
407
+ `;
408
+ if (!fs.existsSync(utilsPath)) {
409
+ await fs.writeFile(utilsPath, utilsContent);
410
+ console.log(chalk.gray("Created lib/utils.ts"));
411
+ }
412
+ const providersPath = path.join(process.cwd(), "components/providers.tsx");
413
+ const providersContent = `'use client';
414
+
415
+ import { ThemeProvider } from 'next-themes';
416
+
417
+ export function Providers({ children }: { children: React.ReactNode }) {
418
+ return (
419
+ <ThemeProvider attribute="class" defaultTheme="system" enableSystem>
420
+ {children}
421
+ </ThemeProvider>
422
+ );
423
+ }
424
+ `;
425
+ if (!fs.existsSync(providersPath)) {
426
+ await fs.writeFile(providersPath, providersContent);
427
+ console.log(chalk.gray("Created components/providers.tsx"));
428
+ }
429
+ console.log(chalk.green("\u2705 Example files created"));
430
+ }
431
+ async function updatePackageScripts() {
432
+ console.log(chalk.blue("\u{1F4CB} Updating package.json scripts..."));
433
+ const packageJsonPath = path.join(process.cwd(), "package.json");
434
+ const packageJson2 = await fs.readJson(packageJsonPath);
435
+ if (!packageJson2.scripts) {
436
+ packageJson2.scripts = {};
437
+ }
438
+ if (!packageJson2.scripts["foundrykit"]) {
439
+ packageJson2.scripts["foundrykit"] = "foundrykit";
440
+ }
441
+ if (!packageJson2.scripts["fk"]) {
442
+ packageJson2.scripts["fk"] = "foundrykit";
443
+ }
444
+ await fs.writeJson(packageJsonPath, packageJson2, { spaces: 2 });
445
+ console.log(chalk.green("\u2705 Package scripts updated"));
446
+ }
447
+
448
+ // src/commands/list.ts
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";
456
+ import chalk2 from "chalk";
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
652
+ function listCommand() {
653
+ return new Command2("list").description("List all available FoundryKit components and blocks").option(
654
+ "-c, --category <category>",
655
+ "filter by category (primitives, components, blocks, animations)"
656
+ ).option("-s, --search <term>", "search components by name or description").action(async (options) => {
657
+ try {
658
+ console.log(chalk3.blue("\u{1F4E6} Available FoundryKit components:"));
659
+ const registry = getRegistry();
660
+ if (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}`));
669
+ console.log(
670
+ chalk3.gray(`Valid categories: ${validCategories.join(", ")}`)
671
+ );
672
+ process.exit(1);
673
+ }
674
+ }
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}`));
689
+ }
690
+ return;
691
+ }
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"));
701
+ } catch (error) {
702
+ console.error(chalk3.red("\u274C Failed to fetch component registry:"));
703
+ console.error(
704
+ chalk3.red(error instanceof Error ? error.message : String(error))
705
+ );
706
+ process.exit(1);
707
+ }
708
+ });
709
+ }
710
+ function displayComponents(components) {
711
+ const grouped = components.reduce(
712
+ (acc, component) => {
713
+ if (!acc[component.category]) {
714
+ acc[component.category] = [];
715
+ }
716
+ acc[component.category].push(component);
717
+ return acc;
718
+ },
719
+ {}
720
+ );
721
+ const categoryOrder = [
722
+ "primitives",
723
+ "components",
724
+ "blocks",
725
+ "animations"
726
+ ];
727
+ for (const category of categoryOrder) {
728
+ const items = grouped[category];
729
+ if (!items || items.length === 0) continue;
730
+ console.log(`
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)}`);
740
+ if (item.tags && item.tags.length > 0) {
741
+ console.log(
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
+ )}`
757
+ );
758
+ }
759
+ console.log();
760
+ }
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})`));
766
+ }
767
+
768
+ // src/commands/add.ts
769
+ import { Command as Command3 } from "commander";
770
+ import chalk4 from "chalk";
771
+ import fs3 from "fs-extra";
772
+ import path3 from "path";
773
+ import inquirer2 from "inquirer";
774
+ function addCommand() {
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) => {
776
+ try {
777
+ if (!id) {
778
+ const selectedIds = await selectComponentsInteractively();
779
+ if (selectedIds.length === 0) {
780
+ console.log(chalk4.yellow("No components selected."));
781
+ return;
782
+ }
783
+ for (const componentId of selectedIds) {
784
+ await addSingleComponent(componentId, options);
785
+ }
786
+ } else {
787
+ await addSingleComponent(id, options);
788
+ }
789
+ } catch (error) {
790
+ console.error(chalk4.red("\u274C Failed to add component:"));
791
+ console.error(
792
+ chalk4.red(error instanceof Error ? error.message : String(error))
793
+ );
794
+ process.exit(1);
795
+ }
796
+ });
797
+ }
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();
805
+ try {
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 [];
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;
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;
830
+ }
831
+ }
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
+ }
855
+ }
856
+ return choices;
857
+ }
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([
867
+ {
868
+ type: "confirm",
869
+ name: "shouldContinue",
870
+ message: `Some files for ${componentData.name} already exist. Overwrite?`,
871
+ default: false
872
+ }
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}`));
886
+ }
887
+ }
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
918
+ };
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
+ }
925
+ }
926
+ async function hasConflictingFiles(componentData, options) {
927
+ const basePath = options.path || process.cwd();
928
+ for (const file of componentData.files) {
929
+ const filePath = path3.join(basePath, file.path);
930
+ if (fs3.existsSync(filePath)) {
931
+ return true;
932
+ }
933
+ }
934
+ return false;
935
+ }
936
+ async function installComponentFiles(componentData, options) {
937
+ const basePath = options.path || process.cwd();
938
+ console.log(chalk4.blue("\u{1F4DD} Installing component files..."));
939
+ for (const file of componentData.files) {
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}`));
944
+ }
945
+ }
946
+ function showUsageExample(componentData) {
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") {
950
+ console.log(
951
+ chalk4.gray(
952
+ `import { ${componentName} } from "@/components/ui/${componentData.id}"`
953
+ )
954
+ );
955
+ } else if (componentData.category === "blocks") {
956
+ console.log(
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}"`
965
+ )
966
+ );
967
+ }
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>"));
986
+ }
987
+ }
988
+
989
+ // src/commands/update.ts
990
+ import { Command as Command4 } from "commander";
991
+ import chalk5 from "chalk";
992
+ function updateCommand() {
993
+ return new Command4("update").description("Update an existing component or block").argument("<id>", "Component or block ID").action(async (id) => {
994
+ console.log(chalk5.blue(`\u{1F504} Updating ${id}...`));
995
+ console.log(chalk5.green(`\u2705 ${id} updated successfully!`));
996
+ });
997
+ }
998
+
999
+ // src/commands/doctor.ts
1000
+ import { Command as Command5 } from "commander";
1001
+ import chalk6 from "chalk";
1002
+ function doctorCommand() {
1003
+ return new Command5("doctor").description("Check project health and configuration").action(async () => {
1004
+ console.log(chalk6.blue("\u{1F50D} Checking project health..."));
1005
+ console.log(chalk6.green("\u2705 All checks passed!"));
1006
+ });
1007
+ }
1008
+
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
+ );
1015
+ var program = new Command6();
1016
+ program.name("foundrykit").description("FoundryKit CLI - Component library management tool").version(packageJson.version);
1017
+ program.addCommand(initCommand());
1018
+ program.addCommand(listCommand());
1019
+ program.addCommand(addCommand());
1020
+ program.addCommand(updateCommand());
1021
+ program.addCommand(doctorCommand());
1022
+ program.parse();
1023
+ //# sourceMappingURL=cli.js.map