@astralkit/cli 4.3.0 → 4.6.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 +29 -0
- package/bin/index.js +4 -3
- package/package.json +10 -2
- package/src/commands/add.js +97 -22
- package/src/commands/init.js +124 -0
- package/src/commands/remove.js +4 -2
- package/src/commands/update.js +3 -2
- package/src/lib/ai-rules.js +46 -20
- package/src/lib/api.js +85 -1
- package/src/lib/ask.js +76 -0
- package/src/lib/merges.js +311 -0
- package/src/lib/validators.js +26 -2
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,35 @@ 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.6.0] — 2026-08-22
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
- **Non-interactive mode.** Every prompt now degrades to a sensible default when stdin/stdout is not a TTY (AI-agent shells, CI, piped invocations) instead of crashing with `uv_tty_init EBADF` mid-install and leaving a partial install (component written, dependencies missing). New `-y`/`--yes` flag and the existing `ASTRALKIT_YES=1` env accept all defaults explicitly. Auto-answered prompts are logged (`message → choice (non-interactive)`). Destructive choices stay fail-safe: overwrite/remove default to NO without explicit consent (`--overwrite`, `--force`, `--yes`, or a TTY answer); dependency installs and required side-effect imports default to YES so the installed component actually builds and renders.
|
|
12
|
+
- **Import-scan dependency safety net.** `add` now scans the fetched component source for bare package imports and installs any missing from the registry's `dependencies` metadata (found live: kanban-01 imports three `@dnd-kit` packages, metadata listed one). Scoped to JS-family files; package names still pass the same `filterSafePackages` validation.
|
|
13
|
+
|
|
14
|
+
### Fixed
|
|
15
|
+
- The `@phosphor-icons/web` conflict prompt no longer crashes agent shells; non-interactive default is to install it (a written component with `ph ph-*` classes must render).
|
|
16
|
+
|
|
17
|
+
## [4.5.0] — 2026-07-04
|
|
18
|
+
|
|
19
|
+
### Added
|
|
20
|
+
- **`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.
|
|
21
|
+
- **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.
|
|
22
|
+
|
|
23
|
+
### Compatibility
|
|
24
|
+
- Additive only. Boosters without `append-unique-block` merges behave exactly as before; older CLI versions report the new strategy as "unknown — skipped" and continue.
|
|
25
|
+
|
|
26
|
+
## [4.4.0] — 2026-05-28
|
|
27
|
+
|
|
28
|
+
### Added
|
|
29
|
+
- **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:
|
|
30
|
+
- `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.
|
|
31
|
+
- `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.
|
|
32
|
+
- Implementation lives in `src/lib/merges.js`; `addBooster` calls `applyMerges` after the dep-install prompt and before `post_install`.
|
|
33
|
+
|
|
34
|
+
### Compatibility
|
|
35
|
+
- 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.
|
|
36
|
+
|
|
8
37
|
## [4.3.0] — 2026-04-22
|
|
9
38
|
|
|
10
39
|
### 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
|
|
@@ -50,6 +50,7 @@ program
|
|
|
50
50
|
.option('--workflow', 'Scaffold a workflow (complete app template)')
|
|
51
51
|
.option('--overlay', 'Merge workflow into current project')
|
|
52
52
|
.option('--dry-run', 'Preview what will be installed without writing files', false)
|
|
53
|
+
.option('-y, --yes', 'Accept all prompts with their defaults (also implied when no TTY is attached — agent/CI shells)', false)
|
|
53
54
|
.action(addCommand);
|
|
54
55
|
|
|
55
56
|
// ─── remove ──────────────────────────────────────────
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@astralkit/cli",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.6.0",
|
|
4
4
|
"description": "AstralKit CLI — Install and manage UI components in your project",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -15,7 +15,15 @@
|
|
|
15
15
|
"engines": {
|
|
16
16
|
"node": ">=18.0.0"
|
|
17
17
|
},
|
|
18
|
-
"keywords": [
|
|
18
|
+
"keywords": [
|
|
19
|
+
"astralkit",
|
|
20
|
+
"ui",
|
|
21
|
+
"components",
|
|
22
|
+
"tailwind",
|
|
23
|
+
"cli",
|
|
24
|
+
"react",
|
|
25
|
+
"nextjs"
|
|
26
|
+
],
|
|
19
27
|
"homepage": "https://astralkit.com",
|
|
20
28
|
"repository": {
|
|
21
29
|
"type": "git",
|
package/src/commands/add.js
CHANGED
|
@@ -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,10 +13,13 @@ 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';
|
|
17
|
+
import { setAssumeYes, confirm as askConfirm, select as askSelect, text as askText } from '../lib/ask.js';
|
|
16
18
|
|
|
17
19
|
const FRAMEWORK_LABELS = { nextjs: 'Next.js', react: 'React' };
|
|
18
20
|
|
|
19
21
|
export async function addCommand(nameOrSlug, options) {
|
|
22
|
+
setAssumeYes(options.yes);
|
|
20
23
|
if (options.apiKey) {
|
|
21
24
|
if (!options.apiKey.startsWith('ak_')) {
|
|
22
25
|
console.log(pc.red('Invalid API key format. Keys start with ak_'));
|
|
@@ -25,7 +28,10 @@ export async function addCommand(nameOrSlug, options) {
|
|
|
25
28
|
saveApiKey(options.apiKey);
|
|
26
29
|
}
|
|
27
30
|
|
|
28
|
-
|
|
31
|
+
// Local registry mode reads boosters/workflows from the developer's own
|
|
32
|
+
// disk — no account needed. Components still require auth (they hit the API).
|
|
33
|
+
const localBoosterInstall = LOCAL_REGISTRY_DIR && (options.booster || options.workflow);
|
|
34
|
+
if (!getApiKey() && !localBoosterInstall) {
|
|
29
35
|
const auth = getAuth();
|
|
30
36
|
if (!auth.token) {
|
|
31
37
|
p.log.warn('No API key found. Run ' + pc.cyan('astralkit init --api-key <key>') + ' first.');
|
|
@@ -105,13 +111,16 @@ export async function addCommand(nameOrSlug, options) {
|
|
|
105
111
|
return addComponent(nameOrSlug, options);
|
|
106
112
|
}
|
|
107
113
|
|
|
108
|
-
// Found in multiple registries — prompt user to choose
|
|
109
|
-
|
|
114
|
+
// Found in multiple registries — prompt user to choose (non-interactive:
|
|
115
|
+
// prefer the component, the most common install target).
|
|
116
|
+
const componentMatch = matches.find(m => m.type === 'component');
|
|
117
|
+
const choice = await askSelect({
|
|
110
118
|
message: `"${nameOrSlug}" found in multiple registries. What would you like to install?`,
|
|
111
119
|
options: matches.map(m => ({
|
|
112
120
|
value: m.type,
|
|
113
121
|
label: `${m.name} (${m.type === 'component' ? 'UI component' : m.type === 'booster' ? 'feature module' : 'app scaffold'})`,
|
|
114
122
|
})),
|
|
123
|
+
nonInteractive: componentMatch ? 'component' : matches[0].type,
|
|
115
124
|
});
|
|
116
125
|
|
|
117
126
|
if (p.isCancel(choice)) { p.cancel('Cancelled.'); process.exit(0); }
|
|
@@ -273,11 +282,15 @@ async function addComponent(componentSlug, options) {
|
|
|
273
282
|
p.log.warn(`Your project already uses ${pc.cyan('@phosphor-icons/react')} (React components) — a ${pc.bold('separate package')} from the same vendor.`);
|
|
274
283
|
p.log.warn(`Installing both ships two icon systems side by side.`);
|
|
275
284
|
|
|
276
|
-
|
|
285
|
+
// Non-interactive default is YES: the component file is already written
|
|
286
|
+
// with `ph ph-*` classes — skipping the package ships broken icons,
|
|
287
|
+
// which is worse than the two-icon-systems consistency tax.
|
|
288
|
+
const proceed = await askConfirm({
|
|
277
289
|
message: 'Install @phosphor-icons/web anyway?',
|
|
278
290
|
initialValue: false,
|
|
291
|
+
nonInteractive: true,
|
|
279
292
|
});
|
|
280
|
-
if (
|
|
293
|
+
if (!proceed) {
|
|
281
294
|
p.log.info('Skipping @phosphor-icons/web and the layout.tsx import.');
|
|
282
295
|
p.log.info(pc.gray('Adapt the component\'s <i className="ph ph-*"> tags to @phosphor-icons/react React components.'));
|
|
283
296
|
usesPhosphorCss = false;
|
|
@@ -289,10 +302,30 @@ async function addComponent(componentSlug, options) {
|
|
|
289
302
|
}
|
|
290
303
|
}
|
|
291
304
|
|
|
292
|
-
|
|
305
|
+
// The registry's `dependencies` metadata can lag behind the code (found
|
|
306
|
+
// live: kanban-01 imports three @dnd-kit packages, metadata listed one).
|
|
307
|
+
// Scan the actual source for bare package imports so a metadata gap never
|
|
308
|
+
// ships a component that doesn't build.
|
|
309
|
+
const importedPackages = new Set();
|
|
310
|
+
const jsCode = (data.files || [])
|
|
311
|
+
.filter(f => /\.(tsx?|jsx?|mjs|cjs)$/.test(f.path))
|
|
312
|
+
.map(f => f.content).join('\n');
|
|
313
|
+
for (const m of jsCode.matchAll(/(?:from|import)\s*\(?\s*['"]((?:@[a-z0-9~][\w.~-]*\/)?[a-z0-9~][\w.~-]*)(?:\/[^'"]*)?['"]/g)) {
|
|
314
|
+
importedPackages.add(m[1]);
|
|
315
|
+
}
|
|
316
|
+
// Packages the host/framework already accounts for.
|
|
317
|
+
for (const skip of ['react', 'react-dom', 'next', 'astralkit', 'clsx', 'tailwind-merge']) {
|
|
318
|
+
importedPackages.delete(skip);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
if (data.dependencies?.length || usesPhosphorCss || importedPackages.size > 0) {
|
|
293
322
|
const pm = detectPackageManager();
|
|
294
323
|
const rawDepList = (data.dependencies || []).filter(d => d !== 'astralkit' && d !== 'clsx' && d !== 'tailwind-merge');
|
|
295
324
|
|
|
325
|
+
for (const pkg of importedPackages) {
|
|
326
|
+
if (!rawDepList.includes(pkg)) rawDepList.push(pkg);
|
|
327
|
+
}
|
|
328
|
+
|
|
296
329
|
// Auto-add @phosphor-icons/web if component uses CSS-based Phosphor icons
|
|
297
330
|
// AND we didn't skip it above due to a @phosphor-icons/react conflict.
|
|
298
331
|
if (usesPhosphorCss && !rawDepList.includes('@phosphor-icons/web')) {
|
|
@@ -317,11 +350,12 @@ async function addComponent(componentSlug, options) {
|
|
|
317
350
|
|
|
318
351
|
if (toInstall.length > 0) {
|
|
319
352
|
// Always ask before running npm install — mirrors the booster flow.
|
|
320
|
-
|
|
353
|
+
// (Non-interactive: yes — a component without its deps doesn't build.)
|
|
354
|
+
const install = await askConfirm({
|
|
321
355
|
message: `Install dependencies? (${toInstall.join(', ')})`,
|
|
322
356
|
initialValue: true,
|
|
323
357
|
});
|
|
324
|
-
if (
|
|
358
|
+
if (install) {
|
|
325
359
|
const s = ora(`Installing ${toInstall.join(', ')}...`).start();
|
|
326
360
|
const result = await runInstall(pm, process.cwd(), toInstall);
|
|
327
361
|
if (result.success) {
|
|
@@ -389,12 +423,16 @@ async function addComponent(componentSlug, options) {
|
|
|
389
423
|
console.log(pc.gray(` ${layoutFile.relative}`));
|
|
390
424
|
for (const imp of missing) console.log(` ${pc.green('+')} ${imp}`);
|
|
391
425
|
|
|
392
|
-
|
|
426
|
+
// Non-interactive default is YES: the exact diff is printed above (never
|
|
427
|
+
// silent — the 2026-04-22 trust rule), and skipping it ships a component
|
|
428
|
+
// whose icons don't render.
|
|
429
|
+
const proceed = await askConfirm({
|
|
393
430
|
message: `Add these imports to ${layoutFile.relative}?`,
|
|
394
431
|
initialValue: false,
|
|
432
|
+
nonInteractive: true,
|
|
395
433
|
});
|
|
396
434
|
|
|
397
|
-
if (
|
|
435
|
+
if (!proceed) {
|
|
398
436
|
p.log.info(`Skipped ${layoutFile.relative} edit. Add these lines manually to enable icons:`);
|
|
399
437
|
for (const imp of missing) console.log(pc.gray(` ${imp}`));
|
|
400
438
|
installSummary.skipped.push({
|
|
@@ -535,8 +573,12 @@ async function addBooster(slug, options) {
|
|
|
535
573
|
spinner.stop();
|
|
536
574
|
console.log(pc.yellow('\nThese files already exist:'));
|
|
537
575
|
conflicts.forEach(c => console.log(pc.gray(` ${c}`)));
|
|
538
|
-
|
|
539
|
-
|
|
576
|
+
// Overwrite stays fail-safe when non-interactive WITHOUT --yes/env:
|
|
577
|
+
// destroying user files needs explicit consent (--overwrite, --yes, or a TTY answer).
|
|
578
|
+
const overwrite = process.env.ASTRALKIT_YES === '1'
|
|
579
|
+
? true
|
|
580
|
+
: await askConfirm({ message: 'Overwrite existing files?', initialValue: false });
|
|
581
|
+
if (!overwrite) return;
|
|
540
582
|
}
|
|
541
583
|
}
|
|
542
584
|
|
|
@@ -562,11 +604,11 @@ async function addBooster(slug, options) {
|
|
|
562
604
|
}
|
|
563
605
|
if (safeDeps.length > 0) {
|
|
564
606
|
console.log();
|
|
565
|
-
const install = await
|
|
607
|
+
const install = await askConfirm({
|
|
566
608
|
message: `Install dependencies? (${safeDeps.join(', ')})`,
|
|
567
609
|
initialValue: true,
|
|
568
610
|
});
|
|
569
|
-
if (
|
|
611
|
+
if (install) {
|
|
570
612
|
const s = ora('Installing dependencies...').start();
|
|
571
613
|
const result = await runInstall(pm, process.cwd(), safeDeps);
|
|
572
614
|
if (result.success) s.succeed('Dependencies installed');
|
|
@@ -575,6 +617,34 @@ async function addBooster(slug, options) {
|
|
|
575
617
|
}
|
|
576
618
|
}
|
|
577
619
|
|
|
620
|
+
// Apply file-merge patches (e.g. wrap layout.tsx with a provider, ensure
|
|
621
|
+
// middleware.ts exists or print merge instructions). Runs after deps install
|
|
622
|
+
// so the wrapped file's imports resolve immediately on `npm run dev`.
|
|
623
|
+
if (Array.isArray(data.merges) && data.merges.length > 0) {
|
|
624
|
+
const mergeSummary = { created: [], modified: [], installed: [], alreadySatisfied: [], skipped: [] };
|
|
625
|
+
await applyMerges(data.merges, process.cwd(), mergeSummary);
|
|
626
|
+
|
|
627
|
+
// Surface what changed in the user's existing files. We don't reuse
|
|
628
|
+
// printInstallSummary here because the booster file list was already
|
|
629
|
+
// printed above; this is the focused "what we touched outside the
|
|
630
|
+
// install_paths" report.
|
|
631
|
+
if (mergeSummary.created.length || mergeSummary.modified.length || mergeSummary.skipped.length) {
|
|
632
|
+
console.log();
|
|
633
|
+
if (mergeSummary.created.length) {
|
|
634
|
+
console.log(pc.green(' Created:'));
|
|
635
|
+
for (const f of mergeSummary.created) console.log(pc.gray(` ${f}`));
|
|
636
|
+
}
|
|
637
|
+
if (mergeSummary.modified.length) {
|
|
638
|
+
console.log(pc.yellow(' Patched:'));
|
|
639
|
+
for (const m of mergeSummary.modified) console.log(pc.gray(` ${m.path} ${pc.dim(m.note)}`));
|
|
640
|
+
}
|
|
641
|
+
if (mergeSummary.skipped.length) {
|
|
642
|
+
console.log(pc.gray(' Merge skipped:'));
|
|
643
|
+
for (const k of mergeSummary.skipped) console.log(pc.gray(` ${k.what} ${pc.dim(`(${k.reason})`)}`));
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
}
|
|
647
|
+
|
|
578
648
|
if (data.dependencies?.env?.length) {
|
|
579
649
|
console.log();
|
|
580
650
|
p.log.warn('Add these to your .env:');
|
|
@@ -616,17 +686,20 @@ async function addWorkflow(slug, options) {
|
|
|
616
686
|
|
|
617
687
|
if (fs.existsSync(path.resolve(process.cwd(), dirName)) && !options.overwrite) {
|
|
618
688
|
spinner.stop();
|
|
619
|
-
|
|
689
|
+
// Non-interactive: cancel — scaffolding over an existing directory
|
|
690
|
+
// needs explicit consent (--overwrite or a TTY answer).
|
|
691
|
+
const action = await askSelect({
|
|
620
692
|
message: `Directory "${dirName}/" already exists.`,
|
|
621
693
|
options: [
|
|
622
694
|
{ label: 'Overwrite it', value: 'overwrite' },
|
|
623
695
|
{ label: 'Use a different name', value: 'rename' },
|
|
624
696
|
{ label: 'Cancel', value: 'cancel' },
|
|
625
697
|
],
|
|
698
|
+
nonInteractive: 'cancel',
|
|
626
699
|
});
|
|
627
700
|
if (p.isCancel(action) || action === 'cancel') return;
|
|
628
701
|
if (action === 'rename') {
|
|
629
|
-
const newDir = await
|
|
702
|
+
const newDir = await askText({ message: 'Enter a directory name:', placeholder: `${slug}-app` });
|
|
630
703
|
if (p.isCancel(newDir)) return;
|
|
631
704
|
dirName = newDir;
|
|
632
705
|
}
|
|
@@ -641,8 +714,8 @@ async function addWorkflow(slug, options) {
|
|
|
641
714
|
console.log(pc.yellow(`${conflicts.length} file(s) would be overwritten:`));
|
|
642
715
|
conflicts.slice(0, 10).forEach(c => console.log(pc.gray(` ${c}`)));
|
|
643
716
|
if (conflicts.length > 10) console.log(pc.gray(` ... and ${conflicts.length - 10} more`));
|
|
644
|
-
const overwrite = await
|
|
645
|
-
if (
|
|
717
|
+
const overwrite = await askConfirm({ message: 'Overwrite these files?', initialValue: false });
|
|
718
|
+
if (!overwrite) return;
|
|
646
719
|
}
|
|
647
720
|
}
|
|
648
721
|
|
|
@@ -658,7 +731,9 @@ async function addWorkflow(slug, options) {
|
|
|
658
731
|
}
|
|
659
732
|
|
|
660
733
|
const pm = detectPackageManager(options.overlay ? process.cwd() : targetDir);
|
|
661
|
-
|
|
734
|
+
// Fresh-directory scaffolds legitimately ship package.json/next.config/
|
|
735
|
+
// .gitignore; overlay installs into an existing project stay strict.
|
|
736
|
+
const fileCount = writeFiles(targetDir, data.files, { scaffold: !options.overlay });
|
|
662
737
|
const label = options.overlay ? './' : `${path.basename(targetDir)}/`;
|
|
663
738
|
|
|
664
739
|
spinner.succeed(`Scaffolded workflow ${pc.cyan(data.name || slug)} in ${label}`);
|
|
@@ -666,8 +741,8 @@ async function addWorkflow(slug, options) {
|
|
|
666
741
|
|
|
667
742
|
if (!options.overlay) {
|
|
668
743
|
console.log();
|
|
669
|
-
const install = await
|
|
670
|
-
if (
|
|
744
|
+
const install = await askConfirm({ message: `Install dependencies with ${pm}?`, initialValue: true });
|
|
745
|
+
if (install) {
|
|
671
746
|
const s = ora(`Installing with ${pm}...`).start();
|
|
672
747
|
const result = await runInstall(pm, targetDir);
|
|
673
748
|
if (result.success) s.succeed('Dependencies installed');
|
package/src/commands/init.js
CHANGED
|
@@ -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
|
+
}
|
package/src/commands/remove.js
CHANGED
|
@@ -4,6 +4,7 @@ import pc from 'picocolors';
|
|
|
4
4
|
import * as p from '@clack/prompts';
|
|
5
5
|
import { getProjectConfig, detectFramework } from '../lib/config.js';
|
|
6
6
|
import { validateSlug } from '../lib/validators.js';
|
|
7
|
+
import { confirm as askConfirm } from '../lib/ask.js';
|
|
7
8
|
|
|
8
9
|
export async function removeCommand(name, options) {
|
|
9
10
|
// Reject anything that isn't a simple slug. Prevents `astralkit remove ../..`
|
|
@@ -49,11 +50,12 @@ export async function removeCommand(name, options) {
|
|
|
49
50
|
console.log();
|
|
50
51
|
|
|
51
52
|
if (!options.force) {
|
|
52
|
-
|
|
53
|
+
// Non-interactive: cancel — deleting files needs explicit consent (--force or a TTY answer).
|
|
54
|
+
const confirm = await askConfirm({
|
|
53
55
|
message: `Remove ${found.length} item(s)?`,
|
|
54
56
|
initialValue: false,
|
|
55
57
|
});
|
|
56
|
-
if (
|
|
58
|
+
if (!confirm) {
|
|
57
59
|
p.cancel('Cancelled.');
|
|
58
60
|
return;
|
|
59
61
|
}
|
package/src/commands/update.js
CHANGED
|
@@ -5,6 +5,7 @@ import * as p from '@clack/prompts';
|
|
|
5
5
|
import { getComponent } from '../lib/api.js';
|
|
6
6
|
import { getProjectConfig, detectFramework } from '../lib/config.js';
|
|
7
7
|
import { isSafePath } from '../lib/validators.js';
|
|
8
|
+
import { confirm as askConfirm } from '../lib/ask.js';
|
|
8
9
|
|
|
9
10
|
export async function updateCommand(componentSlug, options) {
|
|
10
11
|
const ora = (await import('ora')).default;
|
|
@@ -57,11 +58,11 @@ export async function updateCommand(componentSlug, options) {
|
|
|
57
58
|
console.log();
|
|
58
59
|
|
|
59
60
|
if (!options.force) {
|
|
60
|
-
const confirm = await
|
|
61
|
+
const confirm = await askConfirm({
|
|
61
62
|
message: `Update ${pc.cyan(componentSlug)}?`,
|
|
62
63
|
initialValue: true,
|
|
63
64
|
});
|
|
64
|
-
if (
|
|
65
|
+
if (!confirm) {
|
|
65
66
|
p.cancel('Cancelled.');
|
|
66
67
|
return;
|
|
67
68
|
}
|
package/src/lib/ai-rules.js
CHANGED
|
@@ -22,28 +22,54 @@ export function getAiRulesContent() {
|
|
|
22
22
|
function getEmbeddedRules() {
|
|
23
23
|
return `# AstralKit — AI Coding Rules
|
|
24
24
|
|
|
25
|
-
##
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
##
|
|
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
|
-
-
|
|
39
|
-
- Configuration is in \`astralkit.config.json\`
|
|
60
|
+
- Use \`cn()\` for conditional classes: \`import { cn } from '@/lib/utils'\`
|
|
40
61
|
|
|
41
|
-
##
|
|
42
|
-
-
|
|
43
|
-
-
|
|
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
|
-
##
|
|
46
|
-
|
|
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 listLocalRegistryItems('boosters', { search });
|
|
137
149
|
const params = new URLSearchParams();
|
|
138
150
|
if (framework) params.set('framework', framework);
|
|
139
151
|
if (pro) params.set('pro', 'true');
|
|
@@ -144,11 +156,50 @@ 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
|
+
|
|
151
201
|
export async function listWorkflows({ framework, search, pro, free } = {}) {
|
|
202
|
+
if (LOCAL_REGISTRY_DIR) return listLocalRegistryItems('workflows', { search });
|
|
152
203
|
const params = new URLSearchParams();
|
|
153
204
|
if (framework) params.set('framework', framework);
|
|
154
205
|
if (pro) params.set('pro', 'true');
|
|
@@ -159,6 +210,39 @@ export async function listWorkflows({ framework, search, pro, free } = {}) {
|
|
|
159
210
|
}
|
|
160
211
|
|
|
161
212
|
export async function getWorkflow(slug, framework = 'nextjs') {
|
|
213
|
+
if (LOCAL_REGISTRY_DIR) return getLocalWorkflow(slug, framework);
|
|
162
214
|
const res = await apiRequest(`/api/cli/workflows/${encodeURIComponent(slug)}?framework=${encodeURIComponent(framework)}`);
|
|
163
215
|
return res.json();
|
|
164
216
|
}
|
|
217
|
+
|
|
218
|
+
function getLocalWorkflow(slug, framework) {
|
|
219
|
+
const workflowDir = join(LOCAL_REGISTRY_DIR, 'workflows', slug);
|
|
220
|
+
const manifestPath = join(workflowDir, 'workflow.json');
|
|
221
|
+
if (!fs.existsSync(manifestPath)) {
|
|
222
|
+
const err = new Error(`Workflow "${slug}" not found in local registry (${LOCAL_REGISTRY_DIR}).`);
|
|
223
|
+
err.code = 'API_ERROR';
|
|
224
|
+
throw err;
|
|
225
|
+
}
|
|
226
|
+
const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
|
|
227
|
+
return { ...manifest, files: walkLocalFiles(join(workflowDir, framework)) };
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
function listLocalRegistryItems(type, { search } = {}) {
|
|
231
|
+
const root = join(LOCAL_REGISTRY_DIR, type);
|
|
232
|
+
const manifestName = type === 'workflows' ? 'workflow.json' : 'booster.json';
|
|
233
|
+
if (!fs.existsSync(root)) return { [type]: [] };
|
|
234
|
+
const q = (search || '').toLowerCase();
|
|
235
|
+
const items = fs.readdirSync(root, { withFileTypes: true })
|
|
236
|
+
.filter((e) => e.isDirectory() && fs.existsSync(join(root, e.name, manifestName)))
|
|
237
|
+
.map((e) => JSON.parse(fs.readFileSync(join(root, e.name, manifestName), 'utf8')))
|
|
238
|
+
.filter((m) => !q ||
|
|
239
|
+
(m.slug || '').toLowerCase().includes(q) ||
|
|
240
|
+
(m.name || '').toLowerCase().includes(q) ||
|
|
241
|
+
(m.description || '').toLowerCase().includes(q));
|
|
242
|
+
return { [type]: items };
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
export async function getStarterKit() {
|
|
246
|
+
const res = await apiRequest('/api/cli/starter-kit');
|
|
247
|
+
return res.json();
|
|
248
|
+
}
|
package/src/lib/ask.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// Non-interactive-safe prompt wrappers.
|
|
2
|
+
//
|
|
3
|
+
// @clack/prompts crashes with `uv_tty_init EBADF` when stdin is not a TTY —
|
|
4
|
+
// which is every AI-agent shell, CI job, and piped invocation. Agents are now
|
|
5
|
+
// a primary CLI consumer (the AstralKit MCP instructs them to RUN the install
|
|
6
|
+
// command), so every prompt must degrade to a sensible default instead of
|
|
7
|
+
// crashing mid-install and leaving a partial install (component written,
|
|
8
|
+
// dependencies missing).
|
|
9
|
+
//
|
|
10
|
+
// Resolution order: --yes flag / ASTRALKIT_YES=1 env → auto-accept defaults;
|
|
11
|
+
// non-TTY stdin/stdout → auto-accept defaults (logged); real TTY → prompt.
|
|
12
|
+
|
|
13
|
+
import * as p from '@clack/prompts';
|
|
14
|
+
import pc from 'picocolors';
|
|
15
|
+
|
|
16
|
+
let assumeYes = false;
|
|
17
|
+
|
|
18
|
+
/** Wire the --yes flag (call once at command start). ASTRALKIT_YES=1 also works. */
|
|
19
|
+
export function setAssumeYes(v) {
|
|
20
|
+
assumeYes = !!v;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function isNonInteractive() {
|
|
24
|
+
return assumeYes ||
|
|
25
|
+
process.env.ASTRALKIT_YES === '1' ||
|
|
26
|
+
!process.stdin.isTTY ||
|
|
27
|
+
!process.stdout.isTTY;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function autoLog(message, choice) {
|
|
31
|
+
const why = assumeYes || process.env.ASTRALKIT_YES === '1' ? '--yes' : 'non-interactive';
|
|
32
|
+
console.log(pc.gray(` ${message} → ${choice} (${why})`));
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* confirm() that never crashes on a non-TTY. `nonInteractive` is the value
|
|
37
|
+
* used when we cannot (or were told not to) prompt; defaults to initialValue.
|
|
38
|
+
* Returns false on user cancel.
|
|
39
|
+
*/
|
|
40
|
+
export async function confirm({ message, initialValue = false, nonInteractive }) {
|
|
41
|
+
const fallback = nonInteractive ?? initialValue;
|
|
42
|
+
if (isNonInteractive()) {
|
|
43
|
+
autoLog(message, fallback ? 'yes' : 'no');
|
|
44
|
+
return fallback;
|
|
45
|
+
}
|
|
46
|
+
const res = await p.confirm({ message, initialValue });
|
|
47
|
+
return !p.isCancel(res) && res;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* select() that never crashes on a non-TTY. `nonInteractive` is the value used
|
|
52
|
+
* when we cannot prompt; defaults to the first option's value.
|
|
53
|
+
* Returns the clack cancel symbol untouched so callers can keep their
|
|
54
|
+
* isCancel handling.
|
|
55
|
+
*/
|
|
56
|
+
export async function select({ message, options, nonInteractive }) {
|
|
57
|
+
if (isNonInteractive()) {
|
|
58
|
+
const value = nonInteractive ?? options[0]?.value;
|
|
59
|
+
autoLog(message, String(value));
|
|
60
|
+
return value;
|
|
61
|
+
}
|
|
62
|
+
return p.select({ message, options });
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* text() that never crashes on a non-TTY. `nonInteractive` is the value used
|
|
67
|
+
* when we cannot prompt (defaults to the placeholder).
|
|
68
|
+
*/
|
|
69
|
+
export async function text({ message, placeholder, nonInteractive }) {
|
|
70
|
+
if (isNonInteractive()) {
|
|
71
|
+
const value = nonInteractive ?? placeholder ?? '';
|
|
72
|
+
autoLog(message, value);
|
|
73
|
+
return value;
|
|
74
|
+
}
|
|
75
|
+
return p.text({ message, placeholder });
|
|
76
|
+
}
|
|
@@ -0,0 +1,311 @@
|
|
|
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
|
+
import { confirm as askConfirm } from './ask.js';
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Confirm with the user, or auto-accept when non-interactive (--yes,
|
|
33
|
+
* ASTRALKIT_YES=1, or no TTY — agent/CI shells). Merges apply project wiring
|
|
34
|
+
* the installed piece needs, so the non-interactive default is accept.
|
|
35
|
+
* Returns true/false; never a cancel symbol.
|
|
36
|
+
*/
|
|
37
|
+
async function confirmOrAuto(opts) {
|
|
38
|
+
return askConfirm({ ...opts, nonInteractive: true });
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Entry point: walk the merges array and dispatch each to its strategy handler.
|
|
43
|
+
* Mutates `installSummary` so the end-of-install report reflects what changed.
|
|
44
|
+
*/
|
|
45
|
+
export async function applyMerges(merges, projectRoot, installSummary) {
|
|
46
|
+
if (!Array.isArray(merges) || merges.length === 0) return;
|
|
47
|
+
|
|
48
|
+
for (const merge of merges) {
|
|
49
|
+
try {
|
|
50
|
+
if (merge.strategy === 'wrap-jsx-children') {
|
|
51
|
+
await applyWrapJsxChildren(merge, projectRoot, installSummary);
|
|
52
|
+
} else if (merge.strategy === 'ensure-middleware') {
|
|
53
|
+
await applyEnsureMiddleware(merge, projectRoot, installSummary);
|
|
54
|
+
} else if (merge.strategy === 'append-unique-block') {
|
|
55
|
+
await applyAppendUniqueBlock(merge, projectRoot, installSummary);
|
|
56
|
+
} else {
|
|
57
|
+
p.log.warn(`Unknown merge strategy "${merge.strategy}" — skipped`);
|
|
58
|
+
installSummary.skipped.push({
|
|
59
|
+
what: merge.target || merge.strategy,
|
|
60
|
+
reason: `unknown strategy: ${merge.strategy}`,
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
} catch (err) {
|
|
64
|
+
p.log.warn(`Merge failed for ${merge.target}: ${err.message || err}`);
|
|
65
|
+
installSummary.skipped.push({
|
|
66
|
+
what: merge.target,
|
|
67
|
+
reason: `merge error: ${err.message || err}`,
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// ─── Strategy: wrap-jsx-children ──────────────────────────────────────────────
|
|
74
|
+
|
|
75
|
+
async function applyWrapJsxChildren(merge, projectRoot, installSummary) {
|
|
76
|
+
const { target, imports = [], open, close } = merge;
|
|
77
|
+
const anchor = merge.anchor || 'body';
|
|
78
|
+
const marker = merge.idempotency_marker || open;
|
|
79
|
+
|
|
80
|
+
if (!target || !open || !close) {
|
|
81
|
+
p.log.warn(`wrap-jsx-children merge is missing target/open/close — skipped`);
|
|
82
|
+
return;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
if (!isSafeInstallDir(projectRoot, target)) {
|
|
86
|
+
p.log.warn(`Refusing merge: unsafe target path "${target}"`);
|
|
87
|
+
installSummary.skipped.push({ what: target, reason: 'unsafe target path' });
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const filePath = path.resolve(projectRoot, target);
|
|
92
|
+
if (!fs.existsSync(filePath)) {
|
|
93
|
+
p.log.warn(`Cannot wrap ${target} — file does not exist. Skipped.`);
|
|
94
|
+
p.log.info(`Manually add the booster's provider wrap to your layout.`);
|
|
95
|
+
installSummary.skipped.push({ what: target, reason: 'file not found' });
|
|
96
|
+
return;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const original = fs.readFileSync(filePath, 'utf8');
|
|
100
|
+
|
|
101
|
+
// Idempotency: marker already present → already wrapped.
|
|
102
|
+
if (original.includes(marker)) {
|
|
103
|
+
installSummary.skipped.push({ what: target, reason: 'already wrapped' });
|
|
104
|
+
return;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// Locate the anchor tags. We accept simple `<body>` or `<body className="...">`,
|
|
108
|
+
// including multi-line tags, but not nested same-name elements.
|
|
109
|
+
const openRe = new RegExp(`<${anchor}\\b[^>]*>`);
|
|
110
|
+
const closeRe = new RegExp(`</${anchor}>`);
|
|
111
|
+
const openMatch = original.match(openRe);
|
|
112
|
+
const closeMatch = original.match(closeRe);
|
|
113
|
+
|
|
114
|
+
if (!openMatch || !closeMatch) {
|
|
115
|
+
p.log.warn(`Could not locate <${anchor}> in ${target} — skipped.`);
|
|
116
|
+
p.log.info(`Manually wrap the contents of <${anchor}> with: ${open}…${close}`);
|
|
117
|
+
installSummary.skipped.push({
|
|
118
|
+
what: target,
|
|
119
|
+
reason: `no <${anchor}> element found`,
|
|
120
|
+
});
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const openEnd = openMatch.index + openMatch[0].length;
|
|
125
|
+
const closeStart = closeMatch.index;
|
|
126
|
+
if (closeStart <= openEnd) {
|
|
127
|
+
p.log.warn(`Malformed <${anchor}> in ${target} — skipped.`);
|
|
128
|
+
installSummary.skipped.push({ what: target, reason: 'malformed anchor element' });
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// Decide which imports need adding. We do not edit anything unless the user
|
|
133
|
+
// consents to the full diff, so we just calculate the missing set here.
|
|
134
|
+
const missingImports = imports.filter((line) => !original.includes(line));
|
|
135
|
+
|
|
136
|
+
// Compose the new file content.
|
|
137
|
+
const beforeOpen = original.slice(0, openEnd);
|
|
138
|
+
const inside = original.slice(openEnd, closeStart);
|
|
139
|
+
const afterClose = original.slice(closeStart);
|
|
140
|
+
const wrapped = `${beforeOpen}\n ${open}${inside}${close}\n ${afterClose}`;
|
|
141
|
+
|
|
142
|
+
// Insert missing imports after the last existing import (or at file head).
|
|
143
|
+
let withImports = wrapped;
|
|
144
|
+
if (missingImports.length > 0) {
|
|
145
|
+
const lines = wrapped.split('\n');
|
|
146
|
+
let lastImportIdx = -1;
|
|
147
|
+
for (let i = 0; i < lines.length; i++) {
|
|
148
|
+
if (lines[i].trim().startsWith('import ')) lastImportIdx = i;
|
|
149
|
+
}
|
|
150
|
+
if (lastImportIdx >= 0) {
|
|
151
|
+
lines.splice(lastImportIdx + 1, 0, ...missingImports);
|
|
152
|
+
} else {
|
|
153
|
+
lines.unshift(...missingImports, '');
|
|
154
|
+
}
|
|
155
|
+
withImports = lines.join('\n');
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
// Preview before applying — this file is heavily user-owned, so consent is required.
|
|
159
|
+
console.log();
|
|
160
|
+
p.log.step(`Booster wants to patch ${pc.cyan(target)}:`);
|
|
161
|
+
if (missingImports.length > 0) {
|
|
162
|
+
console.log(pc.gray(' Add imports:'));
|
|
163
|
+
for (const imp of missingImports) console.log(` ${pc.green('+')} ${imp}`);
|
|
164
|
+
}
|
|
165
|
+
console.log(pc.gray(` Wrap children of <${anchor}> with:`));
|
|
166
|
+
console.log(` ${pc.green('+')} ${open}…${close}`);
|
|
167
|
+
|
|
168
|
+
const proceed = await confirmOrAuto({
|
|
169
|
+
message: `Apply this patch to ${target}?`,
|
|
170
|
+
initialValue: true,
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
if (!proceed) {
|
|
174
|
+
p.log.info(`Skipped ${target}. Wrap manually with:`);
|
|
175
|
+
if (missingImports.length > 0) {
|
|
176
|
+
for (const imp of missingImports) console.log(pc.gray(` ${imp}`));
|
|
177
|
+
}
|
|
178
|
+
console.log(pc.gray(` Inside <${anchor}>: ${open} ... {children} ... ${close}`));
|
|
179
|
+
installSummary.skipped.push({ what: target, reason: 'user declined wrap' });
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
fs.writeFileSync(filePath, withImports, 'utf8');
|
|
184
|
+
const noteParts = [];
|
|
185
|
+
if (missingImports.length > 0) noteParts.push(`+${missingImports.length} import${missingImports.length === 1 ? '' : 's'}`);
|
|
186
|
+
noteParts.push(`wrapped <${anchor}>`);
|
|
187
|
+
installSummary.modified.push({ path: target, note: noteParts.join(', ') });
|
|
188
|
+
p.log.success(`Patched ${pc.cyan(target)}`);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// ─── Strategy: append-unique-block ────────────────────────────────────────────
|
|
192
|
+
|
|
193
|
+
async function applyAppendUniqueBlock(merge, projectRoot, installSummary) {
|
|
194
|
+
const { target, block, idempotency_marker } = merge;
|
|
195
|
+
|
|
196
|
+
if (!target || !block || !idempotency_marker) {
|
|
197
|
+
p.log.warn(`append-unique-block merge is missing target/block/idempotency_marker — skipped`);
|
|
198
|
+
return;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// The marker must live inside the block itself, otherwise a re-install could
|
|
202
|
+
// never detect the previous append and would duplicate it.
|
|
203
|
+
if (!block.includes(idempotency_marker)) {
|
|
204
|
+
p.log.warn(`append-unique-block for ${target}: idempotency_marker not found inside block — skipped (authoring error)`);
|
|
205
|
+
installSummary.skipped.push({ what: target, reason: 'marker missing from block' });
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
if (!isSafeInstallDir(projectRoot, target)) {
|
|
210
|
+
p.log.warn(`Refusing merge: unsafe target path "${target}"`);
|
|
211
|
+
installSummary.skipped.push({ what: target, reason: 'unsafe target path' });
|
|
212
|
+
return;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
const filePath = path.resolve(projectRoot, target);
|
|
216
|
+
|
|
217
|
+
if (!fs.existsSync(filePath)) {
|
|
218
|
+
// Clean install — create the file with just the block.
|
|
219
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
220
|
+
fs.writeFileSync(filePath, block.endsWith('\n') ? block : `${block}\n`, 'utf8');
|
|
221
|
+
installSummary.created.push(target);
|
|
222
|
+
p.log.success(`Created ${pc.cyan(target)}`);
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
const existing = fs.readFileSync(filePath, 'utf8');
|
|
227
|
+
if (existing.includes(idempotency_marker)) {
|
|
228
|
+
installSummary.skipped.push({ what: target, reason: 'already appended' });
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// Preview before applying — these files (prisma/schema.prisma, .env.example)
|
|
233
|
+
// are user-owned, so consent is required like the other patch strategies.
|
|
234
|
+
const blockLines = block.replace(/\n$/, '').split('\n');
|
|
235
|
+
const PREVIEW_MAX = 20;
|
|
236
|
+
console.log();
|
|
237
|
+
p.log.step(`Booster wants to append to ${pc.cyan(target)}:`);
|
|
238
|
+
for (const line of blockLines.slice(0, PREVIEW_MAX)) {
|
|
239
|
+
console.log(` ${pc.green('+')} ${line}`);
|
|
240
|
+
}
|
|
241
|
+
if (blockLines.length > PREVIEW_MAX) {
|
|
242
|
+
console.log(pc.gray(` … (+${blockLines.length - PREVIEW_MAX} more lines)`));
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const proceed = await confirmOrAuto({
|
|
246
|
+
message: `Append ${blockLines.length} line${blockLines.length === 1 ? '' : 's'} to ${target}?`,
|
|
247
|
+
initialValue: true,
|
|
248
|
+
});
|
|
249
|
+
|
|
250
|
+
if (!proceed) {
|
|
251
|
+
p.log.info(`Skipped ${target}. Append the block manually (it is marker-guarded, shown above).`);
|
|
252
|
+
installSummary.skipped.push({ what: target, reason: 'user declined append' });
|
|
253
|
+
return;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
const separator = existing.endsWith('\n') ? '\n' : '\n\n';
|
|
257
|
+
const appended = `${existing}${separator}${block}${block.endsWith('\n') ? '' : '\n'}`;
|
|
258
|
+
fs.writeFileSync(filePath, appended, 'utf8');
|
|
259
|
+
installSummary.modified.push({ path: target, note: `+${blockLines.length} lines appended` });
|
|
260
|
+
p.log.success(`Patched ${pc.cyan(target)}`);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// ─── Strategy: ensure-middleware ──────────────────────────────────────────────
|
|
264
|
+
|
|
265
|
+
async function applyEnsureMiddleware(merge, projectRoot, installSummary) {
|
|
266
|
+
const { target, content, idempotency_marker, merge_note } = merge;
|
|
267
|
+
|
|
268
|
+
if (!target || !content || !idempotency_marker) {
|
|
269
|
+
p.log.warn(`ensure-middleware merge is missing target/content/idempotency_marker — skipped`);
|
|
270
|
+
return;
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
if (!isSafeInstallDir(projectRoot, target)) {
|
|
274
|
+
p.log.warn(`Refusing merge: unsafe target path "${target}"`);
|
|
275
|
+
installSummary.skipped.push({ what: target, reason: 'unsafe target path' });
|
|
276
|
+
return;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
const filePath = path.resolve(projectRoot, target);
|
|
280
|
+
|
|
281
|
+
if (!fs.existsSync(filePath)) {
|
|
282
|
+
// Clean install — just write it.
|
|
283
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
284
|
+
fs.writeFileSync(filePath, content, 'utf8');
|
|
285
|
+
installSummary.created.push(target);
|
|
286
|
+
p.log.success(`Created ${pc.cyan(target)}`);
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// Existing file. Idempotency check first.
|
|
291
|
+
const existing = fs.readFileSync(filePath, 'utf8');
|
|
292
|
+
if (existing.includes(idempotency_marker)) {
|
|
293
|
+
installSummary.skipped.push({ what: target, reason: 'already wired' });
|
|
294
|
+
return;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
// Conflict: file exists but isn't wired. Print explicit instructions instead
|
|
298
|
+
// of attempting an automated merge — middleware shapes vary too much for a
|
|
299
|
+
// safe one-size-fits-all rewrite, and the cost of a broken edit here is high
|
|
300
|
+
// (every request goes through middleware).
|
|
301
|
+
console.log();
|
|
302
|
+
p.log.warn(`Cannot auto-update ${pc.cyan(target)} — file already exists and the booster's marker is missing.`);
|
|
303
|
+
console.log(pc.gray(' To finish wiring, do the following manually:'));
|
|
304
|
+
for (const line of String(merge_note).split('\n')) {
|
|
305
|
+
console.log(pc.gray(` ${line}`));
|
|
306
|
+
}
|
|
307
|
+
installSummary.skipped.push({
|
|
308
|
+
what: target,
|
|
309
|
+
reason: 'exists — manual merge required (see notes above)',
|
|
310
|
+
});
|
|
311
|
+
}
|
package/src/lib/validators.js
CHANGED
|
@@ -139,14 +139,38 @@ export function isSensitivePath(relPath) {
|
|
|
139
139
|
return segments.some(seg => SENSITIVE_FILE_PATTERNS.some(re => re.test(seg)));
|
|
140
140
|
}
|
|
141
141
|
|
|
142
|
-
|
|
142
|
+
// The subset of "sensitive" files a full-app SCAFFOLD legitimately ships
|
|
143
|
+
// (workflow installs into a fresh directory). Env files, lockfiles, VCS/CI
|
|
144
|
+
// metadata, and shell dotfiles stay blocked even in scaffold mode.
|
|
145
|
+
const SCAFFOLD_ALLOWED_FILES = [
|
|
146
|
+
/^package\.json$/i,
|
|
147
|
+
/^package-lock\.json$/i, // pins the workflow's exact working dependency tree
|
|
148
|
+
/^next\.config\.(js|ts|mjs|cjs)$/i,
|
|
149
|
+
/^\.gitignore$/i,
|
|
150
|
+
// Scaffolds may carry install settings (e.g. legacy-peer-deps). No more
|
|
151
|
+
// powerful than the package.json install scripts a scaffold already ships.
|
|
152
|
+
/^\.npmrc$/i,
|
|
153
|
+
];
|
|
154
|
+
|
|
155
|
+
function isScaffoldAllowed(relPath) {
|
|
156
|
+
const normalized = relPath.replace(/\\/g, '/').replace(/^\.\//, '');
|
|
157
|
+
const segments = normalized.split('/').filter(Boolean);
|
|
158
|
+
if (segments.length === 0) return false;
|
|
159
|
+
const file = segments[segments.length - 1];
|
|
160
|
+
const dirs = segments.slice(0, -1);
|
|
161
|
+
// Directories must still be clean (e.g. `.git/package.json` stays blocked).
|
|
162
|
+
if (dirs.some(seg => SENSITIVE_FILE_PATTERNS.some(re => re.test(seg)))) return false;
|
|
163
|
+
return SCAFFOLD_ALLOWED_FILES.some(re => re.test(file));
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export function writeFiles(baseDir, files, opts = {}) {
|
|
143
167
|
let count = 0;
|
|
144
168
|
for (const file of files) {
|
|
145
169
|
if (!isSafePath(baseDir, file.path)) {
|
|
146
170
|
console.log(pc.red(` Skipping suspicious path: ${file.path}`));
|
|
147
171
|
continue;
|
|
148
172
|
}
|
|
149
|
-
if (isSensitivePath(file.path)) {
|
|
173
|
+
if (isSensitivePath(file.path) && !(opts.scaffold && isScaffoldAllowed(file.path))) {
|
|
150
174
|
console.log(pc.red(` Skipping sensitive path: ${file.path}`));
|
|
151
175
|
continue;
|
|
152
176
|
}
|