@astralkit/cli 4.2.2 → 4.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,25 @@ All notable changes to the `@astralkit/cli` package.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [4.3.0] — 2026-04-22
9
+
10
+ ### Fixed
11
+ - **No more silent modification of `layout.tsx`.** When a component pulls in a side-effect import package (e.g. `@phosphor-icons/web` registering its font CSS), the CLI previously injected `import '@phosphor-icons/web/regular'` lines into `src/app/layout.tsx` without asking. Root layout is one of the most critical files in a Next.js app — silent edits broke trust with users installing into mature projects. The CLI now prints the exact diff and prompts with a default of **No**; declining leaves the component files in place and prints the imports so the user can add them by hand.
12
+ - **Phosphor icon conflict detection.** `@phosphor-icons/web` (CSS classes) and `@phosphor-icons/react` (React components) are separate packages that ship two different icon systems. Installing both in one codebase bloats the bundle and splits the icon convention. If the host project already has `@phosphor-icons/react` as a dependency, the CLI now warns and asks before installing `@phosphor-icons/web` — and if the user declines, skips both the dependency install and the layout-file edit.
13
+ - **End-of-install summary.** After any `astralkit add`, the CLI now prints a grouped summary of Created files, Modified files (with reason), Installed deps, Already-satisfied deps, and Skipped items — so users don't have to run `git diff` to see what changed.
14
+
15
+ ### Compatibility
16
+ - No breaking changes. All new behavior is additive (prompts where there was silent action) and defaults bias toward user consent.
17
+
18
+ ## [4.2.3] — 2026-04-19
19
+
20
+ ### Fixed
21
+ - **v4 init writes the explicit theme path.** Previously `init` wrote `@import "astralkit/theme";` for Tailwind v4 projects, which relied on the SDK's `./theme` default pointing at the v4 file. After the SDK revert in `astralkit@0.3.2` (where `./theme` correctly resolves to the v3 `:root` file), v4 projects need the explicit `@import "astralkit/theme-v4";` import instead. `init` now writes that for v4 projects. v3 projects continue to register tokens via the `astralkit/tailwind.cjs` plugin with no theme CSS import.
22
+ - **README** updated to reflect the v3-default + v4-opt-in model, with distinct `globals.css` examples for each Tailwind major version.
23
+
24
+ ### Compatibility
25
+ - Works with `astralkit >= 0.3.2`. Earlier astralkit versions (0.3.0 / 0.3.1) are not recommended — see the `astralkit` CHANGELOG for the theme-export revert.
26
+
8
27
  ## [4.2.2] — 2026-04-18
9
28
 
10
29
  ### Fixed
package/README.md CHANGED
@@ -32,7 +32,7 @@ npx @astralkit/cli init --api-key ak_YOUR_KEY
32
32
  2. **Detects your framework** — Next.js or React (auto-detected from project files)
33
33
  3. **Detects Tailwind version** — v3 or v4, writes the correct CSS imports
34
34
  4. **Detects TypeScript** — serves `.tsx` or `.jsx` accordingly
35
- 5. **Updates your CSS** — adds `@import "astralkit/theme"` and `@import "astralkit/utilities"` to your globals.css
35
+ 5. **Updates your CSS** — adds the correct AstralKit imports for your Tailwind version: on v3 it adds `@import "astralkit/theme";` + `@import "astralkit/utilities";` and also registers `astralkit/tailwind.cjs` in your `tailwind.config.js`; on v4 it adds `@import "astralkit/theme-v4";` + `@import "astralkit/utilities";` to your globals.css
36
36
  6. **Creates `astralkit-ai-rules.md`** — paste into Cursor, CLAUDE.md, etc.
37
37
 
38
38
  No config file is created. Everything is auto-detected on every command.
@@ -216,8 +216,10 @@ After `astralkit init`, your project has:
216
216
 
217
217
  ```
218
218
  node_modules/astralkit/ ← real npm dependency
219
- ├── astralkit-theme.css ← design tokens
219
+ ├── astralkit-theme.css ← design tokens (v3 :root — default)
220
+ ├── astralkit-theme-v4.css ← design tokens (v4 @theme — opt-in)
220
221
  ├── astralkit-utilities.css ← utility classes
222
+ ├── tailwind.cjs ← v3 plugin (registers ak-* tokens)
221
223
  ├── lib/utils.js ← cn() function
222
224
  └── package.json
223
225
 
@@ -225,12 +227,22 @@ src/components/ui/ ← components go here
225
227
  astralkit-ai-rules.md ← AI coding rules
226
228
  ```
227
229
 
228
- Your `globals.css`:
230
+ Your `globals.css` — **Tailwind v3 (the default):**
229
231
  ```css
230
- @import "tailwindcss";
232
+ @tailwind base;
233
+ @tailwind components;
234
+ @tailwind utilities;
231
235
  @import "astralkit/theme";
232
236
  @import "astralkit/utilities";
233
237
  ```
238
+ `tailwind.config.js` plugins array gets `require('astralkit/tailwind.cjs')` added automatically. The plugin teaches Tailwind about the `ak-*` token names so utilities like `bg-ak-bg` know which CSS variable to output; the theme CSS file provides the `:root { --color-ak-*: ... }` declarations.
239
+
240
+ Your `globals.css` — **Tailwind v4:**
241
+ ```css
242
+ @import "tailwindcss";
243
+ @import "astralkit/theme-v4";
244
+ @import "astralkit/utilities";
245
+ ```
234
246
 
235
247
  Teammates clone and run `npm install` — everything works. No `astralkit init` needed in CI.
236
248
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astralkit/cli",
3
- "version": "4.2.2",
3
+ "version": "4.3.0",
4
4
  "description": "AstralKit CLI — Install and manage UI components in your project",
5
5
  "type": "module",
6
6
  "bin": {
@@ -143,6 +143,27 @@ function resolveExtension(framework) {
143
143
  return isTS ? '.tsx' : '.jsx';
144
144
  }
145
145
 
146
+ // Read the target project's package.json. Used to detect package conflicts
147
+ // (e.g. host already uses @phosphor-icons/react and we're about to add the
148
+ // separate @phosphor-icons/web). Returns null if the file is unreadable.
149
+ function readHostPackageJson() {
150
+ try {
151
+ const raw = fs.readFileSync(path.join(process.cwd(), 'package.json'), 'utf8');
152
+ return JSON.parse(raw);
153
+ } catch {
154
+ return null;
155
+ }
156
+ }
157
+
158
+ function hostHasDep(pkg, name) {
159
+ if (!pkg) return false;
160
+ return Boolean(
161
+ pkg.dependencies?.[name] ||
162
+ pkg.devDependencies?.[name] ||
163
+ pkg.optionalDependencies?.[name]
164
+ );
165
+ }
166
+
146
167
  async function addComponent(componentSlug, options) {
147
168
  if (!validateSlug(componentSlug)) process.exit(1);
148
169
  if (!fs.existsSync(path.join(process.cwd(), 'package.json'))) {
@@ -150,6 +171,17 @@ async function addComponent(componentSlug, options) {
150
171
  return;
151
172
  }
152
173
 
174
+ // Tracked across the full install so the end-of-run summary can tell the
175
+ // user exactly what changed in their project (created files, modified
176
+ // files, installed deps, anything skipped by user confirmation).
177
+ const installSummary = {
178
+ created: [], // relative file paths written
179
+ modified: [], // { path, note }
180
+ installed: [], // dep names
181
+ alreadySatisfied: [], // dep names
182
+ skipped: [], // { what, reason }
183
+ };
184
+
153
185
  const ora = (await import('ora')).default;
154
186
  const framework = resolveFramework(options);
155
187
  const ext = resolveExtension(framework);
@@ -202,16 +234,16 @@ async function addComponent(componentSlug, options) {
202
234
  for (const file of filesToWrite) {
203
235
  if (!isSafePath(dir, file.path)) {
204
236
  console.log(pc.red(` Skipping suspicious path: ${file.path}`));
237
+ installSummary.skipped.push({ what: file.path, reason: 'unsafe path' });
205
238
  continue;
206
239
  }
207
240
  const filePath = path.resolve(dir, file.path);
208
241
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
209
242
  fs.writeFileSync(filePath, file.content);
243
+ installSummary.created.push(path.join(componentsDir, file.path).replace(/\\/g, '/'));
210
244
  }
211
245
 
212
246
  spinner.succeed(`Added ${pc.cyan(data.name || componentSlug)} (${FRAMEWORK_LABELS[framework]})`);
213
- console.log(pc.gray(` ${componentsDir}/`));
214
- for (const file of filesToWrite) console.log(pc.gray(` ${file.path}`));
215
247
 
216
248
  if (!isAstralkitInstalled()) {
217
249
  p.log.warn('Run ' + pc.cyan('astralkit init') + ' to set up design tokens.');
@@ -227,13 +259,42 @@ async function addComponent(componentSlug, options) {
227
259
 
228
260
  // Detect if component uses Phosphor Icons (CSS class-based icons)
229
261
  const componentCode = data.files?.map(f => f.content).join('') || '';
230
- const usesPhosphorCss = componentCode.includes('class="ph ') || componentCode.includes("class='ph ") || componentCode.includes('"ph ph-') || componentCode.includes("'ph ph-");
262
+ let usesPhosphorCss = componentCode.includes('class="ph ') || componentCode.includes("class='ph ") || componentCode.includes('"ph ph-') || componentCode.includes("'ph ph-");
263
+
264
+ // Phosphor conflict guard: @phosphor-icons/web and @phosphor-icons/react
265
+ // are SEPARATE packages (CSS classes vs React components). Installing both
266
+ // ships two icon systems in the same codebase — bundle bloat and a
267
+ // long-term consistency tax. If the host already uses the React package,
268
+ // warn loudly and let the user opt out of auto-installing web.
269
+ if (usesPhosphorCss) {
270
+ const hostPkg = readHostPackageJson();
271
+ if (hostHasDep(hostPkg, '@phosphor-icons/react')) {
272
+ p.log.warn(`This component uses ${pc.cyan('@phosphor-icons/web')} (CSS class-based icons).`);
273
+ p.log.warn(`Your project already uses ${pc.cyan('@phosphor-icons/react')} (React components) — a ${pc.bold('separate package')} from the same vendor.`);
274
+ p.log.warn(`Installing both ships two icon systems side by side.`);
275
+
276
+ const proceed = await p.confirm({
277
+ message: 'Install @phosphor-icons/web anyway?',
278
+ initialValue: false,
279
+ });
280
+ if (p.isCancel(proceed) || !proceed) {
281
+ p.log.info('Skipping @phosphor-icons/web and the layout.tsx import.');
282
+ p.log.info(pc.gray('Adapt the component\'s <i className="ph ph-*"> tags to @phosphor-icons/react React components.'));
283
+ usesPhosphorCss = false;
284
+ installSummary.skipped.push({
285
+ what: '@phosphor-icons/web',
286
+ reason: 'host project uses @phosphor-icons/react; user declined',
287
+ });
288
+ }
289
+ }
290
+ }
231
291
 
232
292
  if (data.dependencies?.length || usesPhosphorCss) {
233
293
  const pm = detectPackageManager();
234
294
  const rawDepList = (data.dependencies || []).filter(d => d !== 'astralkit' && d !== 'clsx' && d !== 'tailwind-merge');
235
295
 
236
296
  // Auto-add @phosphor-icons/web if component uses CSS-based Phosphor icons
297
+ // AND we didn't skip it above due to a @phosphor-icons/react conflict.
237
298
  if (usesPhosphorCss && !rawDepList.includes('@phosphor-icons/web')) {
238
299
  rawDepList.push('@phosphor-icons/web');
239
300
  }
@@ -247,21 +308,46 @@ async function addComponent(componentSlug, options) {
247
308
  }
248
309
 
249
310
  if (depList.length > 0) {
250
- // Always ask before running npm install — mirrors the booster flow.
251
- const install = await p.confirm({
252
- message: `Install dependencies? (${depList.join(', ')})`,
253
- initialValue: true,
254
- });
255
- if (!p.isCancel(install) && install) {
256
- const s = ora(`Installing ${depList.join(', ')}...`).start();
257
- const result = await runInstall(pm, process.cwd(), depList);
258
- if (result.success) s.succeed(`Installed ${depList.join(', ')}`);
259
- else { s.fail(sanitizeForTerminal(result.error || 'Install failed')); if (result.hint) console.log(pc.gray(` ${sanitizeForTerminal(result.hint)}`)); }
311
+ // Split into already-present vs to-install so the user sees both in
312
+ // the end-of-install summary.
313
+ const hostPkg = readHostPackageJson();
314
+ const toInstall = depList.filter(d => !hostHasDep(hostPkg, d));
315
+ const alreadyThere = depList.filter(d => hostHasDep(hostPkg, d));
316
+ for (const d of alreadyThere) installSummary.alreadySatisfied.push(d);
317
+
318
+ if (toInstall.length > 0) {
319
+ // Always ask before running npm install — mirrors the booster flow.
320
+ const install = await p.confirm({
321
+ message: `Install dependencies? (${toInstall.join(', ')})`,
322
+ initialValue: true,
323
+ });
324
+ if (!p.isCancel(install) && install) {
325
+ const s = ora(`Installing ${toInstall.join(', ')}...`).start();
326
+ const result = await runInstall(pm, process.cwd(), toInstall);
327
+ if (result.success) {
328
+ s.succeed(`Installed ${toInstall.join(', ')}`);
329
+ for (const d of toInstall) installSummary.installed.push(d);
330
+ } else {
331
+ s.fail(sanitizeForTerminal(result.error || 'Install failed'));
332
+ if (result.hint) console.log(pc.gray(` ${sanitizeForTerminal(result.hint)}`));
333
+ for (const d of toInstall) {
334
+ installSummary.skipped.push({ what: d, reason: 'install failed' });
335
+ }
336
+ }
337
+ } else {
338
+ for (const d of toInstall) {
339
+ installSummary.skipped.push({ what: d, reason: 'user declined install' });
340
+ }
341
+ }
260
342
  }
261
343
  }
262
344
 
263
345
  // Auto-add JS imports for icon/font packages in layout file
264
- // (CSS @import doesn't resolve node_modules exports in Next.js PostCSS)
346
+ // (CSS @import doesn't resolve node_modules exports in Next.js PostCSS).
347
+ // This modifies a user-owned file — one of the most critical in a
348
+ // Next.js app — so we now show the exact diff and prompt for consent
349
+ // with a default of NO. Silent modification of layout.tsx was a
350
+ // reported trust issue (CLI feedback 2026-04-22).
265
351
  const JS_DEPENDENCY_IMPORTS = {
266
352
  '@phosphor-icons/web': [
267
353
  "import '@phosphor-icons/web/regular'",
@@ -269,10 +355,15 @@ async function addComponent(componentSlug, options) {
269
355
  ],
270
356
  };
271
357
 
358
+ // Only consider packages we actually installed (or that were already
359
+ // present) — no point prompting about imports for a dep the user skipped.
360
+ const effectiveDeps = new Set([
361
+ ...installSummary.installed,
362
+ ...installSummary.alreadySatisfied,
363
+ ]);
272
364
  for (const [pkg, imports] of Object.entries(JS_DEPENDENCY_IMPORTS)) {
273
- if (!depList.includes(pkg)) continue;
365
+ if (!effectiveDeps.has(pkg)) continue;
274
366
 
275
- // Find the layout file
276
367
  const layoutCandidates = [
277
368
  'src/app/layout.tsx', 'src/app/layout.jsx', 'src/app/layout.js',
278
369
  'app/layout.tsx', 'app/layout.jsx', 'app/layout.js',
@@ -291,30 +382,88 @@ async function addComponent(componentSlug, options) {
291
382
 
292
383
  const layoutContent = fs.readFileSync(layoutFile.path, 'utf8');
293
384
  const missing = imports.filter(imp => !layoutContent.includes(imp));
294
- if (missing.length > 0) {
295
- // Add after the first import line
296
- const lines = layoutContent.split('\n');
297
- let lastImportIdx = -1;
298
- for (let i = 0; i < lines.length; i++) {
299
- if (lines[i].trim().startsWith('import ')) lastImportIdx = i;
300
- }
301
- if (lastImportIdx >= 0) {
302
- lines.splice(lastImportIdx + 1, 0, ...missing);
303
- } else {
304
- lines.unshift(...missing);
305
- }
306
- fs.writeFileSync(layoutFile.path, lines.join('\n'));
307
- p.log.success(`Added ${pc.cyan(pkg)} imports to ${pc.cyan(layoutFile.relative)}`);
385
+ if (missing.length === 0) continue;
386
+
387
+ // Show the exact diff we want to apply — never silently modify.
388
+ p.log.warn(`${pc.cyan(pkg)} needs these side-effect imports in your root layout:`);
389
+ console.log(pc.gray(` ${layoutFile.relative}`));
390
+ for (const imp of missing) console.log(` ${pc.green('+')} ${imp}`);
391
+
392
+ const proceed = await p.confirm({
393
+ message: `Add these imports to ${layoutFile.relative}?`,
394
+ initialValue: false,
395
+ });
396
+
397
+ if (p.isCancel(proceed) || !proceed) {
398
+ p.log.info(`Skipped ${layoutFile.relative} edit. Add these lines manually to enable icons:`);
399
+ for (const imp of missing) console.log(pc.gray(` ${imp}`));
400
+ installSummary.skipped.push({
401
+ what: `${layoutFile.relative} imports (${pkg})`,
402
+ reason: 'user declined',
403
+ });
404
+ continue;
405
+ }
406
+
407
+ const lines = layoutContent.split('\n');
408
+ let lastImportIdx = -1;
409
+ for (let i = 0; i < lines.length; i++) {
410
+ if (lines[i].trim().startsWith('import ')) lastImportIdx = i;
411
+ }
412
+ if (lastImportIdx >= 0) {
413
+ lines.splice(lastImportIdx + 1, 0, ...missing);
414
+ } else {
415
+ lines.unshift(...missing);
308
416
  }
417
+ fs.writeFileSync(layoutFile.path, lines.join('\n'));
418
+ installSummary.modified.push({
419
+ path: layoutFile.relative,
420
+ note: `+${missing.length} ${missing.length === 1 ? 'import' : 'imports'} (${pkg})`,
421
+ });
422
+ p.log.success(`Added ${pc.cyan(pkg)} imports to ${pc.cyan(layoutFile.relative)}`);
309
423
  }
310
424
  }
311
425
 
426
+ printInstallSummary(installSummary);
427
+
312
428
  } catch (err) {
313
429
  spinner.fail('Failed to add component.');
314
430
  handleAddError(err, componentSlug, framework);
315
431
  }
316
432
  }
317
433
 
434
+ // End-of-install summary. Prints what the CLI did to the user's project so
435
+ // they never have to run `git diff` just to find out what was touched. Split
436
+ // into Created / Modified / Installed / Skipped so each category is scannable.
437
+ function printInstallSummary(s) {
438
+ const hasAny =
439
+ s.created.length || s.modified.length || s.installed.length ||
440
+ s.alreadySatisfied.length || s.skipped.length;
441
+ if (!hasAny) return;
442
+
443
+ console.log('');
444
+ p.log.step(pc.bold('What changed in your project'));
445
+ if (s.created.length) {
446
+ console.log(pc.green(' Created:'));
447
+ for (const f of s.created) console.log(pc.gray(` ${f}`));
448
+ }
449
+ if (s.modified.length) {
450
+ console.log(pc.yellow(' Modified:'));
451
+ for (const m of s.modified) console.log(pc.gray(` ${m.path} ${pc.dim(m.note)}`));
452
+ }
453
+ if (s.installed.length) {
454
+ console.log(pc.cyan(' Installed:'));
455
+ for (const d of s.installed) console.log(pc.gray(` ${d}`));
456
+ }
457
+ if (s.alreadySatisfied.length) {
458
+ console.log(pc.gray(' Already satisfied:'));
459
+ for (const d of s.alreadySatisfied) console.log(pc.gray(` ${d}`));
460
+ }
461
+ if (s.skipped.length) {
462
+ console.log(pc.gray(' Skipped:'));
463
+ for (const k of s.skipped) console.log(pc.gray(` ${k.what} ${pc.dim(`(${k.reason})`)}`));
464
+ }
465
+ }
466
+
318
467
  async function addBooster(slug, options) {
319
468
  if (!validateSlug(slug, 'booster name')) process.exit(1);
320
469
 
@@ -1,199 +1,199 @@
1
- import fs from 'fs';
2
- import path from 'path';
3
- import pc from 'picocolors';
4
- import * as p from '@clack/prompts';
5
- import {
6
- detectFramework,
7
- detectTailwindVersion,
8
- detectTypeScript,
9
- isAstralkitInstalled,
10
- findCssEntryFile,
11
- getMissingCssImports,
12
- addCssImports,
13
- getRequiredCssImports,
14
- } from '../lib/config.js';
15
- import { getAiRulesContent } from '../lib/ai-rules.js';
16
- import { saveApiKey, getApiKey } from '../lib/auth.js';
17
- import { detectPackageManager, runInstall } from '../lib/pkg-manager.js';
18
-
19
- const FRAMEWORK_LABELS = { nextjs: 'Next.js', react: 'React' };
20
-
21
- export async function initCommand(options) {
22
- p.intro(pc.bgBlue(pc.white(' AstralKit Setup ')));
23
-
24
- // ─── Step 1: API Key ─────────────────────────────────
25
- let apiKey = options.apiKey || getApiKey();
26
-
27
- if (options.apiKey) {
28
- if (!options.apiKey.startsWith('ak_')) {
29
- p.cancel(pc.red('Invalid API key format. Keys start with ak_'));
30
- console.log(pc.gray('Get your key at ') + pc.cyan('https://astralkit.com/account'));
31
- process.exit(1);
32
- }
33
- saveApiKey(options.apiKey);
34
- p.log.success('API key saved');
35
- } else if (!apiKey) {
36
- p.log.warn('No API key found.');
37
- console.log();
38
- console.log(pc.gray(' Get your free API key at: ') + pc.cyan('https://astralkit.com/account'));
39
- console.log();
40
-
41
- const keyInput = await p.text({
42
- message: 'Paste your API key (or press Enter to skip for now):',
43
- placeholder: 'ak_...',
44
- validate(val) {
45
- if (!val) return;
46
- if (!val.startsWith('ak_')) return 'Keys start with ak_ — check astralkit.com/account';
47
- },
48
- });
49
-
50
- if (p.isCancel(keyInput)) {
51
- p.cancel('Setup cancelled.');
52
- process.exit(0);
53
- }
54
-
55
- if (keyInput) {
56
- saveApiKey(keyInput);
57
- apiKey = keyInput;
58
- p.log.success('API key saved');
59
- } else {
60
- p.log.warn('Skipping API key — some features will be unavailable.');
61
- p.log.info('Run ' + pc.cyan('astralkit init --api-key <key>') + ' later to add it.');
62
- }
63
- } else {
64
- p.log.success('API key found');
65
- }
66
-
67
- // ─── Step 2: Detect project ────────────────────────────
68
- const framework = options.framework || detectFramework();
69
- const tailwindVersion = detectTailwindVersion();
70
- const isTS = detectTypeScript();
71
- const pm = detectPackageManager();
72
-
73
- if (framework !== 'react' && framework !== 'nextjs') {
74
- p.log.warn('AstralKit CLI is for React and Next.js projects.');
75
- p.log.info('For HTML, copy components from ' + pc.cyan('https://astralkit.com'));
76
- p.outro('');
77
- return;
78
- }
79
-
80
- p.log.step(`Framework: ${pc.cyan(FRAMEWORK_LABELS[framework])}`);
81
- if (tailwindVersion) p.log.step(`Tailwind: ${pc.cyan('v' + tailwindVersion)}`);
82
- p.log.step(`TypeScript: ${pc.cyan(isTS ? 'Yes' : 'No')}`);
83
- p.log.step(`Package manager: ${pc.cyan(pm)}`);
84
-
85
- // ─── Step 3: Install astralkit (real npm dependency) ────
86
- //
87
- // `npm install astralkit` — a proper package on the public registry.
88
- // Contains: design tokens (CSS), cn() utility, AI rules.
89
- // Listed in package.json. Survives npm ci. Works for teammates and CI/CD.
90
-
91
- if (!isAstralkitInstalled()) {
92
- const ora = (await import('ora')).default;
93
- const spinner = ora('Installing astralkit...').start();
94
- try {
95
- const result = await runInstall(pm, process.cwd(), ['astralkit']);
96
- if (result.success) {
97
- spinner.succeed('Installed astralkit');
98
- } else {
99
- spinner.fail('Failed to install astralkit.');
100
- console.log(pc.gray(' ' + (result.hint || result.error)));
101
- console.log(pc.gray(` Retry manually: ${pm === 'npm' ? 'npm install' : pm + ' add'} astralkit`));
102
- }
103
- } catch (err) {
104
- spinner.fail('Failed to install astralkit.');
105
- console.log(pc.gray(' ' + err.message));
106
- }
107
- } else {
108
- p.log.step('astralkit already installed');
109
- }
110
-
111
- // ─── Step 4: CSS imports ─────────────────────────────
112
- const cssEntry = findCssEntryFile();
113
-
114
- if (cssEntry) {
115
- const missing = getMissingCssImports(cssEntry.path, tailwindVersion);
116
- if (missing.length > 0) {
117
- addCssImports(cssEntry.path, missing);
118
- p.log.success(`Updated ${pc.cyan(cssEntry.relative)}`);
119
- } else {
120
- p.log.step('CSS imports already present');
121
- }
122
- } else {
123
- // Create a default CSS file
124
- const defaultCssPath = path.join(process.cwd(), 'src', 'app', 'globals.css');
125
- const defaultCssRelative = path.relative(process.cwd(), defaultCssPath);
126
- const cssDir = path.dirname(defaultCssPath);
127
- if (!fs.existsSync(cssDir)) fs.mkdirSync(cssDir, { recursive: true });
128
- const imports = getRequiredCssImports(tailwindVersion);
129
- fs.writeFileSync(defaultCssPath, imports.join('\n') + '\n', 'utf-8');
130
- p.log.success(`Created ${pc.cyan(defaultCssRelative)}`);
131
- }
132
-
133
- // ─── Step 4b: Tailwind v3 plugin registration ─────────
134
- //
135
- // In v3, the @theme directive doesn't exist, so ak-* utility classes
136
- // (bg-ak-bg, text-ak-text, p-ak-2, etc.) only work if the Tailwind
137
- // config extends the theme. The astralkit/tailwind plugin does this.
138
- //
139
- if (tailwindVersion === 3) {
140
- const configPath = path.join(process.cwd(), 'tailwind.config.js');
141
- const configPathTs = path.join(process.cwd(), 'tailwind.config.ts');
142
- const configFile = fs.existsSync(configPathTs) ? configPathTs : (fs.existsSync(configPath) ? configPath : null);
143
-
144
- if (configFile) {
145
- const configContent = fs.readFileSync(configFile, 'utf8');
146
- if (!configContent.includes('astralkit/tailwind')) {
147
- // Insert the plugin require into the plugins array
148
- const pluginLine = "require('astralkit/tailwind.cjs')";
149
-
150
- // Match `plugins` followed by optional whitespace/newlines and an
151
- // opening bracket. Covers:
152
- // plugins: [ (current format)
153
- // plugins:[ (no space)
154
- // plugins: \n [ (newline before bracket)
155
- // plugins = [ (variable assignment style, rare)
156
- const arrayOpenRe = /plugins\s*[:=]\s*\[/;
157
-
158
- if (arrayOpenRe.test(configContent)) {
159
- // plugins array exists — inject after the opening bracket, preserving
160
- // the user's indentation style as best we can
161
- const updated = configContent.replace(
162
- arrayOpenRe,
163
- (match) => `${match}\n ${pluginLine},`
164
- );
165
- fs.writeFileSync(configFile, updated, 'utf8');
166
- p.log.success(`Added AstralKit plugin to ${pc.cyan(path.relative(process.cwd(), configFile))}`);
167
- } else if (/plugins\s*[:=]/.test(configContent)) {
168
- // plugins key exists but not as an array — warn
169
- p.log.warn('Could not auto-add plugin to tailwind config (plugins is not an array literal).');
170
- p.log.info(`Add manually: ${pc.cyan(pluginLine)} to your plugins array.`);
171
- } else {
172
- p.log.warn('No plugins array found in tailwind config.');
173
- p.log.info(`Add manually: ${pc.cyan(`plugins: [${pluginLine}]`)}`);
174
- }
175
- } else {
176
- p.log.step('AstralKit Tailwind plugin already registered');
177
- }
178
- } else {
179
- p.log.warn('No tailwind.config found. AstralKit Tailwind v3 plugin not registered.');
180
- p.log.info(`Create one and add: ${pc.cyan("plugins: [require('astralkit/tailwind.cjs')]")}`);
181
- }
182
- }
183
-
184
- // ─── Step 5: AI rules file ───────────────────────────
185
- const rulesFile = 'astralkit-ai-rules.md';
186
- const rulesPath = path.join(process.cwd(), rulesFile);
187
- if (!fs.existsSync(rulesPath)) {
188
- fs.writeFileSync(rulesPath, getAiRulesContent());
189
- p.log.success(`Created ${pc.cyan(rulesFile)}`);
190
- }
191
-
192
- // ─── Done ────────────────────────────────────────────
193
- p.outro(pc.green('AstralKit is ready!'));
194
-
195
- console.log();
196
- console.log(pc.gray(' Add a component:'), pc.cyan('astralkit add button-variants'));
197
- console.log(pc.gray(' Browse all: '), pc.cyan('astralkit list'));
198
- console.log();
199
- }
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import pc from 'picocolors';
4
+ import * as p from '@clack/prompts';
5
+ import {
6
+ detectFramework,
7
+ detectTailwindVersion,
8
+ detectTypeScript,
9
+ isAstralkitInstalled,
10
+ findCssEntryFile,
11
+ getMissingCssImports,
12
+ addCssImports,
13
+ getRequiredCssImports,
14
+ } from '../lib/config.js';
15
+ import { getAiRulesContent } from '../lib/ai-rules.js';
16
+ import { saveApiKey, getApiKey } from '../lib/auth.js';
17
+ import { detectPackageManager, runInstall } from '../lib/pkg-manager.js';
18
+
19
+ const FRAMEWORK_LABELS = { nextjs: 'Next.js', react: 'React' };
20
+
21
+ export async function initCommand(options) {
22
+ p.intro(pc.bgBlue(pc.white(' AstralKit Setup ')));
23
+
24
+ // ─── Step 1: API Key ─────────────────────────────────
25
+ let apiKey = options.apiKey || getApiKey();
26
+
27
+ if (options.apiKey) {
28
+ if (!options.apiKey.startsWith('ak_')) {
29
+ p.cancel(pc.red('Invalid API key format. Keys start with ak_'));
30
+ console.log(pc.gray('Get your key at ') + pc.cyan('https://astralkit.com/account'));
31
+ process.exit(1);
32
+ }
33
+ saveApiKey(options.apiKey);
34
+ p.log.success('API key saved');
35
+ } else if (!apiKey) {
36
+ p.log.warn('No API key found.');
37
+ console.log();
38
+ console.log(pc.gray(' Get your free API key at: ') + pc.cyan('https://astralkit.com/account'));
39
+ console.log();
40
+
41
+ const keyInput = await p.text({
42
+ message: 'Paste your API key (or press Enter to skip for now):',
43
+ placeholder: 'ak_...',
44
+ validate(val) {
45
+ if (!val) return;
46
+ if (!val.startsWith('ak_')) return 'Keys start with ak_ — check astralkit.com/account';
47
+ },
48
+ });
49
+
50
+ if (p.isCancel(keyInput)) {
51
+ p.cancel('Setup cancelled.');
52
+ process.exit(0);
53
+ }
54
+
55
+ if (keyInput) {
56
+ saveApiKey(keyInput);
57
+ apiKey = keyInput;
58
+ p.log.success('API key saved');
59
+ } else {
60
+ p.log.warn('Skipping API key — some features will be unavailable.');
61
+ p.log.info('Run ' + pc.cyan('astralkit init --api-key <key>') + ' later to add it.');
62
+ }
63
+ } else {
64
+ p.log.success('API key found');
65
+ }
66
+
67
+ // ─── Step 2: Detect project ────────────────────────────
68
+ const framework = options.framework || detectFramework();
69
+ const tailwindVersion = detectTailwindVersion();
70
+ const isTS = detectTypeScript();
71
+ const pm = detectPackageManager();
72
+
73
+ if (framework !== 'react' && framework !== 'nextjs') {
74
+ p.log.warn('AstralKit CLI is for React and Next.js projects.');
75
+ p.log.info('For HTML, copy components from ' + pc.cyan('https://astralkit.com'));
76
+ p.outro('');
77
+ return;
78
+ }
79
+
80
+ p.log.step(`Framework: ${pc.cyan(FRAMEWORK_LABELS[framework])}`);
81
+ if (tailwindVersion) p.log.step(`Tailwind: ${pc.cyan('v' + tailwindVersion)}`);
82
+ p.log.step(`TypeScript: ${pc.cyan(isTS ? 'Yes' : 'No')}`);
83
+ p.log.step(`Package manager: ${pc.cyan(pm)}`);
84
+
85
+ // ─── Step 3: Install astralkit (real npm dependency) ────
86
+ //
87
+ // `npm install astralkit` — a proper package on the public registry.
88
+ // Contains: design tokens (CSS), cn() utility, AI rules.
89
+ // Listed in package.json. Survives npm ci. Works for teammates and CI/CD.
90
+
91
+ if (!isAstralkitInstalled()) {
92
+ const ora = (await import('ora')).default;
93
+ const spinner = ora('Installing astralkit...').start();
94
+ try {
95
+ const result = await runInstall(pm, process.cwd(), ['astralkit']);
96
+ if (result.success) {
97
+ spinner.succeed('Installed astralkit');
98
+ } else {
99
+ spinner.fail('Failed to install astralkit.');
100
+ console.log(pc.gray(' ' + (result.hint || result.error)));
101
+ console.log(pc.gray(` Retry manually: ${pm === 'npm' ? 'npm install' : pm + ' add'} astralkit`));
102
+ }
103
+ } catch (err) {
104
+ spinner.fail('Failed to install astralkit.');
105
+ console.log(pc.gray(' ' + err.message));
106
+ }
107
+ } else {
108
+ p.log.step('astralkit already installed');
109
+ }
110
+
111
+ // ─── Step 4: CSS imports ─────────────────────────────
112
+ const cssEntry = findCssEntryFile();
113
+
114
+ if (cssEntry) {
115
+ const missing = getMissingCssImports(cssEntry.path, tailwindVersion);
116
+ if (missing.length > 0) {
117
+ addCssImports(cssEntry.path, missing);
118
+ p.log.success(`Updated ${pc.cyan(cssEntry.relative)}`);
119
+ } else {
120
+ p.log.step('CSS imports already present');
121
+ }
122
+ } else {
123
+ // Create a default CSS file
124
+ const defaultCssPath = path.join(process.cwd(), 'src', 'app', 'globals.css');
125
+ const defaultCssRelative = path.relative(process.cwd(), defaultCssPath);
126
+ const cssDir = path.dirname(defaultCssPath);
127
+ if (!fs.existsSync(cssDir)) fs.mkdirSync(cssDir, { recursive: true });
128
+ const imports = getRequiredCssImports(tailwindVersion);
129
+ fs.writeFileSync(defaultCssPath, imports.join('\n') + '\n', 'utf-8');
130
+ p.log.success(`Created ${pc.cyan(defaultCssRelative)}`);
131
+ }
132
+
133
+ // ─── Step 4b: Tailwind v3 plugin registration ─────────
134
+ //
135
+ // In v3, the @theme directive doesn't exist, so ak-* utility classes
136
+ // (bg-ak-bg, text-ak-text, p-ak-2, etc.) only work if the Tailwind
137
+ // config extends the theme. The astralkit/tailwind plugin does this.
138
+ //
139
+ if (tailwindVersion === 3) {
140
+ const configPath = path.join(process.cwd(), 'tailwind.config.js');
141
+ const configPathTs = path.join(process.cwd(), 'tailwind.config.ts');
142
+ const configFile = fs.existsSync(configPathTs) ? configPathTs : (fs.existsSync(configPath) ? configPath : null);
143
+
144
+ if (configFile) {
145
+ const configContent = fs.readFileSync(configFile, 'utf8');
146
+ if (!configContent.includes('astralkit/tailwind')) {
147
+ // Insert the plugin require into the plugins array
148
+ const pluginLine = "require('astralkit/tailwind.cjs')";
149
+
150
+ // Match `plugins` followed by optional whitespace/newlines and an
151
+ // opening bracket. Covers:
152
+ // plugins: [ (current format)
153
+ // plugins:[ (no space)
154
+ // plugins: \n [ (newline before bracket)
155
+ // plugins = [ (variable assignment style, rare)
156
+ const arrayOpenRe = /plugins\s*[:=]\s*\[/;
157
+
158
+ if (arrayOpenRe.test(configContent)) {
159
+ // plugins array exists — inject after the opening bracket, preserving
160
+ // the user's indentation style as best we can
161
+ const updated = configContent.replace(
162
+ arrayOpenRe,
163
+ (match) => `${match}\n ${pluginLine},`
164
+ );
165
+ fs.writeFileSync(configFile, updated, 'utf8');
166
+ p.log.success(`Added AstralKit plugin to ${pc.cyan(path.relative(process.cwd(), configFile))}`);
167
+ } else if (/plugins\s*[:=]/.test(configContent)) {
168
+ // plugins key exists but not as an array — warn
169
+ p.log.warn('Could not auto-add plugin to tailwind config (plugins is not an array literal).');
170
+ p.log.info(`Add manually: ${pc.cyan(pluginLine)} to your plugins array.`);
171
+ } else {
172
+ p.log.warn('No plugins array found in tailwind config.');
173
+ p.log.info(`Add manually: ${pc.cyan(`plugins: [${pluginLine}]`)}`);
174
+ }
175
+ } else {
176
+ p.log.step('AstralKit Tailwind plugin already registered');
177
+ }
178
+ } else {
179
+ p.log.warn('No tailwind.config found. AstralKit Tailwind v3 plugin not registered.');
180
+ p.log.info(`Create one and add: ${pc.cyan("plugins: [require('astralkit/tailwind.cjs')]")}`);
181
+ }
182
+ }
183
+
184
+ // ─── Step 5: AI rules file ───────────────────────────
185
+ const rulesFile = 'astralkit-ai-rules.md';
186
+ const rulesPath = path.join(process.cwd(), rulesFile);
187
+ if (!fs.existsSync(rulesPath)) {
188
+ fs.writeFileSync(rulesPath, getAiRulesContent());
189
+ p.log.success(`Created ${pc.cyan(rulesFile)}`);
190
+ }
191
+
192
+ // ─── Done ────────────────────────────────────────────
193
+ p.outro(pc.green('AstralKit is ready!'));
194
+
195
+ console.log();
196
+ console.log(pc.gray(' Add a component:'), pc.cyan('astralkit add button-variants'));
197
+ console.log(pc.gray(' Browse all: '), pc.cyan('astralkit list'));
198
+ console.log();
199
+ }
package/src/lib/config.js CHANGED
@@ -1,177 +1,183 @@
1
- import fs from 'fs';
2
- import path from 'path';
3
-
4
- // ─── CSS entry file candidates (searched in order) ────────
5
- export const CSS_ENTRY_CANDIDATES = [
6
- 'src/app/globals.css',
7
- 'src/index.css',
8
- 'src/styles/globals.css',
9
- 'src/styles/index.css',
10
- 'app/globals.css',
11
- 'styles/globals.css',
12
- 'index.css',
13
- ];
14
-
15
- // ─── Framework detection ──────────────────────────────────
16
-
17
- export function detectFramework(dir = process.cwd()) {
18
- // Next.js
19
- if (
20
- fs.existsSync(path.join(dir, 'next.config.js')) ||
21
- fs.existsSync(path.join(dir, 'next.config.mjs')) ||
22
- fs.existsSync(path.join(dir, 'next.config.ts'))
23
- ) return 'nextjs';
24
-
25
- // React (Vite, CRA, etc.)
26
- const pkgPath = path.join(dir, 'package.json');
27
- if (fs.existsSync(pkgPath)) {
28
- try {
29
- const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
30
- const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
31
- if (allDeps['react']) return 'react';
32
- } catch { /* ignore */ }
33
- }
34
-
35
- return 'html';
36
- }
37
-
38
- // ─── Tailwind version detection ───────────────────────────
39
-
40
- export function detectTailwindVersion(dir = process.cwd()) {
41
- const pkgPath = path.join(dir, 'package.json');
42
- if (!fs.existsSync(pkgPath)) return null;
43
- try {
44
- const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
45
- const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
46
- const ver = allDeps['tailwindcss'];
47
- if (!ver) return null;
48
- // Handle: "^4.0.0", "~4.1.2", "4.0.0-beta.1", ">=3.4.0", "file:...", "latest", "next".
49
- // Strip only the leading non-digits (^ ~ >= etc.) then parse. Anything
50
- // that doesn't start with a digit after stripping (file:..., latest, next,
51
- // workspace:*) returns NaN from parseInt and falls through to null —
52
- // better to return null than guess wrong.
53
- const match = ver.match(/^\D*(\d+)/);
54
- if (!match) return null;
55
- const major = parseInt(match[1], 10);
56
- if (Number.isNaN(major)) return null;
57
- if (major >= 4) return 4;
58
- if (major >= 3) return 3;
59
- return null;
60
- } catch { return null; }
61
- }
62
-
63
- // ─── TypeScript detection ─────────────────────────────────
64
-
65
- export function detectTypeScript(dir = process.cwd()) {
66
- return fs.existsSync(path.join(dir, 'tsconfig.json'));
67
- }
68
-
69
- // ─── astralkit installed check ────────────────────────────
70
-
71
- export function isAstralkitInstalled(dir = process.cwd()) {
72
- return fs.existsSync(path.join(dir, 'node_modules', 'astralkit', 'package.json'));
73
- }
74
-
75
- // ─── CSS entry file search ────────────────────────────────
76
-
77
- export function findCssEntryFile(dir = process.cwd()) {
78
- for (const candidate of CSS_ENTRY_CANDIDATES) {
79
- const filePath = path.join(dir, candidate);
80
- if (fs.existsSync(filePath)) return { path: filePath, relative: candidate };
81
- }
82
- return null;
83
- }
84
-
85
- // ─── CSS imports (Tailwind v3 vs v4 aware) ────────────────
86
-
87
- export function getRequiredCssImports(tailwindVersion) {
88
- if (tailwindVersion === 3) {
89
- // v3: no @import "astralkit/theme" — the @theme directive is v4-only.
90
- // The astralkit/tailwind plugin handles token registration for v3 via addBase.
91
- return [
92
- '@tailwind base;',
93
- '@tailwind components;',
94
- '@tailwind utilities;',
95
- '@import "astralkit/utilities";',
96
- ];
97
- }
98
- // v4 or unknown — default to v4 syntax
99
- return [
100
- '@import "tailwindcss";',
101
- '@import "astralkit/theme";',
102
- '@import "astralkit/utilities";',
103
- ];
104
- }
105
-
106
- export function getMissingCssImports(cssFilePath, tailwindVersion) {
107
- try {
108
- const content = fs.readFileSync(cssFilePath, 'utf8');
109
- const required = getRequiredCssImports(tailwindVersion);
110
-
111
- return required.filter(imp => {
112
- // For tailwind directives, check if either v3 or v4 syntax is present
113
- if (imp === '@import "tailwindcss";') {
114
- return !content.includes('@import "tailwindcss"') && !content.includes('@tailwind base');
115
- }
116
- if (imp === '@tailwind base;') {
117
- return !content.includes('@tailwind base') && !content.includes('@import "tailwindcss"');
118
- }
119
- if (imp === '@tailwind components;') {
120
- return !content.includes('@tailwind components');
121
- }
122
- if (imp === '@tailwind utilities;') {
123
- return !content.includes('@tailwind utilities');
124
- }
125
- // AstralKit imports — check directly
126
- return !content.includes(imp);
127
- });
128
- } catch {
129
- return getRequiredCssImports(tailwindVersion);
130
- }
131
- }
132
-
133
- export function addCssImports(cssFilePath, imports) {
134
- const existing = fs.existsSync(cssFilePath) ? fs.readFileSync(cssFilePath, 'utf8') : '';
135
- const astralkitImports = imports.filter(i => i.includes('astralkit'));
136
-
137
- // If Tailwind is already imported/directive'd in the file (v3 @tailwind
138
- // directives OR v4 @import "tailwindcss"), insert astralkit imports AFTER
139
- // the last Tailwind-related line. This preserves the recommended ordering
140
- // (tailwindcss first, astralkit after) instead of prepending astralkit
141
- // imports before tailwindcss in the file.
142
- const tailwindImportRe = /^@import\s+["']tailwindcss["']/;
143
- const hasTailwind = existing.includes('@tailwind utilities') || tailwindImportRe.test(existing);
144
-
145
- if (hasTailwind && astralkitImports.length > 0) {
146
- const lines = existing.split('\n');
147
- let lastTailwindIdx = -1;
148
- for (let i = 0; i < lines.length; i++) {
149
- const trimmed = lines[i].trim();
150
- if (trimmed.startsWith('@tailwind') || tailwindImportRe.test(trimmed)) {
151
- lastTailwindIdx = i;
152
- }
153
- }
154
- if (lastTailwindIdx >= 0) {
155
- lines.splice(lastTailwindIdx + 1, 0, '', ...astralkitImports);
156
- fs.writeFileSync(cssFilePath, lines.join('\n'));
157
- return;
158
- }
159
- }
160
-
161
- // Default: prepend everything (fresh file with no Tailwind yet)
162
- fs.writeFileSync(cssFilePath, imports.join('\n') + '\n\n' + existing);
163
- }
164
-
165
- // ─── Legacy config file support ───────────────────────────
166
- // Reads astralkit.config.json if it exists (from older init versions).
167
- // New installs don't create this file.
168
-
169
- export const CONFIG_FILENAME = 'astralkit.config.json';
170
-
171
- export function getProjectConfig(dir = process.cwd()) {
172
- const configPath = path.join(dir, CONFIG_FILENAME);
173
- if (!fs.existsSync(configPath)) return null;
174
- try {
175
- return JSON.parse(fs.readFileSync(configPath, 'utf8'));
176
- } catch { return null; }
177
- }
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+
4
+ // ─── CSS entry file candidates (searched in order) ────────
5
+ export const CSS_ENTRY_CANDIDATES = [
6
+ 'src/app/globals.css',
7
+ 'src/index.css',
8
+ 'src/styles/globals.css',
9
+ 'src/styles/index.css',
10
+ 'app/globals.css',
11
+ 'styles/globals.css',
12
+ 'index.css',
13
+ ];
14
+
15
+ // ─── Framework detection ──────────────────────────────────
16
+
17
+ export function detectFramework(dir = process.cwd()) {
18
+ // Next.js
19
+ if (
20
+ fs.existsSync(path.join(dir, 'next.config.js')) ||
21
+ fs.existsSync(path.join(dir, 'next.config.mjs')) ||
22
+ fs.existsSync(path.join(dir, 'next.config.ts'))
23
+ ) return 'nextjs';
24
+
25
+ // React (Vite, CRA, etc.)
26
+ const pkgPath = path.join(dir, 'package.json');
27
+ if (fs.existsSync(pkgPath)) {
28
+ try {
29
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
30
+ const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
31
+ if (allDeps['react']) return 'react';
32
+ } catch { /* ignore */ }
33
+ }
34
+
35
+ return 'html';
36
+ }
37
+
38
+ // ─── Tailwind version detection ───────────────────────────
39
+
40
+ export function detectTailwindVersion(dir = process.cwd()) {
41
+ const pkgPath = path.join(dir, 'package.json');
42
+ if (!fs.existsSync(pkgPath)) return null;
43
+ try {
44
+ const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8'));
45
+ const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
46
+ const ver = allDeps['tailwindcss'];
47
+ if (!ver) return null;
48
+ // Handle: "^4.0.0", "~4.1.2", "4.0.0-beta.1", ">=3.4.0", "file:...", "latest", "next".
49
+ // Strip only the leading non-digits (^ ~ >= etc.) then parse. Anything
50
+ // that doesn't start with a digit after stripping (file:..., latest, next,
51
+ // workspace:*) returns NaN from parseInt and falls through to null —
52
+ // better to return null than guess wrong.
53
+ const match = ver.match(/^\D*(\d+)/);
54
+ if (!match) return null;
55
+ const major = parseInt(match[1], 10);
56
+ if (Number.isNaN(major)) return null;
57
+ if (major >= 4) return 4;
58
+ if (major >= 3) return 3;
59
+ return null;
60
+ } catch { return null; }
61
+ }
62
+
63
+ // ─── TypeScript detection ─────────────────────────────────
64
+
65
+ export function detectTypeScript(dir = process.cwd()) {
66
+ return fs.existsSync(path.join(dir, 'tsconfig.json'));
67
+ }
68
+
69
+ // ─── astralkit installed check ────────────────────────────
70
+
71
+ export function isAstralkitInstalled(dir = process.cwd()) {
72
+ return fs.existsSync(path.join(dir, 'node_modules', 'astralkit', 'package.json'));
73
+ }
74
+
75
+ // ─── CSS entry file search ────────────────────────────────
76
+
77
+ export function findCssEntryFile(dir = process.cwd()) {
78
+ for (const candidate of CSS_ENTRY_CANDIDATES) {
79
+ const filePath = path.join(dir, candidate);
80
+ if (fs.existsSync(filePath)) return { path: filePath, relative: candidate };
81
+ }
82
+ return null;
83
+ }
84
+
85
+ // ─── CSS imports (Tailwind v3 vs v4 aware) ────────────────
86
+
87
+ export function getRequiredCssImports(tailwindVersion) {
88
+ if (tailwindVersion === 3) {
89
+ // v3: :root CSS variable declarations come from astralkit/theme (which
90
+ // resolves to astralkit-theme.css — the :root variant). The plugin in
91
+ // tailwind.config.js teaches Tailwind about the token names so utilities
92
+ // like bg-ak-bg know which var() to emit. Utilities CSS is Tailwind-agnostic.
93
+ return [
94
+ '@tailwind base;',
95
+ '@tailwind components;',
96
+ '@tailwind utilities;',
97
+ '@import "astralkit/theme";',
98
+ '@import "astralkit/utilities";',
99
+ ];
100
+ }
101
+ // v4 or unknown — v4 projects explicitly import the @theme-directive file
102
+ // at `astralkit/theme-v4`. The default `astralkit/theme` export resolves
103
+ // to the v3 :root file (v3 is the default customer base); v4 users must
104
+ // opt in via the explicit path.
105
+ return [
106
+ '@import "tailwindcss";',
107
+ '@import "astralkit/theme-v4";',
108
+ '@import "astralkit/utilities";',
109
+ ];
110
+ }
111
+
112
+ export function getMissingCssImports(cssFilePath, tailwindVersion) {
113
+ try {
114
+ const content = fs.readFileSync(cssFilePath, 'utf8');
115
+ const required = getRequiredCssImports(tailwindVersion);
116
+
117
+ return required.filter(imp => {
118
+ // For tailwind directives, check if either v3 or v4 syntax is present
119
+ if (imp === '@import "tailwindcss";') {
120
+ return !content.includes('@import "tailwindcss"') && !content.includes('@tailwind base');
121
+ }
122
+ if (imp === '@tailwind base;') {
123
+ return !content.includes('@tailwind base') && !content.includes('@import "tailwindcss"');
124
+ }
125
+ if (imp === '@tailwind components;') {
126
+ return !content.includes('@tailwind components');
127
+ }
128
+ if (imp === '@tailwind utilities;') {
129
+ return !content.includes('@tailwind utilities');
130
+ }
131
+ // AstralKit imports — check directly
132
+ return !content.includes(imp);
133
+ });
134
+ } catch {
135
+ return getRequiredCssImports(tailwindVersion);
136
+ }
137
+ }
138
+
139
+ export function addCssImports(cssFilePath, imports) {
140
+ const existing = fs.existsSync(cssFilePath) ? fs.readFileSync(cssFilePath, 'utf8') : '';
141
+ const astralkitImports = imports.filter(i => i.includes('astralkit'));
142
+
143
+ // If Tailwind is already imported/directive'd in the file (v3 @tailwind
144
+ // directives OR v4 @import "tailwindcss"), insert astralkit imports AFTER
145
+ // the last Tailwind-related line. This preserves the recommended ordering
146
+ // (tailwindcss first, astralkit after) instead of prepending astralkit
147
+ // imports before tailwindcss in the file.
148
+ const tailwindImportRe = /^@import\s+["']tailwindcss["']/;
149
+ const hasTailwind = existing.includes('@tailwind utilities') || tailwindImportRe.test(existing);
150
+
151
+ if (hasTailwind && astralkitImports.length > 0) {
152
+ const lines = existing.split('\n');
153
+ let lastTailwindIdx = -1;
154
+ for (let i = 0; i < lines.length; i++) {
155
+ const trimmed = lines[i].trim();
156
+ if (trimmed.startsWith('@tailwind') || tailwindImportRe.test(trimmed)) {
157
+ lastTailwindIdx = i;
158
+ }
159
+ }
160
+ if (lastTailwindIdx >= 0) {
161
+ lines.splice(lastTailwindIdx + 1, 0, '', ...astralkitImports);
162
+ fs.writeFileSync(cssFilePath, lines.join('\n'));
163
+ return;
164
+ }
165
+ }
166
+
167
+ // Default: prepend everything (fresh file with no Tailwind yet)
168
+ fs.writeFileSync(cssFilePath, imports.join('\n') + '\n\n' + existing);
169
+ }
170
+
171
+ // ─── Legacy config file support ───────────────────────────
172
+ // Reads astralkit.config.json if it exists (from older init versions).
173
+ // New installs don't create this file.
174
+
175
+ export const CONFIG_FILENAME = 'astralkit.config.json';
176
+
177
+ export function getProjectConfig(dir = process.cwd()) {
178
+ const configPath = path.join(dir, CONFIG_FILENAME);
179
+ if (!fs.existsSync(configPath)) return null;
180
+ try {
181
+ return JSON.parse(fs.readFileSync(configPath, 'utf8'));
182
+ } catch { return null; }
183
+ }