@astralkit/cli 4.6.3 → 4.7.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +13 -0
- package/bin/index.js +2 -2
- package/package.json +1 -1
- package/src/commands/add.js +79 -15
- package/src/commands/init.js +6 -0
- package/src/commands/update.js +5 -0
- package/src/lib/stylesheets.js +170 -0
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,19 @@ 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.7.1] (2026-11-30)
|
|
9
|
+
|
|
10
|
+
### Fixed
|
|
11
|
+
- **The free components install without a key.** `astralkit add button` stopped with "No API key found" before it had asked for anything, so nobody without a key could install even the free set. A component is now asked for first; the registry says when one is premium, and the CLI then gives the three ways to sign in (`astralkit login`, `astralkit init --api-key`, or the `ASTRALKIT_API_KEY` environment variable). Boosters and workflows still need a key.
|
|
12
|
+
- **A name that is not found ends with exit code 1.** `astralkit add no-such-thing` printed "not found" and exited 0, so a script or an agent took it for installed.
|
|
13
|
+
|
|
14
|
+
## [4.7.0] (2026-11-30)
|
|
15
|
+
|
|
16
|
+
### Added
|
|
17
|
+
- **Several at once:** `astralkit add zest-navigation zest-hero zest-faq` installs each name in turn. One that fails does not stop the rest: the end of the run lists what was installed and what was not, and the exit code is 1 if any was not. Before, only the first name was installed and the others were dropped without a word.
|
|
18
|
+
- **A component's stylesheets are added for you.** A website template section keeps its palette and typefaces in the SDK (`astralkit/palettes`, `astralkit/template-fonts`), and a section with a date field or a map asks for `astralkit/datepicker.css` or `astralkit/maps.css`. `add`, `update` and `init` now put the imports a component names into your stylesheet, after the AstralKit theme, once. Before, the file was written and the line was left for you to read: the section drew without its colours or its typefaces.
|
|
19
|
+
- An import the installed `astralkit` cannot resolve is never written (it would break your build). The CLI offers to update `astralkit` once per run (accepted without a prompt in an agent or CI shell) and names anything it could not add.
|
|
20
|
+
|
|
8
21
|
## [4.6.3] (2026-11-24)
|
|
9
22
|
|
|
10
23
|
### Fixed
|
package/bin/index.js
CHANGED
|
@@ -40,8 +40,8 @@ program
|
|
|
40
40
|
|
|
41
41
|
// ─── add ─────────────────────────────────────────────
|
|
42
42
|
program
|
|
43
|
-
.command('add <
|
|
44
|
-
.description('Add
|
|
43
|
+
.command('add <names...>')
|
|
44
|
+
.description('Add one or more components, boosters, or workflows to your project')
|
|
45
45
|
.option('--api-key <key>', 'Your API key')
|
|
46
46
|
.option('-f, --framework <framework>', 'Framework version (html, react, nextjs)')
|
|
47
47
|
.option('--dir <directory>', 'Override output directory')
|
package/package.json
CHANGED
package/src/commands/add.js
CHANGED
|
@@ -14,29 +14,75 @@ import { validateSlug, validateFramework, isSafePath, writeFiles, isSafeInstallD
|
|
|
14
14
|
import { detectPackageManager, getRunCommand, runInstall } from '../lib/pkg-manager.js';
|
|
15
15
|
import { saveApiKey, getApiKey, getAuth } from '../lib/auth.js';
|
|
16
16
|
import { applyMerges } from '../lib/merges.js';
|
|
17
|
+
import { ensureComponentStylesheets } from '../lib/stylesheets.js';
|
|
17
18
|
import { setAssumeYes, confirm as askConfirm, select as askSelect, text as askText } from '../lib/ask.js';
|
|
18
19
|
|
|
19
20
|
const FRAMEWORK_LABELS = { nextjs: 'Next.js', react: 'React' };
|
|
20
21
|
|
|
21
|
-
|
|
22
|
+
// `astralkit add a b c` installs each name in turn. One name failing must not stop the rest, so inside a
|
|
23
|
+
// batch an exit becomes a throw that the loop catches; a single name exits as it always did.
|
|
24
|
+
class ExitSignal extends Error {
|
|
25
|
+
constructor(code) { super('exit'); this.code = code; }
|
|
26
|
+
}
|
|
27
|
+
let inBatch = false;
|
|
28
|
+
function exit(code) {
|
|
29
|
+
if (inBatch) throw new ExitSignal(code);
|
|
30
|
+
process.exit(code);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export async function addCommand(names, options) {
|
|
34
|
+
const list = [...new Set([].concat(names).filter(Boolean))];
|
|
35
|
+
if (list.length <= 1) return addOne(list[0], options);
|
|
36
|
+
|
|
37
|
+
const installed = [];
|
|
38
|
+
const notInstalled = [];
|
|
39
|
+
inBatch = true;
|
|
40
|
+
try {
|
|
41
|
+
for (const [index, name] of list.entries()) {
|
|
42
|
+
console.log();
|
|
43
|
+
p.log.step(`${pc.cyan(name)} (${index + 1} of ${list.length})`);
|
|
44
|
+
let done = false;
|
|
45
|
+
try {
|
|
46
|
+
done = (await addOne(name, options)) === true;
|
|
47
|
+
} catch (err) {
|
|
48
|
+
if (!(err instanceof ExitSignal)) throw err;
|
|
49
|
+
}
|
|
50
|
+
(done ? installed : notInstalled).push(name);
|
|
51
|
+
}
|
|
52
|
+
} finally {
|
|
53
|
+
inBatch = false;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
console.log();
|
|
57
|
+
if (installed.length) p.log.success(`Installed ${installed.length} of ${list.length}: ${installed.join(', ')}`);
|
|
58
|
+
if (notInstalled.length) {
|
|
59
|
+
p.log.warn(`Not installed: ${notInstalled.join(', ')} (the reason for each is printed above)`);
|
|
60
|
+
process.exit(1);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function addOne(nameOrSlug, options) {
|
|
22
65
|
setAssumeYes(options.yes);
|
|
23
66
|
if (options.apiKey) {
|
|
24
67
|
if (!options.apiKey.startsWith('ak_')) {
|
|
25
68
|
console.log(pc.red('Invalid API key format. Keys start with ak_'));
|
|
26
|
-
|
|
69
|
+
exit(1);
|
|
27
70
|
}
|
|
28
71
|
saveApiKey(options.apiKey);
|
|
29
72
|
}
|
|
30
73
|
|
|
31
|
-
//
|
|
32
|
-
//
|
|
74
|
+
// A component needs no key to be asked for (2026-11-30): the free components install for everyone, and the
|
|
75
|
+
// registry itself says when one is premium (handleAddError then tells how to sign in). The CLI used to stop here
|
|
76
|
+
// with "No API key found" before asking, so nobody without a key could install even the free set.
|
|
77
|
+
// Boosters and workflows are for paid plans: they still need a key, unless read from a local registry
|
|
78
|
+
// (the developer's own disk, no account needed).
|
|
33
79
|
const localBoosterInstall = LOCAL_REGISTRY_DIR && (options.booster || options.workflow);
|
|
34
|
-
if (!getApiKey() && !localBoosterInstall) {
|
|
80
|
+
if ((options.booster || options.workflow) && !getApiKey() && !localBoosterInstall) {
|
|
35
81
|
const auth = getAuth();
|
|
36
82
|
if (!auth.token) {
|
|
37
83
|
p.log.warn('No API key found. Run ' + pc.cyan('astralkit init --api-key <key>') + ' first.');
|
|
38
84
|
console.log(pc.gray('Get yours at ') + pc.cyan('https://astralkit.com/account'));
|
|
39
|
-
|
|
85
|
+
exit(1);
|
|
40
86
|
}
|
|
41
87
|
}
|
|
42
88
|
|
|
@@ -98,6 +144,8 @@ export async function addCommand(nameOrSlug, options) {
|
|
|
98
144
|
p.log.error(`"${nameOrSlug}" not found in any registry.`);
|
|
99
145
|
p.log.info('Run ' + pc.cyan('astralkit search "' + nameOrSlug + '"') + ' to browse available content.');
|
|
100
146
|
}
|
|
147
|
+
// nothing was installed: a script or an agent must be able to tell (the exit code was 0)
|
|
148
|
+
process.exitCode = 1;
|
|
101
149
|
return;
|
|
102
150
|
}
|
|
103
151
|
|
|
@@ -123,7 +171,7 @@ export async function addCommand(nameOrSlug, options) {
|
|
|
123
171
|
nonInteractive: componentMatch ? 'component' : matches[0].type,
|
|
124
172
|
});
|
|
125
173
|
|
|
126
|
-
if (p.isCancel(choice)) { p.cancel('Cancelled.');
|
|
174
|
+
if (p.isCancel(choice)) { p.cancel('Cancelled.'); exit(0); }
|
|
127
175
|
|
|
128
176
|
if (choice === 'booster') return addBooster(nameOrSlug, options);
|
|
129
177
|
if (choice === 'workflow') return addWorkflow(nameOrSlug, options);
|
|
@@ -138,7 +186,7 @@ export async function addCommand(nameOrSlug, options) {
|
|
|
138
186
|
|
|
139
187
|
function resolveFramework(options) {
|
|
140
188
|
if (options.framework) {
|
|
141
|
-
if (!validateFramework(options.framework))
|
|
189
|
+
if (!validateFramework(options.framework)) exit(1);
|
|
142
190
|
return options.framework;
|
|
143
191
|
}
|
|
144
192
|
const detected = detectFramework();
|
|
@@ -174,7 +222,7 @@ function hostHasDep(pkg, name) {
|
|
|
174
222
|
}
|
|
175
223
|
|
|
176
224
|
async function addComponent(componentSlug, options) {
|
|
177
|
-
if (!validateSlug(componentSlug))
|
|
225
|
+
if (!validateSlug(componentSlug)) exit(1);
|
|
178
226
|
if (!fs.existsSync(path.join(process.cwd(), 'package.json'))) {
|
|
179
227
|
p.log.warn('No package.json found. Run this inside a project directory.');
|
|
180
228
|
return;
|
|
@@ -198,7 +246,7 @@ async function addComponent(componentSlug, options) {
|
|
|
198
246
|
// Refuse absolute / traversal values of --dir.
|
|
199
247
|
if (!isSafeInstallDir(process.cwd(), componentsDir)) {
|
|
200
248
|
console.log(pc.red(`Refusing install: unsafe --dir value "${componentsDir}"`));
|
|
201
|
-
|
|
249
|
+
exit(1);
|
|
202
250
|
}
|
|
203
251
|
const targetFile = path.resolve(process.cwd(), componentsDir, `${componentSlug}${ext}`);
|
|
204
252
|
|
|
@@ -268,6 +316,10 @@ async function addComponent(componentSlug, options) {
|
|
|
268
316
|
|
|
269
317
|
// Detect if component uses Phosphor Icons (CSS class-based icons)
|
|
270
318
|
const componentCode = data.files?.map(f => f.content).join('') || '';
|
|
319
|
+
|
|
320
|
+
// The stylesheets the component asks for (a template section's palette and typefaces, a date picker's dialog)
|
|
321
|
+
// go into the project's stylesheet. An HTML file loads its own from the CDN.
|
|
322
|
+
if (framework !== 'html') await ensureComponentStylesheets(filesToWrite.map(f => f.content).join('\n'), installSummary);
|
|
271
323
|
let usesPhosphorCss = componentCode.includes('class="ph ') || componentCode.includes("class='ph ") || componentCode.includes('"ph ph-') || componentCode.includes("'ph ph-");
|
|
272
324
|
|
|
273
325
|
// Phosphor conflict guard: @phosphor-icons/web and @phosphor-icons/react
|
|
@@ -462,6 +514,7 @@ async function addComponent(componentSlug, options) {
|
|
|
462
514
|
}
|
|
463
515
|
|
|
464
516
|
printInstallSummary(installSummary);
|
|
517
|
+
return true;
|
|
465
518
|
|
|
466
519
|
} catch (err) {
|
|
467
520
|
spinner.fail('Failed to add component.');
|
|
@@ -503,7 +556,7 @@ function printInstallSummary(s) {
|
|
|
503
556
|
}
|
|
504
557
|
|
|
505
558
|
async function addBooster(slug, options) {
|
|
506
|
-
if (!validateSlug(slug, 'booster name'))
|
|
559
|
+
if (!validateSlug(slug, 'booster name')) exit(1);
|
|
507
560
|
|
|
508
561
|
const ora = (await import('ora')).default;
|
|
509
562
|
const framework = resolveFramework(options);
|
|
@@ -652,6 +705,7 @@ async function addBooster(slug, options) {
|
|
|
652
705
|
}
|
|
653
706
|
|
|
654
707
|
if (data.post_install) { console.log(); console.log(pc.gray(data.post_install)); }
|
|
708
|
+
return true;
|
|
655
709
|
|
|
656
710
|
} catch (err) {
|
|
657
711
|
spinner.fail('Failed to add booster.');
|
|
@@ -660,7 +714,7 @@ async function addBooster(slug, options) {
|
|
|
660
714
|
}
|
|
661
715
|
|
|
662
716
|
async function addWorkflow(slug, options) {
|
|
663
|
-
if (!validateSlug(slug, 'workflow name'))
|
|
717
|
+
if (!validateSlug(slug, 'workflow name')) exit(1);
|
|
664
718
|
|
|
665
719
|
const ora = (await import('ora')).default;
|
|
666
720
|
const framework = resolveFramework(options);
|
|
@@ -761,6 +815,7 @@ async function addWorkflow(slug, options) {
|
|
|
761
815
|
}
|
|
762
816
|
|
|
763
817
|
if (data.post_install) { console.log(); console.log(pc.gray(data.post_install)); }
|
|
818
|
+
return true;
|
|
764
819
|
|
|
765
820
|
} catch (err) {
|
|
766
821
|
spinner.fail('Failed to add workflow.');
|
|
@@ -770,7 +825,16 @@ async function addWorkflow(slug, options) {
|
|
|
770
825
|
|
|
771
826
|
function handleAddError(err, slug, framework) {
|
|
772
827
|
if (err.code === 'AUTH_REQUIRED') {
|
|
773
|
-
|
|
828
|
+
if (!getApiKey() && !getAuth().token) {
|
|
829
|
+
// no key at all: say what the component is and the three ways to give one
|
|
830
|
+
p.log.warn(`${pc.cyan(slug)} is a premium component: it needs your AstralKit API key.`);
|
|
831
|
+
console.log(pc.gray(' Sign in once: ') + pc.cyan('astralkit login'));
|
|
832
|
+
console.log(pc.gray(' Or save a key: ') + pc.cyan('astralkit init --api-key <key>'));
|
|
833
|
+
console.log(pc.gray(' Or for this run: set the ASTRALKIT_API_KEY environment variable'));
|
|
834
|
+
console.log(pc.gray(' Your key is at ') + pc.cyan('https://astralkit.com/account') + pc.gray('. The free components install without one: ') + pc.cyan('astralkit list --free'));
|
|
835
|
+
} else {
|
|
836
|
+
p.log.warn(err.message);
|
|
837
|
+
}
|
|
774
838
|
} else if (err.code === 'PRO_REQUIRED') {
|
|
775
839
|
p.log.warn(`${FRAMEWORK_LABELS[framework] || framework} version requires a Pro subscription.`);
|
|
776
840
|
console.log(pc.gray(' Upgrade at ') + pc.cyan('https://astralkit.com/pricing'));
|
|
@@ -780,10 +844,10 @@ function handleAddError(err, slug, framework) {
|
|
|
780
844
|
if (body.supported_frameworks) {
|
|
781
845
|
p.log.warn(`No ${framework} version available for "${slug}".`);
|
|
782
846
|
console.log(pc.gray(`Available: ${body.supported_frameworks.map(f => FRAMEWORK_LABELS[f] || f).join(', ')}`));
|
|
783
|
-
|
|
847
|
+
exit(1);
|
|
784
848
|
}
|
|
785
849
|
} catch { /* not json */ }
|
|
786
850
|
console.error(pc.red(err.message));
|
|
787
851
|
}
|
|
788
|
-
|
|
852
|
+
exit(1);
|
|
789
853
|
}
|
package/src/commands/init.js
CHANGED
|
@@ -13,6 +13,7 @@ import {
|
|
|
13
13
|
getRequiredCssImports,
|
|
14
14
|
} from '../lib/config.js';
|
|
15
15
|
import { getAiRulesContent } from '../lib/ai-rules.js';
|
|
16
|
+
import { collectDeclaredCssImports, ensureComponentStylesheets } from '../lib/stylesheets.js';
|
|
16
17
|
import { saveApiKey, getApiKey } from '../lib/auth.js';
|
|
17
18
|
import { detectPackageManager, runInstall } from '../lib/pkg-manager.js';
|
|
18
19
|
import { getStarterKit } from '../lib/api.js';
|
|
@@ -135,6 +136,11 @@ export async function initCommand(options) {
|
|
|
135
136
|
p.log.success(`Created ${pc.cyan(defaultCssRelative)}`);
|
|
136
137
|
}
|
|
137
138
|
|
|
139
|
+
// Components already in the project can ask for stylesheets of their own (a template section's palette and
|
|
140
|
+
// typefaces): `astralkit add` leaves them for this step when the SDK was not installed yet.
|
|
141
|
+
const declared = collectDeclaredCssImports();
|
|
142
|
+
if (declared.length) await ensureComponentStylesheets(declared.map(specifier => `@import "${specifier}";`).join('\n'));
|
|
143
|
+
|
|
138
144
|
// ─── Step 4b: Tailwind v3 plugin registration ─────────
|
|
139
145
|
//
|
|
140
146
|
// In v3, the @theme directive doesn't exist, so ak-* utility classes
|
package/src/commands/update.js
CHANGED
|
@@ -6,6 +6,7 @@ import { getComponent } from '../lib/api.js';
|
|
|
6
6
|
import { getProjectConfig, detectFramework } from '../lib/config.js';
|
|
7
7
|
import { isSafePath } from '../lib/validators.js';
|
|
8
8
|
import { confirm as askConfirm } from '../lib/ask.js';
|
|
9
|
+
import { ensureComponentStylesheets } from '../lib/stylesheets.js';
|
|
9
10
|
|
|
10
11
|
export async function updateCommand(componentSlug, options) {
|
|
11
12
|
const ora = (await import('ora')).default;
|
|
@@ -80,6 +81,10 @@ export async function updateCommand(componentSlug, options) {
|
|
|
80
81
|
fs.writeFileSync(filePath, file.content);
|
|
81
82
|
}
|
|
82
83
|
|
|
84
|
+
// A newer version of a component can ask for stylesheets the older one carried in its own file
|
|
85
|
+
// (a template section's palette and typefaces): they go into the project's stylesheet.
|
|
86
|
+
if (framework !== 'html') await ensureComponentStylesheets([...toCreate, ...toUpdate].map(f => f.content).join('\n'));
|
|
87
|
+
|
|
83
88
|
p.outro(pc.green(`✅ ${data.name || componentSlug} updated`));
|
|
84
89
|
|
|
85
90
|
} catch (err) {
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Stylesheets a component asks for
|
|
3
|
+
* ────────────────────────────────
|
|
4
|
+
* A template section carries no stylesheet of its own: its palette is
|
|
5
|
+
* `astralkit/palettes` and its typefaces `astralkit/template-fonts`. A section
|
|
6
|
+
* with a date field asks for `astralkit/datepicker.css`, one with a map for
|
|
7
|
+
* `astralkit/maps.css`. The file says so in its header:
|
|
8
|
+
*
|
|
9
|
+
* Add once to your stylesheet, after the AstralKit theme:
|
|
10
|
+
* @import "astralkit/palettes"; @import "astralkit/template-fonts";
|
|
11
|
+
*
|
|
12
|
+
* Until 2026-11-30 the CLI wrote the file and left that line for the reader.
|
|
13
|
+
* A section installed that way draws without its palette or its typefaces
|
|
14
|
+
* (Zest's orange hero came out near-black, in a fallback face). Here the CLI
|
|
15
|
+
* reads the imports the file names and puts them in the project's stylesheet.
|
|
16
|
+
*
|
|
17
|
+
* The theme and utilities are the project's base setup (`astralkit init`),
|
|
18
|
+
* not these.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import fs from 'fs';
|
|
22
|
+
import path from 'path';
|
|
23
|
+
import pc from 'picocolors';
|
|
24
|
+
import * as p from '@clack/prompts';
|
|
25
|
+
import { findCssEntryFile, isAstralkitInstalled } from './config.js';
|
|
26
|
+
import { detectPackageManager, runInstall } from './pkg-manager.js';
|
|
27
|
+
import { confirm as askConfirm } from './ask.js';
|
|
28
|
+
|
|
29
|
+
const BASE = new Set(['astralkit/theme', 'astralkit/theme-v4', 'astralkit/utilities']);
|
|
30
|
+
/** Whether this run already tried to update astralkit. */
|
|
31
|
+
let updateTried = false;
|
|
32
|
+
const importLine = specifier => `@import "${specifier}";`;
|
|
33
|
+
const importPattern = specifier => new RegExp(`@import\\s+["']${specifier.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&')}["']`);
|
|
34
|
+
|
|
35
|
+
/** The stylesheet imports a component's code names (`astralkit/palettes`), in the order it names them. */
|
|
36
|
+
export function getDeclaredCssImports(code) {
|
|
37
|
+
const found = new Set();
|
|
38
|
+
for (const match of String(code || '').matchAll(/@import\s+["'](astralkit\/[a-z0-9][a-z0-9./-]*)["']/g)) {
|
|
39
|
+
if (!BASE.has(match[1])) found.add(match[1]);
|
|
40
|
+
}
|
|
41
|
+
return [...found];
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Of the imports asked for, the ones the stylesheet does not have yet. */
|
|
45
|
+
export function getMissingDeclaredImports(cssFilePath, specifiers) {
|
|
46
|
+
let content = '';
|
|
47
|
+
try { content = fs.readFileSync(cssFilePath, 'utf8'); } catch { /* no file: all are missing */ }
|
|
48
|
+
return specifiers.filter(specifier => !importPattern(specifier).test(content));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Whether the installed astralkit has the export a specifier names
|
|
53
|
+
* ("astralkit/template-fonts" is "./template-fonts"). null when astralkit is not installed.
|
|
54
|
+
*/
|
|
55
|
+
export function sdkHasExport(specifier, dir = process.cwd()) {
|
|
56
|
+
try {
|
|
57
|
+
const pkg = JSON.parse(fs.readFileSync(path.join(dir, 'node_modules', 'astralkit', 'package.json'), 'utf8'));
|
|
58
|
+
if (!pkg.exports) return true;
|
|
59
|
+
return Object.prototype.hasOwnProperty.call(pkg.exports, `./${specifier.replace(/^astralkit\//, '')}`);
|
|
60
|
+
} catch {
|
|
61
|
+
return null;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function installedSdkVersion(dir = process.cwd()) {
|
|
66
|
+
try {
|
|
67
|
+
return JSON.parse(fs.readFileSync(path.join(dir, 'node_modules', 'astralkit', 'package.json'), 'utf8')).version || null;
|
|
68
|
+
} catch {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Writes the imports into the stylesheet: after the AstralKit theme import, so a palette is read after the theme it
|
|
75
|
+
* builds on and every @import stays at the top of the file. With no theme import, after the last @import or
|
|
76
|
+
* @tailwind line; in an empty file, first. Imports already there are left alone. Returns the ones it added.
|
|
77
|
+
*/
|
|
78
|
+
export function addDeclaredCssImports(cssFilePath, specifiers) {
|
|
79
|
+
const existing = fs.existsSync(cssFilePath) ? fs.readFileSync(cssFilePath, 'utf8') : '';
|
|
80
|
+
const missing = specifiers.filter(specifier => !importPattern(specifier).test(existing));
|
|
81
|
+
if (!missing.length) return [];
|
|
82
|
+
const eol = existing.includes('\r\n') ? '\r\n' : '\n';
|
|
83
|
+
const lines = existing.length ? existing.split(/\r?\n/) : [];
|
|
84
|
+
const lastWhere = test => lines.reduce((found, line, index) => (test(line.trim()) ? index : found), -1);
|
|
85
|
+
let at = lastWhere(line => /^@import\s+["']astralkit\/theme(-v4)?["']/.test(line));
|
|
86
|
+
if (at < 0) at = lastWhere(line => line.startsWith('@import') || line.startsWith('@tailwind'));
|
|
87
|
+
lines.splice(at + 1, 0, ...missing.map(importLine));
|
|
88
|
+
fs.writeFileSync(cssFilePath, lines.join(eol) + (existing.length ? '' : eol));
|
|
89
|
+
return missing;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** The imports named by every component already in the project's component folders (for `astralkit init`). */
|
|
93
|
+
export function collectDeclaredCssImports(dir = process.cwd()) {
|
|
94
|
+
const found = new Set();
|
|
95
|
+
const read = folder => {
|
|
96
|
+
let entries = [];
|
|
97
|
+
try { entries = fs.readdirSync(folder, { withFileTypes: true }); } catch { return; }
|
|
98
|
+
for (const entry of entries) {
|
|
99
|
+
const file = path.join(folder, entry.name);
|
|
100
|
+
if (entry.isDirectory()) { if (entry.name !== 'node_modules') read(file); continue; }
|
|
101
|
+
if (!/\.(tsx|jsx)$/.test(entry.name)) continue;
|
|
102
|
+
try { getDeclaredCssImports(fs.readFileSync(file, 'utf8')).forEach(specifier => found.add(specifier)); } catch { /* unreadable: skip */ }
|
|
103
|
+
}
|
|
104
|
+
};
|
|
105
|
+
for (const folder of ['src/components', 'components']) read(path.join(dir, folder));
|
|
106
|
+
return [...found];
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Puts the stylesheets a component asks for into the project's stylesheet, and says what it did.
|
|
111
|
+
* `summary` is the install summary of `astralkit add` ({ modified, skipped }); it may be left out.
|
|
112
|
+
*
|
|
113
|
+
* It never writes an import the installed astralkit cannot resolve: that would break the project's build. When the
|
|
114
|
+
* installed astralkit is too old it offers to update it (accepted without a prompt in an agent or CI shell, like the
|
|
115
|
+
* component's other dependencies), and if the import still cannot be resolved it is named as not added.
|
|
116
|
+
*/
|
|
117
|
+
export async function ensureComponentStylesheets(code, summary) {
|
|
118
|
+
const wanted = getDeclaredCssImports(code);
|
|
119
|
+
if (!wanted.length) return;
|
|
120
|
+
const skip = (what, reason) => summary?.skipped?.push({ what, reason });
|
|
121
|
+
|
|
122
|
+
const cssEntry = findCssEntryFile();
|
|
123
|
+
if (!cssEntry) {
|
|
124
|
+
p.log.warn('This component needs these lines in your stylesheet, after the AstralKit theme:');
|
|
125
|
+
wanted.forEach(specifier => console.log(pc.gray(` ${importLine(specifier)}`)));
|
|
126
|
+
wanted.forEach(specifier => skip(importLine(specifier), 'no stylesheet found: add it by hand'));
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
const missing = getMissingDeclaredImports(cssEntry.path, wanted);
|
|
131
|
+
if (!missing.length) return;
|
|
132
|
+
|
|
133
|
+
if (!isAstralkitInstalled()) {
|
|
134
|
+
// `astralkit init` installs the SDK and then adds these too (it reads the components already in the project).
|
|
135
|
+
p.log.warn(`This component also needs ${missing.map(s => pc.cyan(s)).join(' and ')} in ${cssEntry.relative}. ${pc.cyan('astralkit init')} adds them.`);
|
|
136
|
+
missing.forEach(specifier => skip(importLine(specifier), 'astralkit is not installed: run astralkit init'));
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
let unavailable = missing.filter(specifier => sdkHasExport(specifier) === false);
|
|
141
|
+
// One update per run: `astralkit add a b c` asks once, not once per component.
|
|
142
|
+
if (unavailable.length && !updateTried) {
|
|
143
|
+
updateTried = true;
|
|
144
|
+
const before = installedSdkVersion();
|
|
145
|
+
p.log.warn(`This component needs a newer ${pc.cyan('astralkit')} than the ${before || 'one'} installed (for ${unavailable.join(', ')}).`);
|
|
146
|
+
const update = await askConfirm({ message: 'Update astralkit to the latest version?', initialValue: true, nonInteractive: true });
|
|
147
|
+
if (update === true) {
|
|
148
|
+
const ora = (await import('ora')).default;
|
|
149
|
+
const spinner = ora('Updating astralkit...').start();
|
|
150
|
+
const result = await runInstall(detectPackageManager(process.cwd()), process.cwd(), ['astralkit@latest']);
|
|
151
|
+
const after = installedSdkVersion();
|
|
152
|
+
if (!result.success) { spinner.fail('Could not update astralkit.'); if (result.hint || result.error) console.log(pc.gray(` ${result.hint || result.error}`)); }
|
|
153
|
+
else if (after === before) spinner.info(`astralkit ${after} is already the latest published version.`);
|
|
154
|
+
else spinner.succeed(`astralkit is now ${after}`);
|
|
155
|
+
unavailable = missing.filter(specifier => sdkHasExport(specifier) === false);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const added = addDeclaredCssImports(cssEntry.path, missing.filter(specifier => !unavailable.includes(specifier)));
|
|
160
|
+
if (added.length) {
|
|
161
|
+
summary?.modified?.push({ path: cssEntry.relative, note: `+${added.length} ${added.length === 1 ? 'import' : 'imports'} (${added.join(', ')})` });
|
|
162
|
+
p.log.success(`Added ${added.map(s => pc.cyan(s)).join(' and ')} to ${pc.cyan(cssEntry.relative)}`);
|
|
163
|
+
}
|
|
164
|
+
if (unavailable.length) {
|
|
165
|
+
p.log.warn(`Not added: ${unavailable.join(', ')}. astralkit ${installedSdkVersion() || ''} does not have it, so the import would break your build.`);
|
|
166
|
+
console.log(pc.gray(' The component will not look as designed until astralkit is updated and this line is in your stylesheet:'));
|
|
167
|
+
unavailable.forEach(specifier => console.log(pc.gray(` ${importLine(specifier)}`)));
|
|
168
|
+
unavailable.forEach(specifier => skip(importLine(specifier), `astralkit ${installedSdkVersion() || ''} does not have it`.replace(' ', ' ')));
|
|
169
|
+
}
|
|
170
|
+
}
|