kaven-cli 0.4.0 → 0.5.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.
Files changed (57) hide show
  1. package/README.md +154 -215
  2. package/dist/EnvManager-NMS3NMIE.js +15 -0
  3. package/dist/MarketplaceClient-YCFH2VU4.js +1 -0
  4. package/dist/chunk-JHLQ46NG.js +1 -0
  5. package/dist/index.d.ts +4 -0
  6. package/dist/index.js +216 -286
  7. package/dist/tier-table-DQMPQSI2.js +6 -0
  8. package/package.json +26 -10
  9. package/dist/commands/auth/login.js +0 -122
  10. package/dist/commands/auth/logout.js +0 -23
  11. package/dist/commands/auth/whoami.js +0 -36
  12. package/dist/commands/cache/index.js +0 -43
  13. package/dist/commands/config/features.js +0 -1026
  14. package/dist/commands/config/index.js +0 -95
  15. package/dist/commands/index.js +0 -2
  16. package/dist/commands/init/index.js +0 -197
  17. package/dist/commands/init-ci/index.js +0 -153
  18. package/dist/commands/license/index.js +0 -10
  19. package/dist/commands/license/status.js +0 -44
  20. package/dist/commands/license/tier-table.js +0 -46
  21. package/dist/commands/marketplace/browse.js +0 -186
  22. package/dist/commands/marketplace/install.js +0 -263
  23. package/dist/commands/marketplace/list.js +0 -122
  24. package/dist/commands/module/activate.js +0 -206
  25. package/dist/commands/module/add.js +0 -69
  26. package/dist/commands/module/doctor.js +0 -175
  27. package/dist/commands/module/publish.js +0 -258
  28. package/dist/commands/module/remove.js +0 -58
  29. package/dist/commands/telemetry/view.js +0 -27
  30. package/dist/commands/upgrade/check.js +0 -162
  31. package/dist/commands/upgrade/index.js +0 -185
  32. package/dist/core/AuthService.js +0 -222
  33. package/dist/core/CacheManager.js +0 -154
  34. package/dist/core/ConfigManager.js +0 -166
  35. package/dist/core/EnvManager.js +0 -196
  36. package/dist/core/ErrorRecovery.js +0 -192
  37. package/dist/core/LicenseService.js +0 -83
  38. package/dist/core/ManifestParser.js +0 -52
  39. package/dist/core/MarkerService.js +0 -62
  40. package/dist/core/ModuleDoctor.js +0 -451
  41. package/dist/core/ModuleInstaller.js +0 -169
  42. package/dist/core/ProjectInitializer.js +0 -166
  43. package/dist/core/RegistryResolver.js +0 -95
  44. package/dist/core/SchemaActivator.js +0 -270
  45. package/dist/core/ScriptRunner.js +0 -73
  46. package/dist/core/SignatureVerifier.js +0 -75
  47. package/dist/core/index.js +0 -2
  48. package/dist/infrastructure/Container.js +0 -37
  49. package/dist/infrastructure/MarketplaceClient.js +0 -399
  50. package/dist/infrastructure/TelemetryBuffer.js +0 -73
  51. package/dist/infrastructure/TransactionalFileSystem.js +0 -77
  52. package/dist/infrastructure/errors.js +0 -63
  53. package/dist/infrastructure/index.js +0 -2
  54. package/dist/types/auth.js +0 -2
  55. package/dist/types/manifest.js +0 -45
  56. package/dist/types/markers.js +0 -10
  57. package/dist/types/marketplace.js +0 -2
@@ -1,258 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.moduleJsonSchema = void 0;
7
- exports.modulePublish = modulePublish;
8
- const chalk_1 = __importDefault(require("chalk"));
9
- const ora_1 = __importDefault(require("ora"));
10
- const path_1 = __importDefault(require("path"));
11
- const fs_extra_1 = __importDefault(require("fs-extra"));
12
- const crypto_1 = __importDefault(require("crypto"));
13
- const os_1 = __importDefault(require("os"));
14
- const zod_1 = require("zod");
15
- const AuthService_1 = require("../../core/AuthService");
16
- const MarketplaceClient_1 = require("../../infrastructure/MarketplaceClient");
17
- // Zod schema for module.json
18
- exports.moduleJsonSchema = zod_1.z.object({
19
- name: zod_1.z.string().min(1),
20
- slug: zod_1.z.string().min(1).regex(/^[a-z0-9-]+$/),
21
- version: zod_1.z.string().regex(/^\d+\.\d+\.\d+$/),
22
- description: zod_1.z.string().min(1),
23
- author: zod_1.z.string().optional(),
24
- license: zod_1.z.string().optional(),
25
- tier: zod_1.z.enum(["free", "starter", "complete", "pro"]),
26
- });
27
- const SIGNING_KEY_PATH = path_1.default.join(os_1.default.homedir(), ".kaven", "signing-key.json");
28
- /** Load or generate Ed25519 signing key pair. */
29
- async function getSigningKey() {
30
- if (await fs_extra_1.default.pathExists(SIGNING_KEY_PATH)) {
31
- try {
32
- const stored = await fs_extra_1.default.readJson(SIGNING_KEY_PATH);
33
- const privateKey = crypto_1.default.createPrivateKey({
34
- key: Buffer.from(stored.privateKey, "base64"),
35
- type: "pkcs8",
36
- format: "der",
37
- });
38
- const publicKey = crypto_1.default.createPublicKey(privateKey);
39
- return { privateKey, publicKey };
40
- }
41
- catch {
42
- // Fall through to generate new key
43
- }
44
- }
45
- const { privateKey, publicKey } = crypto_1.default.generateKeyPairSync("ed25519");
46
- const privateKeyDer = privateKey.export({ type: "pkcs8", format: "der" });
47
- const publicKeyDer = publicKey.export({ type: "spki", format: "der" });
48
- await fs_extra_1.default.ensureDir(path_1.default.dirname(SIGNING_KEY_PATH));
49
- await fs_extra_1.default.writeJson(SIGNING_KEY_PATH, {
50
- privateKey: privateKeyDer.toString("base64"),
51
- publicKey: publicKeyDer.toString("base64"),
52
- }, { spaces: 2 });
53
- if (process.platform !== "win32") {
54
- await fs_extra_1.default.chmod(SIGNING_KEY_PATH, 0o600);
55
- }
56
- return { privateKey, publicKey };
57
- }
58
- /** Generate SHA-256 checksum of a file. */
59
- async function sha256File(filePath) {
60
- const data = await fs_extra_1.default.readFile(filePath);
61
- return crypto_1.default.createHash("sha256").update(data).digest("hex");
62
- }
63
- /** Create tar.gz archive of current directory, excluding common noise. */
64
- async function createTarball(sourceDir, outputPath) {
65
- const tar = await import("tar");
66
- await tar.create({
67
- gzip: true,
68
- file: outputPath,
69
- cwd: sourceDir,
70
- filter: (filePath) => {
71
- const normalized = filePath.replace(/\\/g, "/");
72
- const excluded = [
73
- "node_modules",
74
- ".git",
75
- "dist",
76
- ".env",
77
- ];
78
- for (const exc of excluded) {
79
- if (normalized.startsWith(exc + "/") ||
80
- normalized === exc ||
81
- normalized.endsWith(".log")) {
82
- return false;
83
- }
84
- }
85
- return true;
86
- },
87
- }, ["."]);
88
- }
89
- async function modulePublish(options) {
90
- const cwd = process.cwd();
91
- // 1. Read and validate module.json
92
- const moduleJsonPath = path_1.default.join(cwd, "module.json");
93
- if (!(await fs_extra_1.default.pathExists(moduleJsonPath))) {
94
- console.error(chalk_1.default.red("Error: module.json not found in current directory."));
95
- console.error(chalk_1.default.gray("Try: run this command from inside a module directory"));
96
- process.exit(1);
97
- }
98
- let moduleJson;
99
- try {
100
- const raw = await fs_extra_1.default.readJson(moduleJsonPath);
101
- const result = exports.moduleJsonSchema.safeParse(raw);
102
- if (!result.success) {
103
- console.error(chalk_1.default.red("Error: Invalid module.json:"));
104
- for (const issue of result.error.issues) {
105
- console.error(chalk_1.default.red(` - ${issue.path.join(".")}: ${issue.message}`));
106
- }
107
- process.exit(1);
108
- }
109
- moduleJson = result.data;
110
- }
111
- catch (error) {
112
- console.error(chalk_1.default.red(`Error: Failed to parse module.json: ${error instanceof Error ? error.message : String(error)}`));
113
- process.exit(1);
114
- }
115
- console.log();
116
- console.log(chalk_1.default.bold(`Publishing module: ${moduleJson.name} v${moduleJson.version}`));
117
- console.log(chalk_1.default.gray(`Slug: ${moduleJson.slug} | Tier: ${moduleJson.tier}`));
118
- console.log();
119
- // 2. Create tar.gz
120
- const tarballPath = path_1.default.join(os_1.default.tmpdir(), `kaven-${moduleJson.slug}-${moduleJson.version}.tar.gz`);
121
- const packageSpinner = (0, ora_1.default)("Creating module package...").start();
122
- try {
123
- await createTarball(cwd, tarballPath);
124
- const stats = await fs_extra_1.default.stat(tarballPath);
125
- packageSpinner.succeed(`Package created (${(stats.size / 1024).toFixed(1)} KB)`);
126
- }
127
- catch (error) {
128
- packageSpinner.fail("Failed to create package");
129
- console.error(chalk_1.default.red(error instanceof Error ? error.message : String(error)));
130
- await fs_extra_1.default.remove(tarballPath).catch(() => { });
131
- process.exit(1);
132
- }
133
- // 3. Generate checksum
134
- const checksumSpinner = (0, ora_1.default)("Computing SHA-256 checksum...").start();
135
- let checksum;
136
- try {
137
- checksum = await sha256File(tarballPath);
138
- checksumSpinner.succeed(`Checksum: ${checksum.substring(0, 16)}...`);
139
- }
140
- catch {
141
- checksumSpinner.fail("Failed to compute checksum");
142
- await fs_extra_1.default.remove(tarballPath).catch(() => { });
143
- process.exit(1);
144
- return;
145
- }
146
- // 4. Sign the checksum
147
- const signSpinner = (0, ora_1.default)("Signing package...").start();
148
- let signatureBase64;
149
- let publicKeyBase64;
150
- try {
151
- const { privateKey, publicKey } = await getSigningKey();
152
- const signature = crypto_1.default.sign(null, Buffer.from(checksum), privateKey);
153
- signatureBase64 = signature.toString("base64");
154
- const publicKeyDer = publicKey.export({
155
- type: "spki", format: "der",
156
- });
157
- publicKeyBase64 = publicKeyDer.toString("base64");
158
- signSpinner.succeed(`Package signed (${signatureBase64.substring(0, 16)}...)`);
159
- }
160
- catch {
161
- signSpinner.fail("Failed to sign package");
162
- await fs_extra_1.default.remove(tarballPath).catch(() => { });
163
- process.exit(1);
164
- return;
165
- }
166
- if (options.dryRun) {
167
- console.log();
168
- console.log(chalk_1.default.yellow("Dry-run mode: skipping upload and release creation."));
169
- console.log(chalk_1.default.green("✅ Package validated successfully."));
170
- await fs_extra_1.default.remove(tarballPath).catch(() => { });
171
- return;
172
- }
173
- // 5. Get presigned upload URL
174
- const authService = new AuthService_1.AuthService();
175
- try {
176
- await authService.getValidToken();
177
- }
178
- catch {
179
- console.error(chalk_1.default.red("Error: Not authenticated. Run 'kaven auth login' first."));
180
- await fs_extra_1.default.remove(tarballPath).catch(() => { });
181
- process.exit(1);
182
- return;
183
- }
184
- const client = new MarketplaceClient_1.MarketplaceClient(authService);
185
- const stats = await fs_extra_1.default.stat(tarballPath);
186
- const urlSpinner = (0, ora_1.default)("Getting upload URL...").start();
187
- let uploadUrl;
188
- let s3Key;
189
- try {
190
- const uploadUrlResult = await client.getUploadUrl(moduleJson.slug, moduleJson.version, stats.size);
191
- uploadUrl = uploadUrlResult.uploadUrl;
192
- s3Key = uploadUrlResult.s3Key;
193
- urlSpinner.succeed("Upload URL received");
194
- }
195
- catch (error) {
196
- urlSpinner.fail("Failed to get upload URL");
197
- console.error(chalk_1.default.red(error instanceof Error ? error.message : String(error)));
198
- await fs_extra_1.default.remove(tarballPath).catch(() => { });
199
- process.exit(1);
200
- return;
201
- }
202
- // 6. Upload tar.gz to presigned URL
203
- const uploadSpinner = (0, ora_1.default)(`Uploading package (${(stats.size / 1024).toFixed(1)} KB)...`).start();
204
- try {
205
- const fileBuffer = await fs_extra_1.default.readFile(tarballPath);
206
- const response = await fetch(uploadUrl, {
207
- method: "PUT",
208
- headers: {
209
- "Content-Type": "application/gzip",
210
- "Content-Length": String(stats.size),
211
- },
212
- body: fileBuffer,
213
- });
214
- if (!response.ok) {
215
- throw new Error(`Upload failed: ${response.status} ${response.statusText}`);
216
- }
217
- uploadSpinner.succeed("Package uploaded successfully");
218
- }
219
- catch (error) {
220
- uploadSpinner.fail("Upload failed");
221
- console.error(chalk_1.default.red(error instanceof Error ? error.message : String(error)));
222
- await fs_extra_1.default.remove(tarballPath).catch(() => { });
223
- process.exit(1);
224
- return;
225
- }
226
- // 7. Create release record
227
- const releaseSpinner = (0, ora_1.default)("Creating release record...").start();
228
- try {
229
- const release = await client.createRelease({
230
- moduleSlug: moduleJson.slug,
231
- version: moduleJson.version,
232
- s3Key,
233
- checksum,
234
- signature: signatureBase64,
235
- publicKey: publicKeyBase64,
236
- changelog: options.changelog,
237
- });
238
- releaseSpinner.succeed(`Release created: ${moduleJson.slug}@${release.version} (ID: ${release.id})`);
239
- }
240
- catch (error) {
241
- releaseSpinner.fail("Failed to create release");
242
- console.error(chalk_1.default.red(error instanceof Error ? error.message : String(error)));
243
- await fs_extra_1.default.remove(tarballPath).catch(() => { });
244
- process.exit(1);
245
- return;
246
- }
247
- // Cleanup temp file
248
- await fs_extra_1.default.remove(tarballPath).catch(() => { });
249
- console.log();
250
- console.log(chalk_1.default.green(`✅ Published ${moduleJson.name} v${moduleJson.version} to the Kaven Marketplace!`));
251
- console.log(chalk_1.default.gray(`View your module at: https://marketplace.kaven.site/modules/${moduleJson.slug}`));
252
- // Show next steps
253
- console.log();
254
- console.log(chalk_1.default.bold("Next steps:"));
255
- console.log(chalk_1.default.gray(" 1. Share your module with the community"));
256
- console.log(chalk_1.default.gray(" 2. Monitor installation metrics"));
257
- console.log(chalk_1.default.gray(" 3. Update module with 'kaven module publish' when ready"));
258
- }
@@ -1,58 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.moduleRemove = moduleRemove;
7
- const chalk_1 = __importDefault(require("chalk"));
8
- const ora_1 = __importDefault(require("ora"));
9
- const path_1 = __importDefault(require("path"));
10
- const fs_extra_1 = __importDefault(require("fs-extra"));
11
- const ModuleInstaller_1 = require("../../core/ModuleInstaller");
12
- const TelemetryBuffer_1 = require("../../infrastructure/TelemetryBuffer");
13
- const MarkerService_1 = require("../../core/MarkerService");
14
- async function moduleRemove(moduleName, projectRoot) {
15
- const telemetry = TelemetryBuffer_1.TelemetryBuffer.getInstance();
16
- const startTime = Date.now();
17
- telemetry.capture("cli.module.remove.start", { moduleName });
18
- const root = projectRoot || process.cwd();
19
- const spinner = (0, ora_1.default)(`Removendo módulo ${moduleName}...`).start();
20
- try {
21
- const markerService = new MarkerService_1.MarkerService();
22
- const installer = new ModuleInstaller_1.ModuleInstaller(root, markerService);
23
- // 1. Verificar se o módulo está na config
24
- const configPath = path_1.default.join(root, "kaven.json");
25
- if (!(await fs_extra_1.default.pathExists(configPath))) {
26
- throw new Error("Arquivo kaven.json não encontrado. Este é um projeto Kaven?");
27
- }
28
- const config = await fs_extra_1.default.readJson(configPath);
29
- if (!config.modules || !config.modules[moduleName]) {
30
- throw new Error(`O módulo ${moduleName} não está instalado.`);
31
- }
32
- // 2. Carregar manifest do cache
33
- const manifestPath = path_1.default.join(root, ".kaven", "modules", moduleName, "module.json");
34
- if (!(await fs_extra_1.default.pathExists(manifestPath))) {
35
- throw new Error(`Cache do manifest para ${moduleName} não encontrado em ${manifestPath}. A remoção precisa do manifest original.`);
36
- }
37
- const manifest = await fs_extra_1.default.readJson(manifestPath);
38
- // 3. Desinstalar
39
- spinner.text = `Removendo injeções de ${moduleName}...`;
40
- await installer.uninstall(manifest);
41
- // 4. Atualizar config
42
- spinner.text = "Atualizando configuração do projeto...";
43
- delete config.modules[moduleName];
44
- await fs_extra_1.default.writeJson(configPath, config, { spaces: 2 });
45
- // 5. Limpar cache do manifest
46
- await fs_extra_1.default.remove(path_1.default.dirname(manifestPath));
47
- (0, ora_1.default)().succeed(chalk_1.default.green(`Módulo ${moduleName} removido com sucesso!`));
48
- telemetry.capture("cli.module.remove.success", { moduleName }, Date.now() - startTime);
49
- await telemetry.flush();
50
- }
51
- catch (error) {
52
- telemetry.capture("cli.module.remove.error", { error: error.message }, Date.now() - startTime);
53
- await telemetry.flush();
54
- (0, ora_1.default)().fail(chalk_1.default.red(`Falha ao remover módulo ${moduleName}:`));
55
- spinner.fail(chalk_1.default.red(`${error instanceof Error ? error.message : String(error)}`));
56
- process.exit(1);
57
- }
58
- }
@@ -1,27 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.telemetryView = telemetryView;
7
- const chalk_1 = __importDefault(require("chalk"));
8
- const TelemetryBuffer_1 = require("../../infrastructure/TelemetryBuffer");
9
- async function telemetryView(limit = 10) {
10
- const telemetry = TelemetryBuffer_1.TelemetryBuffer.getInstance();
11
- const events = await telemetry.getRecentEvents(limit);
12
- if (events.length === 0) {
13
- console.log(chalk_1.default.yellow("\nNenhum evento de telemetria encontrado localmente.\n"));
14
- return;
15
- }
16
- console.log(chalk_1.default.blue.bold(`\n📊 Últimos ${events.length} eventos de telemetria:\n`));
17
- events.forEach((e) => {
18
- const time = chalk_1.default.gray(`[${new Date(e.timestamp).toLocaleTimeString()}]`);
19
- const status = e.event.includes("error") ? chalk_1.default.red("✖") : chalk_1.default.green("✔");
20
- const duration = e.duration ? chalk_1.default.yellow(` (${e.duration}ms)`) : "";
21
- console.log(`${time} ${status} ${chalk_1.default.cyan(e.event)}${duration}`);
22
- if (e.metadata && Object.keys(e.metadata).length > 0) {
23
- console.log(chalk_1.default.gray(` > ${JSON.stringify(e.metadata)}`));
24
- }
25
- });
26
- console.log(chalk_1.default.gray("\nLog local: ~/.kaven/telemetry.log\n"));
27
- }
@@ -1,162 +0,0 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.upgradeCheck = upgradeCheck;
7
- exports.upgradeInstall = upgradeInstall;
8
- const chalk_1 = __importDefault(require("chalk"));
9
- const ora_1 = __importDefault(require("ora"));
10
- const path_1 = __importDefault(require("path"));
11
- const child_process_1 = require("child_process");
12
- const fs_1 = __importDefault(require("fs"));
13
- const packageJsonPath = path_1.default.join(__dirname, "../../..", "package.json");
14
- const PACKAGE_JSON = JSON.parse(fs_1.default.readFileSync(packageJsonPath, "utf8"));
15
- const CURRENT_VERSION = PACKAGE_JSON.version;
16
- const CLI_NAME = "kaven-cli";
17
- /**
18
- * C2.3: Check for CLI updates
19
- */
20
- async function upgradeCheck() {
21
- const spinner = (0, ora_1.default)("Checking for updates...").start();
22
- try {
23
- // Fetch latest version from npm registry
24
- const response = await fetch(`https://registry.npmjs.org/${CLI_NAME}`);
25
- if (!response.ok) {
26
- spinner.fail("Could not check for updates");
27
- return;
28
- }
29
- const data = (await response.json());
30
- const distTags = data["dist-tags"];
31
- const latestVersion = distTags?.latest || CURRENT_VERSION;
32
- spinner.stop();
33
- console.log();
34
- console.log(chalk_1.default.bold("Version Check:"));
35
- console.log(` Current: ${chalk_1.default.cyan(CURRENT_VERSION)}`);
36
- console.log(` Latest: ${chalk_1.default.cyan(latestVersion)}`);
37
- console.log();
38
- if (latestVersion === CURRENT_VERSION) {
39
- console.log(chalk_1.default.green("✅ You're on the latest version!"));
40
- return;
41
- }
42
- // Check if update available
43
- const current = parseVersion(CURRENT_VERSION);
44
- const latest = parseVersion(latestVersion);
45
- if (latest.major > current.major ||
46
- (latest.major === current.major && latest.minor > current.minor) ||
47
- (latest.major === current.major &&
48
- latest.minor === current.minor &&
49
- latest.patch > current.patch)) {
50
- console.log(chalk_1.default.yellow(`⚠ Update available: ${latestVersion}`));
51
- console.log();
52
- console.log(chalk_1.default.bold("To upgrade, run:"));
53
- console.log(chalk_1.default.cyan(` npm install -g ${CLI_NAME}@latest`));
54
- console.log(chalk_1.default.cyan(` or`));
55
- console.log(chalk_1.default.cyan(` pnpm add -g ${CLI_NAME}@latest`));
56
- console.log();
57
- console.log(chalk_1.default.gray("Release notes: https://github.com/kaven-co/kaven-cli/releases"));
58
- }
59
- else {
60
- console.log(chalk_1.default.green("✅ You're on the latest version!"));
61
- }
62
- }
63
- catch (error) {
64
- spinner.fail(`Check failed: ${error instanceof Error ? error.message : String(error)}`);
65
- console.log(chalk_1.default.gray("You can manually check at: https://www.npmjs.com/package/kaven-cli"));
66
- }
67
- }
68
- /**
69
- * C2.3: Install latest CLI version
70
- */
71
- async function upgradeInstall() {
72
- console.log();
73
- const spinner = (0, ora_1.default)("Fetching latest version...").start();
74
- try {
75
- // Get latest version
76
- const response = await fetch(`https://registry.npmjs.org/${CLI_NAME}`);
77
- if (!response.ok) {
78
- throw new Error("Failed to fetch package info");
79
- }
80
- const data = (await response.json());
81
- const distTags = data["dist-tags"];
82
- const latestVersion = distTags?.latest || CURRENT_VERSION;
83
- if (latestVersion === CURRENT_VERSION) {
84
- spinner.succeed("Already on latest version");
85
- return;
86
- }
87
- spinner.text = `Installing ${CLI_NAME}@${latestVersion}...`;
88
- // Determine package manager
89
- const packageManager = process.env.npm_config_user_agent?.includes("pnpm")
90
- ? "pnpm"
91
- : "npm";
92
- // Install with appropriate package manager
93
- const exitCode = await runCommand(packageManager, [
94
- "install",
95
- "-g",
96
- `${CLI_NAME}@${latestVersion}`,
97
- ]);
98
- if (exitCode !== 0) {
99
- spinner.fail(`Installation failed with exit code ${exitCode}`);
100
- console.error(chalk_1.default.gray(`Try: ${packageManager} install -g ${CLI_NAME}@latest`));
101
- process.exit(1);
102
- return;
103
- }
104
- spinner.succeed(`Updated to ${latestVersion}`);
105
- // Health check after install
106
- const healthSpinner = (0, ora_1.default)("Running health check...").start();
107
- const health = await verifyInstallation();
108
- if (health.ok) {
109
- healthSpinner.succeed("Installation verified");
110
- console.log();
111
- console.log(chalk_1.default.green("✅ CLI upgraded successfully!"));
112
- console.log(chalk_1.default.gray("Try: kaven --version"));
113
- }
114
- else {
115
- healthSpinner.warn("Installation verification failed");
116
- console.log(chalk_1.default.yellow(health.errors.join("\n")));
117
- }
118
- }
119
- catch (error) {
120
- spinner.fail(`Installation failed: ${error instanceof Error ? error.message : String(error)}`);
121
- process.exit(1);
122
- }
123
- }
124
- /**
125
- * Verify CLI installation is working
126
- */
127
- async function verifyInstallation() {
128
- const errors = [];
129
- try {
130
- // Check if kaven command is available
131
- const code = await runCommand("kaven", ["--version"], { stdio: "pipe" });
132
- if (code !== 0) {
133
- errors.push("kaven command not available in PATH");
134
- }
135
- }
136
- catch {
137
- errors.push("Could not execute kaven command");
138
- }
139
- return { ok: errors.length === 0, errors };
140
- }
141
- /**
142
- * Run shell command
143
- */
144
- function runCommand(cmd, args, options) {
145
- return new Promise((resolve, reject) => {
146
- const proc = (0, child_process_1.spawn)(cmd, args, options || { stdio: "inherit" });
147
- proc.on("error", reject);
148
- proc.on("close", (code) => resolve(code ?? 0));
149
- });
150
- }
151
- /**
152
- * Parse semver version
153
- */
154
- function parseVersion(version) {
155
- const cleaned = version.replace(/^v/, "").split("-")[0];
156
- const [major, minor, patch] = cleaned.split(".").map(Number);
157
- return {
158
- major: major || 0,
159
- minor: minor || 0,
160
- patch: patch || 0,
161
- };
162
- }