@foundrykit/cli 2.0.9 → 2.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@foundrykit/cli",
3
- "version": "2.0.9",
3
+ "version": "2.0.10",
4
4
  "type": "module",
5
5
  "private": false,
6
6
  "main": "./dist/index.js",
@@ -25,7 +25,7 @@
25
25
  "glob": "^10.3.10",
26
26
  "inquirer": "^9.2.15",
27
27
  "node-fetch": "^3.3.0",
28
- "@foundrykit/types": "2.0.4"
28
+ "@foundrykit/types": "2.0.5"
29
29
  },
30
30
  "devDependencies": {
31
31
  "@types/node": "^20.19.9",
@@ -35,8 +35,8 @@
35
35
  "tsup": "^8.0.0",
36
36
  "typescript": "^5.9.2",
37
37
  "vitest": "^1.2.0",
38
- "@foundrykit/typescript-config": "1.0.5",
39
- "@foundrykit/eslint-config": "1.0.5"
38
+ "@foundrykit/eslint-config": "1.0.5",
39
+ "@foundrykit/typescript-config": "1.0.5"
40
40
  },
41
41
  "scripts": {
42
42
  "build": "tsup",
@@ -238,7 +238,7 @@ export async function addSingleComponent(
238
238
  showUsageExample(componentData);
239
239
 
240
240
  // Handle package dependencies
241
- await handlePackageDependencies(componentData);
241
+ await handlePackageDependencies(componentData, options);
242
242
  } catch (error) {
243
243
  console.error(chalk.red(`Failed to add ${id}:`));
244
244
  throw error;
@@ -389,7 +389,8 @@ export async function trackInstalledComponent(
389
389
  * Handle package dependencies - check and auto-install if needed
390
390
  */
391
391
  export async function handlePackageDependencies(
392
- componentData: ComponentData
392
+ componentData: ComponentData,
393
+ options: AddOptions = {}
393
394
  ): Promise<void> {
394
395
  // Only use the package dependencies specified by the component
395
396
  const allDependencies = new Set<string>();
@@ -402,22 +403,38 @@ export async function handlePackageDependencies(
402
403
  return;
403
404
  }
404
405
 
405
- // Check which packages are already installed
406
- const missingPackages = await getMissingPackages(Array.from(allDependencies));
406
+ const dependencies = Array.from(allDependencies);
407
+ const forcePackageUpdate =
408
+ componentData.files.length === 0 && (options.force || options.overwrite);
409
+ const missingPackages = forcePackageUpdate
410
+ ? dependencies
411
+ : await getMissingPackages(dependencies);
407
412
 
408
413
  if (missingPackages.length === 0) {
409
414
  console.log(chalk.green('āœ… All required packages are already installed'));
410
415
  return;
411
416
  }
412
417
 
413
- console.log(chalk.yellow('\nšŸ“¦ Installing required packages...'));
414
- console.log(chalk.gray(` ${missingPackages.join(', ')}`));
418
+ const packagesToInstall = missingPackages.map(pkg =>
419
+ forcePackageUpdate
420
+ ? getPackageInstallSpec(pkg, componentData.version)
421
+ : pkg
422
+ );
423
+
424
+ console.log(
425
+ chalk.yellow(
426
+ forcePackageUpdate
427
+ ? '\nšŸ“¦ Updating required packages...'
428
+ : '\nšŸ“¦ Installing required packages...'
429
+ )
430
+ );
431
+ console.log(chalk.gray(` ${packagesToInstall.join(', ')}`));
415
432
 
416
433
  // Try to detect package manager
417
434
  const packageManager = await detectPackageManager();
418
435
 
419
436
  try {
420
- const installCommand = `${packageManager} add ${missingPackages.join(' ')}`;
437
+ const installCommand = `${packageManager} add ${packagesToInstall.join(' ')}`;
421
438
  console.log(chalk.blue(` Running: ${installCommand}`));
422
439
 
423
440
  const { stdout, stderr } = await execAsync(installCommand);
@@ -431,11 +448,19 @@ export async function handlePackageDependencies(
431
448
  console.log(chalk.yellow('\nāš ļø Could not install packages automatically'));
432
449
  console.log(chalk.gray(' Please install them manually:'));
433
450
  console.log(
434
- chalk.cyan(` ${packageManager} add ${missingPackages.join(' ')}`)
451
+ chalk.cyan(` ${packageManager} add ${packagesToInstall.join(' ')}`)
435
452
  );
436
453
  }
437
454
  }
438
455
 
456
+ function getPackageInstallSpec(packageName: string, version?: string): string {
457
+ if (!packageName.startsWith('@foundrykit/')) {
458
+ return packageName;
459
+ }
460
+
461
+ return `${packageName}@${version ?? 'latest'}`;
462
+ }
463
+
439
464
  /**
440
465
  * Check which packages are missing from the project
441
466
  */
@@ -59,6 +59,20 @@ export function updateCommand() {
59
59
  const config = await fs.readJson(configPath);
60
60
  let installed: Record<string, InstalledComponent> =
61
61
  config.installedComponents ?? {};
62
+ const installedFoundryKitPackages =
63
+ await getInstalledFoundryKitPackageVersions();
64
+
65
+ for (const [pkgId, version] of Object.entries(
66
+ installedFoundryKitPackages
67
+ )) {
68
+ installed[pkgId] = {
69
+ id: pkgId,
70
+ version,
71
+ installedAt:
72
+ installed[pkgId]?.installedAt ?? new Date().toISOString(),
73
+ };
74
+ }
75
+
62
76
  let installedIds = Object.keys(installed);
63
77
 
64
78
  if (installedIds.length === 0) {
@@ -132,13 +146,16 @@ export function updateCommand() {
132
146
  for (const compId of installedIds) {
133
147
  try {
134
148
  const data = await registry.getComponent(compId, options.force);
135
- const installedVersion = installed[compId]?.version ?? null;
149
+ const installedVersion =
150
+ installedFoundryKitPackages[compId] ??
151
+ installed[compId]?.version ??
152
+ null;
136
153
  const latestVersion = data.version ?? null;
137
154
 
138
155
  const hasUpdate =
139
156
  latestVersion !== null &&
140
157
  installedVersion !== null &&
141
- latestVersion !== installedVersion;
158
+ compareVersions(latestVersion, installedVersion) > 0;
142
159
 
143
160
  const unknownVersion =
144
161
  installedVersion === null || latestVersion === null;
@@ -225,6 +242,57 @@ export function updateCommand() {
225
242
  });
226
243
  }
227
244
 
245
+ async function getInstalledFoundryKitPackageVersions(): Promise<
246
+ Record<string, string>
247
+ > {
248
+ const packageJsonPath = path.join(process.cwd(), 'package.json');
249
+ if (!fs.existsSync(packageJsonPath)) {
250
+ return {};
251
+ }
252
+
253
+ const packageJson = await fs.readJson(packageJsonPath);
254
+ const dependencies = {
255
+ ...packageJson.dependencies,
256
+ ...packageJson.devDependencies,
257
+ ...packageJson.optionalDependencies,
258
+ };
259
+
260
+ return Object.fromEntries(
261
+ Object.entries(dependencies)
262
+ .filter(([name]) => name.startsWith('@foundrykit/'))
263
+ .map(([name, version]) => [
264
+ name.replace('@foundrykit/', ''),
265
+ normalizeVersionSpec(String(version)),
266
+ ])
267
+ );
268
+ }
269
+
270
+ function compareVersions(latest: string, installed: string): number {
271
+ const latestParts = normalizeVersionSpec(latest).split('.').map(Number);
272
+ const installedParts = normalizeVersionSpec(installed).split('.').map(Number);
273
+ const length = Math.max(latestParts.length, installedParts.length);
274
+
275
+ for (let index = 0; index < length; index++) {
276
+ const diff = (latestParts[index] ?? 0) - (installedParts[index] ?? 0);
277
+ if (diff !== 0) return diff;
278
+ }
279
+
280
+ return 0;
281
+ }
282
+
283
+ function normalizeVersionSpec(version: string): string {
284
+ if (version === 'workspace:*' || version === '*' || version === 'latest') {
285
+ return '0';
286
+ }
287
+
288
+ return (
289
+ version
290
+ .replace(/^[^\d]*/, '')
291
+ .split('-')[0]
292
+ ?.replace(/[^\d.]/g, '') || '0'
293
+ );
294
+ }
295
+
228
296
  async function runUpdates(ids: string[], options: AddOptions): Promise<void> {
229
297
  let failed = 0;
230
298
  for (const compId of ids) {
@@ -8,6 +8,7 @@ export const CLI_VERSION = '1.0.16';
8
8
 
9
9
  // Default registry URL
10
10
  export const DEFAULT_REGISTRY_URL = 'https://foundry.umiflow.com';
11
+ export const NPM_REGISTRY_URL = 'https://registry.npmjs.org';
11
12
 
12
13
  // Cache settings
13
14
  export const CACHE_TTL = 24 * 60 * 60 * 1000; // 24 hours in milliseconds
@@ -12,6 +12,7 @@ import {
12
12
  CACHE_DIR,
13
13
  CACHE_TTL,
14
14
  FOUNDRYKIT_PACKAGE_ALIASES,
15
+ NPM_REGISTRY_URL,
15
16
  } from './constants.js';
16
17
  import type {
17
18
  ComponentMeta,
@@ -37,6 +38,7 @@ const DEFAULT_CONFIG: CLIConfig = {
37
38
  export class RegistryService {
38
39
  private config: CLIConfig;
39
40
  private cacheFile: string;
41
+ private foundryKitPackagesPromise: Promise<ComponentMeta[]> | null = null;
40
42
 
41
43
  constructor(config?: Partial<CLIConfig>) {
42
44
  this.config = { ...DEFAULT_CONFIG, ...config };
@@ -75,7 +77,7 @@ export class RegistryService {
75
77
  await this.updateCache(components);
76
78
 
77
79
  return this.filterComponents(
78
- this.withFoundryKitPackages(components),
80
+ await this.withFoundryKitPackages(components),
79
81
  category,
80
82
  search
81
83
  );
@@ -85,12 +87,18 @@ export class RegistryService {
85
87
  if (cache && this.isCacheValid(cache)) {
86
88
  console.log(chalk.yellow('Using cached registry data'));
87
89
  return this.filterComponents(
88
- this.withFoundryKitPackages(cache.components),
90
+ await this.withFoundryKitPackages(cache.components),
89
91
  category,
90
92
  search
91
93
  );
92
94
  }
93
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
+
94
102
  // No valid cache, throw error
95
103
  throw new Error(
96
104
  `Failed to connect to registry: ${error instanceof Error ? error.message : 'Unknown error'}\n` +
@@ -110,7 +118,7 @@ export class RegistryService {
110
118
  }
111
119
 
112
120
  const foundryKitPackage = this.resolveFoundryKitPackageName(id);
113
- const isExplicitFoundryKitPackage =
121
+ const isKnownFoundryKitPackage =
114
122
  id.startsWith('@foundrykit/') ||
115
123
  id.endsWith('-plugin') ||
116
124
  FOUNDRYKIT_PACKAGE_ALIASES.includes(
@@ -134,8 +142,12 @@ export class RegistryService {
134
142
 
135
143
  if (!response.ok) {
136
144
  if (response.status === 404) {
137
- if (foundryKitPackage && isExplicitFoundryKitPackage) {
138
- return this.createFoundryKitPackageDependency(foundryKitPackage);
145
+ if (foundryKitPackage) {
146
+ const npmPackage = await this.createFoundryKitPackageDependency(
147
+ foundryKitPackage,
148
+ !isKnownFoundryKitPackage
149
+ );
150
+ if (npmPackage) return npmPackage;
139
151
  }
140
152
  throw new Error(`Component "${id}" not found in registry`);
141
153
  }
@@ -151,8 +163,12 @@ export class RegistryService {
151
163
 
152
164
  return component;
153
165
  } catch (error) {
154
- if (foundryKitPackage && isExplicitFoundryKitPackage) {
155
- return this.createFoundryKitPackageDependency(foundryKitPackage);
166
+ if (foundryKitPackage) {
167
+ const npmPackage = await this.createFoundryKitPackageDependency(
168
+ foundryKitPackage,
169
+ !isKnownFoundryKitPackage
170
+ );
171
+ if (npmPackage) return npmPackage;
156
172
  }
157
173
 
158
174
  // Fall back to any cached component data, even if stale
@@ -215,15 +231,21 @@ export function cn(...inputs: ClassValue[]) {
215
231
  }
216
232
 
217
233
  if (id === 'hooks') {
218
- return this.createFoundryKitPackageDependency('@foundrykit/hooks');
234
+ const component =
235
+ await this.createFoundryKitPackageDependency('@foundrykit/hooks');
236
+ if (component) return component;
219
237
  }
220
238
 
221
239
  if (id === 'types') {
222
- return this.createFoundryKitPackageDependency('@foundrykit/types');
240
+ const component =
241
+ await this.createFoundryKitPackageDependency('@foundrykit/types');
242
+ if (component) return component;
223
243
  }
224
244
 
225
245
  if (id === 'maps') {
226
- return this.createFoundryKitPackageDependency('@foundrykit/maps');
246
+ const component =
247
+ await this.createFoundryKitPackageDependency('@foundrykit/maps');
248
+ if (component) return component;
227
249
  }
228
250
 
229
251
  throw new Error(`Unknown special dependency: ${id}`);
@@ -258,10 +280,7 @@ export function cn(...inputs: ClassValue[]) {
258
280
  }
259
281
 
260
282
  if (
261
- FOUNDRYKIT_PACKAGE_ALIASES.includes(
262
- id as (typeof FOUNDRYKIT_PACKAGE_ALIASES)[number]
263
- ) ||
264
- /^[a-z0-9][a-z0-9-]*-plugin$/i.test(id)
283
+ /^[a-z0-9][a-z0-9-]*$/i.test(id)
265
284
  ) {
266
285
  return `@foundrykit/${id}`;
267
286
  }
@@ -269,15 +288,23 @@ export function cn(...inputs: ClassValue[]) {
269
288
  return null;
270
289
  }
271
290
 
272
- private createFoundryKitPackageDependency(packageName: string): ComponentData {
291
+ private async createFoundryKitPackageDependency(
292
+ packageName: string,
293
+ requirePublishedPackage = false
294
+ ): Promise<ComponentData | null> {
273
295
  const id = packageName.replace('@foundrykit/', '');
274
296
  const category =
275
297
  id === 'maps' ? 'maps' : id === 'hooks' ? 'hooks' : 'packages';
298
+ const metadata = await this.fetchPackageMetadata(packageName);
299
+ if (requirePublishedPackage && !metadata) {
300
+ return null;
301
+ }
276
302
 
277
303
  return {
278
304
  id,
279
305
  name: this.toDisplayName(id),
280
- description: `${packageName} npm package`,
306
+ version: metadata?.version,
307
+ description: metadata?.description ?? `${packageName} npm package`,
281
308
  category,
282
309
  files: [],
283
310
  registryDependencies: [],
@@ -285,20 +312,10 @@ export function cn(...inputs: ClassValue[]) {
285
312
  };
286
313
  }
287
314
 
288
- private withFoundryKitPackages(components: ComponentMeta[]): ComponentMeta[] {
289
- const packageEntries = FOUNDRYKIT_PACKAGE_ALIASES.map(packageId => ({
290
- id: packageId,
291
- name: this.toDisplayName(packageId),
292
- category:
293
- packageId === 'maps'
294
- ? ('maps' as const)
295
- : packageId === 'hooks'
296
- ? ('hooks' as const)
297
- : ('packages' as const),
298
- description: `@foundrykit/${packageId} npm package`,
299
- packageDependencies: [`@foundrykit/${packageId}`],
300
- }));
301
-
315
+ private async withFoundryKitPackages(
316
+ components: ComponentMeta[]
317
+ ): Promise<ComponentMeta[]> {
318
+ const packageEntries = await this.fetchFoundryKitPackages();
302
319
  const seenIds = new Set(components.map(component => component.id));
303
320
  return [
304
321
  ...components,
@@ -313,6 +330,112 @@ export function cn(...inputs: ClassValue[]) {
313
330
  .join(' ');
314
331
  }
315
332
 
333
+ private async fetchFoundryKitPackages(): Promise<ComponentMeta[]> {
334
+ if (!this.foundryKitPackagesPromise) {
335
+ this.foundryKitPackagesPromise = this.fetchFoundryKitPackagesFromNpm();
336
+ }
337
+
338
+ try {
339
+ return await this.foundryKitPackagesPromise;
340
+ } catch {
341
+ return this.getFallbackFoundryKitPackages();
342
+ }
343
+ }
344
+
345
+ private async fetchFoundryKitPackagesFromNpm(): Promise<ComponentMeta[]> {
346
+ const url = `${NPM_REGISTRY_URL}/-/v1/search?text=scope:foundrykit&size=250`;
347
+ console.log(chalk.gray(`Fetching FoundryKit packages from npm: ${url}`));
348
+
349
+ const response = await fetch(url);
350
+ if (!response.ok) {
351
+ throw new Error(
352
+ `npm returned ${response.status}: ${response.statusText}`
353
+ );
354
+ }
355
+
356
+ const data = (await response.json()) as {
357
+ objects?: Array<{
358
+ package?: {
359
+ name?: string;
360
+ version?: string;
361
+ description?: string;
362
+ keywords?: string[];
363
+ };
364
+ }>;
365
+ };
366
+
367
+ return (data.objects ?? [])
368
+ .map(item => item.package)
369
+ .filter((pkg): pkg is NonNullable<typeof pkg> => {
370
+ return Boolean(pkg?.name?.startsWith('@foundrykit/'));
371
+ })
372
+ .map(pkg => this.toPackageComponentMeta(pkg.name!, {
373
+ version: pkg.version,
374
+ description: pkg.description,
375
+ keywords: pkg.keywords,
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 ?? {}).sort(compareVersions).at(-1),
404
+ description: data.description,
405
+ keywords: data.keywords,
406
+ };
407
+ } catch {
408
+ return null;
409
+ }
410
+ }
411
+
412
+ private getFallbackFoundryKitPackages(): ComponentMeta[] {
413
+ return FOUNDRYKIT_PACKAGE_ALIASES.map(packageId =>
414
+ this.toPackageComponentMeta(`@foundrykit/${packageId}`)
415
+ );
416
+ }
417
+
418
+ private toPackageComponentMeta(
419
+ packageName: string,
420
+ metadata: {
421
+ version?: string;
422
+ description?: string;
423
+ keywords?: string[];
424
+ } = {}
425
+ ): ComponentMeta {
426
+ const id = packageName.replace('@foundrykit/', '');
427
+ return {
428
+ id,
429
+ name: this.toDisplayName(id),
430
+ version: metadata.version,
431
+ category:
432
+ id === 'maps' ? 'maps' : id === 'hooks' ? 'hooks' : 'packages',
433
+ description: metadata.description ?? `${packageName} npm package`,
434
+ tags: metadata.keywords,
435
+ packageDependencies: [packageName],
436
+ };
437
+ }
438
+
316
439
  /**
317
440
  * Update the local cache with new component list
318
441
  */
@@ -479,3 +602,23 @@ export function getRegistry(config?: Partial<CLIConfig>): RegistryService {
479
602
  export function resetRegistry(): void {
480
603
  registryInstance = null;
481
604
  }
605
+
606
+ function compareVersions(a: string, b: string): number {
607
+ const aParts = normalizeVersion(a).split('.').map(Number);
608
+ const bParts = normalizeVersion(b).split('.').map(Number);
609
+ const length = Math.max(aParts.length, bParts.length);
610
+
611
+ for (let index = 0; index < length; index++) {
612
+ const diff = (aParts[index] ?? 0) - (bParts[index] ?? 0);
613
+ if (diff !== 0) return diff;
614
+ }
615
+
616
+ return 0;
617
+ }
618
+
619
+ function normalizeVersion(version: string): string {
620
+ return version
621
+ .replace(/^[^\d]*/, '')
622
+ .split('-')[0]
623
+ ?.replace(/[^\d.]/g, '') || '0';
624
+ }
@@ -80,6 +80,108 @@ describe('Dependency Resolution', () => {
80
80
  });
81
81
 
82
82
  describe('Registry Component Fetching', () => {
83
+ it('should merge scoped npm packages into the component list', async () => {
84
+ (global.fetch as any)
85
+ .mockResolvedValueOnce({
86
+ ok: true,
87
+ json: async () => [
88
+ {
89
+ id: 'button',
90
+ name: 'Button',
91
+ category: 'primitives',
92
+ description: 'Button component',
93
+ },
94
+ ],
95
+ })
96
+ .mockResolvedValueOnce({
97
+ ok: true,
98
+ json: async () => ({
99
+ objects: [
100
+ {
101
+ package: {
102
+ name: '@foundrykit/menu-plugin',
103
+ version: '3.1.0',
104
+ description: 'Menu plugin',
105
+ keywords: ['foundrykit', 'plugin'],
106
+ },
107
+ },
108
+ ],
109
+ }),
110
+ });
111
+
112
+ const components = await registry.getComponents();
113
+
114
+ expect(components).toEqual(
115
+ expect.arrayContaining([
116
+ expect.objectContaining({
117
+ id: 'menu-plugin',
118
+ version: '3.1.0',
119
+ category: 'packages',
120
+ packageDependencies: ['@foundrykit/menu-plugin'],
121
+ }),
122
+ ])
123
+ );
124
+ });
125
+
126
+ it('should resolve explicit scoped npm packages when absent from the registry', async () => {
127
+ (global.fetch as any)
128
+ .mockResolvedValueOnce({
129
+ ok: false,
130
+ status: 404,
131
+ statusText: 'Not Found',
132
+ })
133
+ .mockResolvedValueOnce({
134
+ ok: true,
135
+ json: async () => ({
136
+ name: '@foundrykit/menu-plugin',
137
+ description: 'Menu plugin',
138
+ 'dist-tags': {
139
+ latest: '3.1.0',
140
+ },
141
+ }),
142
+ });
143
+
144
+ const component = await registry.getComponent('@foundrykit/menu-plugin');
145
+
146
+ expect(component).toEqual(
147
+ expect.objectContaining({
148
+ id: 'menu-plugin',
149
+ version: '3.1.0',
150
+ category: 'packages',
151
+ files: [],
152
+ packageDependencies: ['@foundrykit/menu-plugin'],
153
+ })
154
+ );
155
+ });
156
+
157
+ it('should resolve bare npm package IDs surfaced by the package list', async () => {
158
+ (global.fetch as any)
159
+ .mockResolvedValueOnce({
160
+ ok: false,
161
+ status: 404,
162
+ statusText: 'Not Found',
163
+ })
164
+ .mockResolvedValueOnce({
165
+ ok: true,
166
+ json: async () => ({
167
+ name: '@foundrykit/menu-plugin',
168
+ 'dist-tags': {
169
+ latest: '3.1.0',
170
+ },
171
+ }),
172
+ });
173
+
174
+ const component = await registry.getComponent('menu-plugin');
175
+
176
+ expect(component).toEqual(
177
+ expect.objectContaining({
178
+ id: 'menu-plugin',
179
+ version: '3.1.0',
180
+ packageDependencies: ['@foundrykit/menu-plugin'],
181
+ })
182
+ );
183
+ });
184
+
83
185
  it('should fetch regular components from registry', async () => {
84
186
  const mockComponent: ComponentData = {
85
187
  id: 'button',