@foundrykit/cli 2.0.12 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,627 +0,0 @@
1
- /**
2
- * Registry service for fetching and caching component data
3
- * Handles communication with the FoundryKit registry
4
- */
5
-
6
- import os from 'node:os';
7
- import path from 'node:path';
8
- import type {
9
- CLIConfig,
10
- ComponentData,
11
- ComponentMeta,
12
- LocalCache,
13
- RegistryComponent,
14
- RegistryIndex,
15
- } from '@foundrykit/types';
16
- import chalk from 'chalk';
17
- import fs from 'fs-extra';
18
- import {
19
- CACHE_DIR,
20
- CACHE_TTL,
21
- DEFAULT_REGISTRY_URL,
22
- FOUNDRYKIT_PACKAGE_ALIASES,
23
- NPM_REGISTRY_URL,
24
- } from './constants.js';
25
-
26
- /**
27
- * Default configuration
28
- */
29
- const DEFAULT_CONFIG: CLIConfig = {
30
- registryUrl: process.env.FOUNDRYKIT_REGISTRY_URL || DEFAULT_REGISTRY_URL,
31
- cacheDir: path.join(os.homedir(), CACHE_DIR, 'cache'),
32
- cacheMaxAge: CACHE_TTL,
33
- };
34
-
35
- /**
36
- * Registry service class
37
- */
38
- export class RegistryService {
39
- private config: CLIConfig;
40
- private cacheFile: string;
41
- private foundryKitPackagesPromise: Promise<ComponentMeta[]> | null = null;
42
-
43
- constructor(config?: Partial<CLIConfig>) {
44
- this.config = { ...DEFAULT_CONFIG, ...config };
45
- this.cacheFile = path.join(this.config.cacheDir, 'registry.json');
46
- }
47
-
48
- /**
49
- * Fetch all components from the registry
50
- */
51
- async getComponents(
52
- category?: string,
53
- search?: string
54
- ): Promise<RegistryIndex> {
55
- try {
56
- // Build query params
57
- const params = new URLSearchParams();
58
- if (category) params.append('category', category);
59
- if (search) params.append('search', search);
60
-
61
- const url = `${this.config.registryUrl}/registry${
62
- params.toString() ? `?${params.toString()}` : ''
63
- }`;
64
-
65
- console.log(chalk.gray(`Fetching from: ${url}`));
66
- const response = await fetch(url);
67
-
68
- if (!response.ok) {
69
- throw new Error(
70
- `Registry returned ${response.status}: ${response.statusText}`
71
- );
72
- }
73
-
74
- const components = (await response.json()) as RegistryIndex;
75
-
76
- // Update cache
77
- await this.updateCache(components);
78
-
79
- return this.filterComponents(
80
- await this.withFoundryKitPackages(components),
81
- category,
82
- search
83
- );
84
- } catch (error) {
85
- // Try to load from cache
86
- const cache = await this.loadCache();
87
- if (cache && this.isCacheValid(cache)) {
88
- console.log(chalk.yellow('Using cached registry data'));
89
- return this.filterComponents(
90
- await this.withFoundryKitPackages(cache.components),
91
- category,
92
- search
93
- );
94
- }
95
-
96
- const npmPackages = await this.fetchFoundryKitPackages();
97
- if (npmPackages.length > 0) {
98
- console.log(chalk.yellow('Using npm package data'));
99
- return this.filterComponents(npmPackages, category, search);
100
- }
101
-
102
- // No valid cache, throw error
103
- throw new Error(
104
- `Failed to connect to registry: ${error instanceof Error ? error.message : 'Unknown error'}\n` +
105
- `Registry URL: ${this.config.registryUrl}\n` +
106
- `Try again later or check your internet connection.`
107
- );
108
- }
109
- }
110
-
111
- /**
112
- * Fetch a specific component by ID
113
- */
114
- async getComponent(id: string, force = false): Promise<ComponentData> {
115
- // Check if it's a special dependency first
116
- if (this.isSpecialDependency(id)) {
117
- return this.createSpecialDependency(id);
118
- }
119
-
120
- const foundryKitPackage = this.resolveFoundryKitPackageName(id);
121
- const isKnownFoundryKitPackage =
122
- id.startsWith('@foundrykit/') ||
123
- id.endsWith('-plugin') ||
124
- FOUNDRYKIT_PACKAGE_ALIASES.includes(
125
- id as (typeof FOUNDRYKIT_PACKAGE_ALIASES)[number]
126
- );
127
-
128
- const cache = await this.loadCache();
129
- const cachedComponent = cache?.componentData?.[id];
130
- const hasValidCache = cache ? this.isCacheValid(cache) : false;
131
-
132
- if (!force && cachedComponent && hasValidCache) {
133
- console.log(chalk.gray(`Using cached data for component: ${id}`));
134
- return cachedComponent;
135
- }
136
-
137
- try {
138
- const url = `${this.config.registryUrl}/registry/${id}`;
139
- console.log(chalk.gray(`Fetching component: ${url}`));
140
-
141
- const response = await fetch(url);
142
-
143
- if (!response.ok) {
144
- if (response.status === 404) {
145
- if (foundryKitPackage) {
146
- const npmPackage = await this.createFoundryKitPackageDependency(
147
- foundryKitPackage,
148
- !isKnownFoundryKitPackage
149
- );
150
- if (npmPackage) return npmPackage;
151
- }
152
- throw new Error(`Component "${id}" not found in registry`);
153
- }
154
- throw new Error(
155
- `Registry returned ${response.status}: ${response.statusText}`
156
- );
157
- }
158
-
159
- const component = (await response.json()) as RegistryComponent;
160
-
161
- // Cache the component data
162
- await this.cacheComponent(component);
163
-
164
- return component;
165
- } catch (error) {
166
- if (foundryKitPackage) {
167
- const npmPackage = await this.createFoundryKitPackageDependency(
168
- foundryKitPackage,
169
- !isKnownFoundryKitPackage
170
- );
171
- if (npmPackage) return npmPackage;
172
- }
173
-
174
- // Fall back to any cached component data, even if stale
175
- if (cachedComponent) {
176
- console.log(chalk.yellow(`Using cached data for component: ${id}`));
177
- return cachedComponent;
178
- }
179
-
180
- // No cached data, throw error
181
- throw new Error(
182
- `Failed to fetch component "${id}": ${error instanceof Error ? error.message : 'Unknown error'}\n` +
183
- `Registry URL: ${this.config.registryUrl}\n` +
184
- `Try again later or check your internet connection.`
185
- );
186
- }
187
- }
188
-
189
- /**
190
- * Check if a dependency ID is a special dependency that should be handled locally
191
- */
192
- private isSpecialDependency(id: string): boolean {
193
- const specialDependencies = [
194
- 'utils',
195
- 'lib',
196
- 'helpers',
197
- 'cn', // Utils aliases
198
- 'hooks',
199
- 'types', // Package dependencies
200
- 'maps',
201
- ];
202
- return specialDependencies.includes(id);
203
- }
204
-
205
- /**
206
- * Create a special dependency component data
207
- */
208
- private async createSpecialDependency(id: string): Promise<ComponentData> {
209
- // Handle utils and its aliases
210
- if (['utils', 'lib', 'helpers', 'cn'].includes(id)) {
211
- return {
212
- id: 'utils',
213
- name: 'Utils',
214
- description: 'Utility functions for className merging',
215
- category: 'primitives',
216
- files: [
217
- {
218
- path: 'lib/utils.ts',
219
- content: `import { type ClassValue, clsx } from 'clsx';
220
- import { twMerge } from 'tailwind-merge';
221
-
222
- export function cn(...inputs: ClassValue[]) {
223
- return twMerge(clsx(inputs));
224
- }`,
225
- type: 'util',
226
- },
227
- ],
228
- registryDependencies: [],
229
- packageDependencies: ['clsx', 'tailwind-merge'],
230
- };
231
- }
232
-
233
- if (id === 'hooks') {
234
- const component =
235
- await this.createFoundryKitPackageDependency('@foundrykit/hooks');
236
- if (component) return component;
237
- }
238
-
239
- if (id === 'types') {
240
- const component =
241
- await this.createFoundryKitPackageDependency('@foundrykit/types');
242
- if (component) return component;
243
- }
244
-
245
- if (id === 'maps') {
246
- const component =
247
- await this.createFoundryKitPackageDependency('@foundrykit/maps');
248
- if (component) return component;
249
- }
250
-
251
- throw new Error(`Unknown special dependency: ${id}`);
252
- }
253
-
254
- /**
255
- * Check if a package is installed in the current project
256
- */
257
- private async isPackageInstalled(packageName: string): Promise<boolean> {
258
- try {
259
- const packageJsonPath = path.join(process.cwd(), 'package.json');
260
- if (!(await fs.pathExists(packageJsonPath))) {
261
- return false;
262
- }
263
-
264
- const packageJson = await fs.readJson(packageJsonPath);
265
- const allDeps = {
266
- ...packageJson.dependencies,
267
- ...packageJson.devDependencies,
268
- ...packageJson.peerDependencies,
269
- };
270
-
271
- return packageName in allDeps;
272
- } catch {
273
- return false;
274
- }
275
- }
276
-
277
- private resolveFoundryKitPackageName(id: string): string | null {
278
- if (/^@foundrykit\/[a-z0-9][a-z0-9-]*$/i.test(id)) {
279
- return id;
280
- }
281
-
282
- if (/^[a-z0-9][a-z0-9-]*$/i.test(id)) {
283
- return `@foundrykit/${id}`;
284
- }
285
-
286
- return null;
287
- }
288
-
289
- private async createFoundryKitPackageDependency(
290
- packageName: string,
291
- requirePublishedPackage = false
292
- ): Promise<ComponentData | null> {
293
- const id = packageName.replace('@foundrykit/', '');
294
- const category =
295
- id === 'maps' ? 'maps' : id === 'hooks' ? 'hooks' : 'packages';
296
- const metadata = await this.fetchPackageMetadata(packageName);
297
- if (requirePublishedPackage && !metadata) {
298
- return null;
299
- }
300
-
301
- return {
302
- id,
303
- name: this.toDisplayName(id),
304
- version: metadata?.version,
305
- description: metadata?.description ?? `${packageName} npm package`,
306
- category,
307
- files: [],
308
- registryDependencies: [],
309
- packageDependencies: [packageName],
310
- };
311
- }
312
-
313
- private async withFoundryKitPackages(
314
- components: ComponentMeta[]
315
- ): Promise<ComponentMeta[]> {
316
- const packageEntries = await this.fetchFoundryKitPackages();
317
- const seenIds = new Set(components.map(component => component.id));
318
- return [
319
- ...components,
320
- ...packageEntries.filter(component => !seenIds.has(component.id)),
321
- ];
322
- }
323
-
324
- private toDisplayName(id: string): string {
325
- return id
326
- .split('-')
327
- .map(part => part.charAt(0).toUpperCase() + part.slice(1))
328
- .join(' ');
329
- }
330
-
331
- private async fetchFoundryKitPackages(): Promise<ComponentMeta[]> {
332
- if (!this.foundryKitPackagesPromise) {
333
- this.foundryKitPackagesPromise = this.fetchFoundryKitPackagesFromNpm();
334
- }
335
-
336
- try {
337
- return await this.foundryKitPackagesPromise;
338
- } catch {
339
- return this.getFallbackFoundryKitPackages();
340
- }
341
- }
342
-
343
- private async fetchFoundryKitPackagesFromNpm(): Promise<ComponentMeta[]> {
344
- const url = `${NPM_REGISTRY_URL}/-/v1/search?text=scope:foundrykit&size=250`;
345
- console.log(chalk.gray(`Fetching FoundryKit packages from npm: ${url}`));
346
-
347
- const response = await fetch(url);
348
- if (!response.ok) {
349
- throw new Error(
350
- `npm returned ${response.status}: ${response.statusText}`
351
- );
352
- }
353
-
354
- const data = (await response.json()) as {
355
- objects?: Array<{
356
- package?: {
357
- name?: string;
358
- version?: string;
359
- description?: string;
360
- keywords?: string[];
361
- };
362
- }>;
363
- };
364
-
365
- return (data.objects ?? [])
366
- .map(item => item.package)
367
- .filter((pkg): pkg is NonNullable<typeof pkg> => {
368
- return Boolean(pkg?.name?.startsWith('@foundrykit/'));
369
- })
370
- .map(pkg =>
371
- this.toPackageComponentMeta(pkg.name!, {
372
- version: pkg.version,
373
- description: pkg.description,
374
- keywords: pkg.keywords,
375
- })
376
- )
377
- .sort((a, b) => a.id.localeCompare(b.id));
378
- }
379
-
380
- private async fetchPackageMetadata(packageName: string): Promise<{
381
- version?: string;
382
- description?: string;
383
- keywords?: string[];
384
- } | null> {
385
- try {
386
- const encodedName = packageName.replace('/', '%2F');
387
- const response = await fetch(`${NPM_REGISTRY_URL}/${encodedName}`);
388
- if (!response.ok) return null;
389
-
390
- const data = (await response.json()) as {
391
- name?: string;
392
- description?: string;
393
- keywords?: string[];
394
- 'dist-tags'?: {
395
- latest?: string;
396
- };
397
- versions?: Record<string, unknown>;
398
- };
399
-
400
- return {
401
- version:
402
- data['dist-tags']?.latest ??
403
- Object.keys(data.versions ?? {})
404
- .sort(compareVersions)
405
- .at(-1),
406
- description: data.description,
407
- keywords: data.keywords,
408
- };
409
- } catch {
410
- return null;
411
- }
412
- }
413
-
414
- private getFallbackFoundryKitPackages(): ComponentMeta[] {
415
- return FOUNDRYKIT_PACKAGE_ALIASES.map(packageId =>
416
- this.toPackageComponentMeta(`@foundrykit/${packageId}`)
417
- );
418
- }
419
-
420
- private toPackageComponentMeta(
421
- packageName: string,
422
- metadata: {
423
- version?: string;
424
- description?: string;
425
- keywords?: string[];
426
- } = {}
427
- ): ComponentMeta {
428
- const id = packageName.replace('@foundrykit/', '');
429
- return {
430
- id,
431
- name: this.toDisplayName(id),
432
- version: metadata.version,
433
- category: id === 'maps' ? 'maps' : id === 'hooks' ? 'hooks' : 'packages',
434
- description: metadata.description ?? `${packageName} npm package`,
435
- tags: metadata.keywords,
436
- packageDependencies: [packageName],
437
- };
438
- }
439
-
440
- /**
441
- * Update the local cache with new component list
442
- */
443
- private async updateCache(components: RegistryIndex): Promise<void> {
444
- try {
445
- const cache = await this.loadCache();
446
- const newCache: LocalCache = {
447
- version: '1.0.0',
448
- lastUpdated: new Date().toISOString(),
449
- components,
450
- componentData: cache?.componentData || {},
451
- };
452
-
453
- await fs.ensureDir(this.config.cacheDir);
454
- await fs.writeJson(this.cacheFile, newCache, { spaces: 2 });
455
- } catch {
456
- // Cache update failed, but don't throw - this is not critical
457
- console.log(chalk.gray('Failed to update cache'));
458
- }
459
- }
460
-
461
- /**
462
- * Cache a specific component
463
- */
464
- private async cacheComponent(component: ComponentData): Promise<void> {
465
- try {
466
- const cache = (await this.loadCache()) ?? {
467
- version: '1.0.0',
468
- lastUpdated: new Date().toISOString(),
469
- components: [],
470
- componentData: {},
471
- };
472
-
473
- cache.componentData[component.id] = component;
474
- cache.lastUpdated = new Date().toISOString();
475
-
476
- await fs.ensureDir(this.config.cacheDir);
477
- await fs.writeJson(this.cacheFile, cache, { spaces: 2 });
478
- } catch {
479
- // Cache update failed, but don't throw
480
- console.log(chalk.gray('Failed to cache component'));
481
- }
482
- }
483
-
484
- /**
485
- * Load the local cache
486
- */
487
- private async loadCache(): Promise<LocalCache | null> {
488
- try {
489
- if (await fs.pathExists(this.cacheFile)) {
490
- return await fs.readJson(this.cacheFile);
491
- }
492
- } catch {
493
- console.log(chalk.gray('Failed to load cache'));
494
- }
495
- return null;
496
- }
497
-
498
- /**
499
- * Check if cache is still valid
500
- */
501
- private isCacheValid(cache: LocalCache): boolean {
502
- const lastUpdated = new Date(cache.lastUpdated).getTime();
503
- const now = Date.now();
504
- return now - lastUpdated < this.config.cacheMaxAge;
505
- }
506
-
507
- /**
508
- * Filter components by category and search
509
- */
510
- private filterComponents(
511
- components: ComponentMeta[],
512
- category?: string,
513
- search?: string
514
- ): ComponentMeta[] {
515
- let filtered = components;
516
-
517
- if (category) {
518
- filtered = filtered.filter(c => c.category === category);
519
- }
520
-
521
- if (search) {
522
- const searchLower = search.toLowerCase();
523
- filtered = filtered.filter(
524
- c =>
525
- c.name.toLowerCase().includes(searchLower) ||
526
- c.description.toLowerCase().includes(searchLower) ||
527
- c.id.toLowerCase().includes(searchLower) ||
528
- c.tags?.some(tag => tag.toLowerCase().includes(searchLower))
529
- );
530
- }
531
-
532
- return filtered;
533
- }
534
-
535
- /**
536
- * Clear the local cache
537
- */
538
- async clearCache(): Promise<void> {
539
- try {
540
- if (await fs.pathExists(this.cacheFile)) {
541
- await fs.remove(this.cacheFile);
542
- console.log(chalk.green('Cache cleared successfully'));
543
- }
544
- } catch (error) {
545
- throw new Error(
546
- `Failed to clear cache: ${error instanceof Error ? error.message : 'Unknown error'}`
547
- );
548
- }
549
- }
550
-
551
- /**
552
- * Get cache statistics
553
- */
554
- async getCacheStats(): Promise<{
555
- exists: boolean;
556
- size: number;
557
- lastUpdated: string | null;
558
- componentCount: number;
559
- }> {
560
- try {
561
- if (await fs.pathExists(this.cacheFile)) {
562
- const cache = await this.loadCache();
563
- const stats = await fs.stat(this.cacheFile);
564
-
565
- return {
566
- exists: true,
567
- size: stats.size,
568
- lastUpdated: cache?.lastUpdated || null,
569
- componentCount: cache?.components.length || 0,
570
- };
571
- }
572
- } catch {
573
- // Ignore errors
574
- }
575
-
576
- return {
577
- exists: false,
578
- size: 0,
579
- lastUpdated: null,
580
- componentCount: 0,
581
- };
582
- }
583
- }
584
-
585
- /**
586
- * Singleton instance
587
- */
588
- let registryInstance: RegistryService | null = null;
589
-
590
- /**
591
- * Get the registry service instance
592
- */
593
- export function getRegistry(config?: Partial<CLIConfig>): RegistryService {
594
- if (!registryInstance) {
595
- registryInstance = new RegistryService(config);
596
- }
597
- return registryInstance;
598
- }
599
-
600
- /**
601
- * Reset the registry instance (mainly for testing)
602
- */
603
- export function resetRegistry(): void {
604
- registryInstance = null;
605
- }
606
-
607
- function compareVersions(a: string, b: string): number {
608
- const aParts = normalizeVersion(a).split('.').map(Number);
609
- const bParts = normalizeVersion(b).split('.').map(Number);
610
- const length = Math.max(aParts.length, bParts.length);
611
-
612
- for (let index = 0; index < length; index++) {
613
- const diff = (aParts[index] ?? 0) - (bParts[index] ?? 0);
614
- if (diff !== 0) return diff;
615
- }
616
-
617
- return 0;
618
- }
619
-
620
- function normalizeVersion(version: string): string {
621
- return (
622
- version
623
- .replace(/^[^\d]*/, '')
624
- .split('-')[0]
625
- ?.replace(/[^\d.]/g, '') || '0'
626
- );
627
- }