@astralkit/cli 2.2.0 → 3.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,343 +1,642 @@
1
- const fs = require('fs');
2
- const path = require('path');
3
- const chalk = require('chalk');
4
- const ora = require('ora');
5
- const { getComponent, getBooster, getWorkflow } = require('../lib/api');
6
- const {
7
- getProjectConfig,
8
- detectFramework,
9
- isAstralkitInstalled,
10
- findCssEntryFile,
11
- getMissingCssImports,
12
- addCssImports,
13
- REQUIRED_CSS_IMPORTS,
14
- } = require('../lib/config');
15
- const { validateSlug, validateFramework, isSafePath, writeFiles } = require('../lib/validators');
16
-
17
- /**
18
- * Route to the correct add handler based on flags.
19
- */
20
- async function addCommand(nameOrSlug, options) {
21
- if (options.booster) {
22
- return addBooster(nameOrSlug, options);
23
- }
24
- if (options.workflow) {
25
- return addWorkflow(nameOrSlug, options);
26
- }
27
- return addComponent(nameOrSlug, options);
28
- }
29
-
30
- /**
31
- * Add a single UI component.
32
- * Drops a single file (.html, .jsx, or .tsx) into src/components/ui/.
33
- * Verifies astralkit npm package is installed and CSS imports are present.
34
- */
35
- async function addComponent(componentSlug, options) {
36
- if (!validateSlug(componentSlug)) process.exit(1);
37
- if (options.framework && !validateFramework(options.framework)) process.exit(1);
38
-
39
- const config = getProjectConfig();
40
- const framework = options.framework || config?.framework || detectFramework();
41
- const componentsDir = options.dir || config?.componentsDir || 'src/components/ui';
42
-
43
- // For react/nextjs, the API returns a single file — write it directly into componentsDir
44
- // For html, also a single file
45
- const ext = framework === 'nextjs' ? '.tsx' : framework === 'react' ? '.jsx' : '.html';
46
- const targetFile = path.resolve(process.cwd(), componentsDir, `${componentSlug}${ext}`);
47
-
48
- if (fs.existsSync(targetFile) && !options.overwrite) {
49
- console.log(chalk.yellow(`Component already exists: ${componentsDir}/${componentSlug}${ext}`));
50
- console.log(chalk.gray('Use --overwrite to replace.'));
51
- return;
52
- }
53
-
54
- const spinner = ora(`Fetching ${componentSlug} (${framework})...`).start();
55
-
56
- try {
57
- const data = await getComponent(componentSlug, framework);
58
-
59
- if (!data.files || data.files.length === 0) {
60
- spinner.fail(`No ${framework} code available for "${componentSlug}".`);
61
- if (data.supported_frameworks?.length) {
62
- console.log(chalk.gray(`Available frameworks: ${data.supported_frameworks.join(', ')}`));
63
- }
64
- return;
65
- }
66
-
67
- // Write the component file(s)
68
- const dir = path.resolve(process.cwd(), componentsDir);
69
- fs.mkdirSync(dir, { recursive: true });
70
-
71
- for (const file of data.files) {
72
- if (!isSafePath(dir, file.path)) {
73
- console.log(chalk.red(` Skipping suspicious file path: ${file.path}`));
74
- continue;
75
- }
76
- const filePath = path.resolve(dir, file.path);
77
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
78
- fs.writeFileSync(filePath, file.content);
79
- }
80
-
81
- spinner.succeed(`Added ${chalk.cyan(data.name || componentSlug)} (${framework})`);
82
-
83
- console.log(chalk.gray(` ${componentsDir}/`));
84
- for (const file of data.files) {
85
- console.log(chalk.gray(` ${file.path}`));
86
- }
87
-
88
- // ─── Post-install checks for react/nextjs ──────────────
89
- if (framework !== 'html') {
90
- console.log();
91
-
92
- // Check astralkit npm package
93
- if (!isAstralkitInstalled()) {
94
- console.log(chalk.yellow('astralkit package not found.'));
95
- console.log(chalk.cyan(' npm install astralkit'));
96
- }
97
-
98
- // Check CSS imports
99
- const cssEntry = findCssEntryFile();
100
- if (cssEntry) {
101
- const missing = getMissingCssImports(cssEntry.path);
102
- if (missing.length > 0) {
103
- console.log(chalk.yellow(`Missing CSS imports in ${cssEntry.relative}:`));
104
- for (const imp of missing) {
105
- console.log(chalk.cyan(` ${imp}`));
106
- }
107
- console.log(chalk.gray('Run `astralkit init` to set up automatically.'));
108
- }
109
- } else {
110
- console.log(chalk.yellow('No CSS entry file found. Add these to your main CSS:'));
111
- for (const imp of REQUIRED_CSS_IMPORTS) {
112
- console.log(chalk.cyan(` ${imp}`));
113
- }
114
- }
115
- }
116
-
117
- if (data.is_pro) {
118
- console.log();
119
- console.log(chalk.magenta('Pro component — thank you for your subscription!'));
120
- }
121
-
122
- } catch (err) {
123
- spinner.fail('Failed to add component.');
124
- handleAddError(err, componentSlug, framework);
125
- }
126
- }
127
-
128
- /**
129
- * Add a booster (multi-file feature module with core + adapter).
130
- */
131
- async function addBooster(slug, options) {
132
- if (!validateSlug(slug, 'booster name')) process.exit(1);
133
- if (options.framework && !validateFramework(options.framework)) process.exit(1);
134
-
135
- const config = getProjectConfig();
136
- const framework = options.framework || config?.framework || detectFramework();
137
-
138
- const spinner = ora(`Fetching booster ${slug} (${framework})...`).start();
139
-
140
- try {
141
- const data = await getBooster(slug, framework);
142
-
143
- const coreFiles = data.core_files || [];
144
- const adapterFiles = data.adapter_files || [];
145
-
146
- if (coreFiles.length === 0 && adapterFiles.length === 0) {
147
- spinner.fail(`No files available for booster "${slug}" (${framework}).`);
148
- if (data.frameworks?.length) {
149
- console.log(chalk.gray(`Available frameworks: ${data.frameworks.join(', ')}`));
150
- }
151
- return;
152
- }
153
-
154
- // Resolve install paths
155
- const corePath = options.dir || data.install_paths?.core || `src/lib/${slug}`;
156
- const adapterPath = data.install_paths?.adapter || `src/components/${slug}`;
157
- const coreDir = path.resolve(process.cwd(), corePath);
158
- const adapterDir = path.resolve(process.cwd(), adapterPath);
159
-
160
- // Check for existing files
161
- if (!options.overwrite) {
162
- const conflicts = [];
163
- for (const file of coreFiles) {
164
- const fp = path.resolve(coreDir, file.path);
165
- if (fs.existsSync(fp)) conflicts.push(`${corePath}/${file.path}`);
166
- }
167
- for (const file of adapterFiles) {
168
- const fp = path.resolve(adapterDir, file.path);
169
- if (fs.existsSync(fp)) conflicts.push(`${adapterPath}/${file.path}`);
170
- }
171
- if (conflicts.length > 0) {
172
- spinner.fail('Some files already exist.');
173
- console.log(chalk.yellow('Conflicting files:'));
174
- for (const c of conflicts) {
175
- console.log(chalk.gray(` ${c}`));
176
- }
177
- console.log(chalk.gray('Use --overwrite to replace existing files.'));
178
- return;
179
- }
180
- }
181
-
182
- // Write core + adapter files
183
- const coreCount = writeFiles(coreDir, coreFiles);
184
- const adapterCount = writeFiles(adapterDir, adapterFiles);
185
-
186
- spinner.succeed(`Added booster ${chalk.cyan(data.name || slug)} (${framework})`);
187
-
188
- // Show files written
189
- if (coreCount > 0) {
190
- console.log(chalk.gray(` Core files → ${corePath}/`));
191
- for (const file of coreFiles) {
192
- console.log(chalk.gray(` ${file.path}`));
193
- }
194
- }
195
- if (adapterCount > 0) {
196
- console.log(chalk.gray(` Adapter files → ${adapterPath}/`));
197
- for (const file of adapterFiles) {
198
- console.log(chalk.gray(` ${file.path}`));
199
- }
200
- }
201
-
202
- printPostInstallInfo(data);
203
-
204
- if (data.is_pro) {
205
- console.log();
206
- console.log(chalk.magenta('Pro booster — thank you for your subscription!'));
207
- }
208
-
209
- } catch (err) {
210
- spinner.fail('Failed to add booster.');
211
- handleAddError(err, slug, framework);
212
- }
213
- }
214
-
215
- /**
216
- * Add a workflow (complete application scaffold).
217
- */
218
- async function addWorkflow(slug, options) {
219
- if (!validateSlug(slug, 'workflow name')) process.exit(1);
220
- if (options.framework && !validateFramework(options.framework)) process.exit(1);
221
-
222
- const config = getProjectConfig();
223
- const framework = options.framework || config?.framework || detectFramework();
224
-
225
- const spinner = ora(`Fetching workflow ${slug} (${framework})...`).start();
226
-
227
- try {
228
- const data = await getWorkflow(slug, framework);
229
-
230
- if (!data.files || data.files.length === 0) {
231
- spinner.fail(`No files available for workflow "${slug}" (${framework}).`);
232
- if (data.frameworks?.length) {
233
- console.log(chalk.gray(`Available frameworks: ${data.frameworks.join(', ')}`));
234
- }
235
- return;
236
- }
237
-
238
- // Determine target directory
239
- let targetDir;
240
- if (options.overlay) {
241
- targetDir = path.resolve(process.cwd());
242
- } else {
243
- const dirName = options.dir || slug;
244
- targetDir = path.resolve(process.cwd(), dirName);
245
- }
246
-
247
- // Check for conflicts in overlay mode
248
- if (options.overlay && !options.overwrite) {
249
- const conflicts = [];
250
- for (const file of data.files) {
251
- const fp = path.resolve(targetDir, file.path);
252
- if (fs.existsSync(fp)) conflicts.push(file.path);
253
- }
254
- if (conflicts.length > 0) {
255
- spinner.fail(`${conflicts.length} file(s) would be overwritten.`);
256
- console.log(chalk.yellow('Conflicting files:'));
257
- for (const c of conflicts.slice(0, 20)) {
258
- console.log(chalk.gray(` ${c}`));
259
- }
260
- if (conflicts.length > 20) {
261
- console.log(chalk.gray(` ... and ${conflicts.length - 20} more`));
262
- }
263
- console.log(chalk.gray('Use --overwrite to replace existing files.'));
264
- return;
265
- }
266
- }
267
-
268
- // Check if target directory exists (non-overlay)
269
- if (!options.overlay && fs.existsSync(targetDir) && !options.overwrite) {
270
- spinner.fail(`Directory "${slug}/" already exists.`);
271
- console.log(chalk.gray('Use --overwrite to replace, or --dir to specify a different name.'));
272
- return;
273
- }
274
-
275
- // Write files
276
- const fileCount = writeFiles(targetDir, data.files);
277
-
278
- const targetLabel = options.overlay ? './' : `${slug}/`;
279
- spinner.succeed(`Scaffolded workflow ${chalk.cyan(data.name || slug)} (${framework}) → ${targetLabel}`);
280
-
281
- console.log(chalk.gray(` ${fileCount} files written to ${targetLabel}`));
282
-
283
- printPostInstallInfo(data, { npmPrefix: options.overlay ? '' : `cd ${slug} && ` });
284
-
285
- if (data.is_pro) {
286
- console.log();
287
- console.log(chalk.magenta('Pro workflow — thank you for your subscription!'));
288
- }
289
-
290
- } catch (err) {
291
- spinner.fail('Failed to add workflow.');
292
- handleAddError(err, slug, framework);
293
- }
294
- }
295
-
296
- /**
297
- * Print post-install info (deps, env vars, setup instructions).
298
- */
299
- function printPostInstallInfo(data, { npmPrefix = '' } = {}) {
300
- if (data.dependencies?.npm?.length) {
301
- console.log();
302
- console.log(chalk.yellow('Install required dependencies:'));
303
- console.log(chalk.cyan(` ${npmPrefix}npm install ${data.dependencies.npm.join(' ')}`));
304
- }
305
- if (data.dependencies?.env?.length) {
306
- console.log();
307
- console.log(chalk.yellow('Add these environment variables to your .env:'));
308
- for (const envVar of data.dependencies.env) {
309
- console.log(chalk.gray(` ${envVar}=`));
310
- }
311
- }
312
- if (data.post_install) {
313
- console.log();
314
- console.log(chalk.white.bold('Setup instructions:'));
315
- console.log(chalk.gray(data.post_install));
316
- }
317
- }
318
-
319
- /**
320
- * Shared error handler for add commands.
321
- */
322
- function handleAddError(err, slug, framework) {
323
- if (err.code === 'AUTH_REQUIRED') {
324
- console.log(chalk.yellow(err.message));
325
- } else if (err.code === 'PRO_REQUIRED') {
326
- console.log(chalk.yellow(err.message));
327
- } else {
328
- try {
329
- const body = JSON.parse(err.message.replace(/^API error \d+: /, ''));
330
- if (body.supported_frameworks) {
331
- console.log(chalk.yellow(`No ${framework} version available for "${slug}".`));
332
- console.log(chalk.gray(`Available frameworks: ${body.supported_frameworks.join(', ')}`));
333
- process.exit(1);
334
- }
335
- } catch {
336
- // Not a JSON parse error
337
- }
338
- console.error(chalk.red(err.message));
339
- }
340
- process.exit(1);
341
- }
342
-
343
- module.exports = { addCommand };
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const chalk = require('chalk');
4
+ const ora = require('ora');
5
+ const inquirer = require('inquirer');
6
+ const { getComponent, getBooster, getWorkflow } = require('../lib/api');
7
+ const {
8
+ getProjectConfig,
9
+ detectFramework,
10
+ isAstralkitInstalled,
11
+ findCssEntryFile,
12
+ getMissingCssImports,
13
+ addCssImports,
14
+ REQUIRED_CSS_IMPORTS,
15
+ } = require('../lib/config');
16
+ const { validateSlug, validateFramework, isSafePath, writeFiles } = require('../lib/validators');
17
+ const { detectPackageManager, getInstallCommand, getRunCommand, runInstall } = require('../lib/pkg-manager');
18
+
19
+ const FRAMEWORK_LABELS = {
20
+ nextjs: 'Next.js',
21
+ react: 'React',
22
+ html: 'HTML',
23
+ };
24
+
25
+ /**
26
+ * Route to the correct add handler.
27
+ * If no --booster or --workflow flag, try auto-detection then prompt.
28
+ */
29
+ async function addCommand(nameOrSlug, options) {
30
+ // If explicit flags, use them directly
31
+ if (options.booster) {
32
+ return addBooster(nameOrSlug, options);
33
+ }
34
+ if (options.workflow) {
35
+ return addWorkflow(nameOrSlug, options);
36
+ }
37
+
38
+ // No flag given — try to auto-detect what the slug is
39
+ if (!options.booster && !options.workflow) {
40
+ const type = await resolveItemType(nameOrSlug, options);
41
+ if (type === 'booster') return addBooster(nameOrSlug, options);
42
+ if (type === 'workflow') return addWorkflow(nameOrSlug, options);
43
+ return addComponent(nameOrSlug, options);
44
+ }
45
+
46
+ return addComponent(nameOrSlug, options);
47
+ }
48
+
49
+ /**
50
+ * Try to find the slug across all registries (component, booster, workflow).
51
+ * If found in one, use it. If found in multiple, prompt. If not found, prompt.
52
+ */
53
+ async function resolveItemType(slug, options) {
54
+ const spinner = ora('Looking up ' + chalk.cyan(slug) + '...').start();
55
+
56
+ const found = [];
57
+
58
+ // Try all three in parallel
59
+ const checks = await Promise.allSettled([
60
+ tryFetch('component', slug, options),
61
+ tryFetch('booster', slug, options),
62
+ tryFetch('workflow', slug, options),
63
+ ]);
64
+
65
+ if (checks[0].status === 'fulfilled' && checks[0].value) found.push('component');
66
+ if (checks[1].status === 'fulfilled' && checks[1].value) found.push('booster');
67
+ if (checks[2].status === 'fulfilled' && checks[2].value) found.push('workflow');
68
+
69
+ spinner.stop();
70
+
71
+ if (found.length === 1) {
72
+ return found[0];
73
+ }
74
+
75
+ if (found.length > 1) {
76
+ // Found in multiple registries — ask the user
77
+ const { type } = await inquirer.prompt([{
78
+ type: 'list',
79
+ name: 'type',
80
+ message: `"${slug}" matches multiple items. What do you want to install?`,
81
+ choices: found.map(t => ({
82
+ name: t === 'component' ? 'Component (UI element)'
83
+ : t === 'booster' ? 'Booster (feature module)'
84
+ : 'Workflow (complete app)',
85
+ value: t,
86
+ })),
87
+ }]);
88
+ return type;
89
+ }
90
+
91
+ // Not found anywhere — ask what they want to install
92
+ const { type } = await inquirer.prompt([{
93
+ type: 'list',
94
+ name: 'type',
95
+ message: `What are you installing?`,
96
+ choices: [
97
+ { name: 'Component (UI element)', value: 'component' },
98
+ { name: 'Booster (feature module)', value: 'booster' },
99
+ { name: 'Workflow (complete app)', value: 'workflow' },
100
+ ],
101
+ }]);
102
+ return type;
103
+ }
104
+
105
+ /**
106
+ * Quick check if a slug exists in a registry. Returns true/false.
107
+ */
108
+ async function tryFetch(type, slug, options) {
109
+ try {
110
+ const config = getProjectConfig();
111
+ const framework = options.framework || config?.framework || detectFramework();
112
+ if (type === 'component') {
113
+ await getComponent(slug, framework);
114
+ } else if (type === 'booster') {
115
+ await getBooster(slug, framework);
116
+ } else {
117
+ await getWorkflow(slug, framework);
118
+ }
119
+ return true;
120
+ } catch {
121
+ return false;
122
+ }
123
+ }
124
+
125
+ /**
126
+ * Resolve framework — use flag, config, auto-detect, or prompt the user.
127
+ */
128
+ async function resolveFramework(options, itemType) {
129
+ // Explicit flag
130
+ if (options.framework) {
131
+ if (!validateFramework(options.framework)) process.exit(1);
132
+ return options.framework;
133
+ }
134
+
135
+ // From project config
136
+ const config = getProjectConfig();
137
+ if (config?.framework) return config.framework;
138
+
139
+ // Auto-detect from project files
140
+ const detected = detectFramework();
141
+ if (detected !== 'html') {
142
+ // We detected a real framework (not the fallback)
143
+ console.log(chalk.gray(` Detected ${FRAMEWORK_LABELS[detected] || detected} project`));
144
+ return detected;
145
+ }
146
+
147
+ // For boosters and workflows, default to nextjs instead of prompting for html
148
+ if (itemType === 'booster' || itemType === 'workflow') {
149
+ const { framework } = await inquirer.prompt([{
150
+ type: 'list',
151
+ name: 'framework',
152
+ message: 'Which framework?',
153
+ choices: [
154
+ { name: 'Next.js', value: 'nextjs' },
155
+ { name: 'React', value: 'react' },
156
+ { name: 'HTML', value: 'html' },
157
+ ],
158
+ default: 'nextjs',
159
+ }]);
160
+ return framework;
161
+ }
162
+
163
+ // For components, prompt with all options
164
+ const { framework } = await inquirer.prompt([{
165
+ type: 'list',
166
+ name: 'framework',
167
+ message: 'Which framework?',
168
+ choices: [
169
+ { name: 'HTML (no framework needed)', value: 'html' },
170
+ { name: 'React', value: 'react' },
171
+ { name: 'Next.js', value: 'nextjs' },
172
+ ],
173
+ }]);
174
+ return framework;
175
+ }
176
+
177
+ /**
178
+ * Check that we're inside a project directory (has package.json).
179
+ * For workflows, offer to create a new directory.
180
+ */
181
+ function checkProjectContext(itemType) {
182
+ const pkgExists = fs.existsSync(path.join(process.cwd(), 'package.json'));
183
+
184
+ if (!pkgExists && itemType !== 'workflow') {
185
+ console.log(chalk.yellow('⚠ No package.json found in the current directory.'));
186
+ console.log(chalk.gray(' Run this inside a project, or use --workflow to scaffold a new app.'));
187
+ return false;
188
+ }
189
+ return true;
190
+ }
191
+
192
+ // ─── Add Component ──────────────────────────────────
193
+
194
+ async function addComponent(componentSlug, options) {
195
+ if (!validateSlug(componentSlug)) process.exit(1);
196
+
197
+ if (!checkProjectContext('component')) return;
198
+
199
+ const framework = await resolveFramework(options, 'component');
200
+ const config = getProjectConfig();
201
+ const componentsDir = options.dir || config?.componentsDir || 'src/components/ui';
202
+
203
+ const ext = framework === 'nextjs' ? '.tsx' : framework === 'react' ? '.jsx' : '.html';
204
+ const targetFile = path.resolve(process.cwd(), componentsDir, `${componentSlug}${ext}`);
205
+
206
+ if (fs.existsSync(targetFile) && !options.overwrite) {
207
+ console.log(chalk.yellow(`Component already exists: ${componentsDir}/${componentSlug}${ext}`));
208
+ console.log(chalk.gray('Use --overwrite to replace.'));
209
+ return;
210
+ }
211
+
212
+ const spinner = ora(`Fetching ${componentSlug} (${FRAMEWORK_LABELS[framework] || framework})...`).start();
213
+
214
+ try {
215
+ const data = await getComponent(componentSlug, framework);
216
+
217
+ if (!data.files || data.files.length === 0) {
218
+ spinner.fail(`No ${framework} code available for "${componentSlug}".`);
219
+ if (data.supported_frameworks?.length) {
220
+ console.log(chalk.gray(`Available: ${data.supported_frameworks.map(f => FRAMEWORK_LABELS[f] || f).join(', ')}`));
221
+ }
222
+ return;
223
+ }
224
+
225
+ // Dry run
226
+ if (options.dryRun) {
227
+ spinner.stop();
228
+ console.log(chalk.white.bold('\n📋 Dry run — no files will be written:\n'));
229
+ for (const file of data.files) {
230
+ const exists = fs.existsSync(path.resolve(process.cwd(), componentsDir, file.path));
231
+ console.log(` ${exists ? chalk.yellow('⚠ overwrite') : chalk.green('+ create')} ${componentsDir}/${file.path}`);
232
+ }
233
+ return;
234
+ }
235
+
236
+ const dir = path.resolve(process.cwd(), componentsDir);
237
+ fs.mkdirSync(dir, { recursive: true });
238
+
239
+ for (const file of data.files) {
240
+ if (!isSafePath(dir, file.path)) {
241
+ console.log(chalk.red(` Skipping suspicious file path: ${file.path}`));
242
+ continue;
243
+ }
244
+ const filePath = path.resolve(dir, file.path);
245
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
246
+ fs.writeFileSync(filePath, file.content);
247
+ }
248
+
249
+ spinner.succeed(`Added ${chalk.cyan(data.name || componentSlug)} (${FRAMEWORK_LABELS[framework] || framework})`);
250
+
251
+ console.log(chalk.gray(` ${componentsDir}/`));
252
+ for (const file of data.files) {
253
+ console.log(chalk.gray(` ${file.path}`));
254
+ }
255
+
256
+ // Post-install checks for react/nextjs
257
+ if (framework !== 'html') {
258
+ console.log();
259
+
260
+ if (!isAstralkitInstalled()) {
261
+ console.log(chalk.yellow('astralkit design tokens not found.'));
262
+ console.log(chalk.cyan(' Run `astralkit init` to set up your project.'));
263
+ }
264
+
265
+ const cssEntry = findCssEntryFile();
266
+ if (cssEntry) {
267
+ const missing = getMissingCssImports(cssEntry.path);
268
+ if (missing.length > 0) {
269
+ console.log(chalk.yellow(`Missing CSS imports in ${cssEntry.relative}:`));
270
+ for (const imp of missing) {
271
+ console.log(chalk.cyan(` ${imp}`));
272
+ }
273
+ console.log(chalk.gray('Run `astralkit init` to set up automatically.'));
274
+ }
275
+ } else {
276
+ console.log(chalk.yellow('No CSS entry file found. Add these to your main CSS:'));
277
+ for (const imp of REQUIRED_CSS_IMPORTS) {
278
+ console.log(chalk.cyan(` ${imp}`));
279
+ }
280
+ }
281
+ }
282
+
283
+ if (data.is_pro) {
284
+ console.log();
285
+ console.log(chalk.magenta('Pro component — thank you for your subscription!'));
286
+ }
287
+
288
+ } catch (err) {
289
+ spinner.fail('Failed to add component.');
290
+ handleAddError(err, componentSlug, framework);
291
+ }
292
+ }
293
+
294
+ // ─── Add Booster ────────────────────────────────────
295
+
296
+ async function addBooster(slug, options) {
297
+ if (!validateSlug(slug, 'booster name')) process.exit(1);
298
+
299
+ const framework = await resolveFramework(options, 'booster');
300
+ const pm = detectPackageManager();
301
+
302
+ const spinner = ora(`Fetching booster ${chalk.cyan(slug)} (${FRAMEWORK_LABELS[framework] || framework})...`).start();
303
+
304
+ try {
305
+ const data = await getBooster(slug, framework);
306
+
307
+ const coreFiles = data.core_files || [];
308
+ const adapterFiles = data.adapter_files || [];
309
+
310
+ if (coreFiles.length === 0 && adapterFiles.length === 0) {
311
+ spinner.fail(`No files available for booster "${slug}" (${framework}).`);
312
+ if (data.frameworks?.length) {
313
+ console.log(chalk.gray(`Available: ${data.frameworks.map(f => FRAMEWORK_LABELS[f] || f).join(', ')}`));
314
+ }
315
+ return;
316
+ }
317
+
318
+ // Resolve install paths
319
+ const corePath = options.dir || data.install_paths?.core || `src/lib/${slug}`;
320
+ const adapterPath = data.install_paths?.adapter || `src/components/${slug}`;
321
+ const coreDir = path.resolve(process.cwd(), corePath);
322
+ const adapterDir = path.resolve(process.cwd(), adapterPath);
323
+
324
+ // Dry run — show what would be written
325
+ if (options.dryRun) {
326
+ spinner.stop();
327
+ console.log(chalk.white.bold('\n📋 Dry run — no files will be written:\n'));
328
+ if (coreFiles.length > 0) {
329
+ console.log(chalk.gray(` Core → ${corePath}/`));
330
+ for (const file of coreFiles) {
331
+ const exists = fs.existsSync(path.resolve(coreDir, file.path));
332
+ console.log(` ${exists ? chalk.yellow('⚠ overwrite') : chalk.green('+ create')} ${file.path}`);
333
+ }
334
+ }
335
+ if (adapterFiles.length > 0) {
336
+ console.log(chalk.gray(` Adapter → ${adapterPath}/`));
337
+ for (const file of adapterFiles) {
338
+ const exists = fs.existsSync(path.resolve(adapterDir, file.path));
339
+ console.log(` ${exists ? chalk.yellow('⚠ overwrite') : chalk.green('+ create')} ${file.path}`);
340
+ }
341
+ }
342
+ if (data.dependencies?.npm?.length) {
343
+ console.log(chalk.gray(`\n Dependencies: ${data.dependencies.npm.join(', ')}`));
344
+ }
345
+ return;
346
+ }
347
+
348
+ // Check for existing files
349
+ if (!options.overwrite) {
350
+ const conflicts = [];
351
+ for (const file of coreFiles) {
352
+ const fp = path.resolve(coreDir, file.path);
353
+ if (fs.existsSync(fp)) conflicts.push(`${corePath}/${file.path}`);
354
+ }
355
+ for (const file of adapterFiles) {
356
+ const fp = path.resolve(adapterDir, file.path);
357
+ if (fs.existsSync(fp)) conflicts.push(`${adapterPath}/${file.path}`);
358
+ }
359
+ if (conflicts.length > 0) {
360
+ spinner.stop();
361
+ console.log(chalk.yellow('\nThese files already exist:'));
362
+ for (const c of conflicts) {
363
+ console.log(chalk.gray(` ${c}`));
364
+ }
365
+ const { overwrite } = await inquirer.prompt([{
366
+ type: 'confirm',
367
+ name: 'overwrite',
368
+ message: 'Overwrite existing files?',
369
+ default: false,
370
+ }]);
371
+ if (!overwrite) return;
372
+ }
373
+ }
374
+
375
+ // Write core + adapter files
376
+ const coreCount = writeFiles(coreDir, coreFiles);
377
+ const adapterCount = writeFiles(adapterDir, adapterFiles);
378
+
379
+ spinner.succeed(`Added booster ${chalk.cyan(data.name || slug)} (${FRAMEWORK_LABELS[framework] || framework})`);
380
+
381
+ if (coreCount > 0) {
382
+ console.log(chalk.gray(` Core files → ${corePath}/`));
383
+ for (const file of coreFiles) {
384
+ console.log(chalk.gray(` ${file.path}`));
385
+ }
386
+ }
387
+ if (adapterCount > 0) {
388
+ console.log(chalk.gray(` Adapter files → ${adapterPath}/`));
389
+ for (const file of adapterFiles) {
390
+ console.log(chalk.gray(` ${file.path}`));
391
+ }
392
+ }
393
+
394
+ // Install npm dependencies
395
+ if (data.dependencies?.npm?.length) {
396
+ console.log();
397
+ const { install } = await inquirer.prompt([{
398
+ type: 'confirm',
399
+ name: 'install',
400
+ message: `Install dependencies? (${data.dependencies.npm.join(', ')})`,
401
+ default: true,
402
+ }]);
403
+
404
+ if (install) {
405
+ const installSpinner = ora('Installing dependencies...').start();
406
+ const result = runInstall(pm, process.cwd(), data.dependencies.npm);
407
+ if (result.success) {
408
+ installSpinner.succeed('Dependencies installed');
409
+ } else {
410
+ installSpinner.fail(result.error);
411
+ if (result.hint) console.log(chalk.gray(` ${result.hint}`));
412
+ }
413
+ }
414
+ }
415
+
416
+ // Post-install info
417
+ printPostInstallInfo(data, { pm });
418
+
419
+ // Next steps
420
+ printNextSteps({ type: 'booster', name: data.name || slug, data, pm });
421
+
422
+ if (data.is_pro) {
423
+ console.log();
424
+ console.log(chalk.magenta('✨ Pro booster — thank you for your subscription!'));
425
+ }
426
+
427
+ } catch (err) {
428
+ spinner.fail('Failed to add booster.');
429
+ handleAddError(err, slug, framework);
430
+ }
431
+ }
432
+
433
+ // ─── Add Workflow ───────────────────────────────────
434
+
435
+ async function addWorkflow(slug, options) {
436
+ if (!validateSlug(slug, 'workflow name')) process.exit(1);
437
+
438
+ const framework = await resolveFramework(options, 'workflow');
439
+
440
+ const spinner = ora(`Fetching workflow ${chalk.cyan(slug)} (${FRAMEWORK_LABELS[framework] || framework})...`).start();
441
+
442
+ try {
443
+ const data = await getWorkflow(slug, framework);
444
+
445
+ if (!data.files || data.files.length === 0) {
446
+ spinner.fail(`No files available for workflow "${slug}" (${framework}).`);
447
+ if (data.frameworks?.length) {
448
+ console.log(chalk.gray(`Available: ${data.frameworks.map(f => FRAMEWORK_LABELS[f] || f).join(', ')}`));
449
+ }
450
+ return;
451
+ }
452
+
453
+ // Determine target directory
454
+ let targetDir;
455
+ if (options.overlay) {
456
+ targetDir = path.resolve(process.cwd());
457
+ } else {
458
+ let dirName = options.dir || slug;
459
+
460
+ // If directory exists, ask the user
461
+ if (fs.existsSync(path.resolve(process.cwd(), dirName)) && !options.overwrite) {
462
+ spinner.stop();
463
+ const { action } = await inquirer.prompt([{
464
+ type: 'list',
465
+ name: 'action',
466
+ message: `Directory "${dirName}/" already exists. What do you want to do?`,
467
+ choices: [
468
+ { name: 'Overwrite it', value: 'overwrite' },
469
+ { name: 'Use a different name', value: 'rename' },
470
+ { name: 'Cancel', value: 'cancel' },
471
+ ],
472
+ }]);
473
+
474
+ if (action === 'cancel') return;
475
+ if (action === 'rename') {
476
+ const { newDir } = await inquirer.prompt([{
477
+ type: 'input',
478
+ name: 'newDir',
479
+ message: 'Enter a directory name:',
480
+ default: `${slug}-app`,
481
+ }]);
482
+ dirName = newDir;
483
+ }
484
+ }
485
+
486
+ targetDir = path.resolve(process.cwd(), dirName);
487
+ }
488
+
489
+ // Check for conflicts in overlay mode
490
+ if (options.overlay && !options.overwrite) {
491
+ const conflicts = [];
492
+ for (const file of data.files) {
493
+ const fp = path.resolve(targetDir, file.path);
494
+ if (fs.existsSync(fp)) conflicts.push(file.path);
495
+ }
496
+ if (conflicts.length > 0) {
497
+ spinner.stop();
498
+ console.log(chalk.yellow(`${conflicts.length} file(s) would be overwritten:`));
499
+ for (const c of conflicts.slice(0, 10)) {
500
+ console.log(chalk.gray(` ${c}`));
501
+ }
502
+ if (conflicts.length > 10) {
503
+ console.log(chalk.gray(` ... and ${conflicts.length - 10} more`));
504
+ }
505
+ const { overwrite } = await inquirer.prompt([{
506
+ type: 'confirm',
507
+ name: 'overwrite',
508
+ message: 'Overwrite these files?',
509
+ default: false,
510
+ }]);
511
+ if (!overwrite) return;
512
+ }
513
+ }
514
+
515
+ const dirName = path.basename(targetDir);
516
+ const targetLabel = options.overlay ? './' : `${dirName}/`;
517
+ const pm = detectPackageManager(options.overlay ? process.cwd() : targetDir);
518
+
519
+ // Dry run — show what would be written
520
+ if (options.dryRun) {
521
+ spinner.stop();
522
+ console.log(chalk.white.bold(`\n📋 Dry run — no files will be written to ${targetLabel}:\n`));
523
+ for (const file of data.files) {
524
+ const exists = fs.existsSync(path.resolve(targetDir, file.path));
525
+ console.log(` ${exists ? chalk.yellow('⚠ overwrite') : chalk.green('+ create')} ${file.path}`);
526
+ }
527
+ if (data.dependencies?.npm?.length) {
528
+ console.log(chalk.gray(`\n Dependencies: ${data.dependencies.npm.join(', ')}`));
529
+ }
530
+ return;
531
+ }
532
+
533
+ // Write files
534
+ const fileCount = writeFiles(targetDir, data.files);
535
+
536
+ spinner.succeed(`Scaffolded workflow ${chalk.cyan(data.name || slug)} (${FRAMEWORK_LABELS[framework] || framework}) → ${targetLabel}`);
537
+
538
+ console.log(chalk.gray(` ${fileCount} files written to ${targetLabel}`));
539
+
540
+ // Offer to install dependencies
541
+ if (!options.overlay) {
542
+ console.log();
543
+ const { install } = await inquirer.prompt([{
544
+ type: 'confirm',
545
+ name: 'install',
546
+ message: `Install dependencies with ${pm}?`,
547
+ default: true,
548
+ }]);
549
+
550
+ if (install) {
551
+ const installSpinner = ora(`Installing dependencies with ${pm}...`).start();
552
+ const result = runInstall(pm, targetDir);
553
+ if (result.success) {
554
+ installSpinner.succeed('Dependencies installed');
555
+ } else {
556
+ installSpinner.fail(result.error);
557
+ if (result.hint) console.log(chalk.gray(` ${result.hint}`));
558
+ }
559
+ }
560
+ }
561
+
562
+ // Next steps
563
+ console.log();
564
+ console.log(chalk.green.bold('✅ Ready to go!\n'));
565
+ if (!options.overlay) {
566
+ console.log(chalk.white(` cd ${dirName}`));
567
+ }
568
+ console.log(chalk.white(` ${getRunCommand(pm, 'dev')}`));
569
+
570
+ if (data.dependencies?.env?.length) {
571
+ console.log();
572
+ console.log(chalk.yellow('Don\'t forget to set up your environment variables:'));
573
+ for (const envVar of data.dependencies.env) {
574
+ console.log(chalk.gray(` ${envVar}=`));
575
+ }
576
+ }
577
+
578
+ if (data.post_install) {
579
+ console.log();
580
+ console.log(chalk.gray(data.post_install));
581
+ }
582
+
583
+ if (data.is_pro) {
584
+ console.log();
585
+ console.log(chalk.magenta('✨ Pro workflow — thank you for your subscription!'));
586
+ }
587
+
588
+ } catch (err) {
589
+ spinner.fail('Failed to add workflow.');
590
+ handleAddError(err, slug, framework);
591
+ }
592
+ }
593
+
594
+ // ─── Helpers ────────────────────────────────────────
595
+
596
+ function printPostInstallInfo(data, { pm = 'npm' } = {}) {
597
+ if (data.dependencies?.env?.length) {
598
+ console.log();
599
+ console.log(chalk.yellow('Add these environment variables to your .env:'));
600
+ for (const envVar of data.dependencies.env) {
601
+ console.log(chalk.gray(` ${envVar}=`));
602
+ }
603
+ }
604
+ if (data.post_install) {
605
+ console.log();
606
+ console.log(chalk.white.bold('Setup:'));
607
+ console.log(chalk.gray(data.post_install));
608
+ }
609
+ }
610
+
611
+ function printNextSteps({ type, name, data, pm = 'npm' }) {
612
+ console.log();
613
+ console.log(chalk.green.bold(`✅ ${name} installed successfully!\n`));
614
+
615
+ if (type === 'booster') {
616
+ console.log(chalk.gray('Import and use the booster in your code.'));
617
+ console.log(chalk.gray(`To remove later: astralkit remove ${data.slug || name}`));
618
+ }
619
+ }
620
+
621
+ function handleAddError(err, slug, framework) {
622
+ if (err.code === 'AUTH_REQUIRED') {
623
+ console.log(chalk.yellow(err.message));
624
+ } else if (err.code === 'PRO_REQUIRED') {
625
+ console.log(chalk.yellow(err.message));
626
+ } else {
627
+ try {
628
+ const body = JSON.parse(err.message.replace(/^API error \d+: /, ''));
629
+ if (body.supported_frameworks) {
630
+ console.log(chalk.yellow(`No ${framework} version available for "${slug}".`));
631
+ console.log(chalk.gray(`Available: ${body.supported_frameworks.map(f => FRAMEWORK_LABELS[f] || f).join(', ')}`));
632
+ process.exit(1);
633
+ }
634
+ } catch {
635
+ // Not a JSON parse error
636
+ }
637
+ console.error(chalk.red(err.message));
638
+ }
639
+ process.exit(1);
640
+ }
641
+
642
+ module.exports = { addCommand };