@astralkit/cli 4.7.3 → 4.8.1

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,853 +1,1054 @@
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, getBooster, getWorkflow, listComponents, listBoosters, listWorkflows, LOCAL_REGISTRY_DIR } from '../lib/api.js';
6
- import {
7
- detectFramework,
8
- detectTypeScript,
9
- isAstralkitInstalled,
10
- findCssEntryFile,
11
- getMissingCssImports,
12
- } from '../lib/config.js';
13
- import { validateSlug, validateFramework, isSafePath, writeFiles, isSafeInstallDir, filterSafePackages, sanitizeForTerminal } from '../lib/validators.js';
14
- import { detectPackageManager, getRunCommand, runInstall } from '../lib/pkg-manager.js';
15
- import { saveApiKey, getApiKey, getAuth } from '../lib/auth.js';
16
- import { applyMerges } from '../lib/merges.js';
17
- import { ensureComponentStylesheets } from '../lib/stylesheets.js';
18
- import { setAssumeYes, confirm as askConfirm, select as askSelect, text as askText } from '../lib/ask.js';
19
-
20
- const FRAMEWORK_LABELS = { nextjs: 'Next.js', react: 'React' };
21
-
22
- // `astralkit add a b c` installs each name in turn. One name failing must not stop the rest, so inside a
23
- // batch an exit becomes a throw that the loop catches; a single name exits as it always did.
24
- class ExitSignal extends Error {
25
- constructor(code) { super('exit'); this.code = code; }
26
- }
27
- let inBatch = false;
28
- function exit(code) {
29
- if (inBatch) throw new ExitSignal(code);
30
- process.exit(code);
31
- }
32
-
33
- export async function addCommand(names, options) {
34
- const list = [...new Set([].concat(names).filter(Boolean))];
35
- if (list.length <= 1) return addOne(list[0], options);
36
-
37
- const installed = [];
38
- const notInstalled = [];
39
- inBatch = true;
40
- try {
41
- for (const [index, name] of list.entries()) {
42
- console.log();
43
- p.log.step(`${pc.cyan(name)} (${index + 1} of ${list.length})`);
44
- let done = false;
45
- try {
46
- done = (await addOne(name, options)) === true;
47
- } catch (err) {
48
- if (!(err instanceof ExitSignal)) throw err;
49
- }
50
- (done ? installed : notInstalled).push(name);
51
- }
52
- } finally {
53
- inBatch = false;
54
- }
55
-
56
- console.log();
57
- if (installed.length) p.log.success(`Installed ${installed.length} of ${list.length}: ${installed.join(', ')}`);
58
- if (notInstalled.length) {
59
- p.log.warn(`Not installed: ${notInstalled.join(', ')} (the reason for each is printed above)`);
60
- process.exit(1);
61
- }
62
- }
63
-
64
- async function addOne(nameOrSlug, options) {
65
- setAssumeYes(options.yes);
66
- if (options.apiKey) {
67
- if (!options.apiKey.startsWith('ak_')) {
68
- console.log(pc.red('Invalid API key format. Keys start with ak_'));
69
- exit(1);
70
- }
71
- saveApiKey(options.apiKey);
72
- }
73
-
74
- // A component needs no key to be asked for (2026-11-30): the free components install for everyone, and the
75
- // registry itself says when one is premium (handleAddError then tells how to sign in). The CLI used to stop here
76
- // with "No API key found" before asking, so nobody without a key could install even the free set.
77
- // Boosters and workflows are for paid plans: they still need a key, unless read from a local registry
78
- // (the developer's own disk, no account needed).
79
- const localBoosterInstall = LOCAL_REGISTRY_DIR && (options.booster || options.workflow);
80
- if ((options.booster || options.workflow) && !getApiKey() && !localBoosterInstall) {
81
- const auth = getAuth();
82
- if (!auth.token) {
83
- p.log.warn('No API key found. Run ' + pc.cyan('astralkit init --api-key <key>') + ' first.');
84
- console.log(pc.gray('Get yours at ') + pc.cyan('https://astralkit.com/account'));
85
- exit(1);
86
- }
87
- }
88
-
89
- // If explicit type flag provided, skip smart detection
90
- if (options.booster) return addBooster(nameOrSlug, options);
91
- if (options.workflow) return addWorkflow(nameOrSlug, options);
92
-
93
- // ─── Smart detection: search all registries for the slug ───
94
- const ora = (await import('ora')).default;
95
- const spinner = ora('Searching registries...').start();
96
-
97
- try {
98
- // Search all three registries in parallel
99
- const [components, boosters, workflows] = await Promise.allSettled([
100
- listComponents({ search: nameOrSlug }).catch(() => ({ data: [] })),
101
- listBoosters({ search: nameOrSlug }).catch(() => ({ data: [] })),
102
- listWorkflows({ search: nameOrSlug }).catch(() => ({ data: [] })),
103
- ]);
104
-
105
- const compMatch = (components.status === 'fulfilled' ? (components.value?.components || components.value?.data || []) : [])
106
- ?.find(c => c.slug === nameOrSlug);
107
- const boosterMatch = (boosters.status === 'fulfilled' ? (boosters.value?.boosters || boosters.value?.data || []) : [])
108
- ?.find(b => b.slug === nameOrSlug);
109
- const workflowMatch = (workflows.status === 'fulfilled' ? (workflows.value?.workflows || workflows.value?.data || []) : [])
110
- ?.find(w => w.slug === nameOrSlug);
111
-
112
- const matches = [];
113
- if (compMatch) matches.push({ type: 'component', name: compMatch.name || nameOrSlug, slug: nameOrSlug });
114
- if (boosterMatch) matches.push({ type: 'booster', name: boosterMatch.name || nameOrSlug, slug: nameOrSlug });
115
- if (workflowMatch) matches.push({ type: 'workflow', name: workflowMatch.name || nameOrSlug, slug: nameOrSlug });
116
-
117
- spinner.stop();
118
-
119
- if (matches.length === 0) {
120
- // No exact match — try fuzzy suggestions
121
- const allItems = [
122
- ...((components.status === 'fulfilled' ? (components.value?.components || components.value?.data || []) : []) || []).map(c => ({ ...c, type: 'component' })),
123
- ...((boosters.status === 'fulfilled' ? (boosters.value?.boosters || boosters.value?.data || []) : []) || []).map(b => ({ ...b, type: 'booster' })),
124
- ...((workflows.status === 'fulfilled' ? (workflows.value?.workflows || workflows.value?.data || []) : []) || []).map(w => ({ ...w, type: 'workflow' })),
125
- ];
126
-
127
- const similar = allItems
128
- .filter(item => item.slug && (
129
- item.slug.includes(nameOrSlug) ||
130
- nameOrSlug.includes(item.slug) ||
131
- item.name?.toLowerCase().includes(nameOrSlug.toLowerCase())
132
- ))
133
- .slice(0, 5);
134
-
135
- if (similar.length > 0) {
136
- p.log.warn(`"${nameOrSlug}" not found.`);
137
- console.log();
138
- console.log(pc.gray(' Did you mean:'));
139
- for (const s of similar) {
140
- console.log(` ${pc.cyan(s.slug)} ${pc.gray(`(${s.type})`)}`);
141
- }
142
- console.log();
143
- } else {
144
- p.log.error(`"${nameOrSlug}" not found in any registry.`);
145
- p.log.info('Run ' + pc.cyan('astralkit search "' + nameOrSlug + '"') + ' to browse available content.');
146
- }
147
- // nothing was installed: a script or an agent must be able to tell (the exit code was 0)
148
- process.exitCode = 1;
149
- return;
150
- }
151
-
152
- if (matches.length === 1) {
153
- // Exact match in one registry — install directly
154
- const match = matches[0];
155
- p.log.step(`Found ${pc.cyan(match.name)} as a ${pc.bold(match.type)}`);
156
-
157
- if (match.type === 'booster') return addBooster(nameOrSlug, options);
158
- if (match.type === 'workflow') return addWorkflow(nameOrSlug, options);
159
- return addComponent(nameOrSlug, options);
160
- }
161
-
162
- // Found in multiple registries — prompt user to choose (non-interactive:
163
- // prefer the component, the most common install target).
164
- const componentMatch = matches.find(m => m.type === 'component');
165
- const choice = await askSelect({
166
- message: `"${nameOrSlug}" found in multiple registries. What would you like to install?`,
167
- options: matches.map(m => ({
168
- value: m.type,
169
- label: `${m.name} (${m.type === 'component' ? 'UI component' : m.type === 'booster' ? 'feature module' : 'app scaffold'})`,
170
- })),
171
- nonInteractive: componentMatch ? 'component' : matches[0].type,
172
- });
173
-
174
- if (p.isCancel(choice)) { p.cancel('Cancelled.'); exit(0); }
175
-
176
- if (choice === 'booster') return addBooster(nameOrSlug, options);
177
- if (choice === 'workflow') return addWorkflow(nameOrSlug, options);
178
- return addComponent(nameOrSlug, options);
179
-
180
- } catch (err) {
181
- spinner.stop();
182
- // If registry search fails, fall back to component (original behavior)
183
- return addComponent(nameOrSlug, options);
184
- }
185
- }
186
-
187
- function resolveFramework(options) {
188
- if (options.framework) {
189
- if (!validateFramework(options.framework)) exit(1);
190
- return options.framework;
191
- }
192
- const detected = detectFramework();
193
- if (detected === 'nextjs' || detected === 'react') return detected;
194
- return 'react';
195
- }
196
-
197
- function resolveExtension(framework) {
198
- const isTS = detectTypeScript();
199
- if (framework === 'nextjs') return '.tsx';
200
- return isTS ? '.tsx' : '.jsx';
201
- }
202
-
203
- // Read the target project's package.json. Used to detect package conflicts
204
- // (e.g. host already uses @phosphor-icons/react and we're about to add the
205
- // separate @phosphor-icons/web). Returns null if the file is unreadable.
206
- function readHostPackageJson() {
207
- try {
208
- const raw = fs.readFileSync(path.join(process.cwd(), 'package.json'), 'utf8');
209
- return JSON.parse(raw);
210
- } catch {
211
- return null;
212
- }
213
- }
214
-
215
- function hostHasDep(pkg, name) {
216
- if (!pkg) return false;
217
- return Boolean(
218
- pkg.dependencies?.[name] ||
219
- pkg.devDependencies?.[name] ||
220
- pkg.optionalDependencies?.[name]
221
- );
222
- }
223
-
224
- async function addComponent(componentSlug, options) {
225
- if (!validateSlug(componentSlug)) exit(1);
226
- if (!fs.existsSync(path.join(process.cwd(), 'package.json'))) {
227
- p.log.warn('No package.json found. Run this inside a project directory.');
228
- return;
229
- }
230
-
231
- // Tracked across the full install so the end-of-run summary can tell the
232
- // user exactly what changed in their project (created files, modified
233
- // files, installed deps, anything skipped by user confirmation).
234
- const installSummary = {
235
- created: [], // relative file paths written
236
- modified: [], // { path, note }
237
- installed: [], // dep names
238
- alreadySatisfied: [], // dep names
239
- skipped: [], // { what, reason }
240
- };
241
-
242
- const ora = (await import('ora')).default;
243
- const framework = resolveFramework(options);
244
- const ext = resolveExtension(framework);
245
- const componentsDir = options.dir || 'src/components/ui';
246
- // Refuse absolute / traversal values of --dir.
247
- if (!isSafeInstallDir(process.cwd(), componentsDir)) {
248
- console.log(pc.red(`Refusing install: unsafe --dir value "${componentsDir}"`));
249
- exit(1);
250
- }
251
- const targetFile = path.resolve(process.cwd(), componentsDir, `${componentSlug}${ext}`);
252
-
253
- if (fs.existsSync(targetFile) && !options.overwrite) {
254
- p.log.warn(`Already exists: ${componentsDir}/${componentSlug}${ext}`);
255
- console.log(pc.gray('Use --overwrite to replace.'));
256
- return;
257
- }
258
-
259
- const spinner = ora(`Fetching ${pc.cyan(componentSlug)} (${FRAMEWORK_LABELS[framework]})...`).start();
260
-
261
- try {
262
- const data = await getComponent(componentSlug, framework);
263
-
264
- if (!data.files?.length) {
265
- spinner.fail(`No ${framework} code available for "${componentSlug}".`);
266
- if (data.supported_frameworks?.length) {
267
- console.log(pc.gray(`Available: ${data.supported_frameworks.map(f => FRAMEWORK_LABELS[f] || f).join(', ')}`));
268
- }
269
- return;
270
- }
271
-
272
- if (options.dryRun) {
273
- spinner.stop();
274
- console.log(pc.bold('\nDry run — no files will be written:\n'));
275
- for (const file of data.files) {
276
- const exists = fs.existsSync(path.resolve(process.cwd(), componentsDir, file.path));
277
- console.log(` ${exists ? pc.yellow('overwrite') : pc.green('+ create')} ${componentsDir}/${file.path}`);
278
- }
279
- return;
280
- }
281
-
282
- const dir = path.resolve(process.cwd(), componentsDir);
283
- fs.mkdirSync(dir, { recursive: true });
284
-
285
- // Filter out supplementary files that aren't needed for React/Next.js
286
- // (styles.css and script.js are for HTML standalone components only)
287
- const filesToWrite = framework === 'html'
288
- ? data.files
289
- : data.files.filter(f => f.path !== 'styles.css' && f.path !== 'script.js');
290
-
291
- for (const file of filesToWrite) {
292
- if (!isSafePath(dir, file.path)) {
293
- console.log(pc.red(` Skipping suspicious path: ${file.path}`));
294
- installSummary.skipped.push({ what: file.path, reason: 'unsafe path' });
295
- continue;
296
- }
297
- const filePath = path.resolve(dir, file.path);
298
- fs.mkdirSync(path.dirname(filePath), { recursive: true });
299
- fs.writeFileSync(filePath, file.content);
300
- installSummary.created.push(path.join(componentsDir, file.path).replace(/\\/g, '/'));
301
- }
302
-
303
- spinner.succeed(`Added ${pc.cyan(data.name || componentSlug)} (${FRAMEWORK_LABELS[framework]})`);
304
-
305
- if (!isAstralkitInstalled()) {
306
- p.log.warn('Run ' + pc.cyan('astralkit init') + ' to set up design tokens.');
307
- }
308
-
309
- const cssEntry = findCssEntryFile();
310
- if (cssEntry) {
311
- const missing = getMissingCssImports(cssEntry.path);
312
- if (missing.length > 0) {
313
- p.log.warn(`Missing CSS imports in ${cssEntry.relative}. Run ${pc.cyan('astralkit init')} to fix.`);
314
- }
315
- }
316
-
317
- // Detect if component uses Phosphor Icons (CSS class-based icons)
318
- const componentCode = data.files?.map(f => f.content).join('') || '';
319
-
320
- // The stylesheets the component asks for (a template section's palette and typefaces, a date picker's dialog)
321
- // go into the project's stylesheet. An HTML file loads its own from the CDN.
322
- if (framework !== 'html') await ensureComponentStylesheets(filesToWrite.map(f => f.content).join('\n'), installSummary);
323
- let usesPhosphorCss = componentCode.includes('class="ph ') || componentCode.includes("class='ph ") || componentCode.includes('"ph ph-') || componentCode.includes("'ph ph-");
324
-
325
- // Phosphor conflict guard: @phosphor-icons/web and @phosphor-icons/react
326
- // are SEPARATE packages (CSS classes vs React components). Installing both
327
- // ships two icon systems in the same codebase — bundle bloat and a
328
- // long-term consistency tax. If the host already uses the React package,
329
- // warn loudly and let the user opt out of auto-installing web.
330
- if (usesPhosphorCss) {
331
- const hostPkg = readHostPackageJson();
332
- if (hostHasDep(hostPkg, '@phosphor-icons/react')) {
333
- p.log.warn(`This component uses ${pc.cyan('@phosphor-icons/web')} (CSS class-based icons).`);
334
- p.log.warn(`Your project already uses ${pc.cyan('@phosphor-icons/react')} (React components) — a ${pc.bold('separate package')} from the same vendor.`);
335
- p.log.warn(`Installing both ships two icon systems side by side.`);
336
-
337
- // Non-interactive default is YES: the component file is already written
338
- // with `ph ph-*` classes — skipping the package ships broken icons,
339
- // which is worse than the two-icon-systems consistency tax.
340
- const proceed = await askConfirm({
341
- message: 'Install @phosphor-icons/web anyway?',
342
- initialValue: false,
343
- nonInteractive: true,
344
- });
345
- if (!proceed) {
346
- p.log.info('Skipping @phosphor-icons/web and the layout.tsx import.');
347
- p.log.info(pc.gray('Adapt the component\'s <i className="ph ph-*"> tags to @phosphor-icons/react React components.'));
348
- usesPhosphorCss = false;
349
- installSummary.skipped.push({
350
- what: '@phosphor-icons/web',
351
- reason: 'host project uses @phosphor-icons/react; user declined',
352
- });
353
- }
354
- }
355
- }
356
-
357
- // The registry's `dependencies` metadata can lag behind the code (found
358
- // live: kanban-01 imports three @dnd-kit packages, metadata listed one).
359
- // Scan the actual source for bare package imports so a metadata gap never
360
- // ships a component that doesn't build.
361
- const importedPackages = new Set();
362
- const jsCode = (data.files || [])
363
- .filter(f => /\.(tsx?|jsx?|mjs|cjs)$/.test(f.path))
364
- .map(f => f.content).join('\n');
365
- for (const m of jsCode.matchAll(/(?:from|import)\s*\(?\s*['"]((?:@[a-z0-9~][\w.~-]*\/)?[a-z0-9~][\w.~-]*)(?:\/[^'"]*)?['"]/g)) {
366
- importedPackages.add(m[1]);
367
- }
368
- // Packages the host/framework already accounts for.
369
- for (const skip of ['react', 'react-dom', 'next', 'astralkit', 'clsx', 'tailwind-merge']) {
370
- importedPackages.delete(skip);
371
- }
372
-
373
- if (data.dependencies?.length || usesPhosphorCss || importedPackages.size > 0) {
374
- const pm = detectPackageManager();
375
- const rawDepList = (data.dependencies || []).filter(d => d !== 'astralkit' && d !== 'clsx' && d !== 'tailwind-merge');
376
-
377
- for (const pkg of importedPackages) {
378
- if (!rawDepList.includes(pkg)) rawDepList.push(pkg);
379
- }
380
-
381
- // Auto-add @phosphor-icons/web if component uses CSS-based Phosphor icons
382
- // AND we didn't skip it above due to a @phosphor-icons/react conflict.
383
- if (usesPhosphorCss && !rawDepList.includes('@phosphor-icons/web')) {
384
- rawDepList.push('@phosphor-icons/web');
385
- }
386
-
387
- // SECURITY: validate package names before passing to npm install — a
388
- // malicious server response could inject "-S", "--registry=evil.com",
389
- // "git+ssh://...", or a tarball URL. We only accept bare npm names.
390
- const { accepted: depList, rejected } = filterSafePackages(rawDepList);
391
- if (rejected.length > 0) {
392
- console.log(pc.yellow(` Skipping invalid package names: ${rejected.map(sanitizeForTerminal).join(', ')}`));
393
- }
394
-
395
- if (depList.length > 0) {
396
- // Split into already-present vs to-install so the user sees both in
397
- // the end-of-install summary.
398
- const hostPkg = readHostPackageJson();
399
- const toInstall = depList.filter(d => !hostHasDep(hostPkg, d));
400
- const alreadyThere = depList.filter(d => hostHasDep(hostPkg, d));
401
- for (const d of alreadyThere) installSummary.alreadySatisfied.push(d);
402
-
403
- if (toInstall.length > 0) {
404
- // Always ask before running npm install — mirrors the booster flow.
405
- // (Non-interactive: yes — a component without its deps doesn't build.)
406
- const install = await askConfirm({
407
- message: `Install dependencies? (${toInstall.join(', ')})`,
408
- initialValue: true,
409
- });
410
- if (install) {
411
- const s = ora(`Installing ${toInstall.join(', ')}...`).start();
412
- const result = await runInstall(pm, process.cwd(), toInstall);
413
- if (result.success) {
414
- s.succeed(`Installed ${toInstall.join(', ')}`);
415
- for (const d of toInstall) installSummary.installed.push(d);
416
- } else {
417
- s.fail(sanitizeForTerminal(result.error || 'Install failed'));
418
- if (result.hint) console.log(pc.gray(` ${sanitizeForTerminal(result.hint)}`));
419
- for (const d of toInstall) {
420
- installSummary.skipped.push({ what: d, reason: 'install failed' });
421
- }
422
- }
423
- } else {
424
- for (const d of toInstall) {
425
- installSummary.skipped.push({ what: d, reason: 'user declined install' });
426
- }
427
- }
428
- }
429
- }
430
-
431
- // Auto-add JS imports for icon/font packages in layout file
432
- // (CSS @import doesn't resolve node_modules exports in Next.js PostCSS).
433
- // This modifies a user-owned file — one of the most critical in a
434
- // Next.js app — so we now show the exact diff and prompt for consent
435
- // with a default of NO. Silent modification of layout.tsx was a
436
- // reported trust issue (CLI feedback 2026-04-22).
437
- const JS_DEPENDENCY_IMPORTS = {
438
- '@phosphor-icons/web': [
439
- "import '@phosphor-icons/web/regular'",
440
- "import '@phosphor-icons/web/fill'",
441
- ],
442
- };
443
-
444
- // Only consider packages we actually installed (or that were already
445
- // present) — no point prompting about imports for a dep the user skipped.
446
- const effectiveDeps = new Set([
447
- ...installSummary.installed,
448
- ...installSummary.alreadySatisfied,
449
- ]);
450
- for (const [pkg, imports] of Object.entries(JS_DEPENDENCY_IMPORTS)) {
451
- if (!effectiveDeps.has(pkg)) continue;
452
-
453
- const layoutCandidates = [
454
- 'src/app/layout.tsx', 'src/app/layout.jsx', 'src/app/layout.js',
455
- 'app/layout.tsx', 'app/layout.jsx', 'app/layout.js',
456
- 'src/pages/_app.tsx', 'src/pages/_app.jsx', 'src/pages/_app.js',
457
- 'pages/_app.tsx', 'pages/_app.jsx', 'pages/_app.js',
458
- ];
459
- let layoutFile = null;
460
- for (const candidate of layoutCandidates) {
461
- const fullPath = path.join(process.cwd(), candidate);
462
- if (fs.existsSync(fullPath)) {
463
- layoutFile = { path: fullPath, relative: candidate };
464
- break;
465
- }
466
- }
467
- if (!layoutFile) continue;
468
-
469
- const layoutContent = fs.readFileSync(layoutFile.path, 'utf8');
470
- const missing = imports.filter(imp => !layoutContent.includes(imp));
471
- if (missing.length === 0) continue;
472
-
473
- // Show the exact diff we want to apply — never silently modify.
474
- p.log.warn(`${pc.cyan(pkg)} needs these side-effect imports in your root layout:`);
475
- console.log(pc.gray(` ${layoutFile.relative}`));
476
- for (const imp of missing) console.log(` ${pc.green('+')} ${imp}`);
477
-
478
- // Non-interactive default is YES: the exact diff is printed above (never
479
- // silent — the 2026-04-22 trust rule), and skipping it ships a component
480
- // whose icons don't render.
481
- const proceed = await askConfirm({
482
- message: `Add these imports to ${layoutFile.relative}?`,
483
- initialValue: false,
484
- nonInteractive: true,
485
- });
486
-
487
- if (!proceed) {
488
- p.log.info(`Skipped ${layoutFile.relative} edit. Add these lines manually to enable icons:`);
489
- for (const imp of missing) console.log(pc.gray(` ${imp}`));
490
- installSummary.skipped.push({
491
- what: `${layoutFile.relative} imports (${pkg})`,
492
- reason: 'user declined',
493
- });
494
- continue;
495
- }
496
-
497
- const lines = layoutContent.split('\n');
498
- let lastImportIdx = -1;
499
- for (let i = 0; i < lines.length; i++) {
500
- if (lines[i].trim().startsWith('import ')) lastImportIdx = i;
501
- }
502
- if (lastImportIdx >= 0) {
503
- lines.splice(lastImportIdx + 1, 0, ...missing);
504
- } else {
505
- lines.unshift(...missing);
506
- }
507
- fs.writeFileSync(layoutFile.path, lines.join('\n'));
508
- installSummary.modified.push({
509
- path: layoutFile.relative,
510
- note: `+${missing.length} ${missing.length === 1 ? 'import' : 'imports'} (${pkg})`,
511
- });
512
- p.log.success(`Added ${pc.cyan(pkg)} imports to ${pc.cyan(layoutFile.relative)}`);
513
- }
514
- }
515
-
516
- printInstallSummary(installSummary);
517
- return true;
518
-
519
- } catch (err) {
520
- spinner.fail('Failed to add component.');
521
- handleAddError(err, componentSlug, framework);
522
- }
523
- }
524
-
525
- // End-of-install summary. Prints what the CLI did to the user's project so
526
- // they never have to run `git diff` just to find out what was touched. Split
527
- // into Created / Modified / Installed / Skipped so each category is scannable.
528
- function printInstallSummary(s) {
529
- const hasAny =
530
- s.created.length || s.modified.length || s.installed.length ||
531
- s.alreadySatisfied.length || s.skipped.length;
532
- if (!hasAny) return;
533
-
534
- console.log('');
535
- p.log.step(pc.bold('What changed in your project'));
536
- if (s.created.length) {
537
- console.log(pc.green(' Created:'));
538
- for (const f of s.created) console.log(pc.gray(` ${f}`));
539
- }
540
- if (s.modified.length) {
541
- console.log(pc.yellow(' Modified:'));
542
- for (const m of s.modified) console.log(pc.gray(` ${m.path} ${pc.dim(m.note)}`));
543
- }
544
- if (s.installed.length) {
545
- console.log(pc.cyan(' Installed:'));
546
- for (const d of s.installed) console.log(pc.gray(` ${d}`));
547
- }
548
- if (s.alreadySatisfied.length) {
549
- console.log(pc.gray(' Already satisfied:'));
550
- for (const d of s.alreadySatisfied) console.log(pc.gray(` ${d}`));
551
- }
552
- if (s.skipped.length) {
553
- console.log(pc.gray(' Skipped:'));
554
- for (const k of s.skipped) console.log(pc.gray(` ${k.what} ${pc.dim(`(${k.reason})`)}`));
555
- }
556
- }
557
-
558
- async function addBooster(slug, options) {
559
- if (!validateSlug(slug, 'booster name')) exit(1);
560
-
561
- const ora = (await import('ora')).default;
562
- const framework = resolveFramework(options);
563
- const pm = detectPackageManager();
564
- const spinner = ora(`Fetching booster ${pc.cyan(slug)} (${FRAMEWORK_LABELS[framework] || framework})...`).start();
565
-
566
- try {
567
- const data = await getBooster(slug, framework);
568
- const coreFiles = data.core_files || [];
569
- const adapterFiles = data.adapter_files || [];
570
-
571
- if (coreFiles.length === 0 && adapterFiles.length === 0) {
572
- spinner.fail(`No files available for booster "${slug}" (${framework}).`);
573
- return;
574
- }
575
-
576
- // SECURITY: Server-supplied install_paths must stay inside cwd. Otherwise
577
- // a compromised API could write to /etc, ~/.ssh, %APPDATA%, etc.
578
- // options.dir comes from the user's own CLI invocation, so it's trusted.
579
- const serverCore = data.install_paths?.core;
580
- const serverAdapter = data.install_paths?.adapter;
581
- if (serverCore && !isSafeInstallDir(process.cwd(), serverCore)) {
582
- spinner.fail(pc.red(`Refusing install: server returned unsafe core path "${serverCore}"`));
583
- return;
584
- }
585
- if (serverAdapter && !isSafeInstallDir(process.cwd(), serverAdapter)) {
586
- spinner.fail(pc.red(`Refusing install: server returned unsafe adapter path "${serverAdapter}"`));
587
- return;
588
- }
589
- const corePath = options.dir || serverCore || `src/lib/${slug}`;
590
- const adapterPath = serverAdapter || `src/components/${slug}`;
591
- // Final defense: even if options.dir came from the user, reject absolute/traversal
592
- // values so --dir "/" or --dir "../.." can't be weaponized.
593
- if (!isSafeInstallDir(process.cwd(), corePath) || !isSafeInstallDir(process.cwd(), adapterPath)) {
594
- spinner.fail(pc.red(`Refusing install: unsafe install path`));
595
- return;
596
- }
597
- const coreDir = path.resolve(process.cwd(), corePath);
598
- const adapterDir = path.resolve(process.cwd(), adapterPath);
599
-
600
- if (options.dryRun) {
601
- spinner.stop();
602
- console.log(pc.bold('\nDry run — no files will be written:\n'));
603
- if (coreFiles.length > 0) {
604
- console.log(pc.gray(` Core: ${corePath}/`));
605
- for (const f of coreFiles) {
606
- const exists = fs.existsSync(path.resolve(coreDir, f.path));
607
- console.log(` ${exists ? pc.yellow('overwrite') : pc.green('+ create')} ${f.path}`);
608
- }
609
- }
610
- if (adapterFiles.length > 0) {
611
- console.log(pc.gray(` Adapter: ${adapterPath}/`));
612
- for (const f of adapterFiles) {
613
- const exists = fs.existsSync(path.resolve(adapterDir, f.path));
614
- console.log(` ${exists ? pc.yellow('overwrite') : pc.green('+ create')} ${f.path}`);
615
- }
616
- }
617
- return;
618
- }
619
-
620
- if (!options.overwrite) {
621
- const conflicts = [
622
- ...coreFiles.filter(f => fs.existsSync(path.resolve(coreDir, f.path))).map(f => `${corePath}/${f.path}`),
623
- ...adapterFiles.filter(f => fs.existsSync(path.resolve(adapterDir, f.path))).map(f => `${adapterPath}/${f.path}`),
624
- ];
625
- if (conflicts.length > 0) {
626
- spinner.stop();
627
- console.log(pc.yellow('\nThese files already exist:'));
628
- conflicts.forEach(c => console.log(pc.gray(` ${c}`)));
629
- // Overwrite stays fail-safe when non-interactive WITHOUT --yes/env:
630
- // destroying user files needs explicit consent (--overwrite, --yes, or a TTY answer).
631
- const overwrite = process.env.ASTRALKIT_YES === '1'
632
- ? true
633
- : await askConfirm({ message: 'Overwrite existing files?', initialValue: false });
634
- if (!overwrite) return;
635
- }
636
- }
637
-
638
- writeFiles(coreDir, coreFiles);
639
- writeFiles(adapterDir, adapterFiles);
640
-
641
- spinner.succeed(`Added booster ${pc.cyan(data.name || slug)} (${FRAMEWORK_LABELS[framework] || framework})`);
642
-
643
- if (coreFiles.length > 0) {
644
- console.log(pc.gray(` Core: ${corePath}/`));
645
- coreFiles.forEach(f => console.log(pc.gray(` ${f.path}`)));
646
- }
647
- if (adapterFiles.length > 0) {
648
- console.log(pc.gray(` Adapter: ${adapterPath}/`));
649
- adapterFiles.forEach(f => console.log(pc.gray(` ${f.path}`)));
650
- }
651
-
652
- if (data.dependencies?.npm?.length) {
653
- // SECURITY: filter out anything that isn't a bare npm package name.
654
- const { accepted: safeDeps, rejected } = filterSafePackages(data.dependencies.npm);
655
- if (rejected.length > 0) {
656
- console.log(pc.yellow(` Skipping invalid package names: ${rejected.map(sanitizeForTerminal).join(', ')}`));
657
- }
658
- if (safeDeps.length > 0) {
659
- console.log();
660
- const install = await askConfirm({
661
- message: `Install dependencies? (${safeDeps.join(', ')})`,
662
- initialValue: true,
663
- });
664
- if (install) {
665
- const s = ora('Installing dependencies...').start();
666
- const result = await runInstall(pm, process.cwd(), safeDeps);
667
- if (result.success) s.succeed('Dependencies installed');
668
- else { s.fail(sanitizeForTerminal(result.error || 'Install failed')); if (result.hint) console.log(pc.gray(` ${sanitizeForTerminal(result.hint)}`)); }
669
- }
670
- }
671
- }
672
-
673
- // Apply file-merge patches (e.g. wrap layout.tsx with a provider, ensure
674
- // middleware.ts exists or print merge instructions). Runs after deps install
675
- // so the wrapped file's imports resolve immediately on `npm run dev`.
676
- if (Array.isArray(data.merges) && data.merges.length > 0) {
677
- const mergeSummary = { created: [], modified: [], installed: [], alreadySatisfied: [], skipped: [] };
678
- await applyMerges(data.merges, process.cwd(), mergeSummary);
679
-
680
- // Surface what changed in the user's existing files. We don't reuse
681
- // printInstallSummary here because the booster file list was already
682
- // printed above; this is the focused "what we touched outside the
683
- // install_paths" report.
684
- if (mergeSummary.created.length || mergeSummary.modified.length || mergeSummary.skipped.length) {
685
- console.log();
686
- if (mergeSummary.created.length) {
687
- console.log(pc.green(' Created:'));
688
- for (const f of mergeSummary.created) console.log(pc.gray(` ${f}`));
689
- }
690
- if (mergeSummary.modified.length) {
691
- console.log(pc.yellow(' Patched:'));
692
- for (const m of mergeSummary.modified) console.log(pc.gray(` ${m.path} ${pc.dim(m.note)}`));
693
- }
694
- if (mergeSummary.skipped.length) {
695
- console.log(pc.gray(' Merge skipped:'));
696
- for (const k of mergeSummary.skipped) console.log(pc.gray(` ${k.what} ${pc.dim(`(${k.reason})`)}`));
697
- }
698
- }
699
- }
700
-
701
- if (data.dependencies?.env?.length) {
702
- console.log();
703
- p.log.warn('Add these to your .env:');
704
- data.dependencies.env.forEach(v => console.log(pc.gray(` ${v}=`)));
705
- }
706
-
707
- if (data.post_install) { console.log(); console.log(pc.gray(data.post_install)); }
708
- return true;
709
-
710
- } catch (err) {
711
- spinner.fail('Failed to add booster.');
712
- handleAddError(err, slug, framework);
713
- }
714
- }
715
-
716
- async function addWorkflow(slug, options) {
717
- if (!validateSlug(slug, 'workflow name')) exit(1);
718
-
719
- const ora = (await import('ora')).default;
720
- const framework = resolveFramework(options);
721
- const spinner = ora(`Fetching workflow ${pc.cyan(slug)} (${FRAMEWORK_LABELS[framework] || framework})...`).start();
722
-
723
- try {
724
- const data = await getWorkflow(slug, framework);
725
-
726
- if (!data.files?.length) {
727
- spinner.fail(`No files available for workflow "${slug}" (${framework}).`);
728
- return;
729
- }
730
-
731
- let targetDir;
732
- if (options.overlay) {
733
- targetDir = path.resolve(process.cwd());
734
- } else {
735
- let dirName = options.dir || slug;
736
- if (!isSafeInstallDir(process.cwd(), dirName)) {
737
- spinner.fail(pc.red(`Refusing install: unsafe --dir value`));
738
- return;
739
- }
740
-
741
- if (fs.existsSync(path.resolve(process.cwd(), dirName)) && !options.overwrite) {
742
- spinner.stop();
743
- // Non-interactive: cancel — scaffolding over an existing directory
744
- // needs explicit consent (--overwrite or a TTY answer).
745
- const action = await askSelect({
746
- message: `Directory "${dirName}/" already exists.`,
747
- options: [
748
- { label: 'Overwrite it', value: 'overwrite' },
749
- { label: 'Use a different name', value: 'rename' },
750
- { label: 'Cancel', value: 'cancel' },
751
- ],
752
- nonInteractive: 'cancel',
753
- });
754
- if (p.isCancel(action) || action === 'cancel') return;
755
- if (action === 'rename') {
756
- const newDir = await askText({ message: 'Enter a directory name:', placeholder: `${slug}-app` });
757
- if (p.isCancel(newDir)) return;
758
- dirName = newDir;
759
- }
760
- }
761
- targetDir = path.resolve(process.cwd(), dirName);
762
- }
763
-
764
- if (options.overlay && !options.overwrite) {
765
- const conflicts = data.files.filter(f => fs.existsSync(path.resolve(targetDir, f.path))).map(f => f.path);
766
- if (conflicts.length > 0) {
767
- spinner.stop();
768
- console.log(pc.yellow(`${conflicts.length} file(s) would be overwritten:`));
769
- conflicts.slice(0, 10).forEach(c => console.log(pc.gray(` ${c}`)));
770
- if (conflicts.length > 10) console.log(pc.gray(` ... and ${conflicts.length - 10} more`));
771
- const overwrite = await askConfirm({ message: 'Overwrite these files?', initialValue: false });
772
- if (!overwrite) return;
773
- }
774
- }
775
-
776
- if (options.dryRun) {
777
- spinner.stop();
778
- const label = options.overlay ? './' : `${path.basename(targetDir)}/`;
779
- console.log(pc.bold(`\nDry run — no files will be written to ${label}:\n`));
780
- data.files.forEach(f => {
781
- const exists = fs.existsSync(path.resolve(targetDir, f.path));
782
- console.log(` ${exists ? pc.yellow('overwrite') : pc.green('+ create')} ${f.path}`);
783
- });
784
- return;
785
- }
786
-
787
- const pm = detectPackageManager(options.overlay ? process.cwd() : targetDir);
788
- // Fresh-directory scaffolds legitimately ship package.json/next.config/
789
- // .gitignore; overlay installs into an existing project stay strict.
790
- const fileCount = writeFiles(targetDir, data.files, { scaffold: !options.overlay });
791
- const label = options.overlay ? './' : `${path.basename(targetDir)}/`;
792
-
793
- spinner.succeed(`Scaffolded workflow ${pc.cyan(data.name || slug)} in ${label}`);
794
- console.log(pc.gray(` ${fileCount} files written`));
795
-
796
- if (!options.overlay) {
797
- console.log();
798
- const install = await askConfirm({ message: `Install dependencies with ${pm}?`, initialValue: true });
799
- if (install) {
800
- const s = ora(`Installing with ${pm}...`).start();
801
- const result = await runInstall(pm, targetDir);
802
- if (result.success) s.succeed('Dependencies installed');
803
- else { s.fail(result.error); if (result.hint) console.log(pc.gray(` ${result.hint}`)); }
804
- }
805
- }
806
-
807
- console.log();
808
- if (!options.overlay) console.log(pc.white(` cd ${path.basename(targetDir)}`));
809
- console.log(pc.white(` ${getRunCommand(pm, 'dev')}`));
810
-
811
- if (data.dependencies?.env?.length) {
812
- console.log();
813
- p.log.warn('Set up your environment variables:');
814
- data.dependencies.env.forEach(v => console.log(pc.gray(` ${v}=`)));
815
- }
816
-
817
- if (data.post_install) { console.log(); console.log(pc.gray(data.post_install)); }
818
- return true;
819
-
820
- } catch (err) {
821
- spinner.fail('Failed to add workflow.');
822
- handleAddError(err, slug, framework);
823
- }
824
- }
825
-
826
- function handleAddError(err, slug, framework) {
827
- if (err.code === 'AUTH_REQUIRED') {
828
- if (!getApiKey() && !getAuth().token) {
829
- // no key at all: say what the component is and the three ways to give one
830
- p.log.warn(`${pc.cyan(slug)} is a premium component: it needs your AstralKit API key.`);
831
- console.log(pc.gray(' Sign in once: ') + pc.cyan('astralkit login'));
832
- console.log(pc.gray(' Or save a key: ') + pc.cyan('astralkit init --api-key <key>'));
833
- console.log(pc.gray(' Or for this run: set the ASTRALKIT_API_KEY environment variable'));
834
- console.log(pc.gray(' Your key is at ') + pc.cyan('https://astralkit.com/account') + pc.gray('. The free components install without one: ') + pc.cyan('astralkit list --free'));
835
- } else {
836
- p.log.warn(err.message);
837
- }
838
- } else if (err.code === 'PRO_REQUIRED') {
839
- p.log.warn(`${FRAMEWORK_LABELS[framework] || framework} version requires a Pro subscription.`);
840
- console.log(pc.gray(' Upgrade at ') + pc.cyan('https://astralkit.com/pricing'));
841
- } else {
842
- try {
843
- const body = JSON.parse(err.message.replace(/^API error \d+: /, ''));
844
- if (body.supported_frameworks) {
845
- p.log.warn(`No ${framework} version available for "${slug}".`);
846
- console.log(pc.gray(`Available: ${body.supported_frameworks.map(f => FRAMEWORK_LABELS[f] || f).join(', ')}`));
847
- exit(1);
848
- }
849
- } catch { /* not json */ }
850
- console.error(pc.red(err.message));
851
- }
852
- exit(1);
853
- }
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, getBooster, getWorkflow, getWebsite, listComponents, listBoosters, listWorkflows, LOCAL_REGISTRY_DIR } from '../lib/api.js';
6
+ import {
7
+ detectFramework,
8
+ detectTypeScript,
9
+ isAstralkitInstalled,
10
+ findCssEntryFile,
11
+ getMissingCssImports,
12
+ } from '../lib/config.js';
13
+ import { validateSlug, validateFramework, isSafePath, writeFiles, isSafeInstallDir, filterSafePackages, sanitizeForTerminal } from '../lib/validators.js';
14
+ import { detectPackageManager, getRunCommand, runInstall } from '../lib/pkg-manager.js';
15
+ import { saveApiKey, getApiKey, getAuth } from '../lib/auth.js';
16
+ import { applyMerges } from '../lib/merges.js';
17
+ import { ensureComponentStylesheets } from '../lib/stylesheets.js';
18
+ import { setAssumeYes, confirm as askConfirm, select as askSelect, text as askText } from '../lib/ask.js';
19
+ import { planPages, pageSource, pointLinksAtRoutes, composeHtml, relativeImport } from '../lib/website.js';
20
+
21
+ const FRAMEWORK_LABELS = { nextjs: 'Next.js', react: 'React' };
22
+
23
+ // `astralkit add a b c` installs each name in turn. One name failing must not stop the rest, so inside a
24
+ // batch an exit becomes a throw that the loop catches; a single name exits as it always did.
25
+ class ExitSignal extends Error {
26
+ constructor(code) { super('exit'); this.code = code; }
27
+ }
28
+ let inBatch = false;
29
+ // Why the last install stopped (AUTH_REQUIRED, PRO_REQUIRED, ...): a website install reads it, so that a missing
30
+ // key is said once, not once for every section.
31
+ let lastFailure = null;
32
+ function exit(code) {
33
+ if (inBatch) throw new ExitSignal(code);
34
+ process.exit(code);
35
+ }
36
+
37
+ export async function addCommand(names, options) {
38
+ const list = [...new Set([].concat(names).filter(Boolean))];
39
+ if (list.length <= 1) return addOne(list[0], options);
40
+
41
+ const installed = [];
42
+ const notInstalled = [];
43
+ inBatch = true;
44
+ try {
45
+ for (const [index, name] of list.entries()) {
46
+ console.log();
47
+ p.log.step(`${pc.cyan(name)} (${index + 1} of ${list.length})`);
48
+ let done = false;
49
+ try {
50
+ done = (await addOne(name, options)) === true;
51
+ } catch (err) {
52
+ if (!(err instanceof ExitSignal)) throw err;
53
+ }
54
+ (done ? installed : notInstalled).push(name);
55
+ }
56
+ } finally {
57
+ inBatch = false;
58
+ }
59
+
60
+ console.log();
61
+ if (installed.length) p.log.success(`Installed ${installed.length} of ${list.length}: ${installed.join(', ')}`);
62
+ if (notInstalled.length) {
63
+ p.log.warn(`Not installed: ${notInstalled.join(', ')} (the reason for each is printed above)`);
64
+ process.exit(1);
65
+ }
66
+ }
67
+
68
+ async function addOne(nameOrSlug, options) {
69
+ setAssumeYes(options.yes);
70
+ if (options.apiKey) {
71
+ if (!options.apiKey.startsWith('ak_')) {
72
+ console.log(pc.red('Invalid API key format. Keys start with ak_'));
73
+ exit(1);
74
+ }
75
+ saveApiKey(options.apiKey);
76
+ }
77
+
78
+ // A component needs no key to be asked for (2026-11-30): the free components install for everyone, and the
79
+ // registry itself says when one is premium (handleAddError then tells how to sign in). The CLI used to stop here
80
+ // with "No API key found" before asking, so nobody without a key could install even the free set.
81
+ // Boosters and workflows are for paid plans: they still need a key, unless read from a local registry
82
+ // (the developer's own disk, no account needed).
83
+ const localBoosterInstall = LOCAL_REGISTRY_DIR && (options.booster || options.workflow);
84
+ if ((options.booster || options.workflow) && !getApiKey() && !localBoosterInstall) {
85
+ const auth = getAuth();
86
+ if (!auth.token) {
87
+ p.log.warn('No API key found. Run ' + pc.cyan('astralkit init --api-key <key>') + ' first.');
88
+ console.log(pc.gray('Get yours at ') + pc.cyan('https://astralkit.com/account'));
89
+ exit(1);
90
+ }
91
+ }
92
+
93
+ // If explicit type flag provided, skip smart detection
94
+ if (options.booster) return addBooster(nameOrSlug, options);
95
+ if (options.workflow) return addWorkflow(nameOrSlug, options);
96
+ if (options.website) return addWebsite(nameOrSlug, options);
97
+
98
+ // ─── Smart detection: search all registries for the slug ───
99
+ const ora = (await import('ora')).default;
100
+ const spinner = ora('Searching registries...').start();
101
+
102
+ try {
103
+ // Search all three registries in parallel
104
+ const [components, boosters, workflows] = await Promise.allSettled([
105
+ listComponents({ search: nameOrSlug }).catch(() => ({ data: [] })),
106
+ listBoosters({ search: nameOrSlug }).catch(() => ({ data: [] })),
107
+ listWorkflows({ search: nameOrSlug }).catch(() => ({ data: [] })),
108
+ ]);
109
+
110
+ const compMatch = (components.status === 'fulfilled' ? (components.value?.components || components.value?.data || []) : [])
111
+ ?.find(c => c.slug === nameOrSlug);
112
+ const boosterMatch = (boosters.status === 'fulfilled' ? (boosters.value?.boosters || boosters.value?.data || []) : [])
113
+ ?.find(b => b.slug === nameOrSlug);
114
+ const workflowMatch = (workflows.status === 'fulfilled' ? (workflows.value?.workflows || workflows.value?.data || []) : [])
115
+ ?.find(w => w.slug === nameOrSlug);
116
+
117
+ const matches = [];
118
+ if (compMatch) matches.push({ type: 'component', name: compMatch.name || nameOrSlug, slug: nameOrSlug });
119
+ if (boosterMatch) matches.push({ type: 'booster', name: boosterMatch.name || nameOrSlug, slug: nameOrSlug });
120
+ if (workflowMatch) matches.push({ type: 'workflow', name: workflowMatch.name || nameOrSlug, slug: nameOrSlug });
121
+
122
+ spinner.stop();
123
+
124
+ if (matches.length === 0) {
125
+ // Not a component, a booster or a workflow: it may be a whole website template (zest, luma).
126
+ const site = await getWebsite(nameOrSlug).catch(() => null);
127
+ if (site) {
128
+ p.log.step(`Found ${pc.cyan(site.name)} as a ${pc.bold('website')}`);
129
+ return addWebsite(nameOrSlug, options, site);
130
+ }
131
+
132
+ // No exact match — try fuzzy suggestions
133
+ const allItems = [
134
+ ...((components.status === 'fulfilled' ? (components.value?.components || components.value?.data || []) : []) || []).map(c => ({ ...c, type: 'component' })),
135
+ ...((boosters.status === 'fulfilled' ? (boosters.value?.boosters || boosters.value?.data || []) : []) || []).map(b => ({ ...b, type: 'booster' })),
136
+ ...((workflows.status === 'fulfilled' ? (workflows.value?.workflows || workflows.value?.data || []) : []) || []).map(w => ({ ...w, type: 'workflow' })),
137
+ ];
138
+
139
+ const similar = allItems
140
+ .filter(item => item.slug && (
141
+ item.slug.includes(nameOrSlug) ||
142
+ nameOrSlug.includes(item.slug) ||
143
+ item.name?.toLowerCase().includes(nameOrSlug.toLowerCase())
144
+ ))
145
+ .slice(0, 5);
146
+
147
+ if (similar.length > 0) {
148
+ p.log.warn(`"${nameOrSlug}" not found.`);
149
+ console.log();
150
+ console.log(pc.gray(' Did you mean:'));
151
+ for (const s of similar) {
152
+ console.log(` ${pc.cyan(s.slug)} ${pc.gray(`(${s.type})`)}`);
153
+ }
154
+ console.log();
155
+ } else {
156
+ p.log.error(`"${nameOrSlug}" not found in any registry.`);
157
+ p.log.info('Run ' + pc.cyan('astralkit search "' + nameOrSlug + '"') + ' to browse available content.');
158
+ }
159
+ // nothing was installed: a script or an agent must be able to tell (the exit code was 0)
160
+ process.exitCode = 1;
161
+ return;
162
+ }
163
+
164
+ if (matches.length === 1) {
165
+ // Exact match in one registry — install directly
166
+ const match = matches[0];
167
+ p.log.step(`Found ${pc.cyan(match.name)} as a ${pc.bold(match.type)}`);
168
+
169
+ if (match.type === 'booster') return addBooster(nameOrSlug, options);
170
+ if (match.type === 'workflow') return addWorkflow(nameOrSlug, options);
171
+ return addComponent(nameOrSlug, options);
172
+ }
173
+
174
+ // Found in multiple registries — prompt user to choose (non-interactive:
175
+ // prefer the component, the most common install target).
176
+ const componentMatch = matches.find(m => m.type === 'component');
177
+ const choice = await askSelect({
178
+ message: `"${nameOrSlug}" found in multiple registries. What would you like to install?`,
179
+ options: matches.map(m => ({
180
+ value: m.type,
181
+ label: `${m.name} (${m.type === 'component' ? 'UI component' : m.type === 'booster' ? 'feature module' : 'app scaffold'})`,
182
+ })),
183
+ nonInteractive: componentMatch ? 'component' : matches[0].type,
184
+ });
185
+
186
+ if (p.isCancel(choice)) { p.cancel('Cancelled.'); exit(0); }
187
+
188
+ if (choice === 'booster') return addBooster(nameOrSlug, options);
189
+ if (choice === 'workflow') return addWorkflow(nameOrSlug, options);
190
+ return addComponent(nameOrSlug, options);
191
+
192
+ } catch (err) {
193
+ spinner.stop();
194
+ // If registry search fails, fall back to component (original behavior)
195
+ return addComponent(nameOrSlug, options);
196
+ }
197
+ }
198
+
199
+ function resolveFramework(options) {
200
+ if (options.framework) {
201
+ if (!validateFramework(options.framework)) exit(1);
202
+ return options.framework;
203
+ }
204
+ const detected = detectFramework();
205
+ if (detected === 'nextjs' || detected === 'react') return detected;
206
+ return 'react';
207
+ }
208
+
209
+ function resolveExtension(framework) {
210
+ const isTS = detectTypeScript();
211
+ if (framework === 'nextjs') return '.tsx';
212
+ return isTS ? '.tsx' : '.jsx';
213
+ }
214
+
215
+ // Read the target project's package.json. Used to detect package conflicts
216
+ // (e.g. host already uses @phosphor-icons/react and we're about to add the
217
+ // separate @phosphor-icons/web). Returns null if the file is unreadable.
218
+ function readHostPackageJson() {
219
+ try {
220
+ const raw = fs.readFileSync(path.join(process.cwd(), 'package.json'), 'utf8');
221
+ return JSON.parse(raw);
222
+ } catch {
223
+ return null;
224
+ }
225
+ }
226
+
227
+ function hostHasDep(pkg, name) {
228
+ if (!pkg) return false;
229
+ return Boolean(
230
+ pkg.dependencies?.[name] ||
231
+ pkg.devDependencies?.[name] ||
232
+ pkg.optionalDependencies?.[name]
233
+ );
234
+ }
235
+
236
+ async function addComponent(componentSlug, options) {
237
+ if (!validateSlug(componentSlug)) exit(1);
238
+ if (!fs.existsSync(path.join(process.cwd(), 'package.json'))) {
239
+ p.log.warn('No package.json found. Run this inside a project directory.');
240
+ return;
241
+ }
242
+
243
+ // Tracked across the full install so the end-of-run summary can tell the
244
+ // user exactly what changed in their project (created files, modified
245
+ // files, installed deps, anything skipped by user confirmation).
246
+ const installSummary = {
247
+ created: [], // relative file paths written
248
+ modified: [], // { path, note }
249
+ installed: [], // dep names
250
+ alreadySatisfied: [], // dep names
251
+ skipped: [], // { what, reason }
252
+ };
253
+
254
+ const ora = (await import('ora')).default;
255
+ const framework = resolveFramework(options);
256
+ const ext = resolveExtension(framework);
257
+ const componentsDir = options.dir || 'src/components/ui';
258
+ // Refuse absolute / traversal values of --dir.
259
+ if (!isSafeInstallDir(process.cwd(), componentsDir)) {
260
+ console.log(pc.red(`Refusing install: unsafe --dir value "${componentsDir}"`));
261
+ exit(1);
262
+ }
263
+ const targetFile = path.resolve(process.cwd(), componentsDir, `${componentSlug}${ext}`);
264
+
265
+ if (fs.existsSync(targetFile) && !options.overwrite) {
266
+ p.log.warn(`Already exists: ${componentsDir}/${componentSlug}${ext}`);
267
+ console.log(pc.gray('Use --overwrite to replace.'));
268
+ return;
269
+ }
270
+
271
+ const spinner = ora(`Fetching ${pc.cyan(componentSlug)} (${FRAMEWORK_LABELS[framework]})...`).start();
272
+
273
+ try {
274
+ const data = await getComponent(componentSlug, framework, {
275
+ onWait: (seconds) => { spinner.text = `The registry asks for a pause: waiting ${seconds} seconds, then fetching ${pc.cyan(componentSlug)}...`; },
276
+ });
277
+
278
+ if (!data.files?.length) {
279
+ spinner.fail(`No ${framework} code available for "${componentSlug}".`);
280
+ if (data.supported_frameworks?.length) {
281
+ console.log(pc.gray(`Available: ${data.supported_frameworks.map(f => FRAMEWORK_LABELS[f] || f).join(', ')}`));
282
+ }
283
+ return;
284
+ }
285
+
286
+ if (options.dryRun) {
287
+ spinner.stop();
288
+ console.log(pc.bold('\nDry run — no files will be written:\n'));
289
+ for (const file of data.files) {
290
+ const exists = fs.existsSync(path.resolve(process.cwd(), componentsDir, file.path));
291
+ console.log(` ${exists ? pc.yellow('overwrite') : pc.green('+ create')} ${componentsDir}/${file.path}`);
292
+ }
293
+ return;
294
+ }
295
+
296
+ const dir = path.resolve(process.cwd(), componentsDir);
297
+ fs.mkdirSync(dir, { recursive: true });
298
+
299
+ // Filter out supplementary files that aren't needed for React/Next.js
300
+ // (styles.css and script.js are for HTML standalone components only)
301
+ const filesToWrite = framework === 'html'
302
+ ? data.files
303
+ : data.files.filter(f => f.path !== 'styles.css' && f.path !== 'script.js');
304
+
305
+ for (const file of filesToWrite) {
306
+ if (!isSafePath(dir, file.path)) {
307
+ console.log(pc.red(` Skipping suspicious path: ${file.path}`));
308
+ installSummary.skipped.push({ what: file.path, reason: 'unsafe path' });
309
+ continue;
310
+ }
311
+ const filePath = path.resolve(dir, file.path);
312
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
313
+ fs.writeFileSync(filePath, file.encoding === 'base64' ? Buffer.from(file.content, 'base64') : file.content);
314
+ installSummary.created.push(path.join(componentsDir, file.path).replace(/\\/g, '/'));
315
+ }
316
+
317
+ spinner.succeed(`Added ${pc.cyan(data.name || componentSlug)} (${FRAMEWORK_LABELS[framework]})`);
318
+
319
+ // (a website install says these once, at its end, not once for every section)
320
+ if (!options.collectInto) printSetupHints();
321
+
322
+ // Detect if component uses Phosphor Icons (CSS class-based icons)
323
+ const componentCode = data.files?.map(f => f.content).join('') || '';
324
+
325
+ // The stylesheets the component asks for (a template section's palette and typefaces, a date picker's dialog)
326
+ // go into the project's stylesheet. An HTML file loads its own from the CDN.
327
+ // (a website install does it once, for all its sections together)
328
+ if (framework !== 'html') {
329
+ if (options.collectInto) options.collectInto.code.push(...filesToWrite.map(f => f.content));
330
+ else await ensureComponentStylesheets(filesToWrite.map(f => f.content).join('\n'), installSummary);
331
+ }
332
+ let usesPhosphorCss = componentCode.includes('class="ph ') || componentCode.includes("class='ph ") || componentCode.includes('"ph ph-') || componentCode.includes("'ph ph-");
333
+
334
+ // Phosphor conflict guard: @phosphor-icons/web and @phosphor-icons/react
335
+ // are SEPARATE packages (CSS classes vs React components). Installing both
336
+ // ships two icon systems in the same codebase — bundle bloat and a
337
+ // long-term consistency tax. If the host already uses the React package,
338
+ // warn loudly and let the user opt out of auto-installing web.
339
+ if (usesPhosphorCss) {
340
+ const hostPkg = readHostPackageJson();
341
+ // (a website install asks once: every section after the first takes the same answer, without the warning)
342
+ const shared = options.collectInto;
343
+ if (shared && shared.phosphorWeb !== undefined) {
344
+ usesPhosphorCss = shared.phosphorWeb;
345
+ } else if (hostHasDep(hostPkg, '@phosphor-icons/react')) {
346
+ p.log.warn(`This component uses ${pc.cyan('@phosphor-icons/web')} (CSS class-based icons).`);
347
+ p.log.warn(`Your project already uses ${pc.cyan('@phosphor-icons/react')} (React components) — a ${pc.bold('separate package')} from the same vendor.`);
348
+ p.log.warn(`Installing both ships two icon systems side by side.`);
349
+
350
+ // Non-interactive default is YES: the component file is already written
351
+ // with `ph ph-*` classes — skipping the package ships broken icons,
352
+ // which is worse than the two-icon-systems consistency tax.
353
+ const proceed = await askConfirm({
354
+ message: 'Install @phosphor-icons/web anyway?',
355
+ initialValue: false,
356
+ nonInteractive: true,
357
+ });
358
+ if (!proceed) {
359
+ p.log.info('Skipping @phosphor-icons/web and the layout.tsx import.');
360
+ p.log.info(pc.gray('Adapt the component\'s <i className="ph ph-*"> tags to @phosphor-icons/react React components.'));
361
+ usesPhosphorCss = false;
362
+ installSummary.skipped.push({
363
+ what: '@phosphor-icons/web',
364
+ reason: 'host project uses @phosphor-icons/react; user declined',
365
+ });
366
+ }
367
+ if (shared) shared.phosphorWeb = usesPhosphorCss;
368
+ }
369
+ }
370
+
371
+ // The registry's `dependencies` metadata can lag behind the code (found
372
+ // live: kanban-01 imports three @dnd-kit packages, metadata listed one).
373
+ // Scan the actual source for bare package imports so a metadata gap never
374
+ // ships a component that doesn't build.
375
+ const importedPackages = new Set();
376
+ const jsCode = (data.files || [])
377
+ .filter(f => /\.(tsx?|jsx?|mjs|cjs)$/.test(f.path))
378
+ .map(f => f.content).join('\n');
379
+ for (const m of jsCode.matchAll(/(?:from|import)\s*\(?\s*['"]((?:@[a-z0-9~][\w.~-]*\/)?[a-z0-9~][\w.~-]*)(?:\/[^'"]*)?['"]/g)) {
380
+ importedPackages.add(m[1]);
381
+ }
382
+ // Packages the host/framework already accounts for.
383
+ for (const skip of ['react', 'react-dom', 'next', 'astralkit', 'clsx', 'tailwind-merge']) {
384
+ importedPackages.delete(skip);
385
+ }
386
+
387
+ if (data.dependencies?.length || usesPhosphorCss || importedPackages.size > 0) {
388
+ const pm = detectPackageManager();
389
+ const rawDepList = (data.dependencies || []).filter(d => d !== 'astralkit' && d !== 'clsx' && d !== 'tailwind-merge');
390
+
391
+ for (const pkg of importedPackages) {
392
+ if (!rawDepList.includes(pkg)) rawDepList.push(pkg);
393
+ }
394
+
395
+ // Auto-add @phosphor-icons/web if component uses CSS-based Phosphor icons
396
+ // AND we didn't skip it above due to a @phosphor-icons/react conflict.
397
+ if (usesPhosphorCss && !rawDepList.includes('@phosphor-icons/web')) {
398
+ rawDepList.push('@phosphor-icons/web');
399
+ }
400
+
401
+ // SECURITY: validate package names before passing to npm install — a
402
+ // malicious server response could inject "-S", "--registry=evil.com",
403
+ // "git+ssh://...", or a tarball URL. We only accept bare npm names.
404
+ const { accepted: depList, rejected } = filterSafePackages(rawDepList);
405
+ if (rejected.length > 0) {
406
+ console.log(pc.yellow(` Skipping invalid package names: ${rejected.map(sanitizeForTerminal).join(', ')}`));
407
+ }
408
+
409
+ if (depList.length > 0) {
410
+ // Split into already-present vs to-install so the user sees both in
411
+ // the end-of-install summary.
412
+ const hostPkg = readHostPackageJson();
413
+ const toInstall = depList.filter(d => !hostHasDep(hostPkg, d));
414
+ const alreadyThere = depList.filter(d => hostHasDep(hostPkg, d));
415
+ for (const d of alreadyThere) installSummary.alreadySatisfied.push(d);
416
+
417
+ if (toInstall.length > 0) {
418
+ // Always ask before running npm install — mirrors the booster flow.
419
+ // (Non-interactive: yes — a component without its deps doesn't build.)
420
+ const install = await askConfirm({
421
+ message: `Install dependencies? (${toInstall.join(', ')})`,
422
+ initialValue: true,
423
+ });
424
+ if (install) {
425
+ const s = ora(`Installing ${toInstall.join(', ')}...`).start();
426
+ const result = await runInstall(pm, process.cwd(), toInstall);
427
+ if (result.success) {
428
+ s.succeed(`Installed ${toInstall.join(', ')}`);
429
+ for (const d of toInstall) installSummary.installed.push(d);
430
+ } else {
431
+ s.fail(sanitizeForTerminal(result.error || 'Install failed'));
432
+ if (result.hint) console.log(pc.gray(` ${sanitizeForTerminal(result.hint)}`));
433
+ for (const d of toInstall) {
434
+ installSummary.skipped.push({ what: d, reason: 'install failed' });
435
+ }
436
+ }
437
+ } else {
438
+ for (const d of toInstall) {
439
+ installSummary.skipped.push({ what: d, reason: 'user declined install' });
440
+ }
441
+ }
442
+ }
443
+ }
444
+
445
+ // Auto-add JS imports for icon/font packages in layout file
446
+ // (CSS @import doesn't resolve node_modules exports in Next.js PostCSS).
447
+ // This modifies a user-owned file — one of the most critical in a
448
+ // Next.js app — so we now show the exact diff and prompt for consent
449
+ // with a default of NO. Silent modification of layout.tsx was a
450
+ // reported trust issue (CLI feedback 2026-04-22).
451
+ const JS_DEPENDENCY_IMPORTS = {
452
+ '@phosphor-icons/web': [
453
+ "import '@phosphor-icons/web/regular'",
454
+ "import '@phosphor-icons/web/fill'",
455
+ ],
456
+ };
457
+
458
+ // Only consider packages we actually installed (or that were already
459
+ // present) — no point prompting about imports for a dep the user skipped.
460
+ const effectiveDeps = new Set([
461
+ ...installSummary.installed,
462
+ ...installSummary.alreadySatisfied,
463
+ ]);
464
+ for (const [pkg, imports] of Object.entries(JS_DEPENDENCY_IMPORTS)) {
465
+ if (!effectiveDeps.has(pkg)) continue;
466
+
467
+ const layoutCandidates = [
468
+ 'src/app/layout.tsx', 'src/app/layout.jsx', 'src/app/layout.js',
469
+ 'app/layout.tsx', 'app/layout.jsx', 'app/layout.js',
470
+ 'src/pages/_app.tsx', 'src/pages/_app.jsx', 'src/pages/_app.js',
471
+ 'pages/_app.tsx', 'pages/_app.jsx', 'pages/_app.js',
472
+ ];
473
+ let layoutFile = null;
474
+ for (const candidate of layoutCandidates) {
475
+ const fullPath = path.join(process.cwd(), candidate);
476
+ if (fs.existsSync(fullPath)) {
477
+ layoutFile = { path: fullPath, relative: candidate };
478
+ break;
479
+ }
480
+ }
481
+ if (!layoutFile) continue;
482
+
483
+ const layoutContent = fs.readFileSync(layoutFile.path, 'utf8');
484
+ const missing = imports.filter(imp => !layoutContent.includes(imp));
485
+ if (missing.length === 0) continue;
486
+
487
+ // Show the exact diff we want to apply — never silently modify.
488
+ p.log.warn(`${pc.cyan(pkg)} needs these side-effect imports in your root layout:`);
489
+ console.log(pc.gray(` ${layoutFile.relative}`));
490
+ for (const imp of missing) console.log(` ${pc.green('+')} ${imp}`);
491
+
492
+ // Non-interactive default is YES: the exact diff is printed above (never
493
+ // silent — the 2026-04-22 trust rule), and skipping it ships a component
494
+ // whose icons don't render.
495
+ const proceed = await askConfirm({
496
+ message: `Add these imports to ${layoutFile.relative}?`,
497
+ initialValue: false,
498
+ nonInteractive: true,
499
+ });
500
+
501
+ if (!proceed) {
502
+ p.log.info(`Skipped ${layoutFile.relative} edit. Add these lines manually to enable icons:`);
503
+ for (const imp of missing) console.log(pc.gray(` ${imp}`));
504
+ installSummary.skipped.push({
505
+ what: `${layoutFile.relative} imports (${pkg})`,
506
+ reason: 'user declined',
507
+ });
508
+ continue;
509
+ }
510
+
511
+ const lines = layoutContent.split('\n');
512
+ let lastImportIdx = -1;
513
+ for (let i = 0; i < lines.length; i++) {
514
+ if (lines[i].trim().startsWith('import ')) lastImportIdx = i;
515
+ }
516
+ if (lastImportIdx >= 0) {
517
+ lines.splice(lastImportIdx + 1, 0, ...missing);
518
+ } else {
519
+ lines.unshift(...missing);
520
+ }
521
+ fs.writeFileSync(layoutFile.path, lines.join('\n'));
522
+ installSummary.modified.push({
523
+ path: layoutFile.relative,
524
+ note: `+${missing.length} ${missing.length === 1 ? 'import' : 'imports'} (${pkg})`,
525
+ });
526
+ p.log.success(`Added ${pc.cyan(pkg)} imports to ${pc.cyan(layoutFile.relative)}`);
527
+ }
528
+ }
529
+
530
+ // a website install prints one summary for all its sections
531
+ if (options.collectInto) mergeSummary(options.collectInto, installSummary);
532
+ else printInstallSummary(installSummary);
533
+ return true;
534
+
535
+ } catch (err) {
536
+ spinner.fail('Failed to add component.');
537
+ handleAddError(err, componentSlug, framework);
538
+ }
539
+ }
540
+
541
+ // What the project still needs before AstralKit components draw as designed.
542
+ function printSetupHints() {
543
+ if (!isAstralkitInstalled()) {
544
+ p.log.warn('Run ' + pc.cyan('astralkit init') + ' to set up design tokens.');
545
+ }
546
+ const cssEntry = findCssEntryFile();
547
+ if (cssEntry) {
548
+ const missing = getMissingCssImports(cssEntry.path);
549
+ if (missing.length > 0) {
550
+ p.log.warn(`Missing CSS imports in ${cssEntry.relative}. Run ${pc.cyan('astralkit init')} to fix.`);
551
+ }
552
+ }
553
+ }
554
+
555
+ function mergeSummary(into, from) {
556
+ for (const key of ['created', 'installed', 'alreadySatisfied']) for (const item of from[key]) if (!into[key].includes(item)) into[key].push(item);
557
+ for (const item of from.modified) if (!into.modified.some(have => have.path === item.path && have.note === item.note)) into.modified.push(item);
558
+ for (const item of from.skipped) if (!into.skipped.some(have => have.what === item.what)) into.skipped.push(item);
559
+ }
560
+
561
+ // End-of-install summary. Prints what the CLI did to the user's project so
562
+ // they never have to run `git diff` just to find out what was touched. Split
563
+ // into Created / Modified / Installed / Skipped so each category is scannable.
564
+ function printInstallSummary(s) {
565
+ const hasAny =
566
+ s.created.length || s.modified.length || s.installed.length ||
567
+ s.alreadySatisfied.length || s.skipped.length;
568
+ if (!hasAny) return;
569
+
570
+ console.log('');
571
+ p.log.step(pc.bold('What changed in your project'));
572
+ if (s.created.length) {
573
+ console.log(pc.green(' Created:'));
574
+ for (const f of s.created) console.log(pc.gray(` ${f}`));
575
+ }
576
+ if (s.modified.length) {
577
+ console.log(pc.yellow(' Modified:'));
578
+ for (const m of s.modified) console.log(pc.gray(` ${m.path} ${pc.dim(m.note)}`));
579
+ }
580
+ if (s.installed.length) {
581
+ console.log(pc.cyan(' Installed:'));
582
+ for (const d of s.installed) console.log(pc.gray(` ${d}`));
583
+ }
584
+ if (s.alreadySatisfied.length) {
585
+ console.log(pc.gray(' Already satisfied:'));
586
+ for (const d of s.alreadySatisfied) console.log(pc.gray(` ${d}`));
587
+ }
588
+ if (s.skipped.length) {
589
+ console.log(pc.gray(' Skipped:'));
590
+ for (const k of s.skipped) console.log(pc.gray(` ${k.what} ${pc.dim(`(${k.reason})`)}`));
591
+ }
592
+ }
593
+
594
+ // A whole website template as one install (2026-12-01): every section as a component, exactly as each installs
595
+ // alone, then one file per page that renders them in page order. `astralkit add zest --website`, or plain
596
+ // `astralkit add zest` when nothing else is called that.
597
+ async function addWebsite(name, options, known) {
598
+ if (!validateSlug(name, 'website name')) exit(1);
599
+ if (!fs.existsSync(path.join(process.cwd(), 'package.json'))) {
600
+ p.log.warn('No package.json found. Run this inside a project directory.');
601
+ return;
602
+ }
603
+ const ora = (await import('ora')).default;
604
+ const framework = resolveFramework(options);
605
+ const ext = resolveExtension(framework);
606
+ const componentsDir = options.dir || 'src/components/ui';
607
+ if (!isSafeInstallDir(process.cwd(), componentsDir)) {
608
+ console.log(pc.red(`Refusing install: unsafe --dir value "${componentsDir}"`));
609
+ exit(1);
610
+ }
611
+
612
+ let site = known;
613
+ if (!site) {
614
+ const spinner = ora(`Looking for the ${pc.cyan(name)} website...`).start();
615
+ try {
616
+ site = await getWebsite(name);
617
+ } catch (err) {
618
+ spinner.fail('Could not ask the registry.');
619
+ console.error(pc.red(err.message));
620
+ exit(1);
621
+ return;
622
+ }
623
+ if (!site) {
624
+ spinner.fail(`There is no website called "${name}".`);
625
+ p.log.info('See every website: ' + pc.cyan('astralkit list --websites'));
626
+ exit(1);
627
+ return;
628
+ }
629
+ spinner.stop();
630
+ }
631
+ // The registry's answer names files and folders: nothing in it may leave the project.
632
+ const safeName = (text) => typeof text === 'string' && /^[a-z0-9]+(-[a-z0-9]+)*$/.test(text);
633
+ const pages = (site.pages || []).filter(page => (page.route === '' || safeName(page.route)) && /^[a-z0-9-]+\.html$/.test(page.file || '') && Array.isArray(page.sections) && page.sections.every(safeName));
634
+ const sections = (site.sections || []).map(section => section.slug).filter(safeName);
635
+ if (!safeName(site.slug) || !sections.length || !pages.length) {
636
+ p.log.error(`The registry's answer for "${name}" cannot be installed.`);
637
+ exit(1);
638
+ return;
639
+ }
640
+ site = { ...site, name: sanitizeForTerminal(site.name || site.slug), pages };
641
+
642
+ const command = `npx @astralkit/cli add ${site.slug} --website`;
643
+ const dir = path.resolve(process.cwd(), componentsDir);
644
+ const plan = planPages({ site, framework, cwd: process.cwd(), componentsDir, ext });
645
+ // a section's file once it is in the project (a React install may be .jsx in a TypeScript project)
646
+ const sectionFile = (slug) => (framework === 'html' ? [`${slug}.html`] : [`${slug}.tsx`, `${slug}.jsx`]).map(file => path.join(dir, file)).find(file => fs.existsSync(file)) || null;
647
+ const label = FRAMEWORK_LABELS[framework] || 'HTML';
648
+ const count = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
649
+
650
+ console.log();
651
+ p.log.step(`${pc.bold(site.name)}: ${count(sections.length, 'section')}, ${count(pages.length, 'page')} (${label})`);
652
+
653
+ if (options.dryRun) {
654
+ console.log(pc.bold('\nDry run, no files will be written:\n'));
655
+ for (const slug of sections) {
656
+ const have = sectionFile(slug);
657
+ const shown = `${componentsDir}/${slug}${framework === 'html' ? '.html' : framework === 'nextjs' ? '.tsx' : '.jsx'}`;
658
+ console.log(` ${have ? (options.overwrite ? pc.yellow('overwrite') : pc.gray('keep ')) : pc.green('+ create')} ${shown}`);
659
+ }
660
+ for (const { file } of plan.pages) {
661
+ const have = fs.existsSync(path.resolve(process.cwd(), file));
662
+ console.log(` ${have ? (options.overwrite ? pc.yellow('overwrite') : pc.gray('keep ')) : pc.green('+ create')} ${file}`);
663
+ }
664
+ return;
665
+ }
666
+
667
+ // 1. every section, as a component
668
+ const summary = { created: [], modified: [], installed: [], alreadySatisfied: [], skipped: [], code: [] };
669
+ const present = new Set();
670
+ const fresh = [];
671
+ const kept = [];
672
+ const failed = [];
673
+ let stopped = null;
674
+ const wasInBatch = inBatch;
675
+ inBatch = true;
676
+ try {
677
+ for (const slug of sections) {
678
+ if (!options.overwrite && sectionFile(slug)) { present.add(slug); kept.push(slug); continue; }
679
+ lastFailure = null;
680
+ let done = false;
681
+ try {
682
+ done = (await addComponent(slug, { ...options, collectInto: summary })) === true;
683
+ } catch (err) {
684
+ if (!(err instanceof ExitSignal)) throw err;
685
+ }
686
+ if (done) { present.add(slug); fresh.push(slug); continue; }
687
+ failed.push(slug);
688
+ // no key, a plan without premium components, or no way to the registry: every other section would say the same
689
+ if (['AUTH_REQUIRED', 'PRO_REQUIRED', 'TIMEOUT', 'NETWORK_ERROR'].includes(lastFailure)) { stopped = lastFailure; break; }
690
+ }
691
+ } finally {
692
+ inBatch = wasInBatch;
693
+ }
694
+ if (stopped) {
695
+ const offline = stopped === 'TIMEOUT' || stopped === 'NETWORK_ERROR';
696
+ console.log();
697
+ p.log.warn(offline ? `The registry could not be reached, so ${pc.bold(site.name)} was not finished.` : `${pc.bold(site.name)} is a premium website: its sections come with Pro and Lifetime.`);
698
+ console.log(pc.gray(` ${fresh.length ? `${count(fresh.length, 'section')} installed before it stopped (they are kept). ` : 'Nothing was installed. '}${offline ? 'Run the same command again in a moment:' : 'Sign in or upgrade, then run the same command again:'}`));
699
+ console.log(` ${pc.cyan(command)}`);
700
+ exit(1);
701
+ return;
702
+ }
703
+
704
+ // the stylesheets the sections ask for (the template's palette and typefaces), once
705
+ if (framework !== 'html' && summary.code.length) await ensureComponentStylesheets(summary.code.join('\n'), summary);
706
+
707
+ // 2. in an app with real routes, the links between the template's pages point at those routes
708
+ if (plan.kind === 'routes' && pages.length > 1) {
709
+ for (const slug of fresh) {
710
+ const file = sectionFile(slug);
711
+ if (!file) continue;
712
+ const pointed = pointLinksAtRoutes(fs.readFileSync(file, 'utf8'), site, plan.base);
713
+ if (!pointed.changed) continue;
714
+ fs.writeFileSync(file, pointed.code);
715
+ summary.modified.push({ path: path.relative(process.cwd(), file).replace(/\\/g, '/'), note: `${count(pointed.changed, 'link')} pointed at ${plan.base}` });
716
+ }
717
+ }
718
+
719
+ // 3. the pages
720
+ const written = [];
721
+ for (const { page, file } of plan.pages) {
722
+ const own = page.sections.filter(slug => present.has(slug));
723
+ const target = path.resolve(process.cwd(), file);
724
+ if (!own.length) { summary.skipped.push({ what: file, reason: 'none of its sections were installed' }); continue; }
725
+ if (fs.existsSync(target) && !options.overwrite) { summary.skipped.push({ what: file, reason: 'already exists, use --overwrite to replace it' }); continue; }
726
+ const content = plan.kind === 'html'
727
+ ? composeHtml({ site, page, documents: own.map(slug => fs.readFileSync(sectionFile(slug), 'utf8')) })
728
+ : pageSource({ site, page, sections: own, command, importFrom: (slug) => relativeImport(target, path.join(dir, slug)) });
729
+ fs.mkdirSync(path.dirname(target), { recursive: true });
730
+ fs.writeFileSync(target, content);
731
+ summary.created.push(file);
732
+ written.push({ page, file });
733
+ }
734
+
735
+ // 4. what happened, once
736
+ console.log();
737
+ if (failed.length) p.log.warn(`${site.name}: ${count(present.size, 'section')} of ${sections.length} are in your project. Not installed: ${failed.join(', ')} (the reason for each is printed above)`);
738
+ else if (!fresh.length && !written.length) p.log.success(`${pc.bold(site.name)} is already in your project: nothing to add. Use ${pc.cyan('--overwrite')} to install it again.`);
739
+ else p.log.success(`${pc.bold(site.name)} is in your project: ${count(present.size, 'section')}${written.length ? `, ${count(written.length, 'page')}` : ''}`);
740
+ if (kept.length) console.log(pc.gray(` Already there, left as they are: ${kept.join(', ')}`));
741
+ if (framework !== 'html') printSetupHints();
742
+ printInstallSummary(summary);
743
+
744
+ const home = written.find(item => !item.page.route) || written[0];
745
+ if (home) {
746
+ console.log();
747
+ p.log.step(pc.bold('Next'));
748
+ if (plan.kind === 'routes') console.log(` Start your app and open ${pc.cyan(plan.base)}. To make it your home page, move ${pc.cyan(home.file)} to ${pc.cyan(home.file.replace(`/${site.slug}/page`, '/page'))}.`);
749
+ else if (plan.kind === 'html') console.log(` Open ${pc.cyan(home.file)} in a browser.`);
750
+ else console.log(` Render the page from ${pc.cyan(home.file)} where your app shows its home page.`);
751
+ if (pages.length > 1 && plan.kind === 'components') console.log(pc.gray(' Its pages link to each other by file name (about.html): point those links at your own routes.'));
752
+ console.log(pc.gray(` The business in it${site.sample_business ? ` (${sanitizeForTerminal(site.sample_business)})` : ''} is sample content: keep each section's layout, and change the name, the copy and the photos.`));
753
+ }
754
+ if (failed.length) { exit(1); return; }
755
+ return true;
756
+ }
757
+
758
+ async function addBooster(slug, options) {
759
+ if (!validateSlug(slug, 'booster name')) exit(1);
760
+
761
+ const ora = (await import('ora')).default;
762
+ const framework = resolveFramework(options);
763
+ const pm = detectPackageManager();
764
+ const spinner = ora(`Fetching booster ${pc.cyan(slug)} (${FRAMEWORK_LABELS[framework] || framework})...`).start();
765
+
766
+ try {
767
+ const data = await getBooster(slug, framework);
768
+ const coreFiles = data.core_files || [];
769
+ const adapterFiles = data.adapter_files || [];
770
+
771
+ if (coreFiles.length === 0 && adapterFiles.length === 0) {
772
+ spinner.fail(`No files available for booster "${slug}" (${framework}).`);
773
+ return;
774
+ }
775
+
776
+ // SECURITY: Server-supplied install_paths must stay inside cwd. Otherwise
777
+ // a compromised API could write to /etc, ~/.ssh, %APPDATA%, etc.
778
+ // options.dir comes from the user's own CLI invocation, so it's trusted.
779
+ const serverCore = data.install_paths?.core;
780
+ const serverAdapter = data.install_paths?.adapter;
781
+ if (serverCore && !isSafeInstallDir(process.cwd(), serverCore)) {
782
+ spinner.fail(pc.red(`Refusing install: server returned unsafe core path "${serverCore}"`));
783
+ return;
784
+ }
785
+ if (serverAdapter && !isSafeInstallDir(process.cwd(), serverAdapter)) {
786
+ spinner.fail(pc.red(`Refusing install: server returned unsafe adapter path "${serverAdapter}"`));
787
+ return;
788
+ }
789
+ const corePath = options.dir || serverCore || `src/lib/${slug}`;
790
+ const adapterPath = serverAdapter || `src/components/${slug}`;
791
+ // Final defense: even if options.dir came from the user, reject absolute/traversal
792
+ // values so --dir "/" or --dir "../.." can't be weaponized.
793
+ if (!isSafeInstallDir(process.cwd(), corePath) || !isSafeInstallDir(process.cwd(), adapterPath)) {
794
+ spinner.fail(pc.red(`Refusing install: unsafe install path`));
795
+ return;
796
+ }
797
+ const coreDir = path.resolve(process.cwd(), corePath);
798
+ const adapterDir = path.resolve(process.cwd(), adapterPath);
799
+
800
+ if (options.dryRun) {
801
+ spinner.stop();
802
+ console.log(pc.bold('\nDry run — no files will be written:\n'));
803
+ if (coreFiles.length > 0) {
804
+ console.log(pc.gray(` Core: ${corePath}/`));
805
+ for (const f of coreFiles) {
806
+ const exists = fs.existsSync(path.resolve(coreDir, f.path));
807
+ console.log(` ${exists ? pc.yellow('overwrite') : pc.green('+ create')} ${f.path}`);
808
+ }
809
+ }
810
+ if (adapterFiles.length > 0) {
811
+ console.log(pc.gray(` Adapter: ${adapterPath}/`));
812
+ for (const f of adapterFiles) {
813
+ const exists = fs.existsSync(path.resolve(adapterDir, f.path));
814
+ console.log(` ${exists ? pc.yellow('overwrite') : pc.green('+ create')} ${f.path}`);
815
+ }
816
+ }
817
+ return;
818
+ }
819
+
820
+ if (!options.overwrite) {
821
+ const conflicts = [
822
+ ...coreFiles.filter(f => fs.existsSync(path.resolve(coreDir, f.path))).map(f => `${corePath}/${f.path}`),
823
+ ...adapterFiles.filter(f => fs.existsSync(path.resolve(adapterDir, f.path))).map(f => `${adapterPath}/${f.path}`),
824
+ ];
825
+ if (conflicts.length > 0) {
826
+ spinner.stop();
827
+ console.log(pc.yellow('\nThese files already exist:'));
828
+ conflicts.forEach(c => console.log(pc.gray(` ${c}`)));
829
+ // Overwrite stays fail-safe when non-interactive WITHOUT --yes/env:
830
+ // destroying user files needs explicit consent (--overwrite, --yes, or a TTY answer).
831
+ const overwrite = process.env.ASTRALKIT_YES === '1'
832
+ ? true
833
+ : await askConfirm({ message: 'Overwrite existing files?', initialValue: false });
834
+ if (!overwrite) return;
835
+ }
836
+ }
837
+
838
+ writeFiles(coreDir, coreFiles);
839
+ writeFiles(adapterDir, adapterFiles);
840
+
841
+ spinner.succeed(`Added booster ${pc.cyan(data.name || slug)} (${FRAMEWORK_LABELS[framework] || framework})`);
842
+
843
+ if (coreFiles.length > 0) {
844
+ console.log(pc.gray(` Core: ${corePath}/`));
845
+ coreFiles.forEach(f => console.log(pc.gray(` ${f.path}`)));
846
+ }
847
+ if (adapterFiles.length > 0) {
848
+ console.log(pc.gray(` Adapter: ${adapterPath}/`));
849
+ adapterFiles.forEach(f => console.log(pc.gray(` ${f.path}`)));
850
+ }
851
+
852
+ if (data.dependencies?.npm?.length) {
853
+ // SECURITY: filter out anything that isn't a bare npm package name.
854
+ const { accepted: safeDeps, rejected } = filterSafePackages(data.dependencies.npm);
855
+ if (rejected.length > 0) {
856
+ console.log(pc.yellow(` Skipping invalid package names: ${rejected.map(sanitizeForTerminal).join(', ')}`));
857
+ }
858
+ if (safeDeps.length > 0) {
859
+ console.log();
860
+ const install = await askConfirm({
861
+ message: `Install dependencies? (${safeDeps.join(', ')})`,
862
+ initialValue: true,
863
+ });
864
+ if (install) {
865
+ const s = ora('Installing dependencies...').start();
866
+ const result = await runInstall(pm, process.cwd(), safeDeps);
867
+ if (result.success) s.succeed('Dependencies installed');
868
+ else { s.fail(sanitizeForTerminal(result.error || 'Install failed')); if (result.hint) console.log(pc.gray(` ${sanitizeForTerminal(result.hint)}`)); }
869
+ }
870
+ }
871
+ }
872
+
873
+ // Apply file-merge patches (e.g. wrap layout.tsx with a provider, ensure
874
+ // middleware.ts exists or print merge instructions). Runs after deps install
875
+ // so the wrapped file's imports resolve immediately on `npm run dev`.
876
+ if (Array.isArray(data.merges) && data.merges.length > 0) {
877
+ const mergeSummary = { created: [], modified: [], installed: [], alreadySatisfied: [], skipped: [] };
878
+ await applyMerges(data.merges, process.cwd(), mergeSummary);
879
+
880
+ // Surface what changed in the user's existing files. We don't reuse
881
+ // printInstallSummary here because the booster file list was already
882
+ // printed above; this is the focused "what we touched outside the
883
+ // install_paths" report.
884
+ if (mergeSummary.created.length || mergeSummary.modified.length || mergeSummary.skipped.length) {
885
+ console.log();
886
+ if (mergeSummary.created.length) {
887
+ console.log(pc.green(' Created:'));
888
+ for (const f of mergeSummary.created) console.log(pc.gray(` ${f}`));
889
+ }
890
+ if (mergeSummary.modified.length) {
891
+ console.log(pc.yellow(' Patched:'));
892
+ for (const m of mergeSummary.modified) console.log(pc.gray(` ${m.path} ${pc.dim(m.note)}`));
893
+ }
894
+ if (mergeSummary.skipped.length) {
895
+ console.log(pc.gray(' Merge skipped:'));
896
+ for (const k of mergeSummary.skipped) console.log(pc.gray(` ${k.what} ${pc.dim(`(${k.reason})`)}`));
897
+ }
898
+ }
899
+ }
900
+
901
+ if (data.dependencies?.env?.length) {
902
+ console.log();
903
+ p.log.warn('Add these to your .env:');
904
+ data.dependencies.env.forEach(v => console.log(pc.gray(` ${v}=`)));
905
+ }
906
+
907
+ if (data.post_install) { console.log(); console.log(pc.gray(data.post_install)); }
908
+ return true;
909
+
910
+ } catch (err) {
911
+ spinner.fail('Failed to add booster.');
912
+ handleAddError(err, slug, framework);
913
+ }
914
+ }
915
+
916
+ async function addWorkflow(slug, options) {
917
+ if (!validateSlug(slug, 'workflow name')) exit(1);
918
+
919
+ const ora = (await import('ora')).default;
920
+ const framework = resolveFramework(options);
921
+ const spinner = ora(`Fetching workflow ${pc.cyan(slug)} (${FRAMEWORK_LABELS[framework] || framework})...`).start();
922
+
923
+ try {
924
+ const data = await getWorkflow(slug, framework);
925
+
926
+ if (!data.files?.length) {
927
+ spinner.fail(`No files available for workflow "${slug}" (${framework}).`);
928
+ return;
929
+ }
930
+
931
+ let targetDir;
932
+ if (options.overlay) {
933
+ targetDir = path.resolve(process.cwd());
934
+ } else {
935
+ let dirName = options.dir || slug;
936
+ if (!isSafeInstallDir(process.cwd(), dirName)) {
937
+ spinner.fail(pc.red(`Refusing install: unsafe --dir value`));
938
+ return;
939
+ }
940
+
941
+ if (fs.existsSync(path.resolve(process.cwd(), dirName)) && !options.overwrite) {
942
+ spinner.stop();
943
+ // Non-interactive: cancel — scaffolding over an existing directory
944
+ // needs explicit consent (--overwrite or a TTY answer).
945
+ const action = await askSelect({
946
+ message: `Directory "${dirName}/" already exists.`,
947
+ options: [
948
+ { label: 'Overwrite it', value: 'overwrite' },
949
+ { label: 'Use a different name', value: 'rename' },
950
+ { label: 'Cancel', value: 'cancel' },
951
+ ],
952
+ nonInteractive: 'cancel',
953
+ });
954
+ if (p.isCancel(action) || action === 'cancel') return;
955
+ if (action === 'rename') {
956
+ const newDir = await askText({ message: 'Enter a directory name:', placeholder: `${slug}-app` });
957
+ if (p.isCancel(newDir)) return;
958
+ dirName = newDir;
959
+ }
960
+ }
961
+ targetDir = path.resolve(process.cwd(), dirName);
962
+ }
963
+
964
+ if (options.overlay && !options.overwrite) {
965
+ const conflicts = data.files.filter(f => fs.existsSync(path.resolve(targetDir, f.path))).map(f => f.path);
966
+ if (conflicts.length > 0) {
967
+ spinner.stop();
968
+ console.log(pc.yellow(`${conflicts.length} file(s) would be overwritten:`));
969
+ conflicts.slice(0, 10).forEach(c => console.log(pc.gray(` ${c}`)));
970
+ if (conflicts.length > 10) console.log(pc.gray(` ... and ${conflicts.length - 10} more`));
971
+ const overwrite = await askConfirm({ message: 'Overwrite these files?', initialValue: false });
972
+ if (!overwrite) return;
973
+ }
974
+ }
975
+
976
+ if (options.dryRun) {
977
+ spinner.stop();
978
+ const label = options.overlay ? './' : `${path.basename(targetDir)}/`;
979
+ console.log(pc.bold(`\nDry run — no files will be written to ${label}:\n`));
980
+ data.files.forEach(f => {
981
+ const exists = fs.existsSync(path.resolve(targetDir, f.path));
982
+ console.log(` ${exists ? pc.yellow('overwrite') : pc.green('+ create')} ${f.path}`);
983
+ });
984
+ return;
985
+ }
986
+
987
+ const pm = detectPackageManager(options.overlay ? process.cwd() : targetDir);
988
+ // Fresh-directory scaffolds legitimately ship package.json/next.config/
989
+ // .gitignore; overlay installs into an existing project stay strict.
990
+ const fileCount = writeFiles(targetDir, data.files, { scaffold: !options.overlay });
991
+ const label = options.overlay ? './' : `${path.basename(targetDir)}/`;
992
+
993
+ spinner.succeed(`Scaffolded workflow ${pc.cyan(data.name || slug)} in ${label}`);
994
+ console.log(pc.gray(` ${fileCount} files written`));
995
+
996
+ if (!options.overlay) {
997
+ console.log();
998
+ const install = await askConfirm({ message: `Install dependencies with ${pm}?`, initialValue: true });
999
+ if (install) {
1000
+ const s = ora(`Installing with ${pm}...`).start();
1001
+ const result = await runInstall(pm, targetDir);
1002
+ if (result.success) s.succeed('Dependencies installed');
1003
+ else { s.fail(result.error); if (result.hint) console.log(pc.gray(` ${result.hint}`)); }
1004
+ }
1005
+ }
1006
+
1007
+ console.log();
1008
+ if (!options.overlay) console.log(pc.white(` cd ${path.basename(targetDir)}`));
1009
+ console.log(pc.white(` ${getRunCommand(pm, 'dev')}`));
1010
+
1011
+ if (data.dependencies?.env?.length) {
1012
+ console.log();
1013
+ p.log.warn('Set up your environment variables:');
1014
+ data.dependencies.env.forEach(v => console.log(pc.gray(` ${v}=`)));
1015
+ }
1016
+
1017
+ if (data.post_install) { console.log(); console.log(pc.gray(data.post_install)); }
1018
+ return true;
1019
+
1020
+ } catch (err) {
1021
+ spinner.fail('Failed to add workflow.');
1022
+ handleAddError(err, slug, framework);
1023
+ }
1024
+ }
1025
+
1026
+ function handleAddError(err, slug, framework) {
1027
+ lastFailure = err.code || 'ERROR';
1028
+ if (err.code === 'AUTH_REQUIRED') {
1029
+ if (!getApiKey() && !getAuth().token) {
1030
+ // no key at all: say what the component is and the three ways to give one
1031
+ p.log.warn(`${pc.cyan(slug)} is a premium component: it needs your AstralKit API key.`);
1032
+ console.log(pc.gray(' Sign in once: ') + pc.cyan('astralkit login'));
1033
+ console.log(pc.gray(' Or save a key: ') + pc.cyan('astralkit init --api-key <key>'));
1034
+ console.log(pc.gray(' Or for this run: set the ASTRALKIT_API_KEY environment variable'));
1035
+ console.log(pc.gray(' Your key is at ') + pc.cyan('https://astralkit.com/account') + pc.gray('. The free components install without one: ') + pc.cyan('astralkit list --free'));
1036
+ } else {
1037
+ p.log.warn(err.message);
1038
+ }
1039
+ } else if (err.code === 'PRO_REQUIRED') {
1040
+ p.log.warn(`${FRAMEWORK_LABELS[framework] || framework} version requires a Pro subscription.`);
1041
+ console.log(pc.gray(' Upgrade at ') + pc.cyan('https://astralkit.com/pricing'));
1042
+ } else {
1043
+ try {
1044
+ const body = JSON.parse(err.message.replace(/^API error \d+: /, ''));
1045
+ if (body.supported_frameworks) {
1046
+ p.log.warn(`No ${framework} version available for "${slug}".`);
1047
+ console.log(pc.gray(`Available: ${body.supported_frameworks.map(f => FRAMEWORK_LABELS[f] || f).join(', ')}`));
1048
+ exit(1);
1049
+ }
1050
+ } catch { /* not json */ }
1051
+ console.error(pc.red(err.message));
1052
+ }
1053
+ exit(1);
1054
+ }