@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.
package/dist/index.js CHANGED
@@ -4,20 +4,24 @@
4
4
  import { readFileSync } from "fs";
5
5
  import { dirname, join } from "path";
6
6
  import { fileURLToPath } from "url";
7
- import { Command as Command6 } from "commander";
7
+ import { Command as Command11 } from "commander";
8
8
 
9
9
  // src/commands/add.ts
10
- import { exec } from "child_process";
11
- import path2 from "path";
12
- import { promisify } from "util";
13
- import chalk2 from "chalk";
10
+ import path5 from "path";
11
+ import chalk3 from "chalk";
14
12
  import { Command } from "commander";
15
- import fs2 from "fs-extra";
13
+ import fs5 from "fs-extra";
14
+ import inquirer2 from "inquirer";
15
+
16
+ // src/lib/apply.ts
17
+ import path3 from "path";
18
+ import chalk2 from "chalk";
19
+ import { createTwoFilesPatch } from "diff";
20
+ import fs3 from "fs-extra";
16
21
  import inquirer from "inquirer";
17
22
 
18
23
  // src/lib/constants.ts
19
- var CLI_VERSION = "1.0.16";
20
- var DEFAULT_REGISTRY_URL = "https://foundry.umiflow.com";
24
+ var DEFAULT_REGISTRY_URL = "https://foundrykit.dokploy.umisites.com";
21
25
  var NPM_REGISTRY_URL = "https://registry.npmjs.org";
22
26
  var CACHE_TTL = 24 * 60 * 60 * 1e3;
23
27
  var CACHE_DIR = ".foundrykit";
@@ -45,15 +49,68 @@ var FOUNDRYKIT_PACKAGE_ALIASES = [
45
49
  "types",
46
50
  "utils"
47
51
  ];
52
+ var SETTINGS_FILE = "foundrykit.json";
53
+ var LOCK_FILE = "foundrykit.lock.json";
54
+ var LEGACY_CONFIG_FILE = "foundrykit.config.json";
55
+ var SCHEMA_URL = "https://unpkg.com/@foundrykit/cli@3/schema.json";
56
+ var LEGACY_DEFAULT_REGISTRY_URL = "https://foundry.umiflow.com";
57
+ var DEFAULT_HUB_URL = "https://foundrykit.dokploy.umisites.com";
58
+ var CREDENTIALS_FILE = "credentials.json";
59
+
60
+ // src/lib/project/files.ts
61
+ import { createHash, randomBytes } from "crypto";
62
+ import path from "path";
63
+ import fs from "fs-extra";
64
+ function fingerprint(content) {
65
+ const hash = createHash("sha256").update(content.replace(/\r\n/g, "\n")).digest("base64");
66
+ return `sha256-${hash}`;
67
+ }
68
+ async function fileStatus(absPath, recorded) {
69
+ if (!await fs.pathExists(absPath)) return "missing";
70
+ if (recorded === void 0) return "unknown";
71
+ const current = fingerprint(await fs.readFile(absPath, "utf8"));
72
+ return current === recorded ? "unchanged" : "edited";
73
+ }
74
+ function sortKeys(value) {
75
+ if (Array.isArray(value)) return value.map(sortKeys);
76
+ if (value && typeof value === "object") {
77
+ return Object.fromEntries(
78
+ Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => [k, sortKeys(v)])
79
+ );
80
+ }
81
+ return value;
82
+ }
83
+ function stableStringify(value) {
84
+ return `${JSON.stringify(sortKeys(value), null, 2)}
85
+ `;
86
+ }
87
+ async function writeFileAtomic(absPath, content) {
88
+ if (await fs.pathExists(absPath) && await fs.readFile(absPath, "utf8") === content) {
89
+ return false;
90
+ }
91
+ await fs.ensureDir(path.dirname(absPath));
92
+ const tmp = `${absPath}.${randomBytes(4).toString("hex")}.tmp`;
93
+ try {
94
+ await fs.writeFile(tmp, content);
95
+ await fs.rename(tmp, absPath);
96
+ } catch (error) {
97
+ await fs.remove(tmp);
98
+ throw error;
99
+ }
100
+ return true;
101
+ }
48
102
 
49
103
  // src/lib/registry.ts
50
104
  import os from "os";
51
- import path from "path";
105
+ import path2 from "path";
52
106
  import chalk from "chalk";
53
- import fs from "fs-extra";
107
+ import fs2 from "fs-extra";
108
+ function resolveRegistryUrl(settings) {
109
+ const url = process.env.FOUNDRYKIT_REGISTRY_URL || settings?.registry || DEFAULT_REGISTRY_URL;
110
+ return url === LEGACY_DEFAULT_REGISTRY_URL ? DEFAULT_REGISTRY_URL : url;
111
+ }
54
112
  var DEFAULT_CONFIG = {
55
- registryUrl: process.env.FOUNDRYKIT_REGISTRY_URL || DEFAULT_REGISTRY_URL,
56
- cacheDir: path.join(os.homedir(), CACHE_DIR, "cache"),
113
+ cacheDir: path2.join(os.homedir(), CACHE_DIR, "cache"),
57
114
  cacheMaxAge: CACHE_TTL
58
115
  };
59
116
  var RegistryService = class {
@@ -61,8 +118,12 @@ var RegistryService = class {
61
118
  cacheFile;
62
119
  foundryKitPackagesPromise = null;
63
120
  constructor(config) {
64
- this.config = { ...DEFAULT_CONFIG, ...config };
65
- this.cacheFile = path.join(this.config.cacheDir, "registry.json");
121
+ this.config = {
122
+ ...DEFAULT_CONFIG,
123
+ registryUrl: resolveRegistryUrl(),
124
+ ...config
125
+ };
126
+ this.cacheFile = path2.join(this.config.cacheDir, "registry.json");
66
127
  }
67
128
  /**
68
129
  * Fetch all components from the registry
@@ -230,11 +291,11 @@ export function cn(...inputs: ClassValue[]) {
230
291
  */
231
292
  async isPackageInstalled(packageName) {
232
293
  try {
233
- const packageJsonPath = path.join(process.cwd(), "package.json");
234
- if (!await fs.pathExists(packageJsonPath)) {
294
+ const packageJsonPath = path2.join(process.cwd(), "package.json");
295
+ if (!await fs2.pathExists(packageJsonPath)) {
235
296
  return false;
236
297
  }
237
- const packageJson2 = await fs.readJson(packageJsonPath);
298
+ const packageJson2 = await fs2.readJson(packageJsonPath);
238
299
  const allDeps = {
239
300
  ...packageJson2.dependencies,
240
301
  ...packageJson2.devDependencies,
@@ -357,8 +418,8 @@ export function cn(...inputs: ClassValue[]) {
357
418
  components,
358
419
  componentData: cache?.componentData || {}
359
420
  };
360
- await fs.ensureDir(this.config.cacheDir);
361
- await fs.writeJson(this.cacheFile, newCache, { spaces: 2 });
421
+ await fs2.ensureDir(this.config.cacheDir);
422
+ await fs2.writeJson(this.cacheFile, newCache, { spaces: 2 });
362
423
  } catch {
363
424
  console.log(chalk.gray("Failed to update cache"));
364
425
  }
@@ -376,8 +437,8 @@ export function cn(...inputs: ClassValue[]) {
376
437
  };
377
438
  cache.componentData[component.id] = component;
378
439
  cache.lastUpdated = (/* @__PURE__ */ new Date()).toISOString();
379
- await fs.ensureDir(this.config.cacheDir);
380
- await fs.writeJson(this.cacheFile, cache, { spaces: 2 });
440
+ await fs2.ensureDir(this.config.cacheDir);
441
+ await fs2.writeJson(this.cacheFile, cache, { spaces: 2 });
381
442
  } catch {
382
443
  console.log(chalk.gray("Failed to cache component"));
383
444
  }
@@ -387,8 +448,8 @@ export function cn(...inputs: ClassValue[]) {
387
448
  */
388
449
  async loadCache() {
389
450
  try {
390
- if (await fs.pathExists(this.cacheFile)) {
391
- return await fs.readJson(this.cacheFile);
451
+ if (await fs2.pathExists(this.cacheFile)) {
452
+ return await fs2.readJson(this.cacheFile);
392
453
  }
393
454
  } catch {
394
455
  console.log(chalk.gray("Failed to load cache"));
@@ -424,8 +485,8 @@ export function cn(...inputs: ClassValue[]) {
424
485
  */
425
486
  async clearCache() {
426
487
  try {
427
- if (await fs.pathExists(this.cacheFile)) {
428
- await fs.remove(this.cacheFile);
488
+ if (await fs2.pathExists(this.cacheFile)) {
489
+ await fs2.remove(this.cacheFile);
429
490
  console.log(chalk.green("Cache cleared successfully"));
430
491
  }
431
492
  } catch (error) {
@@ -439,9 +500,9 @@ export function cn(...inputs: ClassValue[]) {
439
500
  */
440
501
  async getCacheStats() {
441
502
  try {
442
- if (await fs.pathExists(this.cacheFile)) {
503
+ if (await fs2.pathExists(this.cacheFile)) {
443
504
  const cache = await this.loadCache();
444
- const stats = await fs.stat(this.cacheFile);
505
+ const stats = await fs2.stat(this.cacheFile);
445
506
  return {
446
507
  exists: true,
447
508
  size: stats.size,
@@ -460,9 +521,12 @@ export function cn(...inputs: ClassValue[]) {
460
521
  }
461
522
  };
462
523
  var registryInstance = null;
463
- function getRegistry(config) {
464
- if (!registryInstance) {
465
- registryInstance = new RegistryService(config);
524
+ var registryInstanceUrl = null;
525
+ function getRegistry(config, settings) {
526
+ const registryUrl = config?.registryUrl ?? resolveRegistryUrl(settings);
527
+ if (!registryInstance || registryInstanceUrl !== registryUrl) {
528
+ registryInstance = new RegistryService({ ...config, registryUrl });
529
+ registryInstanceUrl = registryUrl;
466
530
  }
467
531
  return registryInstance;
468
532
  }
@@ -480,48 +544,469 @@ function normalizeVersion(version) {
480
544
  return version.replace(/^[^\d]*/, "").split("-")[0]?.replace(/[^\d.]/g, "") || "0";
481
545
  }
482
546
 
547
+ // src/lib/apply.ts
548
+ async function applyComponent(project, data, opts) {
549
+ const result = {
550
+ id: data.id,
551
+ written: [],
552
+ upToDate: [],
553
+ skippedEdited: [],
554
+ skippedUnknown: [],
555
+ kept: [],
556
+ droppedFromLock: [],
557
+ failed: []
558
+ };
559
+ const { settings } = project;
560
+ const previous = project.lock.components[data.id]?.files ?? {};
561
+ const files = {};
562
+ const seen = /* @__PURE__ */ new Set();
563
+ for (const file of data.files) {
564
+ const isUtils = data.id === "utils" || file.path === "lib/utils.ts";
565
+ const resolved = isUtils ? settings.paths.utils || "lib/utils.ts" : resolveComponentPath(file.path, data.category, settings);
566
+ let rel = resolved;
567
+ try {
568
+ let abs = project.resolveInRoot(path3.join(opts.basePath ?? "", resolved));
569
+ rel = path3.relative(project.root, abs).split(path3.sep).join("/");
570
+ if (!previous[rel]) {
571
+ const suffix = resolved.split(/[\\/]/).slice(isUtils ? -1 : -2).join("/");
572
+ const recordedPath = Object.keys(previous).find(
573
+ (key) => !seen.has(key) && (key === suffix || key.endsWith(`/${suffix}`))
574
+ );
575
+ if (recordedPath) {
576
+ rel = recordedPath;
577
+ abs = project.resolveInRoot(recordedPath);
578
+ }
579
+ }
580
+ seen.add(rel);
581
+ const recorded = previous[rel];
582
+ const keepRecorded = () => {
583
+ if (recorded) files[rel] = recorded;
584
+ };
585
+ if (!file.content || file.content.trim() === "") {
586
+ console.log(chalk2.yellow(` \u26A0 Skipping ${rel} - no content available`));
587
+ keepRecorded();
588
+ continue;
589
+ }
590
+ const next = transformImportsForConfig(file.content, settings);
591
+ const disk = await fs3.pathExists(abs) ? await fs3.readFile(abs, "utf8") : void 0;
592
+ if (disk !== void 0 && fingerprint(disk) === fingerprint(next)) {
593
+ files[rel] = fingerprint(next);
594
+ result.upToDate.push(rel);
595
+ continue;
596
+ }
597
+ const status = await fileStatus(abs, recorded);
598
+ let write = status === "missing" || status === "unchanged" || opts.overwrite;
599
+ if (!write && status === "edited") {
600
+ result.skippedEdited.push(rel);
601
+ keepRecorded();
602
+ } else if (!write && opts.prompt) {
603
+ const diff = createTwoFilesPatch(
604
+ rel,
605
+ rel,
606
+ disk ?? "",
607
+ next,
608
+ "your file",
609
+ "registry"
610
+ );
611
+ if (await opts.prompt(rel, diff) === "overwrite") {
612
+ write = true;
613
+ } else {
614
+ files[rel] = fingerprint(next);
615
+ result.kept.push(rel);
616
+ }
617
+ } else if (!write) {
618
+ result.skippedUnknown.push(rel);
619
+ keepRecorded();
620
+ }
621
+ if (write) {
622
+ await fs3.outputFile(abs, next);
623
+ files[rel] = fingerprint(next);
624
+ result.written.push(rel);
625
+ }
626
+ } catch (error) {
627
+ result.failed.push(
628
+ `${rel}: ${error instanceof Error ? error.message : String(error)}`
629
+ );
630
+ const recorded = previous[rel];
631
+ if (recorded) files[rel] = recorded;
632
+ }
633
+ }
634
+ const existing = project.lock.components[data.id];
635
+ if (existing && result.written.length + result.upToDate.length === 0) {
636
+ if (result.kept.length > 0) {
637
+ existing.files = { ...existing.files };
638
+ for (const rel of result.kept) existing.files[rel] = files[rel];
639
+ }
640
+ return result;
641
+ }
642
+ for (const rel of Object.keys(previous)) {
643
+ if (!seen.has(rel)) result.droppedFromLock.push(rel);
644
+ }
645
+ const entry = { version: data.version ?? null };
646
+ const registry = resolveRegistryUrl(settings);
647
+ if (registry !== DEFAULT_REGISTRY_URL && registry !== LEGACY_DEFAULT_REGISTRY_URL) {
648
+ entry.registry = registry;
649
+ }
650
+ if (Object.keys(files).length > 0) entry.files = files;
651
+ project.lock.components[data.id] = entry;
652
+ return result;
653
+ }
654
+ function interactivePrompt() {
655
+ if (!process.stdin.isTTY || !process.stdout.isTTY) return void 0;
656
+ return async (file, diff) => {
657
+ console.log(
658
+ diff.split("\n").map(
659
+ (line) => line.startsWith("+") && !line.startsWith("+++") ? chalk2.green(line) : line.startsWith("-") && !line.startsWith("---") ? chalk2.red(line) : line
660
+ ).join("\n")
661
+ );
662
+ const { choice } = await inquirer.prompt([
663
+ {
664
+ type: "list",
665
+ name: "choice",
666
+ message: `${file} isn't tracked yet and differs from the registry version.`,
667
+ choices: [
668
+ { name: "Keep my file", value: "keep" },
669
+ { name: "Overwrite with the registry version", value: "overwrite" }
670
+ ],
671
+ default: "keep"
672
+ }
673
+ ]);
674
+ return choice;
675
+ };
676
+ }
677
+
678
+ // src/lib/project/index.ts
679
+ import path4 from "path";
680
+ import fs4 from "fs-extra";
681
+
682
+ // src/lib/project/migrate.ts
683
+ var KNOWN_PACKAGE_IDS = [
684
+ ...FOUNDRYKIT_PACKAGE_ALIASES.filter((id) => id !== "utils"),
685
+ "form-plugin",
686
+ "seo-plugin",
687
+ "guides-plugin",
688
+ "history-plugin",
689
+ "media-plugin",
690
+ "menu-plugin",
691
+ "permissions-plugin",
692
+ "search-plugin",
693
+ "svg-maps",
694
+ "tile-maps",
695
+ "biome-config",
696
+ "advanced-seo-plugin",
697
+ "advanced-forms-plugin"
698
+ ];
699
+ function migrateLegacyConfig(legacy, pkg) {
700
+ const { version: _v, installedComponents, registry, ...rest } = legacy;
701
+ const settings = { $schema: SCHEMA_URL, ...rest };
702
+ if (registry && registry !== DEFAULT_REGISTRY_URL && registry !== LEGACY_DEFAULT_REGISTRY_URL) {
703
+ settings.registry = registry;
704
+ }
705
+ const deps = { ...pkg.dependencies, ...pkg.devDependencies };
706
+ const components = {};
707
+ for (const [id, entry] of Object.entries(installedComponents ?? {})) {
708
+ const isPackage = id !== "utils" && (`@foundrykit/${id}` in deps || KNOWN_PACKAGE_IDS.includes(id));
709
+ if (!isPackage) components[id] = { version: entry.version };
710
+ }
711
+ return { settings, lock: { lockfileVersion: 1, components } };
712
+ }
713
+
714
+ // src/lib/project/settings.ts
715
+ var SettingsError = class extends Error {
716
+ constructor(key, expected) {
717
+ super(`foundrykit.json: "${key}" must be ${expected}`);
718
+ this.key = key;
719
+ this.name = "SettingsError";
720
+ }
721
+ };
722
+ var RULES = [
723
+ ["$schema", "string", false],
724
+ ["registry", "string", false],
725
+ ["packageManager", "string", true],
726
+ ["typescript", "boolean", true],
727
+ ["framework", "string", true],
728
+ ["tailwind.css", "string", true],
729
+ ["aliases.@", "string", true],
730
+ ["aliases.@/components", "string", true],
731
+ ["aliases.@/lib", "string", true],
732
+ ["aliases.@/hooks", "string", true],
733
+ ["paths.primitives", "string", true],
734
+ ["paths.components", "string", true],
735
+ ["paths.blocks", "string", true],
736
+ ["paths.animations", "string", true],
737
+ ["paths.utils", "string", true],
738
+ ["paths.hooks", "string", false],
739
+ ["paths.maps", "string", false],
740
+ ["hub.project", "string", false, /^[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9-]*$/],
741
+ ["hub.url", "string", false, /^https?:\/\//]
742
+ ];
743
+ var KNOWN_TOP_LEVEL = new Set(RULES.map(([p]) => p.split(".")[0]));
744
+ var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
745
+ function validateSettings(raw) {
746
+ if (!isObject(raw)) throw new SettingsError("(root)", "an object");
747
+ for (const [path12, type, required, pattern] of RULES) {
748
+ const [parent, child] = path12.includes(".") ? [path12.slice(0, path12.indexOf(".")), path12.slice(path12.indexOf(".") + 1)] : [void 0, path12];
749
+ let holder = raw;
750
+ if (parent) {
751
+ holder = raw[parent];
752
+ if (holder === void 0 && !required) continue;
753
+ if (!isObject(holder)) {
754
+ if (required)
755
+ throw new SettingsError(
756
+ path12,
757
+ `${type} (parent "${parent}" must be an object)`
758
+ );
759
+ throw new SettingsError(parent, "an object");
760
+ }
761
+ }
762
+ const value = holder[child];
763
+ if (value === void 0) {
764
+ if (required) throw new SettingsError(path12, `a ${type} (missing)`);
765
+ continue;
766
+ }
767
+ if (typeof value !== type) throw new SettingsError(path12, `a ${type}`);
768
+ if (pattern && !pattern.test(value))
769
+ throw new SettingsError(path12, `a string matching ${pattern.source}`);
770
+ }
771
+ const warnings = Object.keys(raw).filter((k) => !KNOWN_TOP_LEVEL.has(k)).map((k) => `foundrykit.json: unknown key "${k}" (ignored)`);
772
+ return { settings: raw, warnings };
773
+ }
774
+
775
+ // src/lib/project/index.ts
776
+ var ProjectError = class extends Error {
777
+ constructor(message) {
778
+ super(message);
779
+ this.name = "ProjectError";
780
+ }
781
+ };
782
+ function findProjectRoot(cwd) {
783
+ let dir = path4.resolve(cwd);
784
+ for (; ; ) {
785
+ if (fs4.existsSync(path4.join(dir, SETTINGS_FILE)) || fs4.existsSync(path4.join(dir, LEGACY_CONFIG_FILE))) {
786
+ return dir;
787
+ }
788
+ const parent = path4.dirname(dir);
789
+ if (parent === dir) return null;
790
+ dir = parent;
791
+ }
792
+ }
793
+ async function readJson(file) {
794
+ try {
795
+ return JSON.parse(await fs4.readFile(file, "utf8"));
796
+ } catch (error) {
797
+ throw new ProjectError(
798
+ `Could not read ${path4.basename(file)}: ${error.message}`
799
+ );
800
+ }
801
+ }
802
+ function checkLock(raw) {
803
+ const lock = raw;
804
+ if (!lock || typeof lock !== "object" || lock.lockfileVersion !== 1 || !lock.components || typeof lock.components !== "object") {
805
+ throw new ProjectError(
806
+ `${LOCK_FILE} is invalid: expected lockfileVersion 1 and a "components" object`
807
+ );
808
+ }
809
+ return lock;
810
+ }
811
+ async function loadProject(cwd, opts = {}) {
812
+ const root = findProjectRoot(cwd);
813
+ if (!root) {
814
+ throw new ProjectError(
815
+ `No ${SETTINGS_FILE} found. Run \`foundrykit init\` first.`
816
+ );
817
+ }
818
+ const settingsPath = path4.join(root, SETTINGS_FILE);
819
+ const lockPath = path4.join(root, LOCK_FILE);
820
+ const legacyPath = path4.join(root, LEGACY_CONFIG_FILE);
821
+ const hasSettings = await fs4.pathExists(settingsPath);
822
+ const hasLegacy = await fs4.pathExists(legacyPath);
823
+ let rawSettings;
824
+ let lock = { lockfileVersion: 1, components: {} };
825
+ let migration = "none";
826
+ const warnings = [];
827
+ if (hasSettings) {
828
+ rawSettings = await readJson(settingsPath);
829
+ if (await fs4.pathExists(lockPath)) {
830
+ lock = checkLock(await readJson(lockPath));
831
+ }
832
+ if (hasLegacy) {
833
+ warnings.push(
834
+ `${LEGACY_CONFIG_FILE} is no longer used and can be deleted.`
835
+ );
836
+ }
837
+ } else {
838
+ const pkgPath = path4.join(root, "package.json");
839
+ const pkg = await fs4.pathExists(pkgPath) ? await readJson(pkgPath) : {};
840
+ const migrated = migrateLegacyConfig(
841
+ await readJson(legacyPath),
842
+ pkg
843
+ );
844
+ rawSettings = migrated.settings;
845
+ lock = migrated.lock;
846
+ migration = "pending";
847
+ }
848
+ const validated = validateSettings(rawSettings);
849
+ warnings.push(...validated.warnings);
850
+ const project = {
851
+ root,
852
+ settings: validated.settings,
853
+ lock,
854
+ migration,
855
+ warnings,
856
+ resolveInRoot(p) {
857
+ const abs = path4.resolve(root, p);
858
+ const rel = path4.relative(root, abs);
859
+ if (rel === ".." || rel.startsWith(`..${path4.sep}`) || path4.isAbsolute(rel)) {
860
+ throw new ProjectError(`Path escapes the project root: ${p}`);
861
+ }
862
+ return abs;
863
+ },
864
+ async saveLock() {
865
+ await writeFileAtomic(lockPath, stableStringify(project.lock));
866
+ },
867
+ async saveSettings() {
868
+ await writeFileAtomic(settingsPath, stableStringify(project.settings));
869
+ }
870
+ };
871
+ if (migration === "pending" && !opts.readOnly) {
872
+ await project.saveLock();
873
+ await project.saveSettings();
874
+ await fs4.remove(legacyPath);
875
+ project.migration = "done";
876
+ process.stderr.write(
877
+ `Migrated ${LEGACY_CONFIG_FILE} to ${SETTINGS_FILE} and ${LOCK_FILE}. Commit both new files.
878
+ `
879
+ );
880
+ }
881
+ return project;
882
+ }
883
+
884
+ // src/lib/run.ts
885
+ import { spawn } from "child_process";
886
+ var SPEC_RE = /^(?:@[a-z0-9][a-z0-9._~-]*\/)?[a-z0-9][a-z0-9._~-]*(?:@[A-Za-z0-9^~<>=*.+-]+)?$/;
887
+ function validatePackageSpecs(specs) {
888
+ for (const spec of specs) {
889
+ if (!SPEC_RE.test(spec)) {
890
+ throw new Error(`Invalid package spec: ${JSON.stringify(spec)}`);
891
+ }
892
+ }
893
+ }
894
+ function buildSpawn(pm, args, platform = process.platform) {
895
+ return platform === "win32" ? {
896
+ // One command string (no args array) also avoids Node's DEP0190 warning.
897
+ command: [pm, ...args.map((a) => `"${a}"`)].join(" "),
898
+ args: [],
899
+ shell: true
900
+ } : { command: pm, args, shell: false };
901
+ }
902
+ function killTree(pid, fallback) {
903
+ if (pid === void 0) {
904
+ fallback();
905
+ return;
906
+ }
907
+ if (process.platform === "win32") {
908
+ spawn("taskkill", ["/pid", String(pid), "/T", "/F"], { stdio: "ignore" });
909
+ return;
910
+ }
911
+ try {
912
+ process.kill(-pid, "SIGKILL");
913
+ } catch {
914
+ fallback();
915
+ }
916
+ }
917
+ function runPackageManager(pm, args, opts) {
918
+ const timeoutMs = opts.timeoutMs ?? 10 * 60 * 1e3;
919
+ const label = `${pm} ${args.join(" ")}`;
920
+ const spec = buildSpawn(pm, args);
921
+ return new Promise((resolve, reject) => {
922
+ const options = {
923
+ cwd: opts.cwd,
924
+ stdio: ["ignore", 2, 2],
925
+ env: { ...process.env, CI: process.env.CI ?? "1" },
926
+ shell: spec.shell,
927
+ detached: process.platform !== "win32"
928
+ };
929
+ const child = spec.shell ? spawn(spec.command, options) : spawn(spec.command, spec.args, options);
930
+ const signals = { SIGINT: 130, SIGTERM: 143 };
931
+ const handlers = Object.entries(signals).map(([sig, exitCode]) => {
932
+ const handler = () => {
933
+ killTree(child.pid, () => child.kill("SIGKILL"));
934
+ process.exit(exitCode);
935
+ };
936
+ if (process.platform !== "win32")
937
+ process.once(sig, handler);
938
+ return [sig, handler];
939
+ });
940
+ const cleanup = () => {
941
+ clearTimeout(timer);
942
+ for (const [sig, handler] of handlers) process.off(sig, handler);
943
+ };
944
+ const timer = setTimeout(() => {
945
+ killTree(child.pid, () => child.kill("SIGKILL"));
946
+ cleanup();
947
+ reject(new Error(`\`${label}\` timed out after ${timeoutMs / 1e3}s`));
948
+ }, timeoutMs);
949
+ child.on("error", (err) => {
950
+ cleanup();
951
+ reject(new Error(`\`${label}\` failed to start: ${err.message}`));
952
+ });
953
+ child.on("close", (code) => {
954
+ cleanup();
955
+ if (code === 0) resolve();
956
+ else reject(new Error(`\`${label}\` exited with code ${code}`));
957
+ });
958
+ });
959
+ }
960
+
483
961
  // src/commands/add.ts
484
- var execAsync = promisify(exec);
485
962
  function addCommand() {
486
963
  return new Command("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) => {
487
964
  try {
488
- if (!id) {
489
- const selectedIds = await selectComponentsInteractively();
490
- if (selectedIds.length === 0) {
491
- console.log(chalk2.yellow("No components selected."));
492
- return;
493
- }
494
- for (const componentId of selectedIds) {
495
- await addSingleComponent(componentId, options);
965
+ const project = await loadProject(process.cwd());
966
+ process.chdir(project.root);
967
+ validateProject(project, options);
968
+ const ids = id ? [id] : await selectComponentsInteractively(project);
969
+ if (ids.length === 0) {
970
+ console.log(chalk3.yellow("No components selected."));
971
+ return;
972
+ }
973
+ try {
974
+ for (const componentId of ids) {
975
+ await addSingleComponent(project, componentId, options);
496
976
  }
497
- } else {
498
- await addSingleComponent(id, options);
977
+ } finally {
978
+ await project.saveLock();
499
979
  }
500
980
  } catch (error) {
501
- console.error(chalk2.red("\u274C Failed to add component:"));
981
+ console.error(chalk3.red("\u274C Failed to add component:"));
502
982
  console.error(
503
- chalk2.red(error instanceof Error ? error.message : String(error))
983
+ chalk3.red(error instanceof Error ? error.message : String(error))
504
984
  );
505
985
  process.exit(1);
506
986
  }
507
987
  });
508
988
  }
509
- async function selectComponentsInteractively() {
510
- console.log(chalk2.blue("\u{1F4E6} Select components to add:"));
989
+ async function selectComponentsInteractively(project) {
990
+ if (!process.stdin.isTTY || !process.stdout.isTTY) {
991
+ throw new Error(
992
+ "No component id given. Pass component ids when not running interactively."
993
+ );
994
+ }
995
+ console.log(chalk3.blue("\u{1F4E6} Select components to add:"));
511
996
  console.log(
512
- chalk2.gray(" Use arrow keys to navigate, space to select, a to toggle all")
997
+ chalk3.gray(" Use arrow keys to navigate, space to select, a to toggle all")
513
998
  );
514
- console.log(chalk2.gray(" Press enter when done\n"));
515
- const registry = getRegistry();
999
+ console.log(chalk3.gray(" Press enter when done\n"));
1000
+ const registry = getRegistry(void 0, project.settings);
516
1001
  try {
517
- console.log(chalk2.gray("Fetching components from registry..."));
1002
+ console.log(chalk3.gray("Fetching components from registry..."));
518
1003
  const allComponents = await registry.getComponents();
519
1004
  if (allComponents.length === 0) {
520
- console.log(chalk2.yellow("No components available in the registry."));
1005
+ console.log(chalk3.yellow("No components available in the registry."));
521
1006
  return [];
522
1007
  }
523
1008
  const groupedChoices = createGroupedChoices(allComponents);
524
- const { selectedComponents } = await inquirer.prompt([
1009
+ const { selectedComponents } = await inquirer2.prompt([
525
1010
  {
526
1011
  type: "checkbox",
527
1012
  name: "selectedComponents",
@@ -533,9 +1018,9 @@ async function selectComponentsInteractively() {
533
1018
  ]);
534
1019
  return selectedComponents;
535
1020
  } catch (error) {
536
- console.error(chalk2.red("Failed to fetch components from registry:"));
1021
+ console.error(chalk3.red("Failed to fetch components from registry:"));
537
1022
  console.error(
538
- chalk2.red(error instanceof Error ? error.message : String(error))
1023
+ chalk3.red(error instanceof Error ? error.message : String(error))
539
1024
  );
540
1025
  throw error;
541
1026
  }
@@ -553,13 +1038,13 @@ function createGroupedChoices(components) {
553
1038
  const categoryComponents = components.filter((c) => c.category === category);
554
1039
  if (categoryComponents.length === 0) continue;
555
1040
  choices.push({
556
- name: chalk2.bold.cyan(`\u2500\u2500\u2500 ${category.toUpperCase()} \u2500\u2500\u2500`),
1041
+ name: chalk3.bold.cyan(`\u2500\u2500\u2500 ${category.toUpperCase()} \u2500\u2500\u2500`),
557
1042
  disabled: true,
558
1043
  value: `separator-${category}`
559
1044
  });
560
1045
  for (const component of categoryComponents) {
561
1046
  choices.push({
562
- name: `${component.name} - ${chalk2.gray(component.description)}`,
1047
+ name: `${component.name} - ${chalk3.gray(component.description)}`,
563
1048
  value: component.id,
564
1049
  short: component.name
565
1050
  });
@@ -567,149 +1052,110 @@ function createGroupedChoices(components) {
567
1052
  }
568
1053
  return choices;
569
1054
  }
570
- async function addSingleComponent(id, options) {
571
- console.log(chalk2.blue(`
1055
+ async function addSingleComponent(project, id, options) {
1056
+ console.log(chalk3.blue(`
572
1057
  \u{1F4E6} Adding ${id} to your project...`));
573
- await validateProject();
574
- const registry = getRegistry();
1058
+ const registry = getRegistry(void 0, project.settings);
1059
+ const applyOptions = {
1060
+ overwrite: Boolean(options.overwrite),
1061
+ prompt: interactivePrompt(),
1062
+ basePath: options.path
1063
+ };
1064
+ const depOptions = {
1065
+ overwrite: false,
1066
+ prompt: applyOptions.prompt
1067
+ };
575
1068
  try {
576
1069
  const componentData = await registry.getComponent(id, options.force);
577
- if (!options.overwrite && await hasConflictingFiles(componentData, options)) {
578
- const { shouldContinue } = await inquirer.prompt([
579
- {
580
- type: "confirm",
581
- name: "shouldContinue",
582
- message: `Some files for ${componentData.name} already exist. Overwrite?`,
583
- default: false
584
- }
585
- ]);
586
- if (!shouldContinue) {
587
- console.log(chalk2.yellow(`\u23ED\uFE0F Skipping ${componentData.name}.`));
588
- return;
589
- }
590
- }
1070
+ const results = [];
591
1071
  if (componentData.registryDependencies?.length) {
592
- console.log(chalk2.blue("\u{1F4E6} Installing required dependencies..."));
1072
+ console.log(chalk3.blue("\u{1F4E6} Installing required dependencies..."));
593
1073
  for (const dep of componentData.registryDependencies) {
1074
+ if (["hooks", "types"].includes(dep)) {
1075
+ console.log(chalk3.green(` \u2713 ${dep} package is available`));
1076
+ continue;
1077
+ }
594
1078
  try {
595
1079
  const depData = await registry.getComponent(dep);
596
- if (["hooks", "types"].includes(dep)) {
597
- console.log(chalk2.green(` \u2713 ${dep} package is available`));
598
- continue;
599
- }
600
- const hasExisting = await hasConflictingFiles(depData, options);
601
- if (!hasExisting) {
602
- await installComponentFiles(depData, options);
603
- console.log(chalk2.green(` \u2713 Installed ${dep}`));
604
- } else {
605
- console.log(chalk2.gray(` \u23ED ${dep} already exists`));
606
- }
1080
+ if (depData.files.length === 0) continue;
1081
+ results.push(
1082
+ reportApply(await applyComponent(project, depData, depOptions))
1083
+ );
607
1084
  } catch (error) {
608
1085
  console.log(
609
- chalk2.yellow(
1086
+ chalk3.yellow(
610
1087
  ` \u26A0 Could not install dependency "${dep}": ${error instanceof Error ? error.message : "Unknown error"}`
611
1088
  )
612
1089
  );
613
1090
  }
614
1091
  }
615
1092
  }
616
- await installComponentFiles(componentData, options);
617
- await trackInstalledComponent(componentData);
618
- console.log(chalk2.green(`\u2705 ${componentData.name} added successfully!`));
619
- showUsageExample(componentData);
1093
+ if (componentData.files.length > 0) {
1094
+ console.log(chalk3.blue("\u{1F4DD} Installing component files..."));
1095
+ results.push(
1096
+ reportApply(await applyComponent(project, componentData, applyOptions))
1097
+ );
1098
+ }
1099
+ const failed = results.reduce((n, r) => n + r.failed.length, 0);
1100
+ const skipped = results.reduce(
1101
+ (n, r) => n + r.skippedEdited.length + r.skippedUnknown.length,
1102
+ 0
1103
+ );
1104
+ if (failed > 0) {
1105
+ console.error(
1106
+ chalk3.red(
1107
+ `\u274C ${componentData.name}: ${failed} file(s) could not be written.`
1108
+ )
1109
+ );
1110
+ } else if (skipped > 0) {
1111
+ console.log(
1112
+ chalk3.yellow(
1113
+ `\u26A0\uFE0F ${componentData.name} added with ${skipped} file(s) skipped.`
1114
+ )
1115
+ );
1116
+ } else {
1117
+ console.log(chalk3.green(`\u2705 ${componentData.name} added successfully!`));
1118
+ }
1119
+ showUsageExample(componentData, project.settings);
620
1120
  await handlePackageDependencies(componentData, options);
621
1121
  } catch (error) {
622
- console.error(chalk2.red(`Failed to add ${id}:`));
1122
+ console.error(chalk3.red(`Failed to add ${id}:`));
623
1123
  throw error;
624
1124
  }
625
1125
  }
626
- async function updateConfigVersion() {
627
- const configPath = path2.join(process.cwd(), "foundrykit.config.json");
628
- if (fs2.existsSync(configPath)) {
629
- const config = await fs2.readJson(configPath);
630
- if (config.version !== CLI_VERSION) {
631
- config.version = CLI_VERSION;
632
- await fs2.writeJson(configPath, config, { spaces: 2 });
633
- }
1126
+ function reportApply(result) {
1127
+ console.log(chalk3.bold(` ${result.id}`));
1128
+ for (const f of result.written) console.log(chalk3.gray(` \u2713 Wrote ${f}`));
1129
+ for (const f of result.upToDate)
1130
+ console.log(chalk3.gray(` = ${f} is up to date`));
1131
+ for (const f of result.kept) console.log(chalk3.gray(` \u2022 Kept your ${f}`));
1132
+ for (const f of result.skippedEdited)
1133
+ console.log(
1134
+ chalk3.yellow(` \u26A0 Skipped ${f}: edited locally (use --overwrite)`)
1135
+ );
1136
+ for (const f of result.skippedUnknown)
1137
+ console.log(
1138
+ chalk3.yellow(
1139
+ ` \u26A0 Skipped ${f}: exists but isn't tracked (run in a terminal to review, or use --overwrite)`
1140
+ )
1141
+ );
1142
+ for (const f of result.droppedFromLock)
1143
+ console.log(
1144
+ chalk3.gray(` \u2022 ${f} is no longer part of ${result.id}; left on disk`)
1145
+ );
1146
+ for (const f of result.failed) {
1147
+ console.error(chalk3.red(` \u2717 ${f}`));
1148
+ process.exitCode = 1;
634
1149
  }
1150
+ return result;
635
1151
  }
636
- async function validateProject() {
637
- const packageJsonPath = path2.join(process.cwd(), "package.json");
638
- if (!fs2.existsSync(packageJsonPath)) {
1152
+ function validateProject(project, options) {
1153
+ if (!fs5.existsSync(path5.join(project.root, "package.json"))) {
639
1154
  throw new Error(
640
1155
  "No package.json found. Please run this command in a project root."
641
1156
  );
642
1157
  }
643
- const configPath = path2.join(process.cwd(), "foundrykit.config.json");
644
- if (!fs2.existsSync(configPath)) {
645
- throw new Error('FoundryKit not initialized. Run "foundrykit init" first.');
646
- }
647
- await updateConfigVersion();
648
- }
649
- async function hasConflictingFiles(componentData, options) {
650
- const config = await loadConfig();
651
- const basePath = options.path || process.cwd();
652
- for (const file of componentData.files) {
653
- let resolvedPath;
654
- if (componentData.id === "utils" || file.path === "lib/utils.ts") {
655
- resolvedPath = config.paths.utils || "lib/utils.ts";
656
- } else {
657
- resolvedPath = resolveComponentPath(
658
- file.path,
659
- componentData.category,
660
- config
661
- );
662
- }
663
- const filePath = path2.join(basePath, resolvedPath);
664
- if (fs2.existsSync(filePath)) {
665
- return true;
666
- }
667
- }
668
- return false;
669
- }
670
- async function installComponentFiles(componentData, options) {
671
- const config = await loadConfig();
672
- const basePath = options.path || process.cwd();
673
- if (componentData.files.length === 0) {
674
- return;
675
- }
676
- console.log(chalk2.blue("\u{1F4DD} Installing component files..."));
677
- for (const file of componentData.files) {
678
- let resolvedPath;
679
- if (componentData.id === "utils" || file.path === "lib/utils.ts") {
680
- resolvedPath = config.paths.utils || "lib/utils.ts";
681
- } else {
682
- resolvedPath = resolveComponentPath(
683
- file.path,
684
- componentData.category,
685
- config
686
- );
687
- }
688
- const filePath = path2.join(basePath, resolvedPath);
689
- await fs2.ensureDir(path2.dirname(filePath));
690
- if (!file.content || file.content.trim() === "") {
691
- console.log(
692
- chalk2.yellow(` \u26A0 Skipping ${resolvedPath} - no content available`)
693
- );
694
- continue;
695
- }
696
- const transformedContent = transformImportsForConfig(file.content, config);
697
- await fs2.writeFile(filePath, transformedContent);
698
- console.log(chalk2.gray(` \u2713 Created ${resolvedPath}`));
699
- }
700
- await updateConfigVersion();
701
- }
702
- async function trackInstalledComponent(componentData) {
703
- const configPath = path2.join(process.cwd(), "foundrykit.config.json");
704
- if (!fs2.existsSync(configPath)) return;
705
- const config = await fs2.readJson(configPath);
706
- config.installedComponents = config.installedComponents ?? {};
707
- config.installedComponents[componentData.id] = {
708
- id: componentData.id,
709
- version: componentData.version ?? null,
710
- installedAt: (/* @__PURE__ */ new Date()).toISOString()
711
- };
712
- await fs2.writeJson(configPath, config, { spaces: 2 });
1158
+ if (options.path) project.resolveInRoot(options.path);
713
1159
  }
714
1160
  async function handlePackageDependencies(componentData, options = {}) {
715
1161
  const allDependencies = /* @__PURE__ */ new Set();
@@ -724,32 +1170,36 @@ async function handlePackageDependencies(componentData, options = {}) {
724
1170
  const forcePackageUpdate = componentData.files.length === 0 && (options.force || options.overwrite);
725
1171
  const missingPackages = forcePackageUpdate ? dependencies : await getMissingPackages(dependencies);
726
1172
  if (missingPackages.length === 0) {
727
- console.log(chalk2.green("\u2705 All required packages are already installed"));
1173
+ console.log(chalk3.green("\u2705 All required packages are already installed"));
728
1174
  return;
729
1175
  }
730
1176
  const packagesToInstall = missingPackages.map(
731
1177
  (pkg) => forcePackageUpdate ? getPackageInstallSpec(pkg, componentData.version) : pkg
732
1178
  );
733
1179
  console.log(
734
- chalk2.yellow(
1180
+ chalk3.yellow(
735
1181
  forcePackageUpdate ? "\n\u{1F4E6} Updating required packages..." : "\n\u{1F4E6} Installing required packages..."
736
1182
  )
737
1183
  );
738
- console.log(chalk2.gray(` ${packagesToInstall.join(", ")}`));
1184
+ console.log(chalk3.gray(` ${packagesToInstall.join(", ")}`));
739
1185
  const packageManager = await detectPackageManager();
740
1186
  try {
741
- const installCommand = `${packageManager} add ${packagesToInstall.join(" ")}`;
742
- console.log(chalk2.blue(` Running: ${installCommand}`));
743
- const { stderr } = await execAsync(installCommand);
744
- if (stderr && !stderr.includes("warning")) {
745
- console.error(chalk2.yellow(` Warning: ${stderr}`));
746
- }
747
- console.log(chalk2.green("\u2705 Packages installed successfully"));
748
- } catch {
749
- console.log(chalk2.yellow("\n\u26A0\uFE0F Could not install packages automatically"));
750
- console.log(chalk2.gray(" Please install them manually:"));
1187
+ validatePackageSpecs(packagesToInstall);
751
1188
  console.log(
752
- chalk2.cyan(` ${packageManager} add ${packagesToInstall.join(" ")}`)
1189
+ chalk3.blue(
1190
+ ` Running: ${packageManager} add ${packagesToInstall.join(" ")}`
1191
+ )
1192
+ );
1193
+ await runPackageManager(packageManager, ["add", ...packagesToInstall], {
1194
+ cwd: process.cwd()
1195
+ });
1196
+ console.log(chalk3.green("\u2705 Packages installed successfully"));
1197
+ } catch (error) {
1198
+ console.log(chalk3.yellow("\n\u26A0\uFE0F Could not install packages automatically"));
1199
+ console.log(chalk3.gray(` ${error.message}`));
1200
+ console.log(chalk3.gray(" Please install them manually:"));
1201
+ console.log(
1202
+ chalk3.cyan(` ${packageManager} add ${packagesToInstall.join(" ")}`)
753
1203
  );
754
1204
  }
755
1205
  }
@@ -760,9 +1210,9 @@ function getPackageInstallSpec(packageName, version) {
760
1210
  return `${packageName}@${version ?? "latest"}`;
761
1211
  }
762
1212
  async function getMissingPackages(packages) {
763
- const packageJsonPath = path2.join(process.cwd(), "package.json");
1213
+ const packageJsonPath = path5.join(process.cwd(), "package.json");
764
1214
  try {
765
- const packageJson2 = await fs2.readJson(packageJsonPath);
1215
+ const packageJson2 = await fs5.readJson(packageJsonPath);
766
1216
  const installedPackages = {
767
1217
  ...packageJson2.dependencies,
768
1218
  ...packageJson2.devDependencies
@@ -773,49 +1223,39 @@ async function getMissingPackages(packages) {
773
1223
  }
774
1224
  }
775
1225
  async function detectPackageManager() {
776
- if (await fs2.pathExists(path2.join(process.cwd(), "pnpm-lock.yaml"))) {
1226
+ if (await fs5.pathExists(path5.join(process.cwd(), "pnpm-lock.yaml"))) {
777
1227
  return "pnpm";
778
1228
  }
779
- if (await fs2.pathExists(path2.join(process.cwd(), "yarn.lock"))) {
1229
+ if (await fs5.pathExists(path5.join(process.cwd(), "yarn.lock"))) {
780
1230
  return "yarn";
781
1231
  }
782
- if (await fs2.pathExists(path2.join(process.cwd(), "package-lock.json"))) {
1232
+ if (await fs5.pathExists(path5.join(process.cwd(), "package-lock.json"))) {
783
1233
  return "npm";
784
1234
  }
785
- if (await fs2.pathExists(path2.join(process.cwd(), "bun.lockb"))) {
1235
+ if (await fs5.pathExists(path5.join(process.cwd(), "bun.lockb"))) {
786
1236
  return "bun";
787
1237
  }
788
1238
  return "pnpm";
789
1239
  }
790
- async function showUsageExample(componentData) {
791
- const config = await loadConfig();
792
- console.log(chalk2.cyan("\n\u{1F4A1} Usage:"));
1240
+ function showUsageExample(componentData, config) {
1241
+ console.log(chalk3.cyan("\n\u{1F4A1} Usage:"));
793
1242
  if (componentData.files.length === 0) {
794
1243
  const packageName = componentData.packageDependencies?.find(
795
1244
  (dep) => dep.startsWith("@foundrykit/")
796
1245
  );
797
1246
  if (packageName) {
798
- console.log(chalk2.gray(`import { ... } from "${packageName}"`));
1247
+ console.log(chalk3.gray(`import { ... } from "${packageName}"`));
799
1248
  }
800
1249
  return;
801
1250
  }
802
1251
  const componentName = componentData.name.replace(/\s+/g, "");
803
1252
  const importPath = getImportPath(componentData, config);
804
- console.log(chalk2.gray(`import { ${componentName} } from "${importPath}"`));
1253
+ console.log(chalk3.gray(`import { ${componentName} } from "${importPath}"`));
805
1254
  if (componentData.usageExample) {
806
- console.log(chalk2.gray(`
1255
+ console.log(chalk3.gray(`
807
1256
  ${componentData.usageExample}`));
808
1257
  }
809
1258
  }
810
- async function loadConfig() {
811
- const configPath = path2.join(process.cwd(), "foundrykit.config.json");
812
- if (!fs2.existsSync(configPath)) {
813
- throw new Error(
814
- 'Configuration file not found. Run "foundrykit init" first.'
815
- );
816
- }
817
- return fs2.readJson(configPath);
818
- }
819
1259
  function transformImportsForConfig(content, config) {
820
1260
  let transformed = content;
821
1261
  const importPaths = getConfiguredImportPaths(config);
@@ -1011,22 +1451,22 @@ function getInstalledComponentExportMap(config, category) {
1011
1451
  if (!categoryPath) {
1012
1452
  return exportMap;
1013
1453
  }
1014
- const absoluteCategoryPath = path2.resolve(
1454
+ const absoluteCategoryPath = path5.resolve(
1015
1455
  process.cwd(),
1016
1456
  normalizeConfigPath(categoryPath)
1017
1457
  );
1018
- if (!fs2.existsSync(absoluteCategoryPath)) {
1458
+ if (!fs5.existsSync(absoluteCategoryPath)) {
1019
1459
  return exportMap;
1020
1460
  }
1021
- for (const entry of fs2.readdirSync(absoluteCategoryPath, {
1461
+ for (const entry of fs5.readdirSync(absoluteCategoryPath, {
1022
1462
  withFileTypes: true
1023
1463
  })) {
1024
1464
  if (!entry.isDirectory()) continue;
1025
1465
  const componentPath = entry.name;
1026
- const componentDir = path2.join(absoluteCategoryPath, componentPath);
1027
- const entryFiles = ["index.tsx", "index.ts", "index.jsx", "index.js"].map((fileName) => path2.join(componentDir, fileName)).filter((filePath) => fs2.existsSync(filePath));
1466
+ const componentDir = path5.join(absoluteCategoryPath, componentPath);
1467
+ const entryFiles = ["index.tsx", "index.ts", "index.jsx", "index.js"].map((fileName) => path5.join(componentDir, fileName)).filter((filePath) => fs5.existsSync(filePath));
1028
1468
  for (const filePath of entryFiles) {
1029
- const content = fs2.readFileSync(filePath, "utf-8");
1469
+ const content = fs5.readFileSync(filePath, "utf-8");
1030
1470
  for (const exportName of parseExportNames(content)) {
1031
1471
  exportMap.set(exportName, componentPath);
1032
1472
  }
@@ -1071,34 +1511,34 @@ function resolveComponentPath(originalPath, category, config) {
1071
1511
  return paths.utils || "lib/utils.ts";
1072
1512
  }
1073
1513
  const categoryPath = getConfiguredCategoryPath(config, category) || paths.components;
1074
- const fileName = path2.basename(originalPath);
1075
- const componentName = path2.dirname(originalPath).split("/").pop() || "";
1514
+ const fileName = path5.basename(originalPath);
1515
+ const componentName = path5.dirname(originalPath).split("/").pop() || "";
1076
1516
  if (category === "primitives") {
1077
- return path2.join(categoryPath, componentName, fileName);
1517
+ return path5.join(categoryPath, componentName, fileName);
1078
1518
  } else if (category === "components") {
1079
- return path2.join(paths.components, componentName, fileName);
1519
+ return path5.join(paths.components, componentName, fileName);
1080
1520
  } else if (category === "blocks") {
1081
- return path2.join(
1082
- paths.blocks || path2.join(paths.components, "blocks"),
1521
+ return path5.join(
1522
+ paths.blocks || path5.join(paths.components, "blocks"),
1083
1523
  componentName,
1084
1524
  fileName
1085
1525
  );
1086
1526
  } else if (category === "animations") {
1087
- return path2.join(
1088
- paths.animations || path2.join(paths.components, "animations"),
1527
+ return path5.join(
1528
+ paths.animations || path5.join(paths.components, "animations"),
1089
1529
  componentName,
1090
1530
  fileName
1091
1531
  );
1092
1532
  } else if (category === "maps") {
1093
- return path2.join(
1094
- paths.maps || path2.join(paths.components, "maps"),
1533
+ return path5.join(
1534
+ paths.maps || path5.join(paths.components, "maps"),
1095
1535
  componentName,
1096
1536
  fileName
1097
1537
  );
1098
1538
  } else if (category === "hooks") {
1099
- return path2.join(paths.hooks || "hooks", componentName, fileName);
1539
+ return path5.join(paths.hooks || "hooks", componentName, fileName);
1100
1540
  } else if (category === "packages") {
1101
- return path2.join(paths.components, componentName, fileName);
1541
+ return path5.join(paths.components, componentName, fileName);
1102
1542
  }
1103
1543
  return originalPath;
1104
1544
  }
@@ -1114,7 +1554,7 @@ function getConfiguredCategoryPath(config, category) {
1114
1554
  case "animations":
1115
1555
  return paths.animations;
1116
1556
  case "maps":
1117
- return paths.maps ?? path2.join(paths.components, "maps");
1557
+ return paths.maps ?? path5.join(paths.components, "maps");
1118
1558
  case "hooks":
1119
1559
  return paths.hooks ?? "hooks";
1120
1560
  case "packages":
@@ -1133,8 +1573,8 @@ function getImportPath(componentData, config) {
1133
1573
  maps: "components/maps",
1134
1574
  utils: "lib/utils"
1135
1575
  };
1136
- const componentName = path2.basename(
1137
- path2.dirname(componentData.files[0]?.path || "")
1576
+ const componentName = path5.basename(
1577
+ path5.dirname(componentData.files[0]?.path || "")
1138
1578
  );
1139
1579
  if (componentData.category === "primitives") {
1140
1580
  return `${resolveImportBasePath(paths.primitives, config, {
@@ -1154,7 +1594,7 @@ function getImportPath(componentData, config) {
1154
1594
  })}/${componentName}`;
1155
1595
  } else if (componentData.category === "maps") {
1156
1596
  return `${resolveImportBasePath(
1157
- paths.maps || path2.join(paths.components, "maps"),
1597
+ paths.maps || path5.join(paths.components, "maps"),
1158
1598
  config,
1159
1599
  {
1160
1600
  preferRootAlias: true
@@ -1168,106 +1608,574 @@ function getImportPath(componentData, config) {
1168
1608
  return `@/components/${componentName}`;
1169
1609
  }
1170
1610
 
1171
- // src/commands/doctor.ts
1172
- import path3 from "path";
1173
- import chalk3 from "chalk";
1611
+ // src/commands/connect.ts
1174
1612
  import { Command as Command2 } from "commander";
1175
- import fs3 from "fs-extra";
1176
- function doctorCommand() {
1177
- return new Command2("doctor").description("Check project health and configuration").action(async () => {
1178
- console.log(chalk3.blue("\u{1F50D} Checking project health..."));
1179
- const results = [];
1180
- const packageJsonPath = path3.join(process.cwd(), "package.json");
1181
- const hasPackageJson = await fs3.pathExists(packageJsonPath);
1182
- results.push({
1183
- label: "package.json",
1184
- ok: hasPackageJson,
1185
- detail: hasPackageJson ? "Project manifest found" : "Run this command in a project root"
1186
- });
1187
- let packageJson2 = null;
1188
- if (hasPackageJson) {
1189
- packageJson2 = await fs3.readJson(packageJsonPath);
1190
- }
1191
- const hasNext = !!packageJson2 && !!(packageJson2.dependencies?.next || packageJson2.devDependencies?.next);
1192
- results.push({
1193
- label: "Framework",
1194
- ok: hasNext,
1195
- detail: hasNext ? "Next.js dependency detected" : "FoundryKit currently expects a Next.js project"
1613
+ import inquirer3 from "inquirer";
1614
+
1615
+ // src/lib/hub/credentials.ts
1616
+ import { randomBytes as randomBytes2 } from "crypto";
1617
+ import os2 from "os";
1618
+ import path6 from "path";
1619
+ import fs6 from "fs-extra";
1620
+
1621
+ // src/lib/hub/errors.ts
1622
+ var SESSION_EXPIRED = "Session expired \u2014 run `foundrykit login`";
1623
+ var HubError = class extends Error {
1624
+ constructor(status, code, message) {
1625
+ super(message);
1626
+ this.status = status;
1627
+ this.code = code;
1628
+ this.name = "HubError";
1629
+ }
1630
+ };
1631
+ var unreachable = (hubUrl) => new HubError(
1632
+ 0,
1633
+ "unreachable",
1634
+ `Can't reach the hub at ${hubUrl}. Is it running?`
1635
+ );
1636
+ var unexpectedResponse = (status) => new HubError(status, "internal", "Hub returned an unexpected response");
1637
+
1638
+ // src/lib/hub/credentials.ts
1639
+ var CredentialsError = class extends Error {
1640
+ constructor(file) {
1641
+ super(`${file} is not valid JSON. Delete it and run \`foundrykit login\`.`);
1642
+ this.name = "CredentialsError";
1643
+ }
1644
+ };
1645
+ function normalizeHubUrl(url) {
1646
+ const invalid2 = () => new HubError(
1647
+ 0,
1648
+ "invalid_request",
1649
+ `Invalid hub URL: ${url.replace(/\/\/[^/]*@/, "//")}`
1650
+ );
1651
+ let u;
1652
+ try {
1653
+ u = new URL(url.trim());
1654
+ } catch {
1655
+ throw invalid2();
1656
+ }
1657
+ if (u.protocol !== "http:" && u.protocol !== "https:" || u.username || u.password)
1658
+ throw invalid2();
1659
+ return `${u.protocol}//${u.host}${u.pathname}`.replace(/\/+$/, "");
1660
+ }
1661
+ function resolveHubUrl(opts) {
1662
+ return normalizeHubUrl(
1663
+ opts.flag || process.env.FOUNDRYKIT_HUB_URL || opts.settings?.hub?.url || DEFAULT_HUB_URL
1664
+ );
1665
+ }
1666
+ function credentialsPath(home) {
1667
+ return path6.join(home ?? os2.homedir(), CACHE_DIR, CREDENTIALS_FILE);
1668
+ }
1669
+ async function readAll(file) {
1670
+ let raw;
1671
+ try {
1672
+ raw = await fs6.readFile(file, "utf8");
1673
+ } catch (error) {
1674
+ if (error.code === "ENOENT") return {};
1675
+ throw error;
1676
+ }
1677
+ try {
1678
+ const parsed = JSON.parse(raw);
1679
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
1680
+ return parsed;
1681
+ } catch {
1682
+ }
1683
+ throw new CredentialsError(file);
1684
+ }
1685
+ async function writeAll(file, all) {
1686
+ const dir = path6.dirname(file);
1687
+ await fs6.ensureDir(dir, { mode: 448 });
1688
+ await fs6.chmod(dir, 448);
1689
+ const tmp = `${file}.${randomBytes2(4).toString("hex")}.tmp`;
1690
+ try {
1691
+ await fs6.writeFile(tmp, `${JSON.stringify(all, null, 2)}
1692
+ `, {
1693
+ mode: 384
1196
1694
  });
1197
- const configPath = path3.join(process.cwd(), "foundrykit.config.json");
1198
- const hasConfig = await fs3.pathExists(configPath);
1199
- results.push({
1200
- label: "FoundryKit config",
1201
- ok: hasConfig,
1202
- detail: hasConfig ? "foundrykit.config.json found" : 'Run "foundrykit init" to create the configuration file'
1695
+ await fs6.rename(tmp, file);
1696
+ } catch (error) {
1697
+ await fs6.remove(tmp);
1698
+ throw error;
1699
+ }
1700
+ await fs6.chmod(file, 384);
1701
+ }
1702
+ async function readCredential(hubUrl, home) {
1703
+ const all = await readAll(credentialsPath(home));
1704
+ const entry = all[normalizeHubUrl(hubUrl)];
1705
+ return typeof entry?.token === "string" ? entry : null;
1706
+ }
1707
+ async function saveCredential(hubUrl, cred, home) {
1708
+ const file = credentialsPath(home);
1709
+ const all = await readAll(file);
1710
+ all[normalizeHubUrl(hubUrl)] = cred;
1711
+ await writeAll(file, all);
1712
+ }
1713
+ async function deleteCredential(hubUrl, home) {
1714
+ const file = credentialsPath(home);
1715
+ const all = await readAll(file);
1716
+ const key = normalizeHubUrl(hubUrl);
1717
+ if (!(key in all)) return false;
1718
+ delete all[key];
1719
+ await writeAll(file, all);
1720
+ return true;
1721
+ }
1722
+
1723
+ // src/lib/hub/client.ts
1724
+ var isTimeout = (e) => e?.name === "TimeoutError";
1725
+ var timedOut = (hubUrl) => new HubError(0, "timeout", `The hub at ${hubUrl} didn't answer in time.`);
1726
+ async function hubFetch(hubUrl, token, method, path12, body, opts = {}) {
1727
+ let res;
1728
+ try {
1729
+ res = await fetch(`${hubUrl}${path12}`, {
1730
+ method,
1731
+ // A 307/308 would resend the body (tokens, secrets) to wherever it points.
1732
+ redirect: "error",
1733
+ ...opts.timeoutMs && { signal: AbortSignal.timeout(opts.timeoutMs) },
1734
+ headers: {
1735
+ accept: "application/json",
1736
+ ...body !== void 0 && { "content-type": "application/json" },
1737
+ ...token && { authorization: `Bearer ${token}` }
1738
+ },
1739
+ body: body === void 0 ? void 0 : JSON.stringify(body)
1203
1740
  });
1204
- let config = null;
1205
- if (hasConfig) {
1206
- try {
1207
- config = await loadConfig();
1208
- const hasRequiredPaths = !!config.paths?.utils && !!config.paths?.primitives && !!config.paths?.components && !!config.paths?.blocks && !!config.paths?.animations;
1209
- results.push({
1210
- label: "Config shape",
1211
- ok: hasRequiredPaths,
1212
- detail: hasRequiredPaths ? "Required install paths are configured" : "Configuration is missing one or more required install paths"
1213
- });
1214
- const registryUrl = config.registry || DEFAULT_REGISTRY_URL;
1215
- try {
1216
- const response = await fetch(`${registryUrl}/registry`, {
1217
- headers: { Accept: "application/json" }
1218
- });
1219
- results.push({
1220
- label: "Registry",
1221
- ok: response.ok,
1222
- detail: response.ok ? `Registry reachable at ${registryUrl}` : `Registry returned ${response.status} ${response.statusText}`
1223
- });
1224
- } catch (error) {
1225
- results.push({
1226
- label: "Registry",
1227
- ok: false,
1228
- detail: `Unable to reach ${registryUrl}: ${error instanceof Error ? error.message : "Unknown error"}`
1229
- });
1230
- }
1231
- } catch (error) {
1232
- results.push({
1233
- label: "Config shape",
1234
- ok: false,
1235
- detail: `Failed to read foundrykit.config.json: ${error instanceof Error ? error.message : "Unknown error"}`
1236
- });
1237
- }
1238
- }
1239
- for (const result of results) {
1240
- const icon = result.ok ? chalk3.green("\u2705") : chalk3.red("\u274C");
1241
- console.log(`${icon} ${result.label}: ${result.detail}`);
1242
- }
1243
- const hasFailures = results.some((result) => !result.ok);
1741
+ } catch (e) {
1742
+ throw isTimeout(e) ? timedOut(hubUrl) : unreachable(hubUrl);
1743
+ }
1744
+ if (res.status === 401)
1745
+ throw new HubError(401, "unauthorized", SESSION_EXPIRED);
1746
+ let json;
1747
+ try {
1748
+ json = await res.json();
1749
+ } catch (e) {
1750
+ if (isTimeout(e)) throw timedOut(hubUrl);
1751
+ json = void 0;
1752
+ }
1753
+ if (!res.ok) {
1754
+ const e = json?.error;
1755
+ if (e && typeof e.code === "string" && typeof e.message === "string")
1756
+ throw new HubError(res.status, e.code, e.message);
1757
+ throw new HubError(res.status, "internal", `Hub returned ${res.status}`);
1758
+ }
1759
+ if (json === void 0)
1760
+ throw new HubError(res.status, "internal", `Hub returned ${res.status}`);
1761
+ return json;
1762
+ }
1763
+ async function requireSignedIn(hubUrl, home) {
1764
+ const cred = await readCredential(hubUrl, home);
1765
+ if (!cred)
1766
+ throw new HubError(
1767
+ 401,
1768
+ "unauthorized",
1769
+ `Not signed in to ${hubUrl}. Run \`foundrykit login\`.`
1770
+ );
1771
+ return cred;
1772
+ }
1773
+
1774
+ // src/lib/hub/io.ts
1775
+ import chalk4 from "chalk";
1776
+ function defaultIO() {
1777
+ return {
1778
+ out: (s) => console.log(s),
1779
+ err: (s) => process.stderr.write(`${s}
1780
+ `),
1781
+ isTTY: Boolean(process.stdin.isTTY && process.stdout.isTTY),
1782
+ stdin: process.stdin,
1783
+ cwd: process.cwd()
1784
+ };
1785
+ }
1786
+ function fail(io, json, e) {
1787
+ let code = "internal";
1788
+ let message = e instanceof Error ? e.message : String(e);
1789
+ if (e instanceof HubError) code = e.code;
1790
+ else if (e instanceof ProjectError || e instanceof SettingsError)
1791
+ code = "invalid_request";
1792
+ else if (!(e instanceof CredentialsError))
1793
+ message = message.split("\n")[0] ?? "";
1794
+ io.out(
1795
+ json ? JSON.stringify({ error: { code, message } }) : chalk4.red(message)
1796
+ );
1797
+ return 1;
1798
+ }
1799
+ async function hubUrlFor(flag, io) {
1800
+ return (await resolveHub(flag, io)).url;
1801
+ }
1802
+ async function resolveHub(flag, io) {
1803
+ let hub = { url: resolveHubUrl({ flag }), fromSettings: false };
1804
+ if (!flag && !process.env.FOUNDRYKIT_HUB_URL) {
1805
+ let settings;
1806
+ try {
1807
+ settings = (await loadProject(io.cwd, { readOnly: true })).settings;
1808
+ } catch (e) {
1809
+ if (!(e instanceof ProjectError)) throw e;
1810
+ }
1811
+ hub = {
1812
+ url: resolveHubUrl({ settings }),
1813
+ fromSettings: Boolean(settings?.hub?.url)
1814
+ };
1815
+ }
1816
+ warnIfPlainHttp(hub.url, io);
1817
+ return hub;
1818
+ }
1819
+ var LOOPBACK = ["localhost", "127.0.0.1", "[::1]"];
1820
+ function warnIfPlainHttp(url, io) {
1821
+ let u;
1822
+ try {
1823
+ u = new URL(url);
1824
+ } catch {
1825
+ return;
1826
+ }
1827
+ if (u.protocol === "http:" && !LOOPBACK.includes(u.hostname))
1828
+ io.err(`Warning: ${url} is not https, so your token is sent unencrypted.`);
1829
+ }
1830
+
1831
+ // src/commands/connect.ts
1832
+ var SERVICE_CONFIG = {
1833
+ github: [{ key: "owner", required: false, default: "umi-labs" }],
1834
+ dokploy: [
1835
+ { key: "baseUrl", required: true },
1836
+ { key: "serverId", required: true },
1837
+ { key: "githubProviderId", required: true }
1838
+ ],
1839
+ sentry: [
1840
+ { key: "org", required: true },
1841
+ { key: "team", required: true },
1842
+ { key: "baseUrl", required: false, default: "https://sentry.io" }
1843
+ ]
1844
+ };
1845
+ var SERVICES = Object.keys(SERVICE_CONFIG);
1846
+ var REVOKE_HINT = "Revoke it in the hub (Admin \u203A Connections or Settings).";
1847
+ var invalid = (message) => new HubError(0, "invalid_request", message);
1848
+ function parseConfigPairs(pairs) {
1849
+ const config = {};
1850
+ for (const pair of pairs) {
1851
+ const i = pair.indexOf("=");
1852
+ if (i < 1) throw invalid("Use --config key=value");
1853
+ config[pair.slice(0, i)] = pair.slice(i + 1);
1854
+ }
1855
+ return config;
1856
+ }
1857
+ async function readToken(stdin) {
1858
+ let raw = "";
1859
+ for await (const chunk of stdin) raw += chunk.toString();
1860
+ const token = raw.trim();
1861
+ if (!token) throw invalid("No token on stdin.");
1862
+ return token;
1863
+ }
1864
+ async function runConnect(service, opts, io, deps) {
1865
+ let secret = "";
1866
+ try {
1867
+ if (!SERVICES.includes(service))
1868
+ throw invalid(
1869
+ `Unknown service ${service}. Use github, dokploy or sentry.`
1870
+ );
1871
+ const svc = service;
1872
+ const config = parseConfigPairs(opts.config);
1873
+ const missing = SERVICE_CONFIG[svc].filter((f) => f.required && !config[f.key]).map((f) => f.key);
1874
+ const interactive = io.isTTY && !opts.tokenStdin && !opts.json;
1875
+ if (opts.tokenStdin && io.stdin.isTTY)
1876
+ throw invalid(
1877
+ "--token-stdin needs the token piped in (your terminal would show it). Pipe it, or leave out --token-stdin to be asked."
1878
+ );
1879
+ if (!interactive) {
1880
+ if (!opts.tokenStdin)
1881
+ throw invalid(
1882
+ io.isTTY ? "Pass --token-stdin with --json." : "Pass --token-stdin when not in a terminal."
1883
+ );
1884
+ if (missing.length) throw invalid(`Missing --config ${missing[0]}=`);
1885
+ }
1886
+ const { url: hubUrl, fromSettings } = await resolveHub(void 0, io);
1887
+ const { token } = await requireSignedIn(hubUrl, io.home);
1888
+ io.err(
1889
+ `Sending the token to ${hubUrl}${fromSettings ? " (from foundrykit.json)" : ""}`
1890
+ );
1891
+ let owner = opts.owner ?? (svc === "github" ? "me" : "umi");
1892
+ if (interactive) {
1893
+ const required = (v) => Boolean(v.trim()) || "Required";
1894
+ const answers = await deps.prompt([
1895
+ ...opts.owner ? [] : [
1896
+ {
1897
+ type: "input",
1898
+ name: "owner",
1899
+ message: "Owner (me, umi, <org> or <org>/<project>):",
1900
+ default: owner,
1901
+ validate: required
1902
+ }
1903
+ ],
1904
+ ...missing.map((key) => ({
1905
+ type: "input",
1906
+ name: key,
1907
+ message: `${key}:`,
1908
+ validate: required
1909
+ })),
1910
+ {
1911
+ type: "password",
1912
+ name: "token",
1913
+ message: `${svc} token:`,
1914
+ mask: "*",
1915
+ validate: required
1916
+ }
1917
+ ]);
1918
+ if (!opts.owner) owner = String(answers.owner).trim();
1919
+ for (const key of missing) config[key] = String(answers[key]).trim();
1920
+ secret = String(answers.token).trim();
1921
+ } else {
1922
+ secret = await readToken(io.stdin);
1923
+ }
1924
+ const body = {
1925
+ service: svc,
1926
+ owner,
1927
+ ...opts.label && { label: opts.label },
1928
+ ...Object.keys(config).length && { config },
1929
+ secret
1930
+ };
1931
+ const res = await hubFetch(
1932
+ hubUrl,
1933
+ token,
1934
+ "POST",
1935
+ "/api/cli/connections",
1936
+ body
1937
+ );
1938
+ const c = res.connection;
1939
+ io.out(
1940
+ opts.json ? JSON.stringify(res) : `Connected ${c.service} for ${c.owner} (${c.label}) on ${hubUrl}.`
1941
+ );
1942
+ return 0;
1943
+ } catch (e) {
1944
+ if (e instanceof HubError) {
1945
+ if (secret) e.message = e.message.split(secret).join("***");
1946
+ if (e.code === "conflict") e.message = `${e.message} ${REVOKE_HINT}`;
1947
+ }
1948
+ return fail(io, opts.json, e);
1949
+ }
1950
+ }
1951
+ async function runConnections(opts, io, cwd) {
1952
+ try {
1953
+ let ref;
1954
+ try {
1955
+ ref = (await loadProject(cwd, { readOnly: true })).settings.hub?.project;
1956
+ } catch (e) {
1957
+ if (!(e instanceof ProjectError)) throw e;
1958
+ }
1959
+ const hubUrl = await hubUrlFor(void 0, { ...io, cwd });
1960
+ const { token } = await requireSignedIn(hubUrl, io.home);
1961
+ const res = await hubFetch(
1962
+ hubUrl,
1963
+ token,
1964
+ "GET",
1965
+ `/api/cli/connections${ref ? `?project=${encodeURIComponent(ref)}` : ""}`
1966
+ );
1967
+ if (opts.json) {
1968
+ io.out(JSON.stringify(res));
1969
+ return 0;
1970
+ }
1971
+ if (!res.connections.length && !res.resolved)
1972
+ io.out("No connections. Run `foundrykit connect <service>`.");
1973
+ for (const c of res.connections) {
1974
+ const used = c.lastUsedAt ? c.lastUsedAt.slice(0, 10) : "never";
1975
+ const mark = res.resolved?.[c.service] === c.id ? ` \u2190 used for ${ref}` : "";
1976
+ io.out(`${c.service} ${c.owner} ${c.label} last used ${used}${mark}`);
1977
+ }
1978
+ for (const svc of SERVICES)
1979
+ if (res.resolved?.[svc] === null)
1980
+ io.out(`${svc}: none \u2014 run foundrykit connect ${svc}`);
1981
+ return 0;
1982
+ } catch (e) {
1983
+ return fail(io, opts.json, e);
1984
+ }
1985
+ }
1986
+ function connectCommand() {
1987
+ return new Command2("connect").description("Connect a service (github, dokploy, sentry) on the hub").argument("<service>", "github, dokploy or sentry").option("--owner <owner>", "me, umi, <org> or <org>/<project>").option("--label <label>", "label shown in the hub").option("--token-stdin", "read the token from stdin").option("--config <k=v...>", "service config, e.g. --config org=umi").option("--json", "print JSON").action(
1988
+ async (service, opts) => {
1989
+ process.exitCode = await runConnect(
1990
+ service,
1991
+ {
1992
+ owner: opts.owner,
1993
+ label: opts.label,
1994
+ tokenStdin: Boolean(opts.tokenStdin),
1995
+ config: opts.config ?? [],
1996
+ json: Boolean(opts.json)
1997
+ },
1998
+ defaultIO(),
1999
+ { prompt: inquirer3.prompt }
2000
+ );
2001
+ }
2002
+ );
2003
+ }
2004
+ function connectionsCommand() {
2005
+ return new Command2("connections").description("List your hub connections").option("--json", "print JSON").action(async (opts) => {
2006
+ const io = defaultIO();
2007
+ process.exitCode = await runConnections(
2008
+ { json: Boolean(opts.json) },
2009
+ io,
2010
+ io.cwd
2011
+ );
2012
+ });
2013
+ }
2014
+
2015
+ // src/commands/doctor.ts
2016
+ import path7 from "path";
2017
+ import chalk5 from "chalk";
2018
+ import { Command as Command3 } from "commander";
2019
+ import fs7 from "fs-extra";
2020
+ async function collectDoctorChecks(cwd) {
2021
+ const root = findProjectRoot(cwd);
2022
+ const checks = await collectBasicChecks(root ?? cwd);
2023
+ if (!root) {
2024
+ checks.push({
2025
+ name: "FoundryKit config",
2026
+ ok: false,
2027
+ detail: `No ${SETTINGS_FILE} found. Run "foundrykit init" to create it`
2028
+ });
2029
+ return checks;
2030
+ }
2031
+ const hasSettings = await fs7.pathExists(path7.join(root, SETTINGS_FILE));
2032
+ const hasLock = await fs7.pathExists(path7.join(root, LOCK_FILE));
2033
+ const hasLegacy = await fs7.pathExists(path7.join(root, LEGACY_CONFIG_FILE));
2034
+ checks.push({
2035
+ name: "FoundryKit files",
2036
+ ok: hasSettings && hasLock || !hasSettings && hasLegacy,
2037
+ detail: `${!hasSettings && hasLegacy ? "Migration pending: " : ""}${SETTINGS_FILE} ${hasSettings ? "found" : "missing"}, ${LOCK_FILE} ${hasLock ? "found" : "missing"}${hasLegacy ? `, legacy ${LEGACY_CONFIG_FILE} present` : ""}`
2038
+ });
2039
+ let project;
2040
+ try {
2041
+ project = await loadProject(cwd, { readOnly: true });
2042
+ } catch (error) {
2043
+ checks.push({
2044
+ name: "Settings",
2045
+ ok: false,
2046
+ detail: error instanceof SettingsError ? `Invalid setting "${error.key}": ${error.message}` : error instanceof Error ? error.message : String(error)
2047
+ });
2048
+ return checks;
2049
+ }
2050
+ if (project.migration === "pending") {
2051
+ checks.push({
2052
+ name: "Migration",
2053
+ ok: true,
2054
+ detail: `Migration pending: ${LEGACY_CONFIG_FILE} will be converted to ${SETTINGS_FILE} and ${LOCK_FILE} the next time you run add or update`
2055
+ });
2056
+ }
2057
+ checks.push({
2058
+ name: "Settings",
2059
+ ok: true,
2060
+ detail: `Valid${project.warnings.length ? ` (${project.warnings.join("; ")})` : ""}`
2061
+ });
2062
+ const missing = [];
2063
+ const edited = [];
2064
+ const unreadable = [];
2065
+ for (const entry of Object.values(project.lock.components)) {
2066
+ for (const [file, recorded] of Object.entries(entry.files ?? {})) {
2067
+ try {
2068
+ const status = await fileStatus(project.resolveInRoot(file), recorded);
2069
+ if (status === "missing") missing.push(file);
2070
+ if (status === "edited") edited.push(file);
2071
+ } catch (error) {
2072
+ unreadable.push(
2073
+ `${file} (${error instanceof Error ? error.message : String(error)})`
2074
+ );
2075
+ }
2076
+ }
2077
+ }
2078
+ if (unreadable.length) {
2079
+ checks.push({
2080
+ name: "Lock paths",
2081
+ ok: false,
2082
+ detail: `Lock lists files that can't be checked: ${unreadable.join(", ")}`
2083
+ });
2084
+ }
2085
+ checks.push({
2086
+ name: "Tracked files",
2087
+ ok: missing.length === 0,
2088
+ detail: missing.length ? `Lock lists files that no longer exist: ${missing.join(", ")}` : "All files in the lock exist"
2089
+ });
2090
+ if (edited.length) {
2091
+ checks.push({
2092
+ name: "Edited files",
2093
+ ok: true,
2094
+ detail: `Edited since install (update will skip them): ${edited.join(", ")}`
2095
+ });
2096
+ }
2097
+ return checks;
2098
+ }
2099
+ async function collectBasicChecks(cwd) {
2100
+ const results = [];
2101
+ const packageJsonPath = path7.join(cwd, "package.json");
2102
+ const hasPackageJson = await fs7.pathExists(packageJsonPath);
2103
+ results.push({
2104
+ name: "package.json",
2105
+ ok: hasPackageJson,
2106
+ detail: hasPackageJson ? "Project manifest found" : "Run this command in a project root"
2107
+ });
2108
+ const packageJson2 = hasPackageJson ? await fs7.readJson(packageJsonPath) : null;
2109
+ const hasNext = !!(packageJson2?.dependencies?.next || packageJson2?.devDependencies?.next);
2110
+ results.push({
2111
+ name: "Framework",
2112
+ ok: hasNext,
2113
+ detail: hasNext ? "Next.js dependency detected" : "FoundryKit currently expects a Next.js project"
2114
+ });
2115
+ return results;
2116
+ }
2117
+ async function registryCheck(cwd) {
2118
+ let registryUrl;
2119
+ try {
2120
+ registryUrl = resolveRegistryUrl(
2121
+ (await loadProject(cwd, { readOnly: true })).settings
2122
+ );
2123
+ } catch {
2124
+ return null;
2125
+ }
2126
+ try {
2127
+ const response = await fetch(`${registryUrl}/registry`, {
2128
+ headers: { Accept: "application/json" }
2129
+ });
2130
+ return {
2131
+ name: "Registry",
2132
+ ok: response.ok,
2133
+ detail: response.ok ? `Registry reachable at ${registryUrl}` : `Registry returned ${response.status} ${response.statusText}`
2134
+ };
2135
+ } catch (error) {
2136
+ return {
2137
+ name: "Registry",
2138
+ ok: false,
2139
+ detail: `Unable to reach ${registryUrl}: ${error instanceof Error ? error.message : "Unknown error"}`
2140
+ };
2141
+ }
2142
+ }
2143
+ function doctorCommand() {
2144
+ return new Command3("doctor").description("Check project health and configuration").action(async () => {
2145
+ console.log(chalk5.blue("\u{1F50D} Checking project health..."));
2146
+ const results = await collectDoctorChecks(process.cwd());
2147
+ const registry = await registryCheck(process.cwd());
2148
+ if (registry) results.push(registry);
2149
+ for (const result of results) {
2150
+ const icon = result.ok ? chalk5.green("\u2705") : chalk5.red("\u274C");
2151
+ console.log(`${icon} ${result.name}: ${result.detail}`);
2152
+ }
2153
+ const hasFailures = results.some((result) => !result.ok);
1244
2154
  if (hasFailures) {
1245
2155
  console.log(
1246
- chalk3.yellow(
2156
+ chalk5.yellow(
1247
2157
  "\n\u26A0\uFE0F Found issues that should be resolved before continuing."
1248
2158
  )
1249
2159
  );
1250
2160
  process.exit(1);
1251
2161
  }
1252
- console.log(chalk3.green("\n\u2705 All checks passed!"));
2162
+ console.log(chalk5.green("\n\u2705 All checks passed!"));
1253
2163
  });
1254
2164
  }
1255
2165
 
1256
2166
  // src/commands/init.ts
1257
- import { exec as exec2 } from "child_process";
1258
- import path4 from "path";
1259
- import { promisify as promisify2 } from "util";
1260
- import chalk4 from "chalk";
1261
- import { Command as Command3 } from "commander";
1262
- import fs4 from "fs-extra";
1263
- import inquirer2 from "inquirer";
2167
+ import path8 from "path";
2168
+ import chalk6 from "chalk";
2169
+ import { Command as Command4 } from "commander";
2170
+ import fs8 from "fs-extra";
2171
+ import inquirer4 from "inquirer";
1264
2172
  function initCommand() {
1265
- return new Command3("init").description("Initialize FoundryKit in your project").option("-f, --force", "overwrite existing files").option("--skip-install", "skip installing dependencies").option("--skip-prompts", "use default paths without prompting").action(async (options) => {
2173
+ return new Command4("init").description("Initialize FoundryKit in your project").option("-f, --force", "overwrite existing files").option("--skip-install", "skip installing dependencies").option("--skip-prompts", "use default paths without prompting").action(async (options) => {
1266
2174
  try {
1267
- console.log(chalk4.blue("\u{1F680} Initializing FoundryKit..."));
2175
+ console.log(chalk6.blue("\u{1F680} Initializing FoundryKit..."));
1268
2176
  await validateProject2();
1269
2177
  if (!options.force && await isFoundryKitInitialized()) {
1270
- const { shouldContinue } = await inquirer2.prompt([
2178
+ const { shouldContinue } = await inquirer4.prompt([
1271
2179
  {
1272
2180
  type: "confirm",
1273
2181
  name: "shouldContinue",
@@ -1276,13 +2184,13 @@ function initCommand() {
1276
2184
  }
1277
2185
  ]);
1278
2186
  if (!shouldContinue) {
1279
- console.log(chalk4.yellow("\u274C Initialization cancelled."));
2187
+ console.log(chalk6.yellow("\u274C Initialization cancelled."));
1280
2188
  return;
1281
2189
  }
1282
2190
  }
1283
2191
  const projectStructure = await detectProjectStructure();
1284
2192
  console.log(
1285
- chalk4.gray(
2193
+ chalk6.gray(
1286
2194
  `Detected project structure: ${projectStructure.hasSrc ? "src/" : "root"} based`
1287
2195
  )
1288
2196
  );
@@ -1304,40 +2212,40 @@ function initCommand() {
1304
2212
  await createDirectories(pathConfig);
1305
2213
  await createExampleFiles(pathConfig, projectStructure);
1306
2214
  await updatePackageScripts();
1307
- console.log(chalk4.green("\n\u2705 FoundryKit initialized successfully!"));
1308
- console.log(chalk4.cyan("\n\u{1F4E6} Next steps:"));
2215
+ console.log(chalk6.green("\n\u2705 FoundryKit initialized successfully!"));
2216
+ console.log(chalk6.cyan("\n\u{1F4E6} Next steps:"));
1309
2217
  console.log(
1310
- chalk4.gray(
2218
+ chalk6.gray(
1311
2219
  " 1. Add a component: pnpm dlx @foundrykit/cli add hero-minimal"
1312
2220
  )
1313
2221
  );
1314
2222
  console.log(
1315
- chalk4.gray(
2223
+ chalk6.gray(
1316
2224
  " 2. List available components: pnpm dlx @foundrykit/cli list"
1317
2225
  )
1318
2226
  );
1319
2227
  console.log(
1320
- chalk4.gray(
2228
+ chalk6.gray(
1321
2229
  " 3. Check out the docs: https://foundry-docs.umiflow.com"
1322
2230
  )
1323
2231
  );
1324
2232
  } catch (error) {
1325
- console.error(chalk4.red("\u274C Failed to initialize FoundryKit:"));
2233
+ console.error(chalk6.red("\u274C Failed to initialize FoundryKit:"));
1326
2234
  console.error(
1327
- chalk4.red(error instanceof Error ? error.message : String(error))
2235
+ chalk6.red(error instanceof Error ? error.message : String(error))
1328
2236
  );
1329
2237
  process.exit(1);
1330
2238
  }
1331
2239
  });
1332
2240
  }
1333
2241
  async function validateProject2() {
1334
- const packageJsonPath = path4.join(process.cwd(), "package.json");
1335
- if (!fs4.existsSync(packageJsonPath)) {
2242
+ const packageJsonPath = path8.join(process.cwd(), "package.json");
2243
+ if (!fs8.existsSync(packageJsonPath)) {
1336
2244
  throw new Error(
1337
2245
  "No package.json found. Please run this command in a project directory."
1338
2246
  );
1339
2247
  }
1340
- const packageJson2 = await fs4.readJson(packageJsonPath);
2248
+ const packageJson2 = await fs8.readJson(packageJsonPath);
1341
2249
  const deps = {
1342
2250
  ...packageJson2.dependencies,
1343
2251
  ...packageJson2.devDependencies
@@ -1347,14 +2255,16 @@ async function validateProject2() {
1347
2255
  "Next.js not detected. FoundryKit currently requires Next.js."
1348
2256
  );
1349
2257
  }
1350
- console.log(chalk4.green("\u2705 Next.js project detected"));
2258
+ console.log(chalk6.green("\u2705 Next.js project detected"));
1351
2259
  }
1352
2260
  async function isFoundryKitInitialized() {
1353
- return fs4.existsSync(path4.join(process.cwd(), "foundrykit.config.json"));
2261
+ return [SETTINGS_FILE, LEGACY_CONFIG_FILE].some(
2262
+ (f) => fs8.existsSync(path8.join(process.cwd(), f))
2263
+ );
1354
2264
  }
1355
2265
  async function detectProjectStructure() {
1356
2266
  const cwd = process.cwd();
1357
- const hasSrc = fs4.existsSync(path4.join(cwd, "src"));
2267
+ const hasSrc = fs8.existsSync(path8.join(cwd, "src"));
1358
2268
  let baseDir = "./";
1359
2269
  let appPath;
1360
2270
  let componentsPath;
@@ -1362,48 +2272,48 @@ async function detectProjectStructure() {
1362
2272
  let hooksPath;
1363
2273
  let stylesPath;
1364
2274
  if (hasSrc) {
1365
- const srcHasApp = fs4.existsSync(path4.join(cwd, "src/app"));
2275
+ const srcHasApp = fs8.existsSync(path8.join(cwd, "src/app"));
1366
2276
  if (srcHasApp) {
1367
2277
  baseDir = "./src/";
1368
2278
  appPath = "./src/app";
1369
2279
  } else {
1370
- const rootHasApp = fs4.existsSync(path4.join(cwd, "app"));
2280
+ const rootHasApp = fs8.existsSync(path8.join(cwd, "app"));
1371
2281
  if (rootHasApp) {
1372
2282
  appPath = "./app";
1373
2283
  baseDir = "./src/";
1374
2284
  }
1375
2285
  }
1376
- if (fs4.existsSync(path4.join(cwd, "src/components"))) {
2286
+ if (fs8.existsSync(path8.join(cwd, "src/components"))) {
1377
2287
  componentsPath = "./src/components";
1378
2288
  }
1379
- if (fs4.existsSync(path4.join(cwd, "src/lib"))) {
2289
+ if (fs8.existsSync(path8.join(cwd, "src/lib"))) {
1380
2290
  libPath = "./src/lib";
1381
2291
  }
1382
- if (fs4.existsSync(path4.join(cwd, "src/hooks"))) {
2292
+ if (fs8.existsSync(path8.join(cwd, "src/hooks"))) {
1383
2293
  hooksPath = "./src/hooks";
1384
2294
  }
1385
- if (fs4.existsSync(path4.join(cwd, "src/styles"))) {
2295
+ if (fs8.existsSync(path8.join(cwd, "src/styles"))) {
1386
2296
  stylesPath = "./src/styles";
1387
2297
  }
1388
2298
  } else {
1389
- const hasApp = fs4.existsSync(path4.join(cwd, "app"));
2299
+ const hasApp = fs8.existsSync(path8.join(cwd, "app"));
1390
2300
  if (hasApp) {
1391
2301
  appPath = "./app";
1392
2302
  }
1393
- if (fs4.existsSync(path4.join(cwd, "components"))) {
2303
+ if (fs8.existsSync(path8.join(cwd, "components"))) {
1394
2304
  componentsPath = "./components";
1395
2305
  }
1396
- if (fs4.existsSync(path4.join(cwd, "lib"))) {
2306
+ if (fs8.existsSync(path8.join(cwd, "lib"))) {
1397
2307
  libPath = "./lib";
1398
2308
  }
1399
- if (fs4.existsSync(path4.join(cwd, "hooks"))) {
2309
+ if (fs8.existsSync(path8.join(cwd, "hooks"))) {
1400
2310
  hooksPath = "./hooks";
1401
2311
  }
1402
- if (fs4.existsSync(path4.join(cwd, "styles"))) {
2312
+ if (fs8.existsSync(path8.join(cwd, "styles"))) {
1403
2313
  stylesPath = "./styles";
1404
2314
  }
1405
2315
  }
1406
- const isTypeScript = fs4.existsSync(path4.join(cwd, "tsconfig.json"));
2316
+ const isTypeScript = fs8.existsSync(path8.join(cwd, "tsconfig.json"));
1407
2317
  const packageManager = detectPackageManager2();
1408
2318
  return {
1409
2319
  hasSrc,
@@ -1426,43 +2336,43 @@ async function detectProjectStructure() {
1426
2336
  async function getPathConfiguration(structure, skipPrompts) {
1427
2337
  const ext = structure.isTypeScript ? ".ts" : ".js";
1428
2338
  const defaults = {
1429
- utils: path4.join(
1430
- structure.libPath || path4.join(structure.baseDir, "lib"),
2339
+ utils: path8.join(
2340
+ structure.libPath || path8.join(structure.baseDir, "lib"),
1431
2341
  `utils${ext}`
1432
2342
  ),
1433
- primitives: path4.join(
1434
- structure.componentsPath || path4.join(structure.baseDir, "components"),
2343
+ primitives: path8.join(
2344
+ structure.componentsPath || path8.join(structure.baseDir, "components"),
1435
2345
  "primitives"
1436
2346
  ),
1437
- components: path4.join(
1438
- structure.componentsPath || path4.join(structure.baseDir, "components"),
2347
+ components: path8.join(
2348
+ structure.componentsPath || path8.join(structure.baseDir, "components"),
1439
2349
  "ui"
1440
2350
  ),
1441
- blocks: path4.join(
1442
- structure.componentsPath || path4.join(structure.baseDir, "components"),
2351
+ blocks: path8.join(
2352
+ structure.componentsPath || path8.join(structure.baseDir, "components"),
1443
2353
  "blocks"
1444
2354
  ),
1445
- maps: path4.join(
1446
- structure.componentsPath || path4.join(structure.baseDir, "components"),
2355
+ maps: path8.join(
2356
+ structure.componentsPath || path8.join(structure.baseDir, "components"),
1447
2357
  "maps"
1448
2358
  ),
1449
- animations: path4.join(
1450
- structure.componentsPath || path4.join(structure.baseDir, "components"),
2359
+ animations: path8.join(
2360
+ structure.componentsPath || path8.join(structure.baseDir, "components"),
1451
2361
  "animations"
1452
2362
  ),
1453
- hooks: structure.hooksPath || path4.join(structure.baseDir, "hooks"),
1454
- lib: structure.libPath || path4.join(structure.baseDir, "lib"),
1455
- styles: path4.join(structure.appPath || structure.baseDir, "globals.css")
2363
+ hooks: structure.hooksPath || path8.join(structure.baseDir, "hooks"),
2364
+ lib: structure.libPath || path8.join(structure.baseDir, "lib"),
2365
+ styles: path8.join(structure.appPath || structure.baseDir, "globals.css")
1456
2366
  };
1457
2367
  if (structure.appPath) {
1458
2368
  const possibleStylePaths = [
1459
- path4.join(structure.appPath, "globals.css"),
1460
- path4.join(structure.appPath, "global.css"),
1461
- path4.join(structure.stylesPath || "", "globals.css"),
1462
- path4.join(structure.stylesPath || "", "global.css")
2369
+ path8.join(structure.appPath, "globals.css"),
2370
+ path8.join(structure.appPath, "global.css"),
2371
+ path8.join(structure.stylesPath || "", "globals.css"),
2372
+ path8.join(structure.stylesPath || "", "global.css")
1463
2373
  ];
1464
2374
  for (const stylePath of possibleStylePaths) {
1465
- if (fs4.existsSync(path4.join(process.cwd(), stylePath))) {
2375
+ if (fs8.existsSync(path8.join(process.cwd(), stylePath))) {
1466
2376
  defaults.styles = stylePath;
1467
2377
  break;
1468
2378
  }
@@ -1470,15 +2380,15 @@ async function getPathConfiguration(structure, skipPrompts) {
1470
2380
  }
1471
2381
  if (skipPrompts) {
1472
2382
  console.log(
1473
- chalk4.gray("Using smart defaults based on project structure...")
2383
+ chalk6.gray("Using smart defaults based on project structure...")
1474
2384
  );
1475
2385
  return defaults;
1476
2386
  }
1477
- console.log(chalk4.blue("\n\u{1F4C2} Configure installation paths:"));
2387
+ console.log(chalk6.blue("\n\u{1F4C2} Configure installation paths:"));
1478
2388
  console.log(
1479
- chalk4.gray("Press enter to use the default value shown in parentheses\n")
2389
+ chalk6.gray("Press enter to use the default value shown in parentheses\n")
1480
2390
  );
1481
- const answers = await inquirer2.prompt([
2391
+ const answers = await inquirer4.prompt([
1482
2392
  {
1483
2393
  type: "input",
1484
2394
  name: "utils",
@@ -1541,9 +2451,8 @@ async function getPathConfiguration(structure, skipPrompts) {
1541
2451
  return answers;
1542
2452
  }
1543
2453
  async function installDependencies() {
1544
- console.log(chalk4.blue("\u{1F4E6} Installing dependencies..."));
2454
+ console.log(chalk6.blue("\u{1F4E6} Installing dependencies..."));
1545
2455
  const packageManager = detectPackageManager2();
1546
- const execAsync2 = promisify2(exec2);
1547
2456
  const dependencies = [
1548
2457
  "clsx",
1549
2458
  "tailwind-merge",
@@ -1566,40 +2475,45 @@ async function installDependencies() {
1566
2475
  const devDependencies = ["tailwindcss", "autoprefixer", "postcss"];
1567
2476
  try {
1568
2477
  const installCmd = packageManager === "npm" ? "install" : "add";
1569
- await execAsync2(
1570
- `${packageManager} ${installCmd} ${dependencies.join(" ")}`
1571
- );
2478
+ validatePackageSpecs([...dependencies, ...devDependencies]);
2479
+ const cwd = process.cwd();
2480
+ await runPackageManager(packageManager, [installCmd, ...dependencies], {
2481
+ cwd
2482
+ });
1572
2483
  const devFlag = packageManager === "npm" ? "--save-dev" : "-D";
1573
- await execAsync2(
1574
- `${packageManager} ${installCmd} ${devFlag} ${devDependencies.join(" ")}`
2484
+ await runPackageManager(
2485
+ packageManager,
2486
+ [installCmd, devFlag, ...devDependencies],
2487
+ { cwd }
1575
2488
  );
1576
- console.log(chalk4.green("\u2705 Dependencies installed"));
1577
- } catch {
1578
- console.error(chalk4.yellow("\u26A0\uFE0F Failed to install some dependencies"));
1579
- console.error(chalk4.gray("You may need to install them manually"));
2489
+ console.log(chalk6.green("\u2705 Dependencies installed"));
2490
+ } catch (error) {
2491
+ console.error(chalk6.yellow("\u26A0\uFE0F Failed to install some dependencies"));
2492
+ console.error(chalk6.gray(error.message));
2493
+ console.error(chalk6.gray("You may need to install them manually"));
1580
2494
  }
1581
2495
  }
1582
2496
  function detectPackageManager2() {
1583
- if (fs4.existsSync(path4.join(process.cwd(), "pnpm-lock.yaml"))) return "pnpm";
1584
- if (fs4.existsSync(path4.join(process.cwd(), "yarn.lock"))) return "yarn";
1585
- if (fs4.existsSync(path4.join(process.cwd(), "bun.lockb"))) return "bun";
2497
+ if (fs8.existsSync(path8.join(process.cwd(), "pnpm-lock.yaml"))) return "pnpm";
2498
+ if (fs8.existsSync(path8.join(process.cwd(), "yarn.lock"))) return "yarn";
2499
+ if (fs8.existsSync(path8.join(process.cwd(), "bun.lockb"))) return "bun";
1586
2500
  return "npm";
1587
2501
  }
1588
2502
  async function setupTailwindV4(pathConfig, projectStructure, skipPrompts) {
1589
- console.log(chalk4.blue("\u{1F3A8} Setting up Tailwind CSS v4..."));
2503
+ console.log(chalk6.blue("\u{1F3A8} Setting up Tailwind CSS v4..."));
1590
2504
  const layoutPath = await findLayoutFile(projectStructure);
1591
2505
  if (layoutPath) {
1592
- const layoutContent = await fs4.readFile(layoutPath, "utf-8");
2506
+ const layoutContent = await fs8.readFile(layoutPath, "utf-8");
1593
2507
  if (layoutContent.includes("@foundrykit/tailwind/globals.css")) {
1594
2508
  if (skipPrompts) {
1595
2509
  console.log(
1596
- chalk4.green(
2510
+ chalk6.green(
1597
2511
  "\u2705 Keeping existing import from @foundrykit/tailwind/globals.css"
1598
2512
  )
1599
2513
  );
1600
2514
  return;
1601
2515
  }
1602
- const { importPreference } = await inquirer2.prompt([
2516
+ const { importPreference } = await inquirer4.prompt([
1603
2517
  {
1604
2518
  type: "list",
1605
2519
  name: "importPreference",
@@ -1619,7 +2533,7 @@ async function setupTailwindV4(pathConfig, projectStructure, skipPrompts) {
1619
2533
  ]);
1620
2534
  if (importPreference === "direct") {
1621
2535
  console.log(
1622
- chalk4.green(
2536
+ chalk6.green(
1623
2537
  "\u2705 Keeping direct import from @foundrykit/tailwind/globals.css"
1624
2538
  )
1625
2539
  );
@@ -1635,10 +2549,10 @@ async function setupTailwindV4(pathConfig, projectStructure, skipPrompts) {
1635
2549
  if (globalsCssImportMatch?.[1]) {
1636
2550
  const importPath = globalsCssImportMatch[1];
1637
2551
  const resolvedPath = resolveImportPath(layoutPath, importPath);
1638
- if (fs4.existsSync(resolvedPath)) {
2552
+ if (fs8.existsSync(resolvedPath)) {
1639
2553
  await updateExistingGlobalsCss(resolvedPath);
1640
2554
  console.log(
1641
- chalk4.green("\u2705 Updated existing globals.css with FoundryKit styles")
2555
+ chalk6.green("\u2705 Updated existing globals.css with FoundryKit styles")
1642
2556
  );
1643
2557
  return;
1644
2558
  }
@@ -1646,7 +2560,7 @@ async function setupTailwindV4(pathConfig, projectStructure, skipPrompts) {
1646
2560
  }
1647
2561
  let setupPreference = "local";
1648
2562
  if (!skipPrompts) {
1649
- const answer = await inquirer2.prompt([
2563
+ const answer = await inquirer4.prompt([
1650
2564
  {
1651
2565
  type: "list",
1652
2566
  name: "setupPreference",
@@ -1674,11 +2588,11 @@ async function setupTailwindV4(pathConfig, projectStructure, skipPrompts) {
1674
2588
  await updateLayoutImport(layoutPath, pathConfig);
1675
2589
  }
1676
2590
  }
1677
- console.log(chalk4.green("\u2705 Tailwind CSS v4 configured"));
2591
+ console.log(chalk6.green("\u2705 Tailwind CSS v4 configured"));
1678
2592
  }
1679
2593
  async function createOrUpdateGlobalsCss(pathConfig) {
1680
- const globalsCssPath = path4.join(process.cwd(), pathConfig.styles);
1681
- if (fs4.existsSync(globalsCssPath)) {
2594
+ const globalsCssPath = path8.join(process.cwd(), pathConfig.styles);
2595
+ if (fs8.existsSync(globalsCssPath)) {
1682
2596
  await updateExistingGlobalsCss(globalsCssPath);
1683
2597
  } else {
1684
2598
  const cssContent = `/* Import FoundryKit's Tailwind CSS v4 styles */
@@ -1686,15 +2600,15 @@ async function createOrUpdateGlobalsCss(pathConfig) {
1686
2600
 
1687
2601
  /* Your custom styles below */
1688
2602
  `;
1689
- await fs4.ensureDir(path4.dirname(globalsCssPath));
1690
- await fs4.writeFile(globalsCssPath, cssContent);
1691
- console.log(chalk4.green(`\u2705 Created ${pathConfig.styles}`));
2603
+ await fs8.ensureDir(path8.dirname(globalsCssPath));
2604
+ await fs8.writeFile(globalsCssPath, cssContent);
2605
+ console.log(chalk6.green(`\u2705 Created ${pathConfig.styles}`));
1692
2606
  }
1693
2607
  }
1694
2608
  async function updateExistingGlobalsCss(globalsCssPath) {
1695
- const content = await fs4.readFile(globalsCssPath, "utf-8");
2609
+ const content = await fs8.readFile(globalsCssPath, "utf-8");
1696
2610
  if (content.includes("@foundrykit/tailwind/globals.css")) {
1697
- console.log(chalk4.gray("globals.css already imports FoundryKit styles"));
2611
+ console.log(chalk6.gray("globals.css already imports FoundryKit styles"));
1698
2612
  return;
1699
2613
  }
1700
2614
  if (content.includes('@import "tailwindcss"')) {
@@ -1703,16 +2617,16 @@ async function updateExistingGlobalsCss(globalsCssPath) {
1703
2617
  `/* Import FoundryKit's Tailwind CSS v4 styles */
1704
2618
  @import "@foundrykit/tailwind/globals.css"`
1705
2619
  );
1706
- await fs4.writeFile(globalsCssPath, updatedContent);
1707
- console.log(chalk4.green("\u2705 Updated globals.css with FoundryKit styles"));
2620
+ await fs8.writeFile(globalsCssPath, updatedContent);
2621
+ console.log(chalk6.green("\u2705 Updated globals.css with FoundryKit styles"));
1708
2622
  } else {
1709
2623
  const updatedContent = `/* Import FoundryKit's Tailwind CSS v4 styles */
1710
2624
  @import "@foundrykit/tailwind/globals.css";
1711
2625
 
1712
2626
  /* Your custom styles below */
1713
2627
  ${content}`;
1714
- await fs4.writeFile(globalsCssPath, updatedContent);
1715
- console.log(chalk4.green("\u2705 Updated globals.css with FoundryKit styles"));
2628
+ await fs8.writeFile(globalsCssPath, updatedContent);
2629
+ console.log(chalk6.green("\u2705 Updated globals.css with FoundryKit styles"));
1716
2630
  }
1717
2631
  }
1718
2632
  async function findLayoutFile(projectStructure) {
@@ -1720,8 +2634,8 @@ async function findLayoutFile(projectStructure) {
1720
2634
  if (projectStructure.appPath) {
1721
2635
  const ext = projectStructure.isTypeScript ? ".tsx" : ".jsx";
1722
2636
  possiblePaths.push(
1723
- path4.join(projectStructure.appPath, `layout${ext}`),
1724
- path4.join(projectStructure.appPath, `layout.js`)
2637
+ path8.join(projectStructure.appPath, `layout${ext}`),
2638
+ path8.join(projectStructure.appPath, `layout.js`)
1725
2639
  );
1726
2640
  }
1727
2641
  possiblePaths.push(
@@ -1733,8 +2647,8 @@ async function findLayoutFile(projectStructure) {
1733
2647
  "src/app/layout.js"
1734
2648
  );
1735
2649
  for (const layoutPath of possiblePaths) {
1736
- const fullPath = path4.join(process.cwd(), layoutPath);
1737
- if (fs4.existsSync(fullPath)) {
2650
+ const fullPath = path8.join(process.cwd(), layoutPath);
2651
+ if (fs8.existsSync(fullPath)) {
1738
2652
  return fullPath;
1739
2653
  }
1740
2654
  }
@@ -1742,10 +2656,10 @@ async function findLayoutFile(projectStructure) {
1742
2656
  }
1743
2657
  async function updateLayoutImport(layoutPath, pathConfig) {
1744
2658
  try {
1745
- let content = await fs4.readFile(layoutPath, "utf-8");
1746
- const fromPath = path4.dirname(layoutPath);
1747
- const toPath = path4.join(process.cwd(), pathConfig.styles);
1748
- const relativePath = path4.relative(fromPath, toPath).replace(/\\/g, "/");
2659
+ let content = await fs8.readFile(layoutPath, "utf-8");
2660
+ const fromPath = path8.dirname(layoutPath);
2661
+ const toPath = path8.join(process.cwd(), pathConfig.styles);
2662
+ const relativePath = path8.relative(fromPath, toPath).replace(/\\/g, "/");
1749
2663
  const importPath = relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
1750
2664
  const globalImportRegex = /import\s+['"]([^'"]*globals?\.css)['"]/;
1751
2665
  const match = content.match(globalImportRegex);
@@ -1763,19 +2677,19 @@ async function updateLayoutImport(layoutPath, pathConfig) {
1763
2677
  content = importStatement + content;
1764
2678
  }
1765
2679
  }
1766
- await fs4.writeFile(layoutPath, content);
2680
+ await fs8.writeFile(layoutPath, content);
1767
2681
  console.log(
1768
- chalk4.gray(
1769
- `Updated ${path4.relative(process.cwd(), layoutPath)} with CSS import`
2682
+ chalk6.gray(
2683
+ `Updated ${path8.relative(process.cwd(), layoutPath)} with CSS import`
1770
2684
  )
1771
2685
  );
1772
2686
  } catch {
1773
- console.error(chalk4.yellow("\u26A0\uFE0F Failed to update layout with CSS import"));
2687
+ console.error(chalk6.yellow("\u26A0\uFE0F Failed to update layout with CSS import"));
1774
2688
  }
1775
2689
  }
1776
2690
  async function addDirectImportToLayout(layoutPath) {
1777
2691
  try {
1778
- let content = await fs4.readFile(layoutPath, "utf-8");
2692
+ let content = await fs8.readFile(layoutPath, "utf-8");
1779
2693
  const importStatement = `import '@foundrykit/tailwind/globals.css';
1780
2694
  `;
1781
2695
  if (!content.includes("@foundrykit/tailwind/globals.css")) {
@@ -1787,27 +2701,27 @@ async function addDirectImportToLayout(layoutPath) {
1787
2701
  } else {
1788
2702
  content = importStatement + content;
1789
2703
  }
1790
- await fs4.writeFile(layoutPath, content);
2704
+ await fs8.writeFile(layoutPath, content);
1791
2705
  console.log(
1792
- chalk4.green("\u2705 Added direct import of FoundryKit styles to layout")
2706
+ chalk6.green("\u2705 Added direct import of FoundryKit styles to layout")
1793
2707
  );
1794
2708
  }
1795
2709
  } catch {
1796
- console.error(chalk4.yellow("\u26A0\uFE0F Failed to add CSS import to layout"));
2710
+ console.error(chalk6.yellow("\u26A0\uFE0F Failed to add CSS import to layout"));
1797
2711
  }
1798
2712
  }
1799
2713
  function resolveImportPath(fromFile, importPath) {
1800
2714
  if (importPath.startsWith(".")) {
1801
- return path4.join(path4.dirname(fromFile), importPath);
2715
+ return path8.join(path8.dirname(fromFile), importPath);
1802
2716
  } else if (importPath.startsWith("@/")) {
1803
- return path4.join(process.cwd(), importPath.replace("@/", "src/"));
2717
+ return path8.join(process.cwd(), importPath.replace("@/", "src/"));
1804
2718
  } else if (importPath.startsWith("/")) {
1805
- return path4.join(process.cwd(), importPath);
2719
+ return path8.join(process.cwd(), importPath);
1806
2720
  }
1807
- return path4.join(process.cwd(), importPath);
2721
+ return path8.join(process.cwd(), importPath);
1808
2722
  }
1809
2723
  async function createDirectories(pathConfig) {
1810
- console.log(chalk4.blue("\u{1F4C1} Creating component directories..."));
2724
+ console.log(chalk6.blue("\u{1F4C1} Creating component directories..."));
1811
2725
  const dirs = [
1812
2726
  pathConfig.primitives,
1813
2727
  pathConfig.components,
@@ -1818,15 +2732,15 @@ async function createDirectories(pathConfig) {
1818
2732
  pathConfig.lib
1819
2733
  ];
1820
2734
  for (const dir of dirs) {
1821
- const fullPath = path4.join(process.cwd(), dir);
1822
- await fs4.ensureDir(fullPath);
1823
- console.log(chalk4.gray(`Created ${dir}`));
2735
+ const fullPath = path8.join(process.cwd(), dir);
2736
+ await fs8.ensureDir(fullPath);
2737
+ console.log(chalk6.gray(`Created ${dir}`));
1824
2738
  }
1825
- console.log(chalk4.green("\u2705 Directories created"));
2739
+ console.log(chalk6.green("\u2705 Directories created"));
1826
2740
  }
1827
2741
  async function createExampleFiles(pathConfig, structure) {
1828
- console.log(chalk4.blue("\u{1F4DD} Creating example files..."));
1829
- const utilsPath = path4.join(process.cwd(), pathConfig.utils);
2742
+ console.log(chalk6.blue("\u{1F4DD} Creating example files..."));
2743
+ const utilsPath = path8.join(process.cwd(), pathConfig.utils);
1830
2744
  const utilsContent = `import { type ClassValue, clsx } from 'clsx';
1831
2745
  import { twMerge } from 'tailwind-merge';
1832
2746
 
@@ -1834,14 +2748,14 @@ export function cn(...inputs: ClassValue[]) {
1834
2748
  return twMerge(clsx(inputs));
1835
2749
  }
1836
2750
  `;
1837
- await fs4.ensureDir(path4.dirname(utilsPath));
1838
- if (!fs4.existsSync(utilsPath)) {
1839
- await fs4.writeFile(utilsPath, utilsContent);
1840
- console.log(chalk4.gray(`Created ${pathConfig.utils}`));
2751
+ await fs8.ensureDir(path8.dirname(utilsPath));
2752
+ if (!fs8.existsSync(utilsPath)) {
2753
+ await fs8.writeFile(utilsPath, utilsContent);
2754
+ console.log(chalk6.gray(`Created ${pathConfig.utils}`));
1841
2755
  }
1842
- const providersPath = path4.join(
2756
+ const providersPath = path8.join(
1843
2757
  process.cwd(),
1844
- path4.dirname(pathConfig.components),
2758
+ path8.dirname(pathConfig.components),
1845
2759
  `theme-provider${structure.isTypeScript ? ".tsx" : ".jsx"}`
1846
2760
  );
1847
2761
  const providersContent = `
@@ -1865,44 +2779,41 @@ export function ThemeProvider({ children }: { children: React.ReactNode }) {
1865
2779
  }
1866
2780
 
1867
2781
  `;
1868
- if (!fs4.existsSync(providersPath)) {
1869
- await fs4.writeFile(providersPath, providersContent);
2782
+ if (!fs8.existsSync(providersPath)) {
2783
+ await fs8.writeFile(providersPath, providersContent);
1870
2784
  console.log(
1871
- chalk4.gray(
2785
+ chalk6.gray(
1872
2786
  `Created theme-provider.${structure.isTypeScript ? "tsx" : "jsx"}`
1873
2787
  )
1874
2788
  );
1875
2789
  }
1876
- console.log(chalk4.green("\u2705 Example files created"));
2790
+ console.log(chalk6.green("\u2705 Example files created"));
1877
2791
  }
1878
2792
  async function updatePackageScripts() {
1879
- console.log(chalk4.blue("\u{1F4DD} Updating package.json scripts..."));
1880
- const packageJsonPath = path4.join(process.cwd(), "package.json");
1881
- const packageJson2 = await fs4.readJson(packageJsonPath);
2793
+ console.log(chalk6.blue("\u{1F4DD} Updating package.json scripts..."));
2794
+ const packageJsonPath = path8.join(process.cwd(), "package.json");
2795
+ const packageJson2 = await fs8.readJson(packageJsonPath);
1882
2796
  packageJson2.scripts = {
1883
2797
  ...packageJson2.scripts,
1884
2798
  "foundrykit:add": "pnpm dlx @foundrykit/cli add",
1885
2799
  "foundrykit:update": "pnpm dlx @foundrykit/cli update"
1886
2800
  };
1887
- await fs4.writeJson(packageJsonPath, packageJson2, { spaces: 2 });
1888
- console.log(chalk4.green("\u2705 Package scripts updated"));
2801
+ await fs8.writeJson(packageJsonPath, packageJson2, { spaces: 2 });
2802
+ console.log(chalk6.green("\u2705 Package scripts updated"));
1889
2803
  }
1890
2804
  async function createConfigFile(options, structure, pathConfig) {
1891
- console.log(chalk4.blue("\u{1F4DD} Creating configuration file..."));
1892
- const configPath = path4.join(process.cwd(), "foundrykit.config.json");
1893
- if (fs4.existsSync(configPath) && !options.force) {
1894
- console.log(chalk4.yellow("\u26A0\uFE0F Configuration file already exists"));
2805
+ console.log(chalk6.blue("\u{1F4DD} Creating configuration file..."));
2806
+ if (await isFoundryKitInitialized() && !options.force) {
2807
+ console.log(chalk6.yellow("\u26A0\uFE0F Configuration file already exists"));
1895
2808
  return;
1896
2809
  }
1897
2810
  const normalizePath = (p) => {
1898
- if (p.startsWith("./") || p.startsWith("../") || path4.isAbsolute(p)) {
2811
+ if (p.startsWith("./") || p.startsWith("../") || path8.isAbsolute(p)) {
1899
2812
  return p;
1900
2813
  }
1901
2814
  return `./${p}`;
1902
2815
  };
1903
- const config = {
1904
- version: CLI_VERSION,
1905
- registry: DEFAULT_REGISTRY_URL,
2816
+ const settings = {
1906
2817
  paths: {
1907
2818
  utils: normalizePath(pathConfig.utils),
1908
2819
  primitives: normalizePath(pathConfig.primitives),
@@ -1921,18 +2832,35 @@ async function createConfigFile(options, structure, pathConfig) {
1921
2832
  aliases: {
1922
2833
  "@": normalizePath(structure.baseDir.replace(/\/$/, "") || "."),
1923
2834
  "@/components": normalizePath(
1924
- path4.dirname(pathConfig.components).replace(/\/$/, "")
2835
+ path8.dirname(pathConfig.components).replace(/\/$/, "")
1925
2836
  ),
1926
2837
  "@/lib": normalizePath(pathConfig.lib.replace(/\/$/, "")),
1927
2838
  "@/hooks": normalizePath(pathConfig.hooks.replace(/\/$/, ""))
1928
2839
  }
1929
2840
  };
1930
- await fs4.writeJson(configPath, config, { spaces: 2 });
1931
- console.log(chalk4.green("\u2705 Created foundrykit.config.json"));
2841
+ await createProjectFiles(process.cwd(), settings);
2842
+ console.log(chalk6.green(`\u2705 Created ${SETTINGS_FILE} and ${LOCK_FILE}`));
2843
+ }
2844
+ async function createProjectFiles(root, settings) {
2845
+ validateSettings(settings);
2846
+ const lockPath = path8.join(root, LOCK_FILE);
2847
+ if (await fs8.pathExists(path8.join(root, LEGACY_CONFIG_FILE)) && !await fs8.pathExists(path8.join(root, SETTINGS_FILE))) {
2848
+ await loadProject(root);
2849
+ }
2850
+ await writeFileAtomic(
2851
+ path8.join(root, SETTINGS_FILE),
2852
+ stableStringify({ $schema: SCHEMA_URL, ...settings })
2853
+ );
2854
+ if (!await fs8.pathExists(lockPath)) {
2855
+ await writeFileAtomic(
2856
+ lockPath,
2857
+ stableStringify({ lockfileVersion: 1, components: {} })
2858
+ );
2859
+ }
1932
2860
  }
1933
2861
  async function installUtils(pathConfig) {
1934
- console.log(chalk4.blue("\u{1F4E6} Installing utility functions..."));
1935
- const utilsPath = path4.join(process.cwd(), pathConfig.utils);
2862
+ console.log(chalk6.blue("\u{1F4E6} Installing utility functions..."));
2863
+ const utilsPath = path8.join(process.cwd(), pathConfig.utils);
1936
2864
  const utilsContent = `import { type ClassValue, clsx } from 'clsx';
1937
2865
  import { twMerge } from 'tailwind-merge';
1938
2866
 
@@ -1940,67 +2868,139 @@ export function cn(...inputs: ClassValue[]) {
1940
2868
  return twMerge(clsx(inputs));
1941
2869
  }
1942
2870
  `;
1943
- const utilsDir = path4.dirname(utilsPath);
1944
- await fs4.ensureDir(utilsDir);
1945
- if (!fs4.existsSync(utilsPath)) {
1946
- await fs4.writeFile(utilsPath, utilsContent);
1947
- console.log(chalk4.green("\u2705 Utility functions installed"));
2871
+ const utilsDir = path8.dirname(utilsPath);
2872
+ await fs8.ensureDir(utilsDir);
2873
+ if (!fs8.existsSync(utilsPath)) {
2874
+ await fs8.writeFile(utilsPath, utilsContent);
2875
+ console.log(chalk6.green("\u2705 Utility functions installed"));
1948
2876
  } else {
1949
- console.log(chalk4.gray("Utils file already exists, skipping..."));
2877
+ console.log(chalk6.gray("Utils file already exists, skipping..."));
1950
2878
  }
1951
2879
  }
1952
2880
 
2881
+ // src/commands/link.ts
2882
+ import { Command as Command5 } from "commander";
2883
+ var REF = /^[a-z0-9][a-z0-9-]*\/[a-z0-9][a-z0-9-]*$/;
2884
+ async function runLink(ref, opts, io, cwd) {
2885
+ try {
2886
+ if (!REF.test(ref))
2887
+ throw new HubError(
2888
+ 400,
2889
+ "invalid_request",
2890
+ "Use <org>/<project>, e.g. turquoise/website."
2891
+ );
2892
+ const project = await loadProject(cwd, { readOnly: true });
2893
+ if (project.migration === "pending")
2894
+ throw new ProjectError("Run `foundrykit update` to migrate first.");
2895
+ const { url: hubUrl } = await resolveHub(opts.hub, { ...io, cwd });
2896
+ const { token } = await requireSignedIn(hubUrl, io.home);
2897
+ const { projects } = await hubFetch(
2898
+ hubUrl,
2899
+ token,
2900
+ "GET",
2901
+ "/api/cli/projects"
2902
+ );
2903
+ const found = projects.find((p) => p.ref === ref);
2904
+ if (!found)
2905
+ throw new HubError(
2906
+ 404,
2907
+ "not_found",
2908
+ `No project ${ref} on ${hubUrl} that you can see.`
2909
+ );
2910
+ project.settings.hub = {
2911
+ ...project.settings.hub,
2912
+ project: ref,
2913
+ ...opts.hub && { url: normalizeHubUrl(opts.hub) }
2914
+ };
2915
+ await project.saveSettings();
2916
+ io.out(
2917
+ opts.json ? JSON.stringify({
2918
+ project: {
2919
+ ref,
2920
+ name: found.name,
2921
+ organization: found.organization
2922
+ }
2923
+ }) : `Linked to ${ref} (${found.name}).`
2924
+ );
2925
+ return 0;
2926
+ } catch (e) {
2927
+ return fail(io, opts.json, e);
2928
+ }
2929
+ }
2930
+ function linkCommand() {
2931
+ return new Command5("link").description("Link this project to a project on the Foundry hub").argument("<project>", "<org>/<project>, e.g. turquoise/website").option("--hub <url>", "hub URL (saved to foundrykit.json)").option("--json", "print JSON").action(async (ref, opts) => {
2932
+ const io = defaultIO();
2933
+ process.exitCode = await runLink(
2934
+ ref,
2935
+ { ...opts, json: Boolean(opts.json) },
2936
+ io,
2937
+ io.cwd
2938
+ );
2939
+ });
2940
+ }
2941
+
1953
2942
  // src/commands/list.ts
1954
- import chalk5 from "chalk";
1955
- import { Command as Command4 } from "commander";
2943
+ import chalk7 from "chalk";
2944
+ import { Command as Command6 } from "commander";
2945
+ async function loadRegistrySettings(cwd) {
2946
+ try {
2947
+ return (await loadProject(cwd, { readOnly: true })).settings;
2948
+ } catch (error) {
2949
+ if (error instanceof ProjectError || error instanceof SettingsError) {
2950
+ return void 0;
2951
+ }
2952
+ throw error;
2953
+ }
2954
+ }
1956
2955
  function listCommand() {
1957
- return new Command4("list").description("List all available FoundryKit components and blocks").option(
2956
+ return new Command6("list").description("List all available FoundryKit components and blocks").option(
1958
2957
  "-c, --category <category>",
1959
2958
  "filter by category (primitives, components, blocks, animations)"
1960
2959
  ).option("-s, --search <term>", "search components by name or description").action(async (options) => {
1961
2960
  try {
1962
- console.log(chalk5.blue("\u{1F4E6} Available FoundryKit components:"));
1963
- const registry = getRegistry();
2961
+ console.log(chalk7.blue("\u{1F4E6} Available FoundryKit components:"));
2962
+ const settings = await loadRegistrySettings(process.cwd());
2963
+ const registry = getRegistry(void 0, settings);
1964
2964
  if (options.category) {
1965
2965
  const validCategories = REGISTRY_CATEGORY_ORDER;
1966
2966
  if (!validCategories.includes(options.category)) {
1967
- console.error(chalk5.red(`Invalid category: ${options.category}`));
2967
+ console.error(chalk7.red(`Invalid category: ${options.category}`));
1968
2968
  console.log(
1969
- chalk5.gray(`Valid categories: ${validCategories.join(", ")}`)
2969
+ chalk7.gray(`Valid categories: ${validCategories.join(", ")}`)
1970
2970
  );
1971
2971
  process.exit(1);
1972
2972
  }
1973
2973
  }
1974
- console.log(chalk5.gray("Fetching from registry..."));
2974
+ console.log(chalk7.gray("Fetching from registry..."));
1975
2975
  const components = await registry.getComponents(
1976
2976
  options.category,
1977
2977
  options.search
1978
2978
  );
1979
2979
  if (components.length === 0) {
1980
2980
  console.log(
1981
- chalk5.yellow("\nNo components found matching your criteria.")
2981
+ chalk7.yellow("\nNo components found matching your criteria.")
1982
2982
  );
1983
2983
  if (options.search) {
1984
- console.log(chalk5.gray(`Search term: "${options.search}"`));
2984
+ console.log(chalk7.gray(`Search term: "${options.search}"`));
1985
2985
  }
1986
2986
  if (options.category) {
1987
- console.log(chalk5.gray(`Category: ${options.category}`));
2987
+ console.log(chalk7.gray(`Category: ${options.category}`));
1988
2988
  }
1989
2989
  return;
1990
2990
  }
1991
2991
  displayComponents(components);
1992
- console.log(chalk5.cyan("\n\u{1F4A1} Usage:"));
2992
+ console.log(chalk7.cyan("\n\u{1F4A1} Usage:"));
1993
2993
  console.log(
1994
- chalk5.gray(" foundrykit add # Interactive mode")
2994
+ chalk7.gray(" foundrykit add # Interactive mode")
1995
2995
  );
1996
2996
  console.log(
1997
- chalk5.gray(" foundrykit add <id> # Add specific component")
2997
+ chalk7.gray(" foundrykit add <id> # Add specific component")
1998
2998
  );
1999
- console.log(chalk5.gray(" foundrykit add button # Example"));
2999
+ console.log(chalk7.gray(" foundrykit add button # Example"));
2000
3000
  } catch (error) {
2001
- console.error(chalk5.red("\u274C Failed to fetch component registry:"));
3001
+ console.error(chalk7.red("\u274C Failed to fetch component registry:"));
2002
3002
  console.error(
2003
- chalk5.red(error instanceof Error ? error.message : String(error))
3003
+ chalk7.red(error instanceof Error ? error.message : String(error))
2004
3004
  );
2005
3005
  process.exit(1);
2006
3006
  }
@@ -2030,30 +3030,30 @@ function displayComponents(components) {
2030
3030
  const items = grouped[category];
2031
3031
  if (!items || items.length === 0) continue;
2032
3032
  console.log(`
2033
- ${chalk5.cyan.bold(category.toUpperCase())}`);
2034
- console.log(chalk5.gray("\u2500".repeat(40)));
3033
+ ${chalk7.cyan.bold(category.toUpperCase())}`);
3034
+ console.log(chalk7.gray("\u2500".repeat(40)));
2035
3035
  for (const item of items) {
2036
3036
  console.log(
2037
- `${chalk5.green("\u25CF")} ${chalk5.bold(item.name)} ${chalk5.gray(
3037
+ `${chalk7.green("\u25CF")} ${chalk7.bold(item.name)} ${chalk7.gray(
2038
3038
  `(${item.id})`
2039
3039
  )}`
2040
3040
  );
2041
- console.log(` ${chalk5.gray(item.description)}`);
3041
+ console.log(` ${chalk7.gray(item.description)}`);
2042
3042
  if (item.tags && item.tags.length > 0) {
2043
3043
  console.log(
2044
- ` ${chalk5.blue(item.tags.map((tag) => `#${tag}`).join(" "))}`
3044
+ ` ${chalk7.blue(item.tags.map((tag) => `#${tag}`).join(" "))}`
2045
3045
  );
2046
3046
  }
2047
3047
  if (item.registryDependencies && item.registryDependencies.length > 0) {
2048
3048
  console.log(
2049
- ` ${chalk5.yellow("Requires:")} ${item.registryDependencies.join(
3049
+ ` ${chalk7.yellow("Requires:")} ${item.registryDependencies.join(
2050
3050
  ", "
2051
3051
  )}`
2052
3052
  );
2053
3053
  }
2054
3054
  if (item.packageDependencies && item.packageDependencies.length > 0) {
2055
3055
  console.log(
2056
- ` ${chalk5.magenta("NPM packages:")} ${item.packageDependencies.join(
3056
+ ` ${chalk7.magenta("NPM packages:")} ${item.packageDependencies.join(
2057
3057
  ", "
2058
3058
  )}`
2059
3059
  );
@@ -2063,201 +3063,678 @@ ${chalk5.cyan.bold(category.toUpperCase())}`);
2063
3063
  }
2064
3064
  const total = components.length;
2065
3065
  const byCategory = Object.entries(grouped).map(([cat, items]) => `${items.length} ${cat}`).join(", ");
2066
- console.log(chalk5.gray("\u2500".repeat(40)));
2067
- console.log(chalk5.gray(`Total: ${total} components (${byCategory})`));
3066
+ console.log(chalk7.gray("\u2500".repeat(40)));
3067
+ console.log(chalk7.gray(`Total: ${total} components (${byCategory})`));
2068
3068
  }
2069
3069
 
2070
- // src/commands/update.ts
2071
- import path5 from "path";
2072
- import chalk6 from "chalk";
2073
- import { Command as Command5 } from "commander";
2074
- import fs5 from "fs-extra";
2075
- import inquirer3 from "inquirer";
2076
- function updateCommand() {
2077
- return new Command5("update").description("Update installed components").argument("[id]", "Component or block ID (omit to update all installed)").option(
2078
- "-o, --opt",
2079
- "interactively select which components to update, showing available upgrades"
2080
- ).option("-f, --force", "bypass cache and fetch fresh data from registry").option("-p, --path <path>", "Custom installation path").action(async (id, options) => {
2081
- if (id) {
2082
- try {
2083
- console.log(chalk6.blue(`\u{1F504} Updating ${id}...`));
2084
- await addSingleComponent(id, {
2085
- ...options,
2086
- overwrite: true,
2087
- force: true
2088
- });
2089
- } catch (error) {
2090
- console.error(chalk6.red(`\u274C Failed to update ${id}:`));
2091
- console.error(
2092
- chalk6.red(error instanceof Error ? error.message : String(error))
2093
- );
2094
- process.exit(1);
3070
+ // src/commands/login.ts
3071
+ import { execFile } from "child_process";
3072
+ import { setTimeout as sleep } from "timers/promises";
3073
+ import { Command as Command7 } from "commander";
3074
+ import inquirer5 from "inquirer";
3075
+
3076
+ // src/lib/hub/device.ts
3077
+ var CLIENT_ID = "foundrykit-cli";
3078
+ var str = (v) => typeof v === "string";
3079
+ async function post(hubUrl, path12, body) {
3080
+ let res;
3081
+ try {
3082
+ res = await fetch(`${hubUrl}${path12}`, {
3083
+ method: "POST",
3084
+ redirect: "error",
3085
+ headers: {
3086
+ accept: "application/json",
3087
+ "content-type": "application/json"
3088
+ },
3089
+ body: JSON.stringify(body)
3090
+ });
3091
+ } catch {
3092
+ throw unreachable(hubUrl);
3093
+ }
3094
+ let json = {};
3095
+ try {
3096
+ const parsed = await res.json();
3097
+ if (parsed && typeof parsed === "object")
3098
+ json = parsed;
3099
+ } catch {
3100
+ }
3101
+ return { status: res.status, ok: res.ok, json };
3102
+ }
3103
+ var flatError = (status, json) => str(json.error) ? new HubError(
3104
+ status,
3105
+ json.error,
3106
+ str(json.error_description) && json.error_description ? json.error_description : json.error
3107
+ ) : unexpectedResponse(status);
3108
+ async function deviceLogin(hubUrl, deps) {
3109
+ const start = await post(hubUrl, "/api/auth/device/code", {
3110
+ client_id: CLIENT_ID
3111
+ });
3112
+ const c = start.json;
3113
+ if (!start.ok) throw flatError(start.status, c);
3114
+ if (!str(c.device_code) || !str(c.user_code) || !str(c.verification_uri) || !str(c.verification_uri_complete))
3115
+ throw unexpectedResponse(start.status);
3116
+ deps.onCode({ userCode: c.user_code, url: c.verification_uri_complete });
3117
+ let interval = Math.max(1, Number(c.interval) || 5) * 1e3;
3118
+ const budget = Math.min(Number(c.expires_in) || 600, 1800) * 1e3;
3119
+ let waited = 0;
3120
+ while (waited + interval <= budget) {
3121
+ await deps.sleep(interval);
3122
+ waited += interval;
3123
+ const r = await post(hubUrl, "/api/auth/device/token", {
3124
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code",
3125
+ device_code: c.device_code,
3126
+ client_id: CLIENT_ID
3127
+ });
3128
+ if (r.ok) {
3129
+ if (str(r.json.access_token)) return r.json.access_token;
3130
+ throw unexpectedResponse(r.status);
3131
+ }
3132
+ const error = r.json.error;
3133
+ if (error === "authorization_pending") continue;
3134
+ if (error === "slow_down") {
3135
+ interval += 5e3;
3136
+ continue;
3137
+ }
3138
+ if (error === "access_denied")
3139
+ throw new HubError(400, error, "Sign-in was denied.");
3140
+ if (error === "expired_token") break;
3141
+ throw flatError(r.status, r.json);
3142
+ }
3143
+ throw new HubError(
3144
+ 400,
3145
+ "expired_token",
3146
+ "The code expired. Run `foundrykit login` again."
3147
+ );
3148
+ }
3149
+
3150
+ // src/commands/login.ts
3151
+ function openerCommand(platform, href) {
3152
+ if (platform === "darwin") return ["open", [href]];
3153
+ if (platform === "win32")
3154
+ return ["rundll32", ["url.dll,FileProtocolHandler", href]];
3155
+ return ["xdg-open", [href]];
3156
+ }
3157
+ function openUrl(href) {
3158
+ const [cmd, args] = openerCommand(process.platform, href);
3159
+ try {
3160
+ execFile(cmd, args, () => {
3161
+ }).on("error", () => {
3162
+ });
3163
+ } catch {
3164
+ }
3165
+ }
3166
+ function safeHref(url, hubUrl) {
3167
+ try {
3168
+ const u = new URL(url);
3169
+ if (u.protocol !== "http:" && u.protocol !== "https:") return null;
3170
+ return u.origin === new URL(hubUrl).origin ? u.href : null;
3171
+ } catch {
3172
+ return null;
3173
+ }
3174
+ }
3175
+ async function whoami(hubUrl, token) {
3176
+ const me = await hubFetch(
3177
+ hubUrl,
3178
+ token,
3179
+ "GET",
3180
+ "/api/cli/whoami"
3181
+ );
3182
+ if (typeof me?.user?.email !== "string") throw unexpectedResponse(200);
3183
+ return me;
3184
+ }
3185
+ async function runLogin(opts, io, deps) {
3186
+ try {
3187
+ const { url: hubUrl, fromSettings } = await resolveHub(opts.hub, io);
3188
+ const say = opts.json ? io.err : io.out;
3189
+ if (fromSettings && hubUrl !== DEFAULT_HUB_URL) {
3190
+ if (await readCredential(hubUrl, io.home))
3191
+ io.err(`Signing in to ${hubUrl} (from foundrykit.json)`);
3192
+ else {
3193
+ if (opts.json || !io.isTTY)
3194
+ throw new HubError(
3195
+ 0,
3196
+ "invalid_request",
3197
+ `${hubUrl} comes from foundrykit.json. To sign in to it, run \`foundrykit login --hub ${hubUrl}\`.`
3198
+ );
3199
+ const { confirm } = await deps.prompt([
3200
+ {
3201
+ type: "confirm",
3202
+ name: "confirm",
3203
+ message: `Sign in to ${hubUrl} (from foundrykit.json)?`,
3204
+ default: false
3205
+ }
3206
+ ]);
3207
+ if (!confirm) {
3208
+ io.out("Not signed in.");
3209
+ return 1;
3210
+ }
2095
3211
  }
2096
- return;
2097
3212
  }
2098
- const configPath = path5.join(process.cwd(), "foundrykit.config.json");
2099
- if (!fs5.existsSync(configPath)) {
2100
- console.error(
2101
- chalk6.red(
2102
- '\u274C FoundryKit not initialized. Run "foundrykit init" first.'
2103
- )
3213
+ const token = await deviceLogin(hubUrl, {
3214
+ sleep: deps.sleep,
3215
+ onCode: ({ userCode, url }) => {
3216
+ say(`Your code: ${userCode}`);
3217
+ say(`Approve it at ${url}`);
3218
+ if (!opts.browser || !io.isTTY) return;
3219
+ const href = safeHref(url, hubUrl);
3220
+ if (!href) {
3221
+ io.err(
3222
+ `Didn't open your browser: the link isn't on the hub's address (${hubUrl}).`
3223
+ );
3224
+ return;
3225
+ }
3226
+ io.err("Opening your browser\u2026");
3227
+ deps.openUrl(href);
3228
+ }
3229
+ });
3230
+ const me = await whoami(hubUrl, token);
3231
+ await saveCredential(
3232
+ hubUrl,
3233
+ { token, user: { email: me.user.email } },
3234
+ io.home
3235
+ );
3236
+ io.out(
3237
+ opts.json ? JSON.stringify(me) : `Signed in to ${hubUrl} as ${me.user.email}.`
3238
+ );
3239
+ return 0;
3240
+ } catch (e) {
3241
+ return fail(io, opts.json, e);
3242
+ }
3243
+ }
3244
+ async function runLogout(opts, io) {
3245
+ try {
3246
+ const hubUrl = await hubUrlFor(opts.hub, io);
3247
+ const signedOut = await deleteCredential(hubUrl, io.home);
3248
+ io.out(
3249
+ opts.json ? JSON.stringify({ hub: hubUrl, signedOut }) : signedOut ? `Signed out of ${hubUrl}.` : `Not signed in to ${hubUrl}.`
3250
+ );
3251
+ return 0;
3252
+ } catch (e) {
3253
+ return fail(io, opts.json, e);
3254
+ }
3255
+ }
3256
+ async function runWhoami(opts, io) {
3257
+ try {
3258
+ const hubUrl = await hubUrlFor(void 0, io);
3259
+ const { token } = await requireSignedIn(hubUrl, io.home);
3260
+ const me = await whoami(hubUrl, token);
3261
+ const role = me.umiAdmin ? " (Umi admin)" : me.umiStaff ? " (Umi staff)" : "";
3262
+ io.out(
3263
+ opts.json ? JSON.stringify(me) : `${me.user.email} on ${hubUrl}${role}`
3264
+ );
3265
+ return 0;
3266
+ } catch (e) {
3267
+ return fail(io, opts.json, e);
3268
+ }
3269
+ }
3270
+ function loginCommand() {
3271
+ return new Command7("login").description("Sign in to the Foundry hub").option("--hub <url>", "hub URL").option("--no-browser", "do not open a browser").option("--json", "print JSON").action(
3272
+ async (opts) => {
3273
+ process.exitCode = await runLogin(
3274
+ { ...opts, json: Boolean(opts.json) },
3275
+ defaultIO(),
3276
+ { prompt: inquirer5.prompt, sleep: (ms) => sleep(ms), openUrl }
2104
3277
  );
2105
- process.exit(1);
2106
3278
  }
2107
- const config = await fs5.readJson(configPath);
2108
- const installed = config.installedComponents ?? {};
2109
- const installedFoundryKitPackages = await getInstalledFoundryKitPackageVersions();
2110
- for (const [pkgId, version] of Object.entries(
2111
- installedFoundryKitPackages
2112
- )) {
2113
- installed[pkgId] = {
2114
- id: pkgId,
2115
- version,
2116
- installedAt: installed[pkgId]?.installedAt ?? (/* @__PURE__ */ new Date()).toISOString()
2117
- };
3279
+ );
3280
+ }
3281
+ function logoutCommand() {
3282
+ return new Command7("logout").description("Sign out of the Foundry hub (removes the saved token)").option("--hub <url>", "hub URL").option("--json", "print JSON").action(async (opts) => {
3283
+ process.exitCode = await runLogout(
3284
+ { ...opts, json: Boolean(opts.json) },
3285
+ defaultIO()
3286
+ );
3287
+ });
3288
+ }
3289
+ function whoamiCommand() {
3290
+ return new Command7("whoami").description("Show who you are signed in as on the Foundry hub").option("--json", "print JSON").action(async (opts) => {
3291
+ process.exitCode = await runWhoami(
3292
+ { json: Boolean(opts.json) },
3293
+ defaultIO()
3294
+ );
3295
+ });
3296
+ }
3297
+
3298
+ // src/commands/provision.ts
3299
+ import chalk8 from "chalk";
3300
+ import { Command as Command8 } from "commander";
3301
+ import inquirer6 from "inquirer";
3302
+
3303
+ // src/lib/git.ts
3304
+ import { execFile as execFile2, spawn as spawn2 } from "child_process";
3305
+ import { promisify } from "util";
3306
+ var run = promisify(execFile2);
3307
+ var env = { ...process.env, GIT_TERMINAL_PROMPT: "0" };
3308
+ var realGit = {
3309
+ isRepo: (cwd) => run("git", ["rev-parse", "--is-inside-work-tree"], { cwd, env }).then(
3310
+ (r) => r.stdout.trim() === "true",
3311
+ () => false
3312
+ ),
3313
+ hasOrigin: (cwd) => run("git", ["remote", "get-url", "origin"], { cwd, env }).then(
3314
+ () => true,
3315
+ () => false
3316
+ ),
3317
+ addOrigin: async (cwd, url) => {
3318
+ await run("git", ["remote", "add", "origin", url], { cwd, env });
3319
+ },
3320
+ // git's stdout goes to stderr so `--json` stdout stays one document; prompts/progress still show.
3321
+ pushProd: (cwd) => new Promise((resolve, reject) => {
3322
+ spawn2("git", ["push", "-u", "origin", "HEAD:prod"], {
3323
+ cwd,
3324
+ env,
3325
+ stdio: ["inherit", 2, "inherit"]
3326
+ }).on("error", reject).on(
3327
+ "exit",
3328
+ (code) => code === 0 ? resolve() : reject(new Error(`git push exited with ${code}`))
3329
+ );
3330
+ })
3331
+ };
3332
+
3333
+ // src/commands/provision.ts
3334
+ var COLOR = {
3335
+ create: chalk8.green,
3336
+ skip: chalk8.gray,
3337
+ exists: chalk8.yellow,
3338
+ adopt: chalk8.cyan
3339
+ };
3340
+ var REPO = /^[\w.-]+\/[\w.-]+$/;
3341
+ var APPLY_TIMEOUT_MS = 15 * 6e4;
3342
+ var STILL_PROVISIONING = "The hub is still provisioning; run `foundrykit provision` again to see where it got to.";
3343
+ var ADOPT_HINT = "Found existing resources not recorded in the hub. Re-run with --adopt to record them instead of creating them.";
3344
+ async function maybePush(repo, opts, io, cwd, deps) {
3345
+ const say = opts.json ? io.err : io.out;
3346
+ const url = `https://github.com/${repo}`;
3347
+ const manual = (origin) => {
3348
+ if (origin) say(` git remote add origin ${url}.git`);
3349
+ say(" git push -u origin HEAD:prod");
3350
+ };
3351
+ if (opts.push === false) return "skipped";
3352
+ if (!REPO.test(repo)) {
3353
+ say(
3354
+ "The hub returned a repo name that isn't owner/name, so nothing was pushed."
3355
+ );
3356
+ return "skipped";
3357
+ }
3358
+ try {
3359
+ if (!await deps.git.isRepo(cwd)) {
3360
+ say("This folder is not a git repo. To trigger the first deploy, run:");
3361
+ say(' git init && git add -A && git commit -m "Initial commit"');
3362
+ manual(true);
3363
+ return "skipped";
3364
+ }
3365
+ if (await deps.git.hasOrigin(cwd)) {
3366
+ say(
3367
+ `origin is already set, so nothing was pushed. Push to the prod branch of ${url} to trigger the first deploy.`
3368
+ );
3369
+ return "origin-exists";
2118
3370
  }
2119
- let installedIds = Object.keys(installed);
2120
- if (installedIds.length === 0) {
2121
- console.log(
2122
- chalk6.gray(
2123
- "No install tracking found. Scanning filesystem for installed components..."
2124
- )
3371
+ if (!opts.yes && !opts.push) {
3372
+ if (opts.json || !io.isTTY) {
3373
+ say("Not pushed. To trigger the first deploy, run:");
3374
+ manual(true);
3375
+ return "skipped";
3376
+ }
3377
+ const { confirm } = await deps.prompt([
3378
+ {
3379
+ type: "confirm",
3380
+ name: "confirm",
3381
+ message: `Add ${url}.git as origin and push this branch as prod?`,
3382
+ default: true
3383
+ }
3384
+ ]);
3385
+ if (!confirm) {
3386
+ say("Not pushed. To trigger the first deploy, run:");
3387
+ manual(true);
3388
+ return "skipped";
3389
+ }
3390
+ }
3391
+ await deps.git.addOrigin(cwd, `${url}.git`);
3392
+ await deps.git.pushProd(cwd);
3393
+ return "pushed";
3394
+ } catch (e) {
3395
+ say(chalk8.red(`Push failed: ${e.message}`));
3396
+ say("Resources were provisioned. Push manually:");
3397
+ manual(!await deps.git.hasOrigin(cwd).catch(() => false));
3398
+ return "failed";
3399
+ }
3400
+ }
3401
+ async function runProvision(opts, io, cwd, deps) {
3402
+ try {
3403
+ const project = await loadProject(cwd, { readOnly: true });
3404
+ const ref = project.settings.hub?.project;
3405
+ if (!ref)
3406
+ throw new HubError(
3407
+ 0,
3408
+ "invalid_request",
3409
+ "Not linked to a hub project. Run `foundrykit link <org>/<project>`."
2125
3410
  );
2126
- const registry = getRegistry();
2127
- let allComponents;
2128
- try {
2129
- allComponents = await registry.getComponents();
2130
- } catch (error) {
2131
- console.error(chalk6.red("\u274C Failed to fetch registry:"));
2132
- console.error(
2133
- chalk6.red(error instanceof Error ? error.message : String(error))
3411
+ const hubUrl = await hubUrlFor(void 0, { ...io, cwd });
3412
+ const { token } = await requireSignedIn(hubUrl, io.home);
3413
+ const body = { project: ref, adopt: opts.adopt };
3414
+ const plan = await hubFetch(
3415
+ hubUrl,
3416
+ token,
3417
+ "POST",
3418
+ "/api/cli/provision/plan",
3419
+ body
3420
+ );
3421
+ if (!opts.json)
3422
+ for (const s of plan.steps)
3423
+ io.out(`${COLOR[s.action](s.action)} ${s.kind} ${s.summary}`);
3424
+ const exists = plan.steps.some((s) => s.action === "exists");
3425
+ if (opts.dryRun) {
3426
+ if (opts.json) io.out(JSON.stringify(plan));
3427
+ else if (exists) io.out(chalk8.yellow(ADOPT_HINT));
3428
+ return 0;
3429
+ }
3430
+ if (exists) throw new HubError(0, "adopt_required", ADOPT_HINT);
3431
+ const n = plan.steps.filter(
3432
+ (s) => s.action === "create" || s.action === "adopt"
3433
+ ).length;
3434
+ if (!n) {
3435
+ io.out(opts.json ? JSON.stringify(plan) : "Nothing to provision.");
3436
+ return 0;
3437
+ }
3438
+ if (!opts.yes) {
3439
+ if (opts.json)
3440
+ throw new HubError(
3441
+ 0,
3442
+ "invalid_request",
3443
+ "provision --json needs --yes."
2134
3444
  );
2135
- process.exit(1);
2136
- }
2137
- for (const component of allComponents) {
2138
- try {
2139
- const componentData = await registry.getComponent(component.id);
2140
- if (await hasConflictingFiles(componentData, options)) {
2141
- installed[component.id] = {
2142
- id: component.id,
2143
- version: null,
2144
- installedAt: (/* @__PURE__ */ new Date()).toISOString()
2145
- };
2146
- }
2147
- } catch {
3445
+ if (!io.isTTY)
3446
+ throw new HubError(
3447
+ 0,
3448
+ "invalid_request",
3449
+ "provision needs --yes when not run in a terminal."
3450
+ );
3451
+ const { confirm } = await deps.prompt([
3452
+ {
3453
+ type: "confirm",
3454
+ name: "confirm",
3455
+ message: `Provision ${n} resources for ${ref}?`,
3456
+ default: false
2148
3457
  }
3458
+ ]);
3459
+ if (!confirm) {
3460
+ io.out("Cancelled.");
3461
+ return 0;
2149
3462
  }
2150
- installedIds = Object.keys(installed);
2151
- if (installedIds.length === 0) {
2152
- console.log(
2153
- chalk6.yellow(
2154
- 'No installed components found. Use "foundrykit add" to install components.'
3463
+ }
3464
+ const res = await hubFetch(
3465
+ hubUrl,
3466
+ token,
3467
+ "POST",
3468
+ "/api/cli/provision/apply",
3469
+ body,
3470
+ { timeoutMs: deps.applyTimeoutMs ?? APPLY_TIMEOUT_MS }
3471
+ ).catch((e) => {
3472
+ if (e instanceof HubError && e.code === "timeout")
3473
+ e.message = STILL_PROVISIONING;
3474
+ throw e;
3475
+ });
3476
+ const ok = res.status === "succeeded";
3477
+ const push = () => ok && res.repo ? maybePush(res.repo, opts, io, project.root, deps) : Promise.resolve(null);
3478
+ if (opts.json) {
3479
+ const pushed = await push();
3480
+ io.out(JSON.stringify({ ...res, push: pushed }));
3481
+ return ok && pushed !== "failed" ? 0 : 1;
3482
+ }
3483
+ for (const r of res.resources)
3484
+ io.out(`${r.action} ${r.kind} ${r.url ?? r.externalId}`);
3485
+ for (const item of res.checklist) io.out(`- ${item}`);
3486
+ if (!ok) {
3487
+ io.out(chalk8.red(res.error?.message ?? "Provisioning failed."));
3488
+ io.out("Re-run `foundrykit provision` to continue.");
3489
+ return 1;
3490
+ }
3491
+ return await push() === "failed" ? 1 : 0;
3492
+ } catch (e) {
3493
+ return fail(io, opts.json, e);
3494
+ }
3495
+ }
3496
+ function provisionCommand() {
3497
+ return new Command8("provision").description("Create the linked project\u2019s resources through the hub").option("--dry-run", "show the plan and stop").option(
3498
+ "--yes",
3499
+ "apply without asking; also adds origin and pushes to prod (which deploys) unless --no-push"
3500
+ ).option("--adopt", "record existing resources instead of creating them").option("--push", "push this branch as prod after provisioning").option("--no-push", "never push").option("--json", "print JSON (non-interactive; needs --yes to apply)").action(
3501
+ async (opts) => {
3502
+ const io = defaultIO();
3503
+ process.exitCode = await runProvision(
3504
+ {
3505
+ dryRun: Boolean(opts.dryRun),
3506
+ yes: Boolean(opts.yes),
3507
+ adopt: Boolean(opts.adopt),
3508
+ push: opts.push,
3509
+ json: Boolean(opts.json)
3510
+ },
3511
+ io,
3512
+ io.cwd,
3513
+ { prompt: inquirer6.prompt, git: realGit }
3514
+ );
3515
+ }
3516
+ );
3517
+ }
3518
+
3519
+ // src/commands/update.ts
3520
+ import path9 from "path";
3521
+ import chalk9 from "chalk";
3522
+ import { Command as Command9 } from "commander";
3523
+ import fs9 from "fs-extra";
3524
+ import inquirer7 from "inquirer";
3525
+ function updateCommand() {
3526
+ return new Command9("update").description("Update tracked components").argument("[ids...]", "Component or block IDs (omit to update all tracked)").option(
3527
+ "-o, --opt",
3528
+ "interactively select which components to update, showing available upgrades"
3529
+ ).option("-f, --force", "bypass cache when checking versions (with --opt)").option("--overwrite", "overwrite files edited locally or not yet tracked").action(async (ids, options) => {
3530
+ try {
3531
+ if (options.opt && (!process.stdin.isTTY || !process.stdout.isTTY)) {
3532
+ console.error(
3533
+ chalk9.red(
3534
+ "\u274C --opt needs an interactive terminal. Pass component ids instead."
2155
3535
  )
2156
3536
  );
3537
+ process.exitCode = 1;
2157
3538
  return;
2158
3539
  }
3540
+ const project = await loadProject(process.cwd());
3541
+ process.chdir(project.root);
3542
+ let targets = ids;
3543
+ if (targets.length === 0) {
3544
+ const tracked = Object.keys(project.lock.components);
3545
+ const packages = await getInstalledFoundryKitPackageVersions(
3546
+ project.root
3547
+ );
3548
+ if (tracked.length === 0) {
3549
+ console.log(
3550
+ chalk9.yellow("No tracked components. Use `foundrykit add`.")
3551
+ );
3552
+ }
3553
+ targets = [
3554
+ ...tracked,
3555
+ ...Object.keys(packages).filter((id) => !tracked.includes(id))
3556
+ ];
3557
+ if (targets.length === 0) return;
3558
+ if (options.opt) {
3559
+ targets = await selectUpdates(project, targets, packages, options);
3560
+ if (targets.length === 0) return;
3561
+ }
3562
+ }
2159
3563
  console.log(
2160
- chalk6.gray(
2161
- `Found ${installedIds.length} installed component(s) via filesystem scan.`
2162
- )
3564
+ chalk9.blue(`\u{1F504} Updating ${targets.length} component(s)...`)
2163
3565
  );
2164
- }
2165
- if (options.opt) {
2166
- console.log(
2167
- chalk6.blue(
2168
- `\u{1F50D} Checking for updates across ${installedIds.length} installed component(s)...`
2169
- )
3566
+ let outcome;
3567
+ try {
3568
+ outcome = await runUpdates(project, targets, {
3569
+ overwrite: Boolean(options.overwrite),
3570
+ prompt: interactivePrompt()
3571
+ });
3572
+ } finally {
3573
+ await project.saveLock();
3574
+ }
3575
+ printReport(outcome);
3576
+ if (outcome.failed.length > 0) process.exitCode = 1;
3577
+ } catch (error) {
3578
+ console.error(chalk9.red("\u274C Update failed:"));
3579
+ console.error(
3580
+ chalk9.red(error instanceof Error ? error.message : String(error))
2170
3581
  );
2171
- const registry = getRegistry();
2172
- const withUpdates = [];
2173
- const upToDate = [];
2174
- for (const compId of installedIds) {
3582
+ process.exitCode = 1;
3583
+ }
3584
+ });
3585
+ }
3586
+ async function runUpdates(project, ids, opts) {
3587
+ const targets = ids.length > 0 ? ids : Object.keys(project.lock.components);
3588
+ const registry = getRegistry(void 0, project.settings);
3589
+ const results = [];
3590
+ const failed = /* @__PURE__ */ new Set();
3591
+ const apply = async (data, overwrite = opts.overwrite) => {
3592
+ const result = await applyComponent(project, data, { ...opts, overwrite });
3593
+ results.push(result);
3594
+ if (result.failed.length > 0) failed.add(data.id);
3595
+ };
3596
+ const fail2 = (id, error) => {
3597
+ console.error(
3598
+ chalk9.red(
3599
+ `\u274C Failed to update ${id}: ${error instanceof Error ? error.message : String(error)}`
3600
+ )
3601
+ );
3602
+ failed.add(id);
3603
+ };
3604
+ for (const id of targets) {
3605
+ console.log(chalk9.blue(`
3606
+ \u{1F504} Updating ${id}...`));
3607
+ try {
3608
+ const data = await registry.getComponent(id, true);
3609
+ if (data.files.length > 0) await apply(data);
3610
+ for (const dep of data.registryDependencies ?? []) {
3611
+ if (["hooks", "types"].includes(dep) || project.lock.components[dep])
3612
+ continue;
2175
3613
  try {
2176
- const data = await registry.getComponent(compId, options.force);
2177
- const installedVersion = installedFoundryKitPackages[compId] ?? installed[compId]?.version ?? null;
2178
- const latestVersion = data.version ?? null;
2179
- const hasUpdate = latestVersion !== null && installedVersion !== null && compareVersions2(latestVersion, installedVersion) > 0;
2180
- const unknownVersion = installedVersion === null || latestVersion === null;
2181
- if (hasUpdate || unknownVersion) {
2182
- withUpdates.push({
2183
- id: compId,
2184
- installed: installedVersion,
2185
- latest: latestVersion
2186
- });
2187
- } else {
2188
- upToDate.push(compId);
2189
- }
2190
- } catch {
2191
- withUpdates.push({
2192
- id: compId,
2193
- installed: installed[compId]?.version ?? null,
2194
- latest: null
2195
- });
3614
+ const depData = await registry.getComponent(dep, true);
3615
+ if (depData.files.length > 0) await apply(depData, false);
3616
+ } catch (error) {
3617
+ console.log(
3618
+ chalk9.yellow(
3619
+ ` \u26A0 Could not install dependency "${dep}": ${error instanceof Error ? error.message : String(error)}`
3620
+ )
3621
+ );
2196
3622
  }
2197
3623
  }
2198
- if (upToDate.length > 0) {
2199
- console.log(
2200
- chalk6.gray(`
2201
- \u2713 Already up to date: ${upToDate.join(", ")}`)
2202
- );
2203
- }
2204
- if (withUpdates.length === 0) {
2205
- console.log(chalk6.green("\n\u2705 All components are up to date."));
2206
- return;
3624
+ await handlePackageDependencies(data, { force: true });
3625
+ } catch (error) {
3626
+ fail2(id, error);
3627
+ }
3628
+ }
3629
+ return { results, failed: [...failed] };
3630
+ }
3631
+ function printReport({
3632
+ results,
3633
+ failed
3634
+ }) {
3635
+ console.log("");
3636
+ for (const result of results) reportApply(result);
3637
+ const count = (key) => results.reduce((n, r) => n + r[key].length, 0);
3638
+ const summary = [
3639
+ `${count("written")} written`,
3640
+ `${count("upToDate")} up to date`,
3641
+ `${count("kept")} kept`,
3642
+ `${count("skippedEdited")} skipped (edited)`,
3643
+ `${count("skippedUnknown")} skipped (untracked)`,
3644
+ `${count("droppedFromLock")} no longer tracked`
3645
+ ].join(", ");
3646
+ console.log(chalk9.bold(`
3647
+ ${summary}`));
3648
+ if (failed.length > 0) {
3649
+ console.error(
3650
+ chalk9.red(`\u274C ${failed.length} component(s) failed: ${failed.join(", ")}`)
3651
+ );
3652
+ } else {
3653
+ console.log(chalk9.green("\u2705 Update complete."));
3654
+ }
3655
+ }
3656
+ async function selectUpdates(project, targets, packages, options) {
3657
+ console.log(
3658
+ chalk9.blue(
3659
+ `\u{1F50D} Checking for updates across ${targets.length} component(s)...`
3660
+ )
3661
+ );
3662
+ const registry = getRegistry(void 0, project.settings);
3663
+ const withUpdates = [];
3664
+ const upToDate = [];
3665
+ for (const compId of targets) {
3666
+ const installedVersion = packages[compId] ?? project.lock.components[compId]?.version ?? null;
3667
+ try {
3668
+ const data = await registry.getComponent(compId, options.force);
3669
+ const latestVersion = data.version ?? null;
3670
+ const hasUpdate = latestVersion !== null && installedVersion !== null && compareVersions2(latestVersion, installedVersion) > 0;
3671
+ const unknownVersion = installedVersion === null || latestVersion === null;
3672
+ if (hasUpdate || unknownVersion) {
3673
+ withUpdates.push({
3674
+ id: compId,
3675
+ installed: installedVersion,
3676
+ latest: latestVersion
3677
+ });
3678
+ } else {
3679
+ upToDate.push(compId);
2207
3680
  }
2208
- const choices = withUpdates.map(
2209
- ({ id: compId, installed: inst, latest }) => {
2210
- let versionLabel;
2211
- if (inst === null && latest === null) {
2212
- versionLabel = chalk6.gray("(version unknown)");
2213
- } else if (latest === null) {
2214
- versionLabel = chalk6.gray(
2215
- `(installed: ${inst} \u2014 registry version unknown)`
2216
- );
2217
- } else if (inst === null) {
2218
- versionLabel = chalk6.cyan(
2219
- `(latest: ${latest} \u2014 install version not tracked)`
2220
- );
2221
- } else {
2222
- versionLabel = chalk6.cyan(`(${inst} \u2192 ${latest})`);
2223
- }
2224
- return {
2225
- name: `${compId} ${versionLabel}`,
2226
- value: compId,
2227
- checked: true
2228
- };
2229
- }
3681
+ } catch {
3682
+ withUpdates.push({
3683
+ id: compId,
3684
+ installed: installedVersion,
3685
+ latest: null
3686
+ });
3687
+ }
3688
+ }
3689
+ if (upToDate.length > 0) {
3690
+ console.log(chalk9.gray(`
3691
+ \u2713 Already up to date: ${upToDate.join(", ")}`));
3692
+ }
3693
+ if (withUpdates.length === 0) {
3694
+ console.log(chalk9.green("\n\u2705 All components are up to date."));
3695
+ return [];
3696
+ }
3697
+ const choices = withUpdates.map(({ id: compId, installed: inst, latest }) => {
3698
+ let versionLabel;
3699
+ if (inst === null && latest === null) {
3700
+ versionLabel = chalk9.gray("(version unknown)");
3701
+ } else if (latest === null) {
3702
+ versionLabel = chalk9.gray(
3703
+ `(installed: ${inst} \u2014 registry version unknown)`
2230
3704
  );
2231
- const { selectedIds } = await inquirer3.prompt([
2232
- {
2233
- type: "checkbox",
2234
- name: "selectedIds",
2235
- message: "Select components to update:",
2236
- choices,
2237
- pageSize: 20
2238
- }
2239
- ]);
2240
- if (selectedIds.length === 0) {
2241
- console.log(chalk6.yellow("No components selected."));
2242
- return;
2243
- }
2244
- await runUpdates(selectedIds, options);
2245
- } else {
2246
- console.log(
2247
- chalk6.blue(
2248
- `\u{1F504} Updating all ${installedIds.length} installed component(s)...`
2249
- )
3705
+ } else if (inst === null) {
3706
+ versionLabel = chalk9.cyan(
3707
+ `(latest: ${latest} \u2014 install version not tracked)`
2250
3708
  );
2251
- await runUpdates(installedIds, options);
3709
+ } else {
3710
+ versionLabel = chalk9.cyan(`(${inst} \u2192 ${latest})`);
2252
3711
  }
3712
+ return {
3713
+ name: `${compId} ${versionLabel}`,
3714
+ value: compId,
3715
+ checked: true
3716
+ };
2253
3717
  });
3718
+ const { selectedIds } = await inquirer7.prompt([
3719
+ {
3720
+ type: "checkbox",
3721
+ name: "selectedIds",
3722
+ message: "Select components to update:",
3723
+ choices,
3724
+ pageSize: 20
3725
+ }
3726
+ ]);
3727
+ if (selectedIds.length === 0) {
3728
+ console.log(chalk9.yellow("No components selected."));
3729
+ }
3730
+ return selectedIds;
2254
3731
  }
2255
- async function getInstalledFoundryKitPackageVersions() {
2256
- const packageJsonPath = path5.join(process.cwd(), "package.json");
2257
- if (!fs5.existsSync(packageJsonPath)) {
3732
+ async function getInstalledFoundryKitPackageVersions(root) {
3733
+ const packageJsonPath = path9.join(root, "package.json");
3734
+ if (!fs9.existsSync(packageJsonPath)) {
2258
3735
  return {};
2259
3736
  }
2260
- const packageJson2 = await fs5.readJson(packageJsonPath);
3737
+ const packageJson2 = await fs9.readJson(packageJsonPath);
2261
3738
  const dependencies = {
2262
3739
  ...packageJson2.dependencies,
2263
3740
  ...packageJson2.devDependencies,
@@ -2286,35 +3763,206 @@ function normalizeVersionSpec(version) {
2286
3763
  }
2287
3764
  return version.replace(/^[^\d]*/, "").split("-")[0]?.replace(/[^\d.]/g, "") || "0";
2288
3765
  }
2289
- async function runUpdates(ids, options) {
2290
- let failed = 0;
2291
- for (const compId of ids) {
2292
- try {
2293
- console.log(chalk6.blue(`
2294
- \u{1F504} Updating ${compId}...`));
2295
- await addSingleComponent(compId, {
2296
- ...options,
2297
- overwrite: true,
2298
- force: true
3766
+
3767
+ // src/commands/upgrade.ts
3768
+ import { execFile as execFile3 } from "child_process";
3769
+ import path11 from "path";
3770
+ import { promisify as promisify2 } from "util";
3771
+ import chalk10 from "chalk";
3772
+ import { Command as Command10 } from "commander";
3773
+ import fs11 from "fs-extra";
3774
+ import inquirer8 from "inquirer";
3775
+
3776
+ // src/lib/codemods.ts
3777
+ import path10 from "path";
3778
+ import fs10 from "fs-extra";
3779
+ import { glob } from "glob";
3780
+ var DEP_FIELDS = [
3781
+ "dependencies",
3782
+ "devDependencies",
3783
+ "peerDependencies",
3784
+ "optionalDependencies"
3785
+ ];
3786
+ var SOURCE_GLOB = "**/*.{ts,tsx,mts,cts,js,jsx,mjs,cjs,json,md,mdx,css,scss}";
3787
+ var IGNORE = [
3788
+ "**/node_modules/**",
3789
+ "**/.next/**",
3790
+ "**/dist/**",
3791
+ "**/build/**",
3792
+ "**/.git/**",
3793
+ "**/package-lock.json",
3794
+ "**/CHANGELOG.md"
3795
+ ];
3796
+ var escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
3797
+ function renameDependency(pkg, from, to, range) {
3798
+ let changed = false;
3799
+ for (const field of DEP_FIELDS) {
3800
+ const deps = pkg[field];
3801
+ if (!deps || !(from in deps)) continue;
3802
+ pkg[field] = Object.fromEntries(
3803
+ Object.entries(deps).map(([k, v]) => k === from ? [to, range] : [k, v])
3804
+ );
3805
+ changed = true;
3806
+ }
3807
+ return changed;
3808
+ }
3809
+ function renamePackage(from, to, range) {
3810
+ const specifier = new RegExp(`${escapeRe(from)}(?![a-z0-9._~-])`, "g");
3811
+ return {
3812
+ id: `rename:${from}`,
3813
+ detect(pkg) {
3814
+ for (const field of DEP_FIELDS) {
3815
+ const version = pkg[field]?.[from];
3816
+ if (version) return `${from}@${version} \u2192 ${to}@${range}`;
3817
+ }
3818
+ return null;
3819
+ },
3820
+ async run(root, opts = {}) {
3821
+ const files = await glob(SOURCE_GLOB, {
3822
+ cwd: root,
3823
+ ignore: IGNORE,
3824
+ nodir: true
2299
3825
  });
2300
- } catch (error) {
2301
- console.error(chalk6.red(`\u274C Failed to update ${compId}:`));
2302
- console.error(
2303
- chalk6.red(error instanceof Error ? error.message : String(error))
2304
- );
2305
- failed++;
3826
+ const changed = [];
3827
+ for (const rel of files.sort()) {
3828
+ const file = path10.join(root, rel);
3829
+ const text = await fs10.readFile(file, "utf8");
3830
+ if (!text.includes(from)) continue;
3831
+ let next = text;
3832
+ if (path10.basename(rel) === "package.json") {
3833
+ const pkg = JSON.parse(text);
3834
+ if (renameDependency(pkg, from, to, range)) {
3835
+ const indent = text.match(/^[ \t]+(?=")/m)?.[0] ?? " ";
3836
+ next = `${JSON.stringify(pkg, null, indent)}
3837
+ `;
3838
+ }
3839
+ }
3840
+ next = next.replace(specifier, to);
3841
+ if (next === text) continue;
3842
+ if (!opts.dryRun) await fs10.writeFile(file, next);
3843
+ changed.push(rel);
3844
+ }
3845
+ return changed;
2306
3846
  }
3847
+ };
3848
+ }
3849
+ var CODEMODS = [
3850
+ renamePackage(
3851
+ "@foundrykit/advanced-forms-plugin",
3852
+ "@foundrykit/form-plugin",
3853
+ "^1.16.4"
3854
+ ),
3855
+ renamePackage(
3856
+ "@foundrykit/advanced-seo-plugin",
3857
+ "@foundrykit/seo-plugin",
3858
+ "^0.3.1"
3859
+ )
3860
+ ];
3861
+
3862
+ // src/commands/upgrade.ts
3863
+ async function hasUncommittedChanges(cwd) {
3864
+ try {
3865
+ const { stdout } = await promisify2(execFile3)(
3866
+ "git",
3867
+ ["status", "--porcelain"],
3868
+ { cwd }
3869
+ );
3870
+ return stdout.trim() !== "";
3871
+ } catch {
3872
+ return false;
2307
3873
  }
2308
- if (failed > 0) {
2309
- console.log(chalk6.yellow(`
2310
- \u26A0 ${failed} component(s) failed to update.`));
2311
- process.exit(1);
2312
- } else {
3874
+ }
3875
+ async function runUpgrade(opts, cwd, prompt = inquirer8.prompt) {
3876
+ const pkgPath = path11.join(cwd, "package.json");
3877
+ if (!await fs11.pathExists(pkgPath)) {
3878
+ console.error(
3879
+ chalk10.red("No package.json here. Run this in your project root.")
3880
+ );
3881
+ return 1;
3882
+ }
3883
+ const pkg = await fs11.readJson(pkgPath);
3884
+ const found = CODEMODS.map((mod) => ({ mod, summary: mod.detect(pkg) })).filter(
3885
+ (f) => f.summary !== null
3886
+ );
3887
+ if (found.length === 0) {
2313
3888
  console.log(
2314
- chalk6.green(`
2315
- \u2705 ${ids.length} component(s) updated successfully!`)
3889
+ chalk10.green("Nothing to upgrade. No codemods apply to this project.")
2316
3890
  );
3891
+ return 0;
3892
+ }
3893
+ console.log(chalk10.bold("These codemods apply to this project:"));
3894
+ for (const f of found) console.log(` \u2022 ${f.summary}`);
3895
+ let selected = found;
3896
+ if (!opts.yes && !opts.dryRun) {
3897
+ if (await hasUncommittedChanges(cwd)) {
3898
+ const { go } = await prompt([
3899
+ {
3900
+ type: "confirm",
3901
+ name: "go",
3902
+ message: "You have uncommitted changes. Codemods edit files in place; continue anyway?",
3903
+ default: false
3904
+ }
3905
+ ]);
3906
+ if (!go) return 1;
3907
+ }
3908
+ const { ids } = await prompt([
3909
+ {
3910
+ type: "checkbox",
3911
+ name: "ids",
3912
+ message: "Run which codemods?",
3913
+ choices: found.map((f) => ({
3914
+ name: f.summary,
3915
+ value: f.mod.id,
3916
+ checked: true
3917
+ }))
3918
+ }
3919
+ ]);
3920
+ selected = found.filter((f) => ids.includes(f.mod.id));
3921
+ if (selected.length === 0) return 0;
2317
3922
  }
3923
+ const changed = /* @__PURE__ */ new Set();
3924
+ for (const { mod, summary } of selected) {
3925
+ const files = await mod.run(cwd, { dryRun: opts.dryRun });
3926
+ console.log(`
3927
+ ${chalk10.cyan(summary)}: ${files.length} file(s)`);
3928
+ for (const file of files) {
3929
+ console.log(` ${file}`);
3930
+ changed.add(file);
3931
+ }
3932
+ }
3933
+ if (opts.dryRun) {
3934
+ console.log(chalk10.yellow("\nDry run: nothing was written."));
3935
+ return 0;
3936
+ }
3937
+ const pm = await detectPackageManager();
3938
+ if (opts.install !== false) {
3939
+ console.log(chalk10.blue(`
3940
+ Running ${pm} install...`));
3941
+ try {
3942
+ await runPackageManager(pm, ["install"], { cwd });
3943
+ } catch (e) {
3944
+ console.error(chalk10.red(e.message));
3945
+ console.log(`Run \`${pm} install\` yourself to finish.`);
3946
+ return 1;
3947
+ }
3948
+ }
3949
+ console.log(chalk10.green(`
3950
+ Done. ${changed.size} file(s) changed.`));
3951
+ console.log("Next:");
3952
+ console.log(
3953
+ ` \u2022 Payload site? Run \`${pm} payload generate:importmap\` to regenerate the admin import map.`
3954
+ );
3955
+ console.log(
3956
+ " \u2022 Review with `git diff`, then build and test before committing."
3957
+ );
3958
+ return 0;
3959
+ }
3960
+ function upgradeCommand() {
3961
+ return new Command10("upgrade").description(
3962
+ "Find and run codemods for renamed or changed FoundryKit packages"
3963
+ ).option("-y, --yes", "run every applicable codemod without asking").option("--dry-run", "list the files that would change and stop").option("--no-install", "skip the package manager install afterwards").action(async (opts) => {
3964
+ process.exitCode = await runUpgrade(opts, process.cwd());
3965
+ });
2318
3966
  }
2319
3967
 
2320
3968
  // src/index.ts
@@ -2323,12 +3971,20 @@ var __dirname = dirname(__filename);
2323
3971
  var packageJson = JSON.parse(
2324
3972
  readFileSync(join(__dirname, "..", "package.json"), "utf-8")
2325
3973
  );
2326
- var program = new Command6();
3974
+ var program = new Command11();
2327
3975
  program.name("foundrykit").description("FoundryKit CLI - Component library management tool").version(packageJson.version);
2328
3976
  program.addCommand(initCommand());
2329
3977
  program.addCommand(listCommand());
2330
3978
  program.addCommand(addCommand());
2331
3979
  program.addCommand(updateCommand());
3980
+ program.addCommand(upgradeCommand());
2332
3981
  program.addCommand(doctorCommand());
3982
+ program.addCommand(loginCommand());
3983
+ program.addCommand(logoutCommand());
3984
+ program.addCommand(whoamiCommand());
3985
+ program.addCommand(linkCommand());
3986
+ program.addCommand(connectCommand());
3987
+ program.addCommand(connectionsCommand());
3988
+ program.addCommand(provisionCommand());
2333
3989
  program.parse();
2334
3990
  //# sourceMappingURL=index.js.map