Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

refactor(cli): extract init into api/init (thin handler + receipt) (#4460)

Joey93be9abdf7f7
diff --git a/.changeset/cli-thin-api-init.md b/.changeset/cli-thin-api-init.md
new file mode 100644
index 0000000000..3605b82585
--- /dev/null
+++ b/.changeset/cli-thin-api-init.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] CLI: `init` is now fully scriptable through the `./api` barrel — the non-interactive installer (agent-docs cheat sheet, starter template, `--remove-agents`) lives in `api/init` and returns a typed receipt (`init.run` | `init.remove`), with the CLI reduced to a thin parse → API call → render wrapper. Human output is emitted through an injectable logger, so a scripted `init()` stays silent while the CLI output is byte-identical for existing usage.
+@josephfarina
diff --git a/packages/cli/api/index.mjs b/packages/cli/api/index.mjs
index 3a081e012f..9ba9aeff5d 100644
--- a/packages/cli/api/index.mjs
+++ b/packages/cli/api/index.mjs
@@ -30,6 +30,7 @@ export {search} from './search/search.mjs';
export {build} from './build/build.mjs';
export {swizzle} from './swizzle/swizzle.mjs';
export {upgrade} from './upgrade/upgrade.mjs';
+export {init} from './init/init.mjs';
export {doctor} from './doctor/doctor.mjs';
export {layoutExpand, layoutCheck, layoutGrammar} from './layout/layout.mjs';
export {
diff --git a/packages/cli/api/init/init.mjs b/packages/cli/api/init/init.mjs
new file mode 100644
index 0000000000..00c29c55c0
--- /dev/null
+++ b/packages/cli/api/init/init.mjs
@@ -0,0 +1,279 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file init API — non-interactive project setup + feature installer.
+ *
+ * `init(options)` installs the AGENTS.md/CLAUDE.md agent-docs cheat sheet, points
+ * at the theme + page-building workflows, and (optionally) scaffolds a starter
+ * template — with NO prompts, so it behaves identically for humans, agents, CI,
+ * and piped I/O. It performs the side effects and returns a receipt:
+ * - `init.run` — the setup receipt (docs written, features, template outcome)
+ * - `init.remove` — the `--remove-agents` receipt
+ * Hard errors (unknown feature/template) throw AstryxError with a stable code.
+ * Human output is emitted through the injected `logger` (silent by default) so
+ * the CLI keeps its exact plain output and a programmatic caller stays quiet.
+ *
+ * The logger here is a PLAIN log/error pair, NOT the clack-style term-log used by
+ * upgrade/theme: init's output has always been flat humanLog lines, so a
+ * byte-identical CLI needs a plain passthrough, not intro/step/success framing.
+ *
+ * Note: `--remove-agents` calls removeAgentDocs(), which still logs its own
+ * per-file lines via humanLog (shared lib behavior) — so a programmatic remove
+ * is not perfectly silent yet. Threading a logger through agent-docs is a
+ * separate cleanup.
+ */
+
+import * as path from 'node:path';
+import * as fs from 'node:fs';
+import {CLI_ROOT} from '../../utils/paths.mjs';
+import {PathSafetyError} from '../../utils/path-safety.mjs';
+import {getCliInvocation} from '../../utils/package-manager.mjs';
+import {
+ installAgentDocs,
+ removeAgentDocs,
+} from '../../lib/agent-docs/agent-docs.mjs';
+import {listTemplates} from '../template/template.mjs';
+import {AstryxError} from '../error.mjs';
+import {ERROR_CODES} from '../../lib/error-codes.mjs';
+
+const VALID_FEATURES = ['agents', 'theme', 'template'];
+
+/**
+ * Plain injectable logger for init's flat output.
+ * @typedef {object} InitLogger
+ * @property {(m?: string) => void} log stdout line (the CLI maps this to humanLog)
+ * @property {(m?: string) => void} error stderr line (the CLI maps this to console.error)
+ */
+
+/** Silent logger — the default for programmatic callers. @type {InitLogger} */
+export const noopInitLogger = {log() {}, error() {}};
+
+/**
+ * @typedef {object} InitOptions
+ * @property {string} [features] comma-separated features (agents, theme, template)
+ * @property {boolean} [all] install all features
+ * @property {boolean} [removeAgents] remove the managed agent-docs block
+ * @property {string} [agent] agent preset (claude, cursor, codex, hermes, all)
+ * @property {string | string[]} [agentDocsPath] explicit agent-docs path(s)
+ * @property {string} [templateName] programmatic-only; the CLI never sets it
+ */
+
+/**
+ * @typedef {object} InitRunData
+ * @property {'default' | 'features'} mode
+ * @property {string[]} features features that were run
+ * @property {string[]} docsWritten agent-doc files written (empty if not run/failed)
+ * @property {{kind: 'path-safety' | 'install-failed', message?: string} | null} docsError
+ * @property {boolean} theme whether theme guidance was emitted
+ * @property {'workflow' | 'created' | 'skipped' | null} template template outcome
+ * @property {string | null} templatePath relative path when `template === 'created'`
+ * @property {boolean} nextSteps whether the getting-started next-steps were emitted
+ */
+
+/**
+ * Build the "Next steps" lines printed at the end of `astryx init`.
+ *
+ * Theme guidance must match the runtime recommendation emitted by core's
+ * <Theme> component (packages/core/src/theme/Theme.tsx): the pre-built theme
+ * path (`/built` import + `theme.css`) plus the base CSS import, so users
+ * don't end up with an unstyled app or the slower runtime style-injection
+ * path. See https://github.com/facebook/astryx/issues/3080.
+ *
+ * @param {string} invocation install-aware CLI invocation stem (e.g. `npx astryx`, `pnpm exec astryx`, or `npx @astryxdesign/cli` for one-off runs)
+ * @returns {string[]} ordered list of human-facing lines
+ */
+export function getNextSteps(invocation) {
+ return [
+ '',
+ ' Next steps:',
+ " 1. Import base styles: import '@astryxdesign/core/reset.css'",
+ " and import '@astryxdesign/core/astryx.css'",
+ " 2. Import components: import { Button } from '@astryxdesign/core'",
+ ' 3. Optionally add a theme (use the pre-built path for performance):',
+ " import { neutralTheme } from '@astryxdesign/theme-neutral/built'",
+ " import '@astryxdesign/theme-neutral/theme.css'",
+ ' <Theme theme={neutralTheme}>...</Theme>',
+ ` For custom themes, run \`${invocation} theme build <file>\` to generate the built artifacts.`,
+ ` 4. ${invocation} --help for all commands`,
+ '',
+ ];
+}
+
+/**
+ * Install the agent-docs block; records the outcome (or soft error) on `data`.
+ * Mirrors the CLI's historical soft-error policy: a PathSafetyError surfaces its
+ * precise message and flags a non-zero exit; any other failure prints the
+ * generic retry hint and continues without changing the exit code.
+ *
+ * @param {string} cwd
+ * @param {InitOptions} options
+ * @param {string} run
+ * @param {InitLogger} logger
+ * @param {InitRunData} data
+ */
+function applyAgents(cwd, options, run, logger, data) {
+ try {
+ const paths = options.agentDocsPath
+ ? Array.isArray(options.agentDocsPath)
+ ? options.agentDocsPath
+ : [options.agentDocsPath]
+ : undefined;
+ const written = installAgentDocs(cwd, {agent: options.agent, paths});
+ data.docsWritten = written;
+ logger.log(`✓ AI agent docs installed → ${written.join(', ')}`);
+ } catch (err) {
+ // PathSafetyError carries a precise, user-actionable message — surface it
+ // (and flag exit 1) instead of the generic "could not install" warning so
+ // misconfigured --agent-docs-path values aren't silently swallowed.
+ if (err instanceof PathSafetyError) {
+ logger.error(`Error: ${err.message}`);
+ data.docsError = {kind: 'path-safety', message: err.message};
+ return;
+ }
+ logger.error(
+ `Could not install agent docs. Try again with \`${run} init --features agents\`.`,
+ );
+ data.docsError = {kind: 'install-failed'};
+ }
+}
+
+/**
+ * Emit the template guidance, or (programmatic-only) scaffold a named template.
+ * The CLI never passes `templateName`, so from the CLI this always emits the
+ * build-workflow prose (or nothing when no templates are bundled).
+ *
+ * @param {string} cwd
+ * @param {{templateName?: string}} opts
+ * @param {string} run
+ * @param {InitLogger} logger
+ * @param {InitRunData} data
+ */
+function applyTemplate(cwd, {templateName}, run, logger, data) {
+ const templates = listTemplates();
+ if (templates.length === 0) {
+ data.template = 'skipped';
+ return;
+ }
+
+ if (!templateName) {
+ // Point agents at the build workflow rather than dumping page-template
+ // names — `build` surfaces pages AND blocks AND components for an idea,
+ // and `build` with no args is the full how-to-build playbook.
+ logger.log('✓ To build UI, use these commands:');
+ logger.log('');
+ logger.log(
+ ` ${run} build "<what you're building>" build a page — kit: closest template + blocks + components`,
+ );
+ logger.log(
+ ` ${run} build the how-to-build workflow (read this first)`,
+ );
+ logger.log(
+ ` ${run} search <query> find anything — components, docs, templates, blocks`,
+ );
+ logger.log('');
+ data.template = 'workflow';
+ return;
+ }
+
+ if (!templates.includes(templateName)) {
+ throw new AstryxError(
+ `Unknown template "${templateName}". Available: ${templates.join(', ')}`,
+ undefined,
+ ERROR_CODES.ERR_UNKNOWN_TEMPLATE,
+ );
+ }
+
+ const outputDir = path.resolve(cwd, `./src/pages/${templateName}`);
+ const srcPath = path.join(CLI_ROOT, 'templates', 'pages', templateName, 'page.tsx');
+ fs.mkdirSync(outputDir, {recursive: true});
+ fs.copyFileSync(srcPath, path.join(outputDir, 'page.tsx'));
+ const rel = path.relative(cwd, outputDir);
+ logger.log(`✓ Template created at ${rel}/page.tsx`);
+ data.template = 'created';
+ data.templatePath = rel;
+}
+
+/**
+ * Run the non-interactive init flow. Performs the side effects (agent-docs
+ * install, template scaffold, or agent-docs removal) and returns a receipt.
+ * Progress is emitted through `logger` (silent by default); unknown feature or
+ * template names throw AstryxError with a stable code.
+ *
+ * @param {InitOptions} [options]
+ * @param {{cwd?: string, logger?: InitLogger}} [ctx]
+ * @returns {Promise<{type: 'init.run', data: InitRunData} | {type: 'init.remove', data: {removed: true}}>}
+ */
+export async function init(options = {}, {cwd = process.cwd(), logger = noopInitLogger} = {}) {
+ const run = getCliInvocation();
+
+ // Remove mode.
+ if (options.removeAgents) {
+ removeAgentDocs(cwd);
+ logger.log('✓ AI agent docs removed.');
+ return {type: 'init.remove', data: {removed: true}};
+ }
+
+ // Non-interactive feature install: --features or --all.
+ if (options.features || options.all) {
+ const features = options.all
+ ? VALID_FEATURES
+ : String(options.features)
+ .split(',')
+ .map(f => f.trim().toLowerCase());
+
+ const invalid = features.filter(f => !VALID_FEATURES.includes(f));
+ if (invalid.length > 0) {
+ throw new AstryxError(
+ `Unknown features: ${invalid.join(', ')}. Valid features: ${VALID_FEATURES.join(', ')}`,
+ undefined,
+ ERROR_CODES.ERR_UNKNOWN_FEATURE,
+ );
+ }
+
+ /** @type {InitRunData} */
+ const data = {
+ mode: 'features',
+ features,
+ docsWritten: [],
+ docsError: null,
+ theme: false,
+ template: null,
+ templatePath: null,
+ nextSteps: false,
+ };
+ for (const feature of features) {
+ if (feature === 'agents') applyAgents(cwd, options, run, logger, data);
+ if (feature === 'theme') {
+ logger.log(
+ `✓ For a custom theme, run \`${run} theme\` (browse) or \`${run} theme add <slug>\` (scaffold).`,
+ );
+ data.theme = true;
+ }
+ if (feature === 'template') {
+ applyTemplate(cwd, {templateName: options.templateName}, run, logger, data);
+ }
+ }
+ return {type: 'init.run', data};
+ }
+
+ // No flags: TTY-free default — install the AI agent cheat sheet with NO
+ // prompts, then print the getting-started guidance.
+ /** @type {InitRunData} */
+ const data = {
+ mode: 'default',
+ features: ['agents'],
+ docsWritten: [],
+ docsError: null,
+ theme: false,
+ template: null,
+ templatePath: null,
+ nextSteps: true,
+ };
+ applyAgents(cwd, options, run, logger, data);
+ logger.log('');
+ logger.log(
+ ` Tip: \`${run} init --all\` also points you to the theme and page-building workflows.`,
+ );
+ for (const line of getNextSteps(run)) logger.log(line);
+ return {type: 'init.run', data};
+}
diff --git a/packages/cli/api/init/init.test.mjs b/packages/cli/api/init/init.test.mjs
new file mode 100644
index 0000000000..119dceb25c
--- /dev/null
+++ b/packages/cli/api/init/init.test.mjs
@@ -0,0 +1,149 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Direct-API tests for init(). These call the function straight (no CLI
+ * harness) against a throwaway cwd, asserting the receipt, the on-disk effects,
+ * cwd honoring, silence-by-default, and the exact lines emitted through the
+ * injected logger (the CLI's byte-for-byte source). Command-level behavior
+ * (flag parsing, exit codes) is covered by cli/commands/init.behavior.test.mjs.
+ */
+
+import {describe, it, expect, beforeEach, afterEach, vi} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import * as os from 'node:os';
+import {init, getNextSteps} from './init.mjs';
+import {AstryxError} from '../error.mjs';
+import {ERROR_CODES} from '../../lib/error-codes.mjs';
+
+const MARKER_START = '<!-- ASTRYX:START -->';
+
+let tmpDir;
+
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-init-api-'));
+});
+
+afterEach(() => {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+/** @param {string} rel */
+const read = rel => fs.readFileSync(path.join(tmpDir, rel), 'utf8');
+/** @param {string} rel */
+const exists = rel => fs.existsSync(path.join(tmpDir, rel));
+
+describe('init() — receipts + side effects', () => {
+ it('default mode installs AGENTS.md and returns an init.run receipt', async () => {
+ const res = await init({}, {cwd: tmpDir});
+ expect(res.type).toBe('init.run');
+ if (res.type !== 'init.run') return;
+ expect(res.data.mode).toBe('default');
+ expect(res.data.nextSteps).toBe(true);
+ expect(res.data.docsWritten).toContain('AGENTS.md');
+ expect(res.data.docsError).toBeNull();
+ expect(exists('AGENTS.md')).toBe(true);
+ expect(read('AGENTS.md')).toContain(MARKER_START);
+ });
+
+ it('writes to the cwd param, not process.cwd() (no chdir)', async () => {
+ // Regression guard: the fixture lives in tmpDir while process.cwd() stays
+ // the repo root. A cwd-honoring API must land AGENTS.md in tmpDir.
+ const before = process.cwd();
+ const res = await init({features: 'agents'}, {cwd: tmpDir});
+ expect(process.cwd()).toBe(before);
+ expect(exists('AGENTS.md')).toBe(true);
+ expect(res.type === 'init.run' && res.data.docsWritten).toContain('AGENTS.md');
+ });
+
+ it('--features theme emits guidance, writes no files, and flags theme', async () => {
+ const res = await init({features: 'theme'}, {cwd: tmpDir});
+ expect(res.type).toBe('init.run');
+ if (res.type !== 'init.run') return;
+ expect(res.data.theme).toBe(true);
+ expect(res.data.docsWritten).toEqual([]);
+ expect(fs.readdirSync(tmpDir)).toEqual([]);
+ });
+
+ it('--features template returns the workflow (or skipped) outcome, no crash', async () => {
+ const res = await init({features: 'template'}, {cwd: tmpDir});
+ expect(res.type).toBe('init.run');
+ if (res.type !== 'init.run') return;
+ expect(['workflow', 'skipped']).toContain(res.data.template);
+ });
+
+ it('--all runs every feature', async () => {
+ const res = await init({all: true}, {cwd: tmpDir});
+ expect(res.type).toBe('init.run');
+ if (res.type !== 'init.run') return;
+ expect(res.data.features).toEqual(['agents', 'theme', 'template']);
+ expect(exists('AGENTS.md')).toBe(true);
+ expect(res.data.theme).toBe(true);
+ });
+
+ it('--agent claude targets .claude/CLAUDE.md', async () => {
+ await init({agent: 'claude'}, {cwd: tmpDir});
+ expect(exists('.claude/CLAUDE.md')).toBe(true);
+ expect(read('.claude/CLAUDE.md')).toContain(MARKER_START);
+ });
+
+ it('--remove-agents returns an init.remove receipt and deletes the block', async () => {
+ await init({features: 'agents'}, {cwd: tmpDir});
+ expect(exists('AGENTS.md')).toBe(true);
+ const res = await init({removeAgents: true}, {cwd: tmpDir});
+ expect(res.type).toBe('init.remove');
+ expect(res.data).toEqual({removed: true});
+ expect(exists('AGENTS.md')).toBe(false);
+ });
+});
+
+describe('init() — errors', () => {
+ it('throws AstryxError(ERR_UNKNOWN_FEATURE) for an invalid feature', async () => {
+ await expect(init({features: 'bogus'}, {cwd: tmpDir})).rejects.toMatchObject({
+ code: ERROR_CODES.ERR_UNKNOWN_FEATURE,
+ });
+ // Nothing written on rejection.
+ expect(fs.readdirSync(tmpDir)).toEqual([]);
+ });
+
+ it('the thrown error is an AstryxError with a helpful message', async () => {
+ let caught;
+ try {
+ await init({features: 'nope,agents'}, {cwd: tmpDir});
+ } catch (e) {
+ caught = e;
+ }
+ expect(caught).toBeInstanceOf(AstryxError);
+ expect(caught.message).toMatch(/Unknown features: nope/);
+ expect(caught.message).toMatch(/agents, theme, template/);
+ });
+});
+
+describe('init() — logger', () => {
+ it('is silent by default (noop logger — no console output)', async () => {
+ const out = [];
+ const err = [];
+ const logSpy = vi.spyOn(console, 'log').mockImplementation((...a) => out.push(a.join(' ')));
+ const errSpy = vi.spyOn(console, 'error').mockImplementation((...a) => err.push(a.join(' ')));
+ try {
+ await init({features: 'theme'}, {cwd: tmpDir});
+ } finally {
+ logSpy.mockRestore();
+ errSpy.mockRestore();
+ }
+ expect(out).toEqual([]);
+ expect(err).toEqual([]);
+ });
+
+ it('emits the install line + full next-steps through the injected logger', async () => {
+ /** @type {string[]} */
+ const lines = [];
+ const logger = {log: m => lines.push(m ?? ''), error: m => lines.push(`ERR:${m}`)};
+ await init({}, {cwd: tmpDir, logger});
+ const text = lines.join('\n');
+ expect(text).toContain('✓ AI agent docs installed → AGENTS.md');
+ expect(text).toContain(' Next steps:');
+ // The exact next-steps block the CLI prints comes from getNextSteps().
+ expect(text).toContain(getNextSteps('npx astryx')[2].slice(0, 20));
+ });
+});
diff --git a/packages/cli/cli/commands/init.mjs b/packages/cli/cli/commands/init.mjs
index fbf5fa25f6..9830a2755c 100644
--- a/packages/cli/cli/commands/init.mjs
+++ b/packages/cli/cli/commands/init.mjs
@@ -1,136 +1,22 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file init command — non-interactive setup + feature installer
+ * @file init command — thin wrapper around the init API.
*
* `astryx init` is non-interactive by default: it installs the AGENTS.md/
* CLAUDE.md cheat sheet with NO prompts, so it behaves identically for humans,
* AI agents, CI, and piped I/O — it never hangs or errors on a missing TTY.
* Non-interactive feature install: `astryx init --features agents,theme,template`
- * Re-runnable: safe to run multiple times, idempotent
+ * Re-runnable: safe to run multiple times, idempotent.
*
- * Features:
- * agents — Install AGENTS.md/CLAUDE.md cheat sheet for AI coding agents
- * theme — Point to the theme workflow (`astryx theme`)
- * template — Copy a starter page template
+ * All logic + side effects live in api/init/init.mjs. This handler only parses
+ * flags, wires a plain logger to the CLI's humanLog/console.error, calls init(),
+ * and maps the receipt's soft agent-docs error to the exit code.
*/
-import * as path from 'node:path';
-import * as fs from 'node:fs';
-import {CLI_ROOT} from '../../utils/paths.mjs';
-import {PathSafetyError} from '../../utils/path-safety.mjs';
-import {getCliInvocation} from '../../utils/package-manager.mjs';
-import {installAgentDocs, removeAgentDocs} from '../../lib/agent-docs/agent-docs.mjs';
-import {listTemplates} from './template.mjs';
+import {init} from '../../api/init/init.mjs';
import {humanLog} from '../../lib/json.mjs';
import {cliError} from '../../lib/cli-error.mjs';
-import {ERROR_CODES} from '../../lib/error-codes.mjs';
-
-const VALID_FEATURES = ['agents', 'theme', 'template'];
-const run = getCliInvocation();
-
-/**
- * Build the "Next steps" lines printed at the end of `astryx init`.
- *
- * Theme guidance must match the runtime recommendation emitted by core's
- * <Theme> component (packages/core/src/theme/Theme.tsx): the pre-built theme
- * path (`/built` import + `theme.css`) plus the base CSS import, so users
- * don't end up with an unstyled app or the slower runtime style-injection
- * path. See https://github.com/facebook/astryx/issues/3080.
- *
- * Exported for testing.
- *
- * @param {string} invocation install-aware CLI invocation stem (e.g. `npx astryx`, `pnpm exec astryx`, or `npx @astryxdesign/cli` for one-off runs)
- * @returns {string[]} ordered list of human-facing lines
- */
-export function getNextSteps(invocation) {
- return [
- '',
- ' Next steps:',
- " 1. Import base styles: import '@astryxdesign/core/reset.css'",
- " and import '@astryxdesign/core/astryx.css'",
- " 2. Import components: import { Button } from '@astryxdesign/core'",
- ' 3. Optionally add a theme (use the pre-built path for performance):',
- " import { neutralTheme } from '@astryxdesign/theme-neutral/built'",
- " import '@astryxdesign/theme-neutral/theme.css'",
- ' <Theme theme={neutralTheme}>...</Theme>',
- ` For custom themes, run \`${invocation} theme build <file>\` to generate the built artifacts.`,
- ` 4. ${invocation} --help for all commands`,
- '',
- ];
-}
-
-// ─── Feature: agents ─────────────────────────────────────────────────────────
-
-/**
- * @param {string} targetDir
- * @param {{agent?: string, agentDocsPath?: string | string[]}} [opts]
- */
-function runAgents(targetDir, {agent, agentDocsPath} = {}) {
- try {
- const paths = agentDocsPath
- ? Array.isArray(agentDocsPath)
- ? agentDocsPath
- : [agentDocsPath]
- : undefined;
- const written = installAgentDocs(targetDir, {agent, paths});
- const summary = written.join(', ');
- humanLog(`✓ AI agent docs installed → ${summary}`);
- } catch (err) {
- // PathSafetyError carries a precise, user-actionable message —
- // surface it instead of the generic "could not install" warning so
- // misconfigured --agent-docs-path values aren't silently swallowed.
- if (err instanceof PathSafetyError) {
- console.error(`Error: ${err.message}`);
- process.exitCode = 1;
- return;
- }
- console.error(`Could not install agent docs. Try again with \`${run} init --features agents\`.`);
- }
-}
-
-// ─── Feature: theme ──────────────────────────────────────────────────────────
-
-function runTheme() {
- humanLog(`✓ For a custom theme, run \`${run} theme\` (browse) or \`${run} theme add <slug>\` (scaffold).`);
-}
-
-// ─── Feature: template ───────────────────────────────────────────────────────
-
-/**
- * @param {string} targetDir
- * @param {{templateName?: string}} [opts]
- */
-function runTemplate(targetDir, {templateName} = {}) {
- const templates = listTemplates();
- if (templates.length === 0) return;
-
- if (!templateName) {
- // Point agents at the build workflow rather than dumping page-template
- // names — `build` surfaces pages AND blocks AND components for an idea,
- // and `build` with no args is the full how-to-build playbook.
- humanLog('✓ To build UI, use these commands:');
- humanLog('');
- humanLog(` ${run} build "<what you're building>" build a page — kit: closest template + blocks + components`);
- humanLog(` ${run} build the how-to-build workflow (read this first)`);
- humanLog(` ${run} search <query> find anything — components, docs, templates, blocks`);
- humanLog('');
- return;
- }
-
- if (!templates.includes(templateName)) {
- cliError(`Unknown template "${templateName}". Available: ${templates.join(', ')}`, {code: ERROR_CODES.ERR_UNKNOWN_TEMPLATE});
- return;
- }
-
- const outputDir = path.resolve(targetDir, `./src/pages/${templateName}`);
- const srcPath = path.join(CLI_ROOT, 'templates', 'pages', templateName, 'page.tsx');
- fs.mkdirSync(outputDir, {recursive: true});
- fs.copyFileSync(srcPath, path.join(outputDir, 'page.tsx'));
- humanLog(`✓ Template created at ${path.relative(targetDir, outputDir)}/page.tsx`);
-}
-
-// ─── Command ─────────────────────────────────────────────────────────────────
/**
* @param {import('commander').Command} program
@@ -144,52 +30,21 @@ export function registerInit(program) {
.option('--remove-agents', 'Remove AI agent docs from all agent doc files')
.option('--agent <tool>', 'Target AI tool for agent docs: claude, cursor, codex, hermes, all')
.option('--agent-docs-path <path...>', 'Explicit file path(s) for agent docs')
- .action((/** @type {{features?: string, all?: boolean, removeAgents?: boolean, agent?: string, agentDocsPath?: string | string[]}} */ options) => {
- const targetDir = process.cwd();
-
- // Remove mode
- if (options.removeAgents) {
- removeAgentDocs(targetDir);
- humanLog('✓ AI agent docs removed.');
- return;
- }
-
- // Non-interactive: --features or --all
- if (options.features || options.all) {
- const features = options.all
- ? VALID_FEATURES
- : /** @type {string} */ (options.features).split(',').map(f => f.trim().toLowerCase());
-
- const invalid = features.filter(f => !VALID_FEATURES.includes(f));
- if (invalid.length > 0) {
- cliError(`Unknown features: ${invalid.join(', ')}. Valid features: ${VALID_FEATURES.join(', ')}`, {code: ERROR_CODES.ERR_UNKNOWN_FEATURE});
- return;
- }
-
- for (const feature of features) {
- if (feature === 'agents') runAgents(targetDir, {
- agent: options.agent,
- agentDocsPath: options.agentDocsPath,
- });
- if (feature === 'theme') runTheme();
- if (feature === 'template') runTemplate(targetDir, {});
+ .action(async (/** @type {import('../../api/init/init.mjs').InitOptions} */ options) => {
+ // Plain logger: init's output is flat humanLog lines (stdout) + raw
+ // console.error (stderr), never the clack-style term-log.
+ /** @type {import('../../api/init/init.mjs').InitLogger} */
+ const logger = {log: humanLog, error: m => console.error(m)};
+ try {
+ const receipt = await init(options, {cwd: process.cwd(), logger});
+ // A path-safety failure already printed its error but the run
+ // continued; reflect it in the exit code (historical soft-error policy).
+ if (receipt.type === 'init.run' && receipt.data.docsError?.kind === 'path-safety') {
+ process.exitCode = 1;
}
- return;
- }
-
- // No flags: TTY-free default. `astryx init` installs the AI agent cheat
- // sheet with NO prompts, so it behaves identically for humans, agents, CI,
- // and piped I/O — it never hangs or errors on a missing TTY. (A guided
- // `--interactive` setup may return later as an explicit opt-in.)
- runAgents(targetDir, {
- agent: options.agent,
- agentDocsPath: options.agentDocsPath,
- });
- humanLog('');
- humanLog(` Tip: \`${run} init --all\` also points you to the theme and page-building workflows.`);
-
- for (const line of getNextSteps(run)) {
- humanLog(line);
+ } catch (err) {
+ const e = /** @type {import('../../api/error.mjs').AstryxError} */ (err);
+ cliError(e.message, {suggestions: e.suggestions, code: e.code});
}
});
}
diff --git a/packages/cli/cli/commands/init.next-steps.test.mjs b/packages/cli/cli/commands/init.next-steps.test.mjs
index 72ef640cac..1211118d23 100644
--- a/packages/cli/cli/commands/init.next-steps.test.mjs
+++ b/packages/cli/cli/commands/init.next-steps.test.mjs
@@ -20,7 +20,7 @@
*/
import {describe, it, expect} from 'vitest';
-import {getNextSteps} from './init.mjs';
+import {getNextSteps} from '../../api/init/init.mjs';
describe('init Next steps theme guidance', () => {
const text = getNextSteps('npx astryx').join('\n');
diff --git a/packages/cli/types/api.d.ts b/packages/cli/types/api.d.ts
index 9ee4a3a59a..afcc6d0894 100644
--- a/packages/cli/types/api.d.ts
+++ b/packages/cli/types/api.d.ts
@@ -60,6 +60,7 @@ import type {
UpgradeRunResponse,
} from './upgrade';
import type {BlogListResponse, BlogDetailResponse} from './blog';
+import type {InitRunResponse, InitRemoveResponse} from './init';
import type {Suggestion} from './base';
/** Structured API error with a stable machine-readable code. */
@@ -351,3 +352,30 @@ export declare function upgrade(
export declare function blog(
slug?: string,
): Promise<BlogListResponse | BlogDetailResponse>;
+
+// ── Init ─────────────────────────────────────────────────────────────
+
+export interface InitOptions {
+ /** Comma-separated features to install (agents, theme, template). */
+ features?: string;
+ /** Install all features. */
+ all?: boolean;
+ /** Remove the managed agent-docs block instead of installing. */
+ removeAgents?: boolean;
+ /** Agent preset: claude, cursor, codex, hermes, all. */
+ agent?: string;
+ /** Explicit agent-docs file path(s). */
+ agentDocsPath?: string | string[];
+ /** Scaffold a named page template (programmatic only; the CLI never sets it). */
+ templateName?: string;
+}
+
+/**
+ * Run the non-interactive init flow (agent-docs install, template scaffold, or
+ * agent-docs removal). Performs the effect and returns a receipt; throws
+ * AstryxError on an unknown feature or template name.
+ */
+export declare function init(
+ options?: InitOptions,
+ ctx?: {cwd?: string},
+): Promise<InitRunResponse | InitRemoveResponse>;
diff --git a/packages/cli/types/init.d.ts b/packages/cli/types/init.d.ts
new file mode 100644
index 0000000000..45447baa09
--- /dev/null
+++ b/packages/cli/types/init.d.ts
@@ -0,0 +1,35 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Response types for the `init` API (@astryxdesign/cli/api → init).
+ * Options live in api.d.ts (like UpgradeOptions).
+ */
+
+export interface InitRunData {
+ /** `default` (no flags) or `features` (--features/--all). */
+ mode: 'default' | 'features';
+ /** Features that were run, in order. */
+ features: string[];
+ /** Agent-doc files written (empty if agents weren't run or install failed). */
+ docsWritten: string[];
+ /** Soft agent-docs failure, if any. `path-safety` also implies a non-zero exit. */
+ docsError: {kind: 'path-safety' | 'install-failed'; message?: string} | null;
+ /** Whether theme guidance was emitted. */
+ theme: boolean;
+ /** Template outcome (`workflow` is the CLI default; `created`/`skipped` are programmatic). */
+ template: 'workflow' | 'created' | 'skipped' | null;
+ /** Relative output path when `template === 'created'`. */
+ templatePath: string | null;
+ /** Whether the getting-started "Next steps" were emitted (default mode). */
+ nextSteps: boolean;
+}
+
+export interface InitRunResponse {
+ type: 'init.run';
+ data: InitRunData;
+}
+
+export interface InitRemoveResponse {
+ type: 'init.remove';
+ data: {removed: true};
+}