@astralkit/cli 4.7.3 → 4.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  import pc from 'picocolors';
2
2
  import * as p from '@clack/prompts';
3
- import { listComponents, listBoosters, listWorkflows } from '../lib/api.js';
3
+ import { listComponents, listBoosters, listWorkflows, listWebsites } from '../lib/api.js';
4
4
  import { sanitizeForTerminal, firstSentence } from '../lib/validators.js';
5
5
 
6
6
  // Server-supplied string passthrough protection — strips ANSI/control sequences
@@ -9,7 +9,33 @@ const s = (v) => sanitizeForTerminal(v || '');
9
9
 
10
10
  const FRAMEWORK_LABELS = { nextjs: 'Next.js', react: 'React', html: 'HTML' };
11
11
 
12
+ /** The website templates: each is one install of all its sections and pages. */
13
+ async function listWebsitesCommand() {
14
+ const ora = (await import('ora')).default;
15
+ const spinner = ora('Fetching websites...').start();
16
+ try {
17
+ const res = await listWebsites();
18
+ const items = res?.websites || [];
19
+ spinner.stop();
20
+ if (!items.length) { p.log.info('No websites found.'); return; }
21
+ console.log();
22
+ console.log(pc.bold(` ${items.length} websites available\n`));
23
+ for (const item of items) {
24
+ const pages = item.pages > 1 ? `, ${item.pages} pages` : '';
25
+ console.log(` ${pc.cyan(s(item.slug))}${item.is_pro ? pc.magenta(' [PRO]') : pc.green(' [FREE]')}`);
26
+ console.log(pc.gray(` ${s(item.name)}. ${s(item.industry)}. ${item.sections} sections${pages}.`));
27
+ console.log();
28
+ }
29
+ console.log(pc.gray(' astralkit add <name> --website to install the whole website'));
30
+ } catch (err) {
31
+ spinner.fail('Failed to fetch websites.');
32
+ console.error(pc.red(err.message));
33
+ process.exit(1);
34
+ }
35
+ }
36
+
12
37
  export async function listCommand(options) {
38
+ if (options.websites) return listWebsitesCommand();
13
39
  const ora = (await import('ora')).default;
14
40
  const type = options.boosters ? 'boosters' : options.workflows ? 'workflows' : 'components';
15
41
  const spinner = ora(`Fetching ${type}...`).start();
@@ -78,7 +78,7 @@ export async function updateCommand(componentSlug, options) {
78
78
  }
79
79
  const filePath = path.resolve(dir, file.path);
80
80
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
81
- fs.writeFileSync(filePath, file.content);
81
+ fs.writeFileSync(filePath, file.encoding === 'base64' ? Buffer.from(file.content, 'base64') : file.content);
82
82
  }
83
83
 
84
84
  // A newer version of a component can ask for stylesheets the older one carried in its own file
package/src/lib/api.js CHANGED
@@ -117,6 +117,10 @@ export async function apiRequest(urlPath, options = {}) {
117
117
  const safeBody = (body || response.statusText || '').replace(/[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]/g, '').slice(0, 500);
118
118
  const err = new Error(`API error ${response.status}: ${safeBody}`);
119
119
  err.code = 'API_ERROR';
120
+ err.status = response.status;
121
+ // a 429 says how long to wait
122
+ const wait = Number(response.headers.get('retry-after'));
123
+ if (Number.isFinite(wait) && wait > 0) err.retryAfter = wait;
120
124
  throw err;
121
125
  }
122
126
 
@@ -139,8 +143,41 @@ export async function listComponents({ category, framework, pro, free, search }
139
143
  return res.json();
140
144
  }
141
145
 
142
- export async function getComponent(slug, framework = 'html') {
143
- const res = await apiRequest(`/api/cli/components/${encodeURIComponent(slug)}?framework=${encodeURIComponent(framework)}`);
146
+ /**
147
+ * A component's files. The registry allows a number of downloads a minute; a whole website is many sections, so a
148
+ * "too many requests" answer is waited out once (as long as the registry says, at most 70 seconds) instead of failing
149
+ * the install half way. `onWait(seconds)` lets the caller say so on screen.
150
+ */
151
+ export async function getComponent(slug, framework = 'html', { onWait } = {}) {
152
+ const urlPath = `/api/cli/components/${encodeURIComponent(slug)}?framework=${encodeURIComponent(framework)}`;
153
+ try {
154
+ return await (await apiRequest(urlPath)).json();
155
+ } catch (err) {
156
+ if (err.status !== 429) throw err;
157
+ const seconds = Math.min(Math.max(Math.ceil(err.retryAfter || 60), 1), 70);
158
+ onWait?.(seconds);
159
+ await new Promise(done => setTimeout(done, seconds * 1000));
160
+ return (await apiRequest(urlPath)).json();
161
+ }
162
+ }
163
+
164
+ /**
165
+ * A website template as one install: its pages and the sections of each, in page order. Null when there is no
166
+ * website by that name (or it is not published yet). No code is in the answer: each section is then asked for as
167
+ * a component.
168
+ */
169
+ export async function getWebsite(name) {
170
+ try {
171
+ return await (await apiRequest(`/api/cli/websites/${encodeURIComponent(name)}`)).json();
172
+ } catch (err) {
173
+ if (err.status === 404 || err.status === 400) return null;
174
+ throw err;
175
+ }
176
+ }
177
+
178
+ /** The website templates that can be installed as one unit. */
179
+ export async function listWebsites() {
180
+ const res = await apiRequest('/api/cli/websites');
144
181
  return res.json();
145
182
  }
146
183
 
@@ -202,7 +202,8 @@ export function writeFiles(baseDir, files, opts = {}) {
202
202
  }
203
203
  const filePath = path.resolve(baseDir, file.path);
204
204
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
205
- fs.writeFileSync(filePath, file.content);
205
+ // a binary file (a workflow's images, video, fonts) arrives as base64 and is written as bytes
206
+ fs.writeFileSync(filePath, file.encoding === 'base64' ? Buffer.from(file.content, 'base64') : file.content);
206
207
  count++;
207
208
  }
208
209
  return count;
@@ -0,0 +1,147 @@
1
+ /**
2
+ * A website template as one install: the page files that put its sections in order.
3
+ *
4
+ * `astralkit add zest --website` installs every section of the template as a component (the same files, in the same
5
+ * folder, as installing each alone), then writes one file per page that renders them in page order:
6
+ *
7
+ * Next.js, App Router app/zest/page.tsx (and app/luma/about/page.tsx for a template of several pages)
8
+ * React, Pages Router src/components/ui/zest-page.jsx
9
+ * HTML src/components/ui/zest/index.html (and about.html beside it)
10
+ *
11
+ * Nothing here talks to the network or the terminal: it works out file names and file contents.
12
+ */
13
+ import fs from 'fs';
14
+ import path from 'path';
15
+
16
+ const posix = (file) => file.replace(/\\/g, '/');
17
+
18
+ /** zest-hero -> ZestHero. A name that would start with a digit gets a letter in front. */
19
+ export function componentName(slug) {
20
+ const name = String(slug).split(/[^a-zA-Z0-9]+/).filter(Boolean).map(part => part[0].toUpperCase() + part.slice(1)).join('');
21
+ return /^[A-Z]/.test(name) ? name : `Page${name}`;
22
+ }
23
+
24
+ /** The App Router folder of a Next.js project, if it has one. */
25
+ export function appDirOf(cwd) {
26
+ for (const candidate of ['src/app', 'app']) if (fs.existsSync(path.join(cwd, candidate))) return candidate;
27
+ return null;
28
+ }
29
+
30
+ /**
31
+ * Where each page of the website goes. Returns { kind, pages: [{ page, file }], base }:
32
+ * kind 'routes' real routes (Next.js App Router); `base` is the address of the home page (/zest)
33
+ * kind 'components' one component per page, next to the sections
34
+ * kind 'html' one .html file per page, in a folder of their own
35
+ */
36
+ export function planPages({ site, framework, cwd, componentsDir, ext }) {
37
+ if (framework === 'html') {
38
+ return { kind: 'html', base: null, pages: site.pages.map(page => ({ page, file: posix(path.join(componentsDir, site.slug, page.file)) })) };
39
+ }
40
+ const appDir = framework === 'nextjs' ? appDirOf(cwd) : null;
41
+ if (appDir) {
42
+ return {
43
+ kind: 'routes',
44
+ base: `/${site.slug}`,
45
+ pages: site.pages.map(page => ({ page, file: posix(path.join(appDir, site.slug, page.route, `page${ext}`)) })),
46
+ };
47
+ }
48
+ return {
49
+ kind: 'components',
50
+ base: null,
51
+ pages: site.pages.map(page => ({ page, file: posix(path.join(componentsDir, `${site.slug}${page.route ? `-${page.route}` : ''}-page${ext}`)) })),
52
+ };
53
+ }
54
+
55
+ /**
56
+ * A page as a React component: the navigation and the footer are landmarks of their own, so they sit beside <main>,
57
+ * not in it. `sections` are the slugs that are really in the project; `importFrom(slug)` is the path to import one from.
58
+ */
59
+ export function pageSource({ site, page, sections, importFrom, command }) {
60
+ const header = sections[0]?.endsWith('-navigation') ? sections[0] : null;
61
+ const footer = sections.length > 1 && sections[sections.length - 1].endsWith('-footer') ? sections[sections.length - 1] : null;
62
+ const body = sections.filter(slug => slug !== header && slug !== footer);
63
+ const tag = (slug) => `<${componentName(slug)} />`;
64
+ const title = page.route ? `${site.name}: ${page.name}` : site.name;
65
+ return [
66
+ '/**',
67
+ ` * ${title}`,
68
+ ` * The ${site.name} website template${page.route ? `, its "${page.name}" page` : ''}: its sections, in page order.`,
69
+ ` * Written by: ${command}`,
70
+ ' *',
71
+ ' * Each section is a component of its own. The business in them is sample content: keep the layout,',
72
+ ' * and change the name, the copy and the photos in the section files.',
73
+ ' */',
74
+ ...sections.map(slug => `import ${componentName(slug)} from '${importFrom(slug)}';`),
75
+ '',
76
+ `export default function ${componentName(`${site.slug}-${page.route || ''}-page`)}() {`,
77
+ ' return (',
78
+ ' <>',
79
+ ...(header ? [` ${tag(header)}`] : []),
80
+ ...(body.length ? [' <main>', ...body.map(slug => ` ${tag(slug)}`), ' </main>'] : []),
81
+ ...(footer ? [` ${tag(footer)}`] : []),
82
+ ' </>',
83
+ ' );',
84
+ '}',
85
+ '',
86
+ ].join('\n');
87
+ }
88
+
89
+ /**
90
+ * A template of several pages links them by file name (href="about.html", href="index.html#care"), which is right
91
+ * for a folder of HTML files. In an app with real routes those links are pointed at the routes: /luma/about, /luma#care.
92
+ * Only links to the template's own pages are touched. Returns the new code and how many links changed.
93
+ */
94
+ export function pointLinksAtRoutes(code, site, base) {
95
+ const routeOf = new Map(site.pages.map(page => [page.file, page.route ? `${base}/${page.route}` : base]));
96
+ let changed = 0;
97
+ const out = code.replace(/(href=)(["'])([\w-]+\.html)(#[^"']*)?\2/g, (whole, attr, quote, file, hash = '') => {
98
+ if (!routeOf.has(file)) return whole;
99
+ changed++;
100
+ return `${attr}${quote}${routeOf.get(file)}${hash}${quote}`;
101
+ });
102
+ return { code: out, changed };
103
+ }
104
+
105
+ /**
106
+ * One HTML page out of the HTML files of its sections. Each section file is a whole document with the same kind of
107
+ * head (the AstralKit and Tailwind scripts, the template's palette and typefaces): the page takes every head line
108
+ * once, in the order first seen, and the bodies one after another.
109
+ */
110
+ export function composeHtml({ site, page, documents }) {
111
+ const head = [];
112
+ const seen = new Set();
113
+ const bodies = [];
114
+ for (const html of documents) {
115
+ const headPart = /<head[^>]*>([\s\S]*?)<\/head>/i.exec(html)?.[1] || '';
116
+ for (const line of headPart.split('\n').map(text => text.trim()).filter(Boolean)) {
117
+ if (/^<title[\s>]/i.test(line) || seen.has(line)) continue;
118
+ seen.add(line);
119
+ head.push(line);
120
+ }
121
+ const bodyPart = /<body[^>]*>([\s\S]*)<\/body>/i.exec(html)?.[1];
122
+ if (bodyPart) bodies.push(bodyPart.trim());
123
+ }
124
+ const title = (page.route ? `${site.name}: ${page.name}` : site.name).replace(/&/g, '&amp;').replace(/</g, '&lt;');
125
+ const charset = head.findIndex(line => /<meta[^>]+charset/i.test(line));
126
+ const at = charset < 0 ? 0 : charset + 1;
127
+ head.splice(at, 0, `<title>${title}</title>`);
128
+ return [
129
+ `<!-- ${site.name}${page.route ? `: ${page.name}` : ''}. The ${site.name} website template from AstralKit: its sections, in page order. -->`,
130
+ '<!DOCTYPE html>',
131
+ '<html lang="en">',
132
+ '<head>',
133
+ ...head.map(line => ` ${line}`),
134
+ '</head>',
135
+ '<body>',
136
+ bodies.join('\n'),
137
+ '</body>',
138
+ '</html>',
139
+ '',
140
+ ].join('\n');
141
+ }
142
+
143
+ /** The import path of a file from another file's folder, without its extension ("../../components/ui/zest-hero"). */
144
+ export function relativeImport(fromFile, toFile) {
145
+ const to = posix(path.relative(path.dirname(fromFile), toFile)).replace(/\.(tsx|jsx|ts|js)$/, '');
146
+ return to.startsWith('.') ? to : `./${to}`;
147
+ }