@astralkit/cli 4.3.0 → 4.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,26 @@ 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.5.0] — 2026-07-04
9
+
10
+ ### Added
11
+ - **`append-unique-block` merge strategy.** Boosters can now append a marker-guarded text block to a file the user owns, creating it if absent. Built for Prisma model additions (`prisma/schema.prisma`) and `.env.example` variable appends. The block must contain the `idempotency_marker` (the CLI rejects the merge otherwise), so re-installs detect the previous append and skip. Shows the block (first 20 lines) and prompts before applying; files created fresh don't prompt.
12
+ - **Local registry mode for boosters (dev/QA).** Setting `ASTRALKIT_REGISTRY_DIR` to a local `registry-dev/` checkout serves `add <slug> --booster` and booster listings straight from disk — no API, no auth — so boosters can be QA'd before being pushed to the live registry. Components and workflows still require the API.
13
+
14
+ ### Compatibility
15
+ - Additive only. Boosters without `append-unique-block` merges behave exactly as before; older CLI versions report the new strategy as "unknown — skipped" and continue.
16
+
17
+ ## [4.4.0] — 2026-05-28
18
+
19
+ ### Added
20
+ - **Booster file-merge strategies.** Boosters can now declare a `merges` array in `booster.json` that the CLI applies after copying files. Two strategies are supported in this release:
21
+ - `wrap-jsx-children` — injects imports and wraps the children of a JSX anchor element (default `<body>`) with an opening/closing fragment. Used by Stack Auth boosters to wrap the user's existing `layout.tsx` with `<StackProvider><StackTheme>` without overwriting it. Shows the exact diff and prompts before applying (default Yes); skips silently if an idempotency marker is already present so re-installs are safe.
22
+ - `ensure-middleware` — creates `src/middleware.ts` if it doesn't exist; if it does and the booster's marker isn't found, prints explicit merge instructions instead of overwriting. Used by WorkOS boosters so they never blow away a user's existing middleware.
23
+ - Implementation lives in `src/lib/merges.js`; `addBooster` calls `applyMerges` after the dep-install prompt and before `post_install`.
24
+
25
+ ### Compatibility
26
+ - Additive only. Boosters without a `merges` array behave exactly as before. Older CLI versions ignore the `merges` field harmlessly — they fall back to whatever the booster's `post_install` documents.
27
+
8
28
  ## [4.3.0] — 2026-04-22
9
29
 
10
30
  ### Fixed
package/bin/index.js CHANGED
@@ -31,12 +31,12 @@ program
31
31
 
32
32
  // ─── init ────────────────────────────────────────────
33
33
  program
34
- .command('init')
35
- .description('Initialize AstralKit in your project')
34
+ .command('init [project-name]')
35
+ .description('Initialize AstralKit in your project, or scaffold a new project from the Starter Kit')
36
36
  .option('--api-key <key>', 'Your API key (from astralkit.com/account)')
37
37
  .option('--framework <framework>', 'Framework to use (auto-detected if omitted)')
38
38
  .option('--dir <directory>', 'Component output directory', 'src/components/ui')
39
- .action(initCommand);
39
+ .action((projectName, options) => initCommand({ ...options, projectName }));
40
40
 
41
41
  // ─── add ─────────────────────────────────────────────
42
42
  program
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astralkit/cli",
3
- "version": "4.3.0",
3
+ "version": "4.5.0",
4
4
  "description": "AstralKit CLI — Install and manage UI components in your project",
5
5
  "type": "module",
6
6
  "bin": {
@@ -2,7 +2,7 @@ import fs from 'fs';
2
2
  import path from 'path';
3
3
  import pc from 'picocolors';
4
4
  import * as p from '@clack/prompts';
5
- import { getComponent, getBooster, getWorkflow, listComponents, listBoosters, listWorkflows } from '../lib/api.js';
5
+ import { getComponent, getBooster, getWorkflow, listComponents, listBoosters, listWorkflows, LOCAL_REGISTRY_DIR } from '../lib/api.js';
6
6
  import {
7
7
  detectFramework,
8
8
  detectTypeScript,
@@ -13,6 +13,7 @@ import {
13
13
  import { validateSlug, validateFramework, isSafePath, writeFiles, isSafeInstallDir, filterSafePackages, sanitizeForTerminal } from '../lib/validators.js';
14
14
  import { detectPackageManager, getRunCommand, runInstall } from '../lib/pkg-manager.js';
15
15
  import { saveApiKey, getApiKey, getAuth } from '../lib/auth.js';
16
+ import { applyMerges } from '../lib/merges.js';
16
17
 
17
18
  const FRAMEWORK_LABELS = { nextjs: 'Next.js', react: 'React' };
18
19
 
@@ -25,7 +26,10 @@ export async function addCommand(nameOrSlug, options) {
25
26
  saveApiKey(options.apiKey);
26
27
  }
27
28
 
28
- if (!getApiKey()) {
29
+ // Local registry mode reads boosters from the developer's own disk — no
30
+ // account needed. Components/workflows still require auth (they hit the API).
31
+ const localBoosterInstall = LOCAL_REGISTRY_DIR && options.booster;
32
+ if (!getApiKey() && !localBoosterInstall) {
29
33
  const auth = getAuth();
30
34
  if (!auth.token) {
31
35
  p.log.warn('No API key found. Run ' + pc.cyan('astralkit init --api-key <key>') + ' first.');
@@ -535,7 +539,9 @@ async function addBooster(slug, options) {
535
539
  spinner.stop();
536
540
  console.log(pc.yellow('\nThese files already exist:'));
537
541
  conflicts.forEach(c => console.log(pc.gray(` ${c}`)));
538
- const overwrite = await p.confirm({ message: 'Overwrite existing files?', initialValue: false });
542
+ const overwrite = process.env.ASTRALKIT_YES === '1'
543
+ ? true
544
+ : await p.confirm({ message: 'Overwrite existing files?', initialValue: false });
539
545
  if (p.isCancel(overwrite) || !overwrite) return;
540
546
  }
541
547
  }
@@ -562,10 +568,12 @@ async function addBooster(slug, options) {
562
568
  }
563
569
  if (safeDeps.length > 0) {
564
570
  console.log();
565
- const install = await p.confirm({
566
- message: `Install dependencies? (${safeDeps.join(', ')})`,
567
- initialValue: true,
568
- });
571
+ const install = process.env.ASTRALKIT_YES === '1'
572
+ ? true
573
+ : await p.confirm({
574
+ message: `Install dependencies? (${safeDeps.join(', ')})`,
575
+ initialValue: true,
576
+ });
569
577
  if (!p.isCancel(install) && install) {
570
578
  const s = ora('Installing dependencies...').start();
571
579
  const result = await runInstall(pm, process.cwd(), safeDeps);
@@ -575,6 +583,34 @@ async function addBooster(slug, options) {
575
583
  }
576
584
  }
577
585
 
586
+ // Apply file-merge patches (e.g. wrap layout.tsx with a provider, ensure
587
+ // middleware.ts exists or print merge instructions). Runs after deps install
588
+ // so the wrapped file's imports resolve immediately on `npm run dev`.
589
+ if (Array.isArray(data.merges) && data.merges.length > 0) {
590
+ const mergeSummary = { created: [], modified: [], installed: [], alreadySatisfied: [], skipped: [] };
591
+ await applyMerges(data.merges, process.cwd(), mergeSummary);
592
+
593
+ // Surface what changed in the user's existing files. We don't reuse
594
+ // printInstallSummary here because the booster file list was already
595
+ // printed above; this is the focused "what we touched outside the
596
+ // install_paths" report.
597
+ if (mergeSummary.created.length || mergeSummary.modified.length || mergeSummary.skipped.length) {
598
+ console.log();
599
+ if (mergeSummary.created.length) {
600
+ console.log(pc.green(' Created:'));
601
+ for (const f of mergeSummary.created) console.log(pc.gray(` ${f}`));
602
+ }
603
+ if (mergeSummary.modified.length) {
604
+ console.log(pc.yellow(' Patched:'));
605
+ for (const m of mergeSummary.modified) console.log(pc.gray(` ${m.path} ${pc.dim(m.note)}`));
606
+ }
607
+ if (mergeSummary.skipped.length) {
608
+ console.log(pc.gray(' Merge skipped:'));
609
+ for (const k of mergeSummary.skipped) console.log(pc.gray(` ${k.what} ${pc.dim(`(${k.reason})`)}`));
610
+ }
611
+ }
612
+ }
613
+
578
614
  if (data.dependencies?.env?.length) {
579
615
  console.log();
580
616
  p.log.warn('Add these to your .env:');
@@ -15,10 +15,15 @@ import {
15
15
  import { getAiRulesContent } from '../lib/ai-rules.js';
16
16
  import { saveApiKey, getApiKey } from '../lib/auth.js';
17
17
  import { detectPackageManager, runInstall } from '../lib/pkg-manager.js';
18
+ import { getStarterKit } from '../lib/api.js';
18
19
 
19
20
  const FRAMEWORK_LABELS = { nextjs: 'Next.js', react: 'React' };
20
21
 
21
22
  export async function initCommand(options) {
23
+ if (options.projectName) {
24
+ return scaffoldCommand(options);
25
+ }
26
+
22
27
  p.intro(pc.bgBlue(pc.white(' AstralKit Setup ')));
23
28
 
24
29
  // ─── Step 1: API Key ─────────────────────────────────
@@ -197,3 +202,122 @@ export async function initCommand(options) {
197
202
  console.log(pc.gray(' Browse all: '), pc.cyan('astralkit list'));
198
203
  console.log();
199
204
  }
205
+
206
+ async function scaffoldCommand(options) {
207
+ const projectName = options.projectName;
208
+ p.intro(pc.bgBlue(pc.white(' AstralKit Starter Kit ')));
209
+
210
+ // Validate project name
211
+ if (!/^[a-zA-Z0-9_-]+$/.test(projectName)) {
212
+ p.cancel(pc.red('Project name can only contain letters, numbers, hyphens, and underscores.'));
213
+ process.exit(1);
214
+ }
215
+
216
+ const targetDir = path.resolve(process.cwd(), projectName);
217
+ if (fs.existsSync(targetDir)) {
218
+ p.cancel(pc.red(`Directory "${projectName}" already exists.`));
219
+ process.exit(1);
220
+ }
221
+
222
+ // API key is required for downloading the starter kit
223
+ let apiKey = options.apiKey || getApiKey();
224
+
225
+ if (options.apiKey) {
226
+ if (!options.apiKey.startsWith('ak_')) {
227
+ p.cancel(pc.red('Invalid API key format. Keys start with ak_'));
228
+ console.log(pc.gray('Get your key at ') + pc.cyan('https://astralkit.com/account'));
229
+ process.exit(1);
230
+ }
231
+ saveApiKey(options.apiKey);
232
+ p.log.success('API key saved');
233
+ } else if (!apiKey) {
234
+ p.log.warn('An API key is required to download the Starter Kit.');
235
+ console.log();
236
+ console.log(pc.gray(' Get your free API key at: ') + pc.cyan('https://astralkit.com/account'));
237
+ console.log();
238
+
239
+ const keyInput = await p.text({
240
+ message: 'Paste your API key:',
241
+ placeholder: 'ak_...',
242
+ validate(val) {
243
+ if (!val) return 'API key is required for the Starter Kit';
244
+ if (!val.startsWith('ak_')) return 'Keys start with ak_ — check astralkit.com/account';
245
+ },
246
+ });
247
+
248
+ if (p.isCancel(keyInput)) {
249
+ p.cancel('Setup cancelled.');
250
+ process.exit(0);
251
+ }
252
+
253
+ saveApiKey(keyInput);
254
+ apiKey = keyInput;
255
+ p.log.success('API key saved');
256
+ } else {
257
+ p.log.success('API key found');
258
+ }
259
+
260
+ // Download starter kit
261
+ const ora = (await import('ora')).default;
262
+ const spinner = ora('Downloading Starter Kit...').start();
263
+
264
+ let data;
265
+ try {
266
+ data = await getStarterKit();
267
+ } catch (err) {
268
+ spinner.fail('Failed to download Starter Kit.');
269
+ if (err.code === 'AUTH_REQUIRED') {
270
+ console.log(pc.gray(' Your API key may be invalid. Get a new one at ') + pc.cyan('https://astralkit.com/account'));
271
+ } else {
272
+ console.log(pc.gray(' ' + err.message));
273
+ }
274
+ process.exit(1);
275
+ }
276
+
277
+ if (!data.files || data.files.length === 0) {
278
+ spinner.fail('Starter Kit is empty or unavailable.');
279
+ process.exit(1);
280
+ }
281
+
282
+ spinner.succeed(`Downloaded ${data.files.length} files`);
283
+
284
+ // Write files to target directory
285
+ const writeSpinner = ora(`Creating ${pc.cyan(projectName)}/...`).start();
286
+
287
+ for (const file of data.files) {
288
+ const filePath = path.join(targetDir, file.path);
289
+ const dir = path.dirname(filePath);
290
+ if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
291
+ fs.writeFileSync(filePath, file.content, 'utf8');
292
+ }
293
+
294
+ writeSpinner.succeed(`Created ${pc.cyan(projectName)}/`);
295
+
296
+ // Install dependencies
297
+ const pm = detectPackageManager();
298
+ const installSpinner = ora(`Installing dependencies with ${pm}...`).start();
299
+
300
+ try {
301
+ const result = await runInstall(pm, targetDir, []);
302
+ if (result.success) {
303
+ installSpinner.succeed('Dependencies installed');
304
+ } else {
305
+ installSpinner.warn('Could not install dependencies automatically.');
306
+ console.log(pc.gray(` Run ${pm === 'npm' ? 'npm install' : pm + ' install'} manually in ${projectName}/`));
307
+ }
308
+ } catch {
309
+ installSpinner.warn('Could not install dependencies automatically.');
310
+ console.log(pc.gray(` Run ${pm === 'npm' ? 'npm install' : pm + ' install'} manually in ${projectName}/`));
311
+ }
312
+
313
+ p.outro(pc.green('Starter Kit is ready!'));
314
+
315
+ console.log();
316
+ console.log(pc.gray(' Get started:'));
317
+ console.log(pc.cyan(` cd ${projectName}`));
318
+ console.log(pc.cyan(` ${pm === 'npm' ? 'npm run' : pm} dev`));
319
+ console.log();
320
+ console.log(pc.gray(' Add a component:'), pc.cyan('astralkit add button-variants'));
321
+ console.log(pc.gray(' Browse all: '), pc.cyan('astralkit list'));
322
+ console.log();
323
+ }
@@ -22,28 +22,54 @@ export function getAiRulesContent() {
22
22
  function getEmbeddedRules() {
23
23
  return `# AstralKit — AI Coding Rules
24
24
 
25
- ## Component Usage
26
- - Import components from the components directory: \`import { Button } from '@/components/ui/button'\`
27
- - Use the \`cn()\` helper for conditional classes: \`import { cn } from '@/lib/utils'\`
28
- - All components use Tailwind CSS for styling
29
- - Components are built on top of Radix UI primitives where applicable
30
-
31
- ## Design Tokens
32
- - Use CSS variables for colors: \`var(--color-primary)\`
33
- - Spacing follows Tailwind's scale
34
- - All tokens are defined in \`astralkit/theme\`
35
-
36
- ## File Structure
25
+ ## Token-First Rule
26
+ ALWAYS use \`ak-*\` design tokens. NEVER use arbitrary bracket values or raw Tailwind defaults.
27
+
28
+ \`\`\`tsx
29
+ // CORRECT
30
+ <div className="p-ak-3 gap-ak-2 text-ak-base bg-ak-surface text-ak-text rounded-ak-lg">
31
+
32
+ // WRONG — arbitrary values silently collapse in Tailwind v4
33
+ <div className="p-[1.5rem] gap-4 text-base bg-gray-50 text-gray-900 rounded-lg">
34
+ \`\`\`
35
+
36
+ ## Semantic Colors
37
+ - Backgrounds: \`bg-ak-bg\`, \`bg-ak-surface\`, \`bg-ak-surface-2\`, \`bg-ak-hover\`
38
+ - Text: \`text-ak-text\`, \`text-ak-text-secondary\`, \`text-ak-text-muted\`
39
+ - Borders: \`border-ak-border\`, \`border-ak-border-subtle\`, \`border-ak-border-strong\`
40
+ - Primary: \`bg-ak-primary\`, \`text-ak-on-primary\`, \`bg-ak-primary-hover\`
41
+ - Status: \`bg-ak-success\`, \`bg-ak-danger\`, \`bg-ak-warning\`, \`bg-ak-info\` (+ \`-subtle\` variants)
42
+
43
+ ## Typography
44
+ - Use \`text-ak-*\` sizes: \`text-ak-xs\` (12px), \`text-ak-sm\` (14px), \`text-ak-base\` (16px), \`text-ak-lg\` (18px), \`text-ak-xl\` (20px), \`text-ak-2xl\` (24px), up to \`text-ak-10xl\`
45
+ - Fluid responsive: \`text-ak-fl-*\` (scales from 320px→1400px viewport, zero breakpoints)
46
+ - Display/hero: \`text-ak-display-*\` (dramatic scaling for marketing headings)
47
+ - Fonts: \`font-ak-sans\` (Inter), \`font-ak-serif\` (DM Serif Display), \`font-ak-mono\` (JetBrains Mono)
48
+
49
+ ## Spacing
50
+ Use \`ak-*\` spacing tokens: \`ak-0_5\` (4px), \`ak-1\` (8px), \`ak-1_5\` (12px), \`ak-2\` (16px), \`ak-3\` (24px), \`ak-4\` (32px), \`ak-6\` (48px), \`ak-8\` (64px)
51
+ - Fluid: \`ak-fl-xs\` through \`ak-fl-3xl\` (responsive, no breakpoints)
52
+ - Page margin: \`px-ak-fl-page-margin\` (16px mobile → 80px desktop)
53
+
54
+ ## Icons
55
+ Phosphor Icons ONLY (\`@phosphor-icons/react\`). Never inline SVGs or other icon libraries.
56
+
57
+ ## Components
58
+ - Install via CLI: \`astralkit add <component-name>\`
37
59
  - Components live in \`src/components/ui/\`
38
- - Boosters live in \`src/lib/<booster-name>/\` (core) and \`src/components/<booster-name>/\` (adapters)
39
- - Configuration is in \`astralkit.config.json\`
60
+ - Use \`cn()\` for conditional classes: \`import { cn } from '@/lib/utils'\`
40
61
 
41
- ## Adding Components
42
- - Use the CLI: \`astralkit add <component-name>\`
43
- - Never manually copy components — always use the CLI to get the latest version
62
+ ## Conventions
63
+ - No inline \`style={{}}\` — use Tailwind classes
64
+ - No shadows on panels/dropdowns — use borders
65
+ - No Framer Motion — use CSS animations
66
+ - 16px body floor + AAA contrast minimum
67
+ - All buttons/inputs: \`min-h-[3rem]\` touch target + \`cursor-pointer\`
68
+ - Dark mode: \`.dark\` class or \`data-theme="dark"\` on \`<html>\`
69
+ - Palettes: \`data-ak-theme="ocean-blue"\` (16 presets available)
70
+ - Density: \`data-ak-density="compact|spacious"\` on any container
44
71
 
45
- ## Pro Components
46
- - Run \`astralkit login\` to access Pro content
47
- - Pro components are marked with ✨ in the CLI output
72
+ ## For the full token reference
73
+ See \`.claude/CLAUDE.md\` if present, or visit https://astralkit.com/docs
48
74
  `;
49
75
  }
package/src/lib/api.js CHANGED
@@ -1,6 +1,7 @@
1
+ import fs from 'fs';
1
2
  import { createRequire } from 'module';
2
3
  import { fileURLToPath } from 'url';
3
- import { dirname, join } from 'path';
4
+ import { dirname, join, relative, resolve } from 'path';
4
5
  import { getAuth, getApiKey } from './auth.js';
5
6
 
6
7
  const __dirname = dirname(fileURLToPath(import.meta.url));
@@ -11,6 +12,16 @@ const CLI_VERSION = pkg.version;
11
12
  const DEFAULT_API_BASE = 'https://astralkit.com';
12
13
  const REQUEST_TIMEOUT_MS = 30_000;
13
14
 
15
+ /**
16
+ * Local registry mode (dev/QA only). When ASTRALKIT_REGISTRY_DIR points at a
17
+ * local registry-dev/ checkout, booster reads are served straight from disk
18
+ * instead of the live API — used to QA boosters before pushing them to the
19
+ * astral-kit/registry repo. Components and workflows still hit the API.
20
+ */
21
+ export const LOCAL_REGISTRY_DIR = process.env.ASTRALKIT_REGISTRY_DIR
22
+ ? resolve(process.env.ASTRALKIT_REGISTRY_DIR)
23
+ : null;
24
+
14
25
  export const API_BASE = (() => {
15
26
  const override = process.env.ASTRALKIT_API_URL;
16
27
  if (!override) return DEFAULT_API_BASE;
@@ -134,6 +145,7 @@ export async function getComponent(slug, framework = 'html') {
134
145
  }
135
146
 
136
147
  export async function listBoosters({ framework, search, pro, free } = {}) {
148
+ if (LOCAL_REGISTRY_DIR) return listLocalBoosters({ search });
137
149
  const params = new URLSearchParams();
138
150
  if (framework) params.set('framework', framework);
139
151
  if (pro) params.set('pro', 'true');
@@ -144,10 +156,61 @@ export async function listBoosters({ framework, search, pro, free } = {}) {
144
156
  }
145
157
 
146
158
  export async function getBooster(slug, framework = 'nextjs') {
159
+ if (LOCAL_REGISTRY_DIR) return getLocalBooster(slug, framework);
147
160
  const res = await apiRequest(`/api/cli/boosters/${encodeURIComponent(slug)}?framework=${encodeURIComponent(framework)}`);
148
161
  return res.json();
149
162
  }
150
163
 
164
+ // ─── Local registry implementations ──────────────────────────────────────────
165
+
166
+ function walkLocalFiles(root) {
167
+ if (!fs.existsSync(root)) return [];
168
+ const out = [];
169
+ const stack = [root];
170
+ while (stack.length > 0) {
171
+ const dir = stack.pop();
172
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
173
+ const full = join(dir, entry.name);
174
+ if (entry.isDirectory()) stack.push(full);
175
+ else out.push({
176
+ path: relative(root, full).split('\\').join('/'),
177
+ content: fs.readFileSync(full, 'utf8'),
178
+ });
179
+ }
180
+ }
181
+ return out;
182
+ }
183
+
184
+ function getLocalBooster(slug, framework) {
185
+ const boosterDir = join(LOCAL_REGISTRY_DIR, 'boosters', slug);
186
+ const manifestPath = join(boosterDir, 'booster.json');
187
+ if (!fs.existsSync(manifestPath)) {
188
+ const err = new Error(`Booster "${slug}" not found in local registry (${LOCAL_REGISTRY_DIR}).`);
189
+ err.code = 'API_ERROR';
190
+ throw err;
191
+ }
192
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
193
+ return {
194
+ ...manifest,
195
+ core_files: walkLocalFiles(join(boosterDir, 'core')),
196
+ adapter_files: walkLocalFiles(join(boosterDir, 'adapters', framework)),
197
+ };
198
+ }
199
+
200
+ function listLocalBoosters({ search } = {}) {
201
+ const boostersRoot = join(LOCAL_REGISTRY_DIR, 'boosters');
202
+ if (!fs.existsSync(boostersRoot)) return { boosters: [] };
203
+ const q = (search || '').toLowerCase();
204
+ const boosters = fs.readdirSync(boostersRoot, { withFileTypes: true })
205
+ .filter((e) => e.isDirectory() && fs.existsSync(join(boostersRoot, e.name, 'booster.json')))
206
+ .map((e) => JSON.parse(fs.readFileSync(join(boostersRoot, e.name, 'booster.json'), 'utf8')))
207
+ .filter((m) => !q ||
208
+ (m.slug || '').toLowerCase().includes(q) ||
209
+ (m.name || '').toLowerCase().includes(q) ||
210
+ (m.description || '').toLowerCase().includes(q));
211
+ return { boosters };
212
+ }
213
+
151
214
  export async function listWorkflows({ framework, search, pro, free } = {}) {
152
215
  const params = new URLSearchParams();
153
216
  if (framework) params.set('framework', framework);
@@ -162,3 +225,8 @@ export async function getWorkflow(slug, framework = 'nextjs') {
162
225
  const res = await apiRequest(`/api/cli/workflows/${encodeURIComponent(slug)}?framework=${encodeURIComponent(framework)}`);
163
226
  return res.json();
164
227
  }
228
+
229
+ export async function getStarterKit() {
230
+ const res = await apiRequest('/api/cli/starter-kit');
231
+ return res.json();
232
+ }
@@ -0,0 +1,310 @@
1
+ /**
2
+ * Booster Merge Strategies
3
+ * ────────────────────────
4
+ * Patches the CLI applies to files the user already owns. A booster declares
5
+ * these in its `merges` array (see BoosterJson.merges in src/lib/github-registry.ts).
6
+ *
7
+ * Strategies:
8
+ * - wrap-jsx-children — inject imports + wrap the children of a JSX anchor
9
+ * element (default <body>) with an opening/closing fragment. Used by Stack
10
+ * Auth and similar boosters to wrap layout.tsx with <Provider><Theme>.
11
+ *
12
+ * - ensure-middleware — create src/middleware.ts if it doesn't exist; if it
13
+ * does and the booster's marker isn't found, print explicit merge instructions
14
+ * instead of overwriting. Used by WorkOS-style middleware boosters.
15
+ *
16
+ * - append-unique-block — append a marker-guarded text block to a file the
17
+ * user owns (creating it if absent). Used for Prisma model additions
18
+ * (prisma/schema.prisma) and .env.example variable appends. The block MUST
19
+ * contain the idempotency_marker so re-installs detect it.
20
+ *
21
+ * Each strategy is idempotent: re-running an install detects the marker and skips.
22
+ */
23
+
24
+ import fs from 'fs';
25
+ import path from 'path';
26
+ import pc from 'picocolors';
27
+ import * as p from '@clack/prompts';
28
+ import { isSafePath, isSafeInstallDir } from './validators.js';
29
+
30
+ /**
31
+ * Confirm with the user, or auto-accept when ASTRALKIT_YES=1 (CI/QA runs where
32
+ * no TTY is attached). Returns true/false; never a cancel symbol.
33
+ */
34
+ async function confirmOrAuto(opts) {
35
+ if (process.env.ASTRALKIT_YES === '1') return true;
36
+ const answer = await p.confirm(opts);
37
+ return !p.isCancel(answer) && answer;
38
+ }
39
+
40
+ /**
41
+ * Entry point: walk the merges array and dispatch each to its strategy handler.
42
+ * Mutates `installSummary` so the end-of-install report reflects what changed.
43
+ */
44
+ export async function applyMerges(merges, projectRoot, installSummary) {
45
+ if (!Array.isArray(merges) || merges.length === 0) return;
46
+
47
+ for (const merge of merges) {
48
+ try {
49
+ if (merge.strategy === 'wrap-jsx-children') {
50
+ await applyWrapJsxChildren(merge, projectRoot, installSummary);
51
+ } else if (merge.strategy === 'ensure-middleware') {
52
+ await applyEnsureMiddleware(merge, projectRoot, installSummary);
53
+ } else if (merge.strategy === 'append-unique-block') {
54
+ await applyAppendUniqueBlock(merge, projectRoot, installSummary);
55
+ } else {
56
+ p.log.warn(`Unknown merge strategy "${merge.strategy}" — skipped`);
57
+ installSummary.skipped.push({
58
+ what: merge.target || merge.strategy,
59
+ reason: `unknown strategy: ${merge.strategy}`,
60
+ });
61
+ }
62
+ } catch (err) {
63
+ p.log.warn(`Merge failed for ${merge.target}: ${err.message || err}`);
64
+ installSummary.skipped.push({
65
+ what: merge.target,
66
+ reason: `merge error: ${err.message || err}`,
67
+ });
68
+ }
69
+ }
70
+ }
71
+
72
+ // ─── Strategy: wrap-jsx-children ──────────────────────────────────────────────
73
+
74
+ async function applyWrapJsxChildren(merge, projectRoot, installSummary) {
75
+ const { target, imports = [], open, close } = merge;
76
+ const anchor = merge.anchor || 'body';
77
+ const marker = merge.idempotency_marker || open;
78
+
79
+ if (!target || !open || !close) {
80
+ p.log.warn(`wrap-jsx-children merge is missing target/open/close — skipped`);
81
+ return;
82
+ }
83
+
84
+ if (!isSafeInstallDir(projectRoot, target)) {
85
+ p.log.warn(`Refusing merge: unsafe target path "${target}"`);
86
+ installSummary.skipped.push({ what: target, reason: 'unsafe target path' });
87
+ return;
88
+ }
89
+
90
+ const filePath = path.resolve(projectRoot, target);
91
+ if (!fs.existsSync(filePath)) {
92
+ p.log.warn(`Cannot wrap ${target} — file does not exist. Skipped.`);
93
+ p.log.info(`Manually add the booster's provider wrap to your layout.`);
94
+ installSummary.skipped.push({ what: target, reason: 'file not found' });
95
+ return;
96
+ }
97
+
98
+ const original = fs.readFileSync(filePath, 'utf8');
99
+
100
+ // Idempotency: marker already present → already wrapped.
101
+ if (original.includes(marker)) {
102
+ installSummary.skipped.push({ what: target, reason: 'already wrapped' });
103
+ return;
104
+ }
105
+
106
+ // Locate the anchor tags. We accept simple `<body>` or `<body className="...">`,
107
+ // including multi-line tags, but not nested same-name elements.
108
+ const openRe = new RegExp(`<${anchor}\\b[^>]*>`);
109
+ const closeRe = new RegExp(`</${anchor}>`);
110
+ const openMatch = original.match(openRe);
111
+ const closeMatch = original.match(closeRe);
112
+
113
+ if (!openMatch || !closeMatch) {
114
+ p.log.warn(`Could not locate <${anchor}> in ${target} — skipped.`);
115
+ p.log.info(`Manually wrap the contents of <${anchor}> with: ${open}…${close}`);
116
+ installSummary.skipped.push({
117
+ what: target,
118
+ reason: `no <${anchor}> element found`,
119
+ });
120
+ return;
121
+ }
122
+
123
+ const openEnd = openMatch.index + openMatch[0].length;
124
+ const closeStart = closeMatch.index;
125
+ if (closeStart <= openEnd) {
126
+ p.log.warn(`Malformed <${anchor}> in ${target} — skipped.`);
127
+ installSummary.skipped.push({ what: target, reason: 'malformed anchor element' });
128
+ return;
129
+ }
130
+
131
+ // Decide which imports need adding. We do not edit anything unless the user
132
+ // consents to the full diff, so we just calculate the missing set here.
133
+ const missingImports = imports.filter((line) => !original.includes(line));
134
+
135
+ // Compose the new file content.
136
+ const beforeOpen = original.slice(0, openEnd);
137
+ const inside = original.slice(openEnd, closeStart);
138
+ const afterClose = original.slice(closeStart);
139
+ const wrapped = `${beforeOpen}\n ${open}${inside}${close}\n ${afterClose}`;
140
+
141
+ // Insert missing imports after the last existing import (or at file head).
142
+ let withImports = wrapped;
143
+ if (missingImports.length > 0) {
144
+ const lines = wrapped.split('\n');
145
+ let lastImportIdx = -1;
146
+ for (let i = 0; i < lines.length; i++) {
147
+ if (lines[i].trim().startsWith('import ')) lastImportIdx = i;
148
+ }
149
+ if (lastImportIdx >= 0) {
150
+ lines.splice(lastImportIdx + 1, 0, ...missingImports);
151
+ } else {
152
+ lines.unshift(...missingImports, '');
153
+ }
154
+ withImports = lines.join('\n');
155
+ }
156
+
157
+ // Preview before applying — this file is heavily user-owned, so consent is required.
158
+ console.log();
159
+ p.log.step(`Booster wants to patch ${pc.cyan(target)}:`);
160
+ if (missingImports.length > 0) {
161
+ console.log(pc.gray(' Add imports:'));
162
+ for (const imp of missingImports) console.log(` ${pc.green('+')} ${imp}`);
163
+ }
164
+ console.log(pc.gray(` Wrap children of <${anchor}> with:`));
165
+ console.log(` ${pc.green('+')} ${open}…${close}`);
166
+
167
+ const proceed = await confirmOrAuto({
168
+ message: `Apply this patch to ${target}?`,
169
+ initialValue: true,
170
+ });
171
+
172
+ if (!proceed) {
173
+ p.log.info(`Skipped ${target}. Wrap manually with:`);
174
+ if (missingImports.length > 0) {
175
+ for (const imp of missingImports) console.log(pc.gray(` ${imp}`));
176
+ }
177
+ console.log(pc.gray(` Inside <${anchor}>: ${open} ... {children} ... ${close}`));
178
+ installSummary.skipped.push({ what: target, reason: 'user declined wrap' });
179
+ return;
180
+ }
181
+
182
+ fs.writeFileSync(filePath, withImports, 'utf8');
183
+ const noteParts = [];
184
+ if (missingImports.length > 0) noteParts.push(`+${missingImports.length} import${missingImports.length === 1 ? '' : 's'}`);
185
+ noteParts.push(`wrapped <${anchor}>`);
186
+ installSummary.modified.push({ path: target, note: noteParts.join(', ') });
187
+ p.log.success(`Patched ${pc.cyan(target)}`);
188
+ }
189
+
190
+ // ─── Strategy: append-unique-block ────────────────────────────────────────────
191
+
192
+ async function applyAppendUniqueBlock(merge, projectRoot, installSummary) {
193
+ const { target, block, idempotency_marker } = merge;
194
+
195
+ if (!target || !block || !idempotency_marker) {
196
+ p.log.warn(`append-unique-block merge is missing target/block/idempotency_marker — skipped`);
197
+ return;
198
+ }
199
+
200
+ // The marker must live inside the block itself, otherwise a re-install could
201
+ // never detect the previous append and would duplicate it.
202
+ if (!block.includes(idempotency_marker)) {
203
+ p.log.warn(`append-unique-block for ${target}: idempotency_marker not found inside block — skipped (authoring error)`);
204
+ installSummary.skipped.push({ what: target, reason: 'marker missing from block' });
205
+ return;
206
+ }
207
+
208
+ if (!isSafeInstallDir(projectRoot, target)) {
209
+ p.log.warn(`Refusing merge: unsafe target path "${target}"`);
210
+ installSummary.skipped.push({ what: target, reason: 'unsafe target path' });
211
+ return;
212
+ }
213
+
214
+ const filePath = path.resolve(projectRoot, target);
215
+
216
+ if (!fs.existsSync(filePath)) {
217
+ // Clean install — create the file with just the block.
218
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
219
+ fs.writeFileSync(filePath, block.endsWith('\n') ? block : `${block}\n`, 'utf8');
220
+ installSummary.created.push(target);
221
+ p.log.success(`Created ${pc.cyan(target)}`);
222
+ return;
223
+ }
224
+
225
+ const existing = fs.readFileSync(filePath, 'utf8');
226
+ if (existing.includes(idempotency_marker)) {
227
+ installSummary.skipped.push({ what: target, reason: 'already appended' });
228
+ return;
229
+ }
230
+
231
+ // Preview before applying — these files (prisma/schema.prisma, .env.example)
232
+ // are user-owned, so consent is required like the other patch strategies.
233
+ const blockLines = block.replace(/\n$/, '').split('\n');
234
+ const PREVIEW_MAX = 20;
235
+ console.log();
236
+ p.log.step(`Booster wants to append to ${pc.cyan(target)}:`);
237
+ for (const line of blockLines.slice(0, PREVIEW_MAX)) {
238
+ console.log(` ${pc.green('+')} ${line}`);
239
+ }
240
+ if (blockLines.length > PREVIEW_MAX) {
241
+ console.log(pc.gray(` … (+${blockLines.length - PREVIEW_MAX} more lines)`));
242
+ }
243
+
244
+ const proceed = await confirmOrAuto({
245
+ message: `Append ${blockLines.length} line${blockLines.length === 1 ? '' : 's'} to ${target}?`,
246
+ initialValue: true,
247
+ });
248
+
249
+ if (!proceed) {
250
+ p.log.info(`Skipped ${target}. Append the block manually (it is marker-guarded, shown above).`);
251
+ installSummary.skipped.push({ what: target, reason: 'user declined append' });
252
+ return;
253
+ }
254
+
255
+ const separator = existing.endsWith('\n') ? '\n' : '\n\n';
256
+ const appended = `${existing}${separator}${block}${block.endsWith('\n') ? '' : '\n'}`;
257
+ fs.writeFileSync(filePath, appended, 'utf8');
258
+ installSummary.modified.push({ path: target, note: `+${blockLines.length} lines appended` });
259
+ p.log.success(`Patched ${pc.cyan(target)}`);
260
+ }
261
+
262
+ // ─── Strategy: ensure-middleware ──────────────────────────────────────────────
263
+
264
+ async function applyEnsureMiddleware(merge, projectRoot, installSummary) {
265
+ const { target, content, idempotency_marker, merge_note } = merge;
266
+
267
+ if (!target || !content || !idempotency_marker) {
268
+ p.log.warn(`ensure-middleware merge is missing target/content/idempotency_marker — skipped`);
269
+ return;
270
+ }
271
+
272
+ if (!isSafeInstallDir(projectRoot, target)) {
273
+ p.log.warn(`Refusing merge: unsafe target path "${target}"`);
274
+ installSummary.skipped.push({ what: target, reason: 'unsafe target path' });
275
+ return;
276
+ }
277
+
278
+ const filePath = path.resolve(projectRoot, target);
279
+
280
+ if (!fs.existsSync(filePath)) {
281
+ // Clean install — just write it.
282
+ fs.mkdirSync(path.dirname(filePath), { recursive: true });
283
+ fs.writeFileSync(filePath, content, 'utf8');
284
+ installSummary.created.push(target);
285
+ p.log.success(`Created ${pc.cyan(target)}`);
286
+ return;
287
+ }
288
+
289
+ // Existing file. Idempotency check first.
290
+ const existing = fs.readFileSync(filePath, 'utf8');
291
+ if (existing.includes(idempotency_marker)) {
292
+ installSummary.skipped.push({ what: target, reason: 'already wired' });
293
+ return;
294
+ }
295
+
296
+ // Conflict: file exists but isn't wired. Print explicit instructions instead
297
+ // of attempting an automated merge — middleware shapes vary too much for a
298
+ // safe one-size-fits-all rewrite, and the cost of a broken edit here is high
299
+ // (every request goes through middleware).
300
+ console.log();
301
+ p.log.warn(`Cannot auto-update ${pc.cyan(target)} — file already exists and the booster's marker is missing.`);
302
+ console.log(pc.gray(' To finish wiring, do the following manually:'));
303
+ for (const line of String(merge_note).split('\n')) {
304
+ console.log(pc.gray(` ${line}`));
305
+ }
306
+ installSummary.skipped.push({
307
+ what: target,
308
+ reason: 'exists — manual merge required (see notes above)',
309
+ });
310
+ }