@astralkit/cli 3.1.0 → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,107 +1,57 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const chalk = require('chalk');
4
- const ora = require('ora');
5
- const { getComponent } = require('../lib/api');
6
- const { getProjectConfig, detectFramework } = require('../lib/config');
7
- const { validateSlug, validateFramework, isSafePath } = require('../lib/validators');
8
-
9
- async function diffCommand(componentSlug, options) {
10
- // Validate inputs
11
- if (!validateSlug(componentSlug)) process.exit(1);
12
- if (!validateFramework(options.framework)) process.exit(1);
13
-
14
- const config = getProjectConfig();
15
- const framework = options.framework || config?.framework || detectFramework();
16
- const componentsDir = options.dir || config?.componentsDir || 'src/components/ui';
17
- const targetDir = path.resolve(process.cwd(), componentsDir, componentSlug);
18
-
19
- // Check if component exists locally
20
- if (!fs.existsSync(targetDir)) {
21
- console.log(chalk.yellow(`Component "${componentSlug}" not found locally at ${componentsDir}/${componentSlug}/`));
22
- console.log(chalk.gray('Nothing to diff.'));
23
- return;
24
- }
25
-
26
- const spinner = ora(`Fetching latest ${componentSlug} (${framework})...`).start();
27
-
28
- try {
29
- const data = await getComponent(componentSlug, framework);
30
-
31
- if (!data.files || data.files.length === 0) {
32
- spinner.fail(`No ${framework} code available for "${componentSlug}" on remote.`);
33
- return;
34
- }
35
-
36
- spinner.stop();
37
-
38
- console.log(chalk.blue.bold(`Diff: ${componentSlug} (${framework})`));
39
- console.log();
40
-
41
- let hasChanges = false;
42
-
43
- for (const remoteFile of data.files) {
44
- // Path traversal protection
45
- if (!isSafePath(targetDir, remoteFile.path)) {
46
- console.log(chalk.red(` Skipping suspicious file path: ${remoteFile.path}`));
47
- continue;
48
- }
49
-
50
- const localPath = path.resolve(targetDir, remoteFile.path);
51
-
52
- if (!fs.existsSync(localPath)) {
53
- console.log(chalk.green(`+ ${remoteFile.path}`), chalk.gray('(new file on remote)'));
54
- hasChanges = true;
55
- continue;
56
- }
57
-
58
- const localContent = fs.readFileSync(localPath, 'utf8');
59
- const remoteContent = remoteFile.content;
60
-
61
- if (localContent === remoteContent) {
62
- console.log(chalk.gray(` ${remoteFile.path}`), chalk.green('(up to date)'));
63
- } else {
64
- hasChanges = true;
65
- console.log(chalk.yellow(`~ ${remoteFile.path}`), chalk.yellow('(modified)'));
66
-
67
- // Show simple line count diff
68
- const localLines = localContent.split('\n').length;
69
- const remoteLines = remoteContent.split('\n').length;
70
- const diff = remoteLines - localLines;
71
- if (diff > 0) {
72
- console.log(chalk.gray(` Remote has ${diff} more line(s)`));
73
- } else if (diff < 0) {
74
- console.log(chalk.gray(` Local has ${Math.abs(diff)} more line(s)`));
75
- } else {
76
- console.log(chalk.gray(` Same line count, content differs`));
77
- }
78
- }
79
- }
80
-
81
- // Check for local files not on remote
82
- {
83
- const localFiles = fs.readdirSync(targetDir);
84
- const remoteFilenames = new Set(data.files.map(f => f.path));
85
- for (const localFile of localFiles) {
86
- if (!remoteFilenames.has(localFile)) {
87
- console.log(chalk.red(`- ${localFile}`), chalk.gray('(local only, not on remote)'));
88
- hasChanges = true;
89
- }
90
- }
91
- }
92
-
93
- console.log();
94
- if (hasChanges) {
95
- console.log(chalk.yellow('Changes detected.'));
96
- console.log(chalk.gray(`Run ${chalk.cyan(`astralkit update ${componentSlug}`)} to update.`));
97
- } else {
98
- console.log(chalk.green('All files are up to date.'));
99
- }
100
- } catch (err) {
101
- spinner.fail('Diff failed.');
102
- console.error(chalk.red(err.message));
103
- process.exit(1);
104
- }
105
- }
106
-
107
- module.exports = { diffCommand };
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import pc from 'picocolors';
4
+ import * as p from '@clack/prompts';
5
+ import { getComponent } from '../lib/api.js';
6
+ import { getProjectConfig, detectFramework } from '../lib/config.js';
7
+
8
+ export async function diffCommand(componentSlug, options) {
9
+ const ora = (await import('ora')).default;
10
+ const config = getProjectConfig();
11
+ const framework = options.framework || config?.framework || detectFramework();
12
+ const componentsDir = options.dir || config?.componentsDir || 'src/components/ui';
13
+
14
+ const spinner = ora(`Fetching latest ${pc.cyan(componentSlug)}...`).start();
15
+
16
+ try {
17
+ const data = await getComponent(componentSlug, framework);
18
+ spinner.stop();
19
+
20
+ if (!data.files?.length) {
21
+ p.log.warn(`No ${framework} version available for "${componentSlug}".`);
22
+ return;
23
+ }
24
+
25
+ let hasDiff = false;
26
+
27
+ for (const file of data.files) {
28
+ const localPath = path.resolve(process.cwd(), componentsDir, file.path);
29
+ if (!fs.existsSync(localPath)) {
30
+ console.log(pc.yellow(` Not installed: ${file.path}`));
31
+ hasDiff = true;
32
+ continue;
33
+ }
34
+
35
+ const localContent = fs.readFileSync(localPath, 'utf8');
36
+ if (localContent !== file.content) {
37
+ console.log(pc.yellow(` Modified: ${file.path}`));
38
+ hasDiff = true;
39
+ } else {
40
+ console.log(pc.green(` Up to date: ${file.path}`));
41
+ }
42
+ }
43
+
44
+ if (!hasDiff) {
45
+ console.log();
46
+ p.log.success(`${componentSlug} is up to date.`);
47
+ } else {
48
+ console.log();
49
+ p.log.info(`Run ${pc.cyan(`astralkit update ${componentSlug}`)} to update.`);
50
+ }
51
+ } catch (err) {
52
+ spinner.fail('Failed to fetch component.');
53
+ if (err.code === 'AUTH_REQUIRED' || err.code === 'PRO_REQUIRED') p.log.warn(err.message);
54
+ else console.error(pc.red(err.message));
55
+ process.exit(1);
56
+ }
57
+ }
@@ -1,125 +1,148 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const chalk = require('chalk');
4
- const inquirer = require('inquirer');
5
- const ora = require('ora');
6
- const { execSync } = require('child_process');
7
- const {
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import pc from 'picocolors';
4
+ import * as p from '@clack/prompts';
5
+ import {
8
6
  detectFramework,
7
+ detectTailwindVersion,
8
+ isTypeScriptProject,
9
9
  isAstralkitInstalled,
10
10
  findCssEntryFile,
11
11
  getMissingCssImports,
12
12
  addCssImports,
13
- REQUIRED_CSS_IMPORTS,
14
- } = require('../lib/config');
15
- const { validateFramework } = require('../lib/validators');
16
- const { getAiRulesContent } = require('../lib/ai-rules');
17
- const { saveApiKey, getApiKey } = require('../lib/auth');
18
-
19
- async function initCommand(options) {
20
- console.log(chalk.blue.bold('AstralKit — Project Setup'));
21
- console.log();
13
+ } from '../lib/config.js';
14
+ import { validateFramework } from '../lib/validators.js';
15
+ import { getAiRulesContent } from '../lib/ai-rules.js';
16
+ import { saveApiKey, getApiKey } from '../lib/auth.js';
17
+ import { detectPackageManager, runInstall } from '../lib/pkg-manager.js';
18
+ import { apiRequest } from '../lib/api.js';
19
+
20
+ const FRAMEWORK_LABELS = { nextjs: 'Next.js', react: 'React', html: 'HTML' };
21
+
22
+ export async function initCommand(options) {
23
+ p.intro(pc.bgBlue(pc.white(' AstralKit Setup ')));
24
+
25
+ // ─── Step 1: API Key ─────────────────────────────────
26
+ let apiKey = options.apiKey || getApiKey();
22
27
 
23
- // ─── Save API key if provided ────────────────────────
24
28
  if (options.apiKey) {
25
29
  if (!options.apiKey.startsWith('ak_')) {
26
- console.log(chalk.red('Invalid API key format. Keys start with ak_'));
27
- console.log(chalk.gray('Get your key at https://astralkit.com/account'));
30
+ p.cancel(pc.red('Invalid API key format. Keys start with ak_'));
31
+ console.log(pc.gray('Get your key at ') + pc.cyan('https://astralkit.com/account'));
28
32
  process.exit(1);
29
33
  }
30
34
  saveApiKey(options.apiKey);
31
- console.log(chalk.green(' API key saved'));
32
- } else if (!getApiKey()) {
33
- console.log(chalk.yellow('No API key found.'));
34
- console.log(chalk.gray('Get your key at'), chalk.cyan('astralkit.com/account'));
35
- console.log(chalk.gray('Then run:'), chalk.cyan('npx @astralkit/cli init --api-key <your-key>'));
35
+ p.log.success('API key saved');
36
+ } else if (!apiKey) {
37
+ p.log.warn('No API key found.');
38
+ console.log();
39
+ console.log(pc.gray(' Get your free API key at: ') + pc.cyan('https://astralkit.com/account'));
36
40
  console.log();
37
- process.exit(1);
38
- }
39
41
 
40
- // Auto-detect framework
41
- let framework = options.framework;
42
- if (framework && !validateFramework(framework)) process.exit(1);
43
- if (!framework) framework = detectFramework();
44
- console.log(chalk.gray(` Framework: ${framework}`));
42
+ const keyInput = await p.text({
43
+ message: 'Paste your API key (or press Enter to skip for now):',
44
+ placeholder: 'ak_...',
45
+ validate(val) {
46
+ if (!val) return;
47
+ if (!val.startsWith('ak_')) return 'Keys start with ak_ — check astralkit.com/account';
48
+ },
49
+ });
50
+
51
+ if (p.isCancel(keyInput)) {
52
+ p.cancel('Setup cancelled.');
53
+ process.exit(0);
54
+ }
45
55
 
46
- // Detect Tailwind version
47
- const twVersion = detectTailwindVersion();
48
- if (twVersion) console.log(chalk.gray(` Tailwind: v${twVersion}`));
56
+ if (keyInput) {
57
+ saveApiKey(keyInput);
58
+ apiKey = keyInput;
59
+ p.log.success('API key saved');
60
+ } else {
61
+ p.log.warn('Skipping API key — some features will be unavailable.');
62
+ p.log.info('Run ' + pc.cyan('astralkit init --api-key <your-key>') + ' later to add it.');
63
+ }
64
+ } else {
65
+ p.log.success('API key found');
66
+ }
49
67
 
50
- // Detect TypeScript
51
- const isTS = fs.existsSync(path.join(process.cwd(), 'tsconfig.json'));
52
- if (isTS) console.log(chalk.gray(' TypeScript: Yes'));
68
+ // ─── Step 2: Detect Project ────────────────────────────
69
+ if (options.framework && !validateFramework(options.framework)) {
70
+ process.exit(1);
71
+ }
53
72
 
54
- // Component directory — adapt to project structure
73
+ let framework = options.framework || detectFramework();
74
+ const twVersion = detectTailwindVersion();
75
+ const isTS = isTypeScriptProject();
55
76
  const hasSrc = fs.existsSync(path.join(process.cwd(), 'src'));
56
- const componentDir = options.dir || (hasSrc ? 'src/components/ui' : 'components/ui');
57
-
58
- // ─── Step 1: Install astralkit as a real npm dependency ─────
59
- // Downloaded as a tarball from the API, installed via npm/pnpm/yarn/bun.
60
- // This makes it a real dependency in package.json that survives npm ci.
61
- {
62
- if (!isAstralkitInstalled()) {
63
- const spinner = ora('Installing astralkit design tokens...').start();
77
+ const pm = detectPackageManager();
78
+
79
+ p.log.step(`Framework: ${pc.cyan(FRAMEWORK_LABELS[framework] || framework)}`);
80
+ if (twVersion) p.log.step(`Tailwind: ${pc.cyan('v' + twVersion)}`);
81
+ if (isTS) p.log.step(`TypeScript: ${pc.cyan('Yes')}`);
82
+ p.log.step(`Package manager: ${pc.cyan(pm)}`);
83
+
84
+ // ─── Step 3: Install astralkit as a real npm dependency ────
85
+ if (!isAstralkitInstalled()) {
86
+ if (apiKey) {
87
+ const ora = (await import('ora')).default;
88
+ const spinner = ora('Downloading AstralKit design tokens...').start();
64
89
  try {
65
- const { apiRequest, API_BASE } = require('../lib/api');
66
-
67
- // Download the tarball from the API
68
90
  const response = await apiRequest('/api/cli/sdk/tarball');
69
- const arrayBuffer = await response.arrayBuffer();
70
- const tgzBuffer = Buffer.from(arrayBuffer);
71
-
72
- // Save tarball to a temp location
73
- const tgzPath = path.join(process.cwd(), '.astralkit-sdk.tgz');
74
- fs.writeFileSync(tgzPath, tgzBuffer);
75
-
76
- // Install via the detected package manager — this makes it a REAL dependency
77
- const pm = detectPackageManager();
78
- const installCmd = pm === 'yarn' ? `yarn add ${tgzPath}`
79
- : pm === 'pnpm' ? `pnpm add ${tgzPath}`
80
- : pm === 'bun' ? `bun add ${tgzPath}`
81
- : `npm install ${tgzPath}`;
82
- execSync(installCmd, { stdio: 'pipe', cwd: process.cwd() });
83
-
84
- // Clean up the temp tarball
85
- if (fs.existsSync(tgzPath)) fs.unlinkSync(tgzPath);
86
-
87
- // Verify it installed
88
- if (isAstralkitInstalled()) {
91
+ const contentDisposition = response.headers.get('content-disposition') || '';
92
+ const filenameMatch = contentDisposition.match(/filename="([^"]+)"/);
93
+ const tgzFilename = filenameMatch?.[1] || 'astralkit-0.1.0.tgz';
94
+
95
+ const tgzPath = path.join(process.cwd(), tgzFilename);
96
+ const buffer = Buffer.from(await response.arrayBuffer());
97
+ fs.writeFileSync(tgzPath, buffer);
98
+
99
+ spinner.text = `Installing astralkit via ${pm}...`;
100
+
101
+ const result = await runInstall(pm, process.cwd(), [`./${tgzFilename}`]);
102
+
103
+ if (result.success) {
89
104
  spinner.succeed('Installed astralkit design tokens');
105
+ p.log.info(pc.gray(`Commit ${tgzFilename} to git so teammates get it on npm install`));
90
106
  } else {
91
- spinner.fail('Install completed but astralkit not found in node_modules');
107
+ spinner.fail('Failed to install astralkit.');
108
+ console.log(pc.gray(' ' + (result.hint || result.error)));
92
109
  }
93
110
  } catch (err) {
94
- spinner.fail('Failed to install astralkit');
95
- if (err.message?.includes('API key')) {
96
- console.log(chalk.yellow('Invalid API key. Check your key at astralkit.com/account'));
111
+ spinner.fail('Could not download design tokens.');
112
+ if (err.code === 'AUTH_REQUIRED') {
113
+ p.log.info('Add your API key: ' + pc.cyan('astralkit init --api-key <key>'));
114
+ } else if (err.code === 'NETWORK_ERROR' || err.code === 'TIMEOUT') {
115
+ p.log.info('Check your connection and run ' + pc.cyan('astralkit init') + ' again.');
97
116
  } else {
98
- console.log(chalk.yellow(err.message || 'Check your internet connection and try again.'));
117
+ p.log.info(pc.gray(err.message));
99
118
  }
100
- // Clean up temp file on error
101
- const tgzPath = path.join(process.cwd(), '.astralkit-sdk.tgz');
102
- if (fs.existsSync(tgzPath)) fs.unlinkSync(tgzPath);
103
- return;
104
119
  }
105
120
  } else {
106
- console.log(chalk.gray(' astralkit already installed'));
121
+ p.log.warn('Skipping design token install — no API key.');
122
+ p.log.info('Run ' + pc.cyan('astralkit init --api-key <key>') + ' to install them.');
107
123
  }
124
+ } else {
125
+ p.log.step('astralkit design tokens already installed');
108
126
  }
109
127
 
110
- // ─── Step 2: Add CSS imports ────────────────────────────
128
+ // ─── Step 4: CSS imports ─────────────────────────────
111
129
  const cssEntry = findCssEntryFile();
112
130
  if (cssEntry) {
113
131
  const missing = getMissingCssImports(cssEntry.path);
114
132
  if (missing.length > 0) {
115
- console.log(chalk.gray(` Found CSS entry: ${cssEntry.relative}`));
116
- addCssImports(cssEntry.path, missing);
117
- console.log(chalk.green(' Added CSS imports'));
133
+ const addImports = await p.confirm({
134
+ message: `Add AstralKit CSS imports to ${pc.cyan(cssEntry.relative)}?`,
135
+ initialValue: true,
136
+ });
137
+ if (!p.isCancel(addImports) && addImports) {
138
+ addCssImports(cssEntry.path, missing);
139
+ p.log.success(`CSS imports added to ${cssEntry.relative}`);
140
+ }
118
141
  } else {
119
- console.log(chalk.gray(' CSS imports already present'));
142
+ p.log.step('CSS imports already present');
120
143
  }
121
144
  } else {
122
- // No CSS entry found — create one
145
+ // No CSS entry found — create one at the framework-appropriate location
123
146
  const defaultCssPath = (framework === 'nextjs' && hasSrc)
124
147
  ? path.join(process.cwd(), 'src', 'app', 'globals.css')
125
148
  : (framework === 'nextjs')
@@ -129,60 +152,26 @@ async function initCommand(options) {
129
152
  : path.join(process.cwd(), 'index.css');
130
153
  const defaultCssRelative = path.relative(process.cwd(), defaultCssPath);
131
154
 
132
- const cssContent = REQUIRED_CSS_IMPORTS.join('\n') + '\n';
155
+ const allImports = getMissingCssImports('/nonexistent'); // get all imports
133
156
  const cssDir = path.dirname(defaultCssPath);
134
157
  if (!fs.existsSync(cssDir)) fs.mkdirSync(cssDir, { recursive: true });
135
- fs.writeFileSync(defaultCssPath, cssContent, 'utf-8');
136
- console.log(chalk.green(' Created'), chalk.cyan(defaultCssRelative), chalk.green('with AstralKit imports'));
158
+ addCssImports(defaultCssPath, allImports);
159
+ p.log.success(`Created ${pc.cyan(defaultCssRelative)} with AstralKit imports`);
137
160
  }
138
161
 
139
- // ─── Step 3: AI coding rules ─────────────────────────
162
+ // ─── Step 5: AI rules file ───────────────────────────
140
163
  const rulesFile = 'astralkit-ai-rules.md';
141
164
  const rulesPath = path.join(process.cwd(), rulesFile);
142
165
  if (!fs.existsSync(rulesPath)) {
143
166
  fs.writeFileSync(rulesPath, getAiRulesContent());
144
- console.log(chalk.green(' Created'), chalk.cyan(rulesFile));
145
- } else {
146
- console.log(chalk.gray(` ${rulesFile} already exists`));
167
+ p.log.success(`Created ${pc.cyan(rulesFile)}`);
147
168
  }
148
169
 
149
170
  // ─── Done ────────────────────────────────────────────
171
+ p.outro(pc.green('AstralKit is ready!'));
172
+
150
173
  console.log();
151
- console.log(chalk.green('AstralKit initialized.'));
174
+ console.log(pc.gray(' Add a component:'), pc.cyan('astralkit add pricing-table'));
175
+ console.log(pc.gray(' Browse all: '), pc.cyan('astralkit list'));
152
176
  console.log();
153
- console.log(chalk.gray(' Add a component:'), chalk.cyan(`astralkit add sidebar-light`));
154
- console.log(chalk.gray(' Browse components:'), chalk.cyan('astralkit list'));
155
- }
156
-
157
- /**
158
- * Detect which package manager the project uses.
159
- */
160
- function detectPackageManager(dir = process.cwd()) {
161
- if (fs.existsSync(path.join(dir, 'bun.lockb')) || fs.existsSync(path.join(dir, 'bun.lock'))) return 'bun';
162
- if (fs.existsSync(path.join(dir, 'pnpm-lock.yaml'))) return 'pnpm';
163
- if (fs.existsSync(path.join(dir, 'yarn.lock'))) return 'yarn';
164
- return 'npm';
165
177
  }
166
-
167
- /**
168
- * Detect Tailwind CSS version from package.json.
169
- * Returns 3, 4, or null.
170
- */
171
- function detectTailwindVersion(dir = process.cwd()) {
172
- try {
173
- const pkgPath = path.join(dir, 'package.json');
174
- if (!fs.existsSync(pkgPath)) return null;
175
- const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
176
- const deps = { ...pkg.dependencies, ...pkg.devDependencies };
177
- const ver = deps['tailwindcss'];
178
- if (!ver) return null;
179
- const major = parseInt(ver.replace(/[^0-9]/, ''), 10);
180
- if (major >= 4) return 4;
181
- if (major === 3) return 3;
182
- return null;
183
- } catch {
184
- return null;
185
- }
186
- }
187
-
188
- module.exports = { initCommand };