Skip to content

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

TypeScript

feat(cli): full API coverage — build/swizzle/layout/validate as thin CLI (#4302)

Joey7c053eca756e
diff --git a/.github/scripts/api-cli-parity-test.mjs b/.github/scripts/api-cli-parity-test.mjs
index 6a6a22ee6e..a709b0b0e0 100644
--- a/.github/scripts/api-cli-parity-test.mjs
+++ b/.github/scripts/api-cli-parity-test.mjs
@@ -254,9 +254,22 @@ add('discover (list)', ['discover'],
// checks (and their statuses) is deterministic and must match exactly.
add('doctor', ['doctor'], () => apiCall(api.doctor, {cwd: ROOT}));
+// Build — playbook signal (build.help) + composition kit (build.kit).
+add('build', ['build'],
+ () => apiCall(api.build, undefined, {cwd: ROOT}));
+add('build dashboard', ['build', 'dashboard'],
+ () => apiCall(api.build, 'dashboard', {cwd: ROOT}));
+add('build (no match)', ['build', 'zzznomatch99'],
+ () => apiCall(api.build, 'zzznomatch99', {cwd: ROOT}));
+
+// Swizzle — list + not-found are read-only; the api matches the CLI envelope.
+add('swizzle --list', ['swizzle', '--list'],
+ () => apiCall(api.swizzle, undefined, {list: true, cwd: ROOT}));
+add('swizzle (not found)', ['swizzle', 'NotARealComponent99'],
+ () => apiCall(api.swizzle, 'NotARealComponent99', {cwd: ROOT}));
+
// Other commands — probe with safe read-only args (no API yet)
const otherCommands = [
- ['swizzle', '--list'],
['upgrade', '--list'],
];
for (const args of otherCommands) {
diff --git a/.github/scripts/cli-json-smoke-test.mjs b/.github/scripts/cli-json-smoke-test.mjs
index bbca61bd50..e40232f6e2 100644
--- a/.github/scripts/cli-json-smoke-test.mjs
+++ b/.github/scripts/cli-json-smoke-test.mjs
@@ -234,6 +234,11 @@ console.log('\nswizzle --json');
checkJson('swizzle --list', ['swizzle', '--list'], {expectType: 'swizzle.list'});
checkJson('swizzle (not found)', ['swizzle', 'NonexistentComponent99'], {expectError: true});
+// ── Build ────────────────────────────────────────────────────────────
+console.log('\nbuild --json');
+checkJson('build (playbook)', ['build'], {expectType: 'build.help'});
+checkJson('build dashboard', ['build', 'dashboard'], {expectType: 'build.kit'});
+
// ── Summary ──────────────────────────────────────────────────────────
console.log(`\n${passed + failed} checks: ${passed} passed, ${failed} failed`);
console.log(`types seen: ${[...seenTypes].sort().join(', ')}`);
diff --git a/packages/cli/CONTRIBUTING.md b/packages/cli/CONTRIBUTING.md
index 6ba59aa84b..351390363d 100644
--- a/packages/cli/CONTRIBUTING.md
+++ b/packages/cli/CONTRIBUTING.md
@@ -18,58 +18,73 @@ User calls API function User runs CLI
Both paths run identical code. The CLI handler just adds argument parsing and output formatting.
+The package is organized into pillars (no `src/` — it was dissolved in the reorg). The
+top-level directory _is_ the module boundary:
+
```
-src/
+packages/cli/
api/ # Programmatic API (exported as @astryxdesign/cli/api)
- index.mjs # barrel: component, docs, discover, template, AstryxError
- component.mjs # component(name?, opts?) → { type, data }
- docs.mjs # docs(topic?, section?, opts?) → { type, data }
- discover.mjs # discover(query?, opts?) → { type, data }
- template.mjs # template(name?, opts?) → { type, data }
- error.mjs # AstryxError class (carries .suggestions)
- commands/ # CLI wrappers (thin: parse args → call API → format output)
- component/index.mjs # calls api/component.mjs
- docs.mjs # calls api/docs.mjs
- discover.mjs # calls api/discover.mjs
- template.mjs # calls api/template.mjs
- hook/index.mjs # calls api/hook.mjs
- swizzle.mjs # CLI-only (side-effect: copies + rewrites imports)
- build-theme.mjs # CLI-only (side-effect: compiles theme to CSS)
- upgrade.mjs # CLI-only (side-effect: runs codemods)
- init.mjs # CLI-only (interactive prompts)
- lib/
+ index.mjs # barrel: component, docs, blog, discover, template,
+ # theme, hook, search, build, swizzle, doctor,
+ # layout*, validateIntegration, AstryxError
+ error.mjs # AstryxError class (carries .suggestions + .code)
+ component/component.mjs # component(name?, opts?) → { type, data }
+ docs/docs.mjs # docs(topic?, section?, opts?) → { type, data }
+ build/build.mjs # build(query, opts?) → build.kit | build.help (raw entries)
+ swizzle/swizzle.mjs # swizzle(component?, opts?) → receipt (side effect in API)
+ integration/ # validateIntegration(pkg?, opts?) → integration.validate
+ ... # one dir per command surface
+ cli/ # CLI layer — MUST NOT be imported by api/
+ index.mjs # program setup + JSON_SUPPORTED set + fallback hook
+ commands/ # thin wrappers: parse args → one API call → render
+ component/index.mjs # calls api/component
+ swizzle.mjs # thin: calls api/swizzle, renders receipt + error codes
+ build.mjs # thin: calls api/build, renders kit (pm-prefixing lives here)
+ upgrade.mjs # side-effect (codemods) — API extraction pending (see Roadmap)
+ build-theme.mjs # side-effect (theme→CSS/TS) — API extraction pending
+ init.mjs # interactive prompts stay CLI-side; core → api/init pending
+ codemods/ # version-to-version migrations (consumed by upgrade)
+ authoring/ # component/doc authoring scaffolds
+ lib/ # shared infra (NOT a data API)
json.mjs # jsonOut(type, data), jsonError(msg) — internal
parse.mjs # parseResponse, isError, assertResponse — consumer
- types/
+ agent-docs/ # ~700-line doc generator/injector (shared: init/upgrade/hook)
+ manifest.mjs # CLI-special: reflects the command tree (injects `program`)
+ utils/ # small pure helpers (package-manager, path-safety, ...)
+ schemas/ # zod/JSON schemas
+ types/ # hand-written .d.ts (see Roadmap: migrating to generated)
api.d.ts # API function signatures + AstryxError
base.d.ts # CLIError, CLIResult<T>, CLIAnyResponse, CLIResponseType
component.d.ts # ComponentListResponse, ComponentDetailResponse, ...
- discover.d.ts # DiscoverListResponse, ...
- docs.d.ts # DocsListResponse, ...
- template.d.ts # TemplateListResponse, TemplateShowResponse, ...
+ build.d.ts # BuildKitResponse, BuildHelpResponse
swizzle.d.ts # SwizzleListResponse, SwizzleCopyResponse
- theme.d.ts # ThemeBuildResponse
- upgrade.d.ts # UpgradeListResponse, UpgradeRunResponse
- index.d.ts # barrel re-export
+ ... # one .d.ts per command; index.d.ts is the barrel
+ bin/ scripts/ docs/ templates/
```
+**Hard boundary:** `api/` never imports from `cli/`. The API is the reusable core;
+the CLI is one consumer of it. Anything shared by both (doc generation, manifest,
+package-manager detection) lives in `lib/` or `utils/`, not `cli/`. Side-effecting
+commands perform the effect _in the API_ and return a `{type, data}` receipt; the CLI
+only chooses how to render it and what exit code to set.
+
## Adding a new command
### Does it need an API function?
-**Yes** if the command returns data that consumers might want programmatically — component docs, template source, lists, search results. Put the logic in `src/api/`, export from `@astryxdesign/cli/api`, and make the CLI handler a thin wrapper.
+**Yes** if the command returns data that consumers might want programmatically — component docs, template source, lists, search results. Put the logic in `api/`, export from `@astryxdesign/cli/api`, and make the CLI handler a thin wrapper.
-**No** if the command is purely interactive or only makes sense in a terminal — `init` (interactive prompts). These can live entirely in `src/commands/`.
+**No** if the command is purely interactive or only makes sense in a terminal — `init` (interactive prompts). The interactive shell can live in `cli/commands/`, but any reusable core (the actual scaffolding work) still belongs in `api/`.
**Rule of thumb:** if it supports `--json`, it should have an API function. The parity test (`api-cli-parity-test.mjs`) will flag any `--json` type that doesn't have API coverage.
### 1. Write the API function
-Add a file in `src/api/` with all the logic. It returns `{ type, data }` on success and throws `AstryxError` on failure. The CLI handler should have zero logic — just arg parsing and text formatting:
+Add a file in `api/<command>/` with all the logic. It returns `{ type, data }` on success and throws `AstryxError` on failure. The CLI handler should have zero logic — just arg parsing and text formatting:
```javascript
-// src/api/my-command.mjs
-import {AstryxError} from './error.mjs';
+// api/my-command/my-command.mjs
+import {AstryxError} from '../error.mjs';
export async function myCommand(name, options = {}) {
if (!name) {
@@ -85,10 +100,10 @@ export async function myCommand(name, options = {}) {
}
```
-Export it from `src/api/index.mjs`:
+Export it from `api/index.mjs`:
```javascript
-export {myCommand} from './my-command.mjs';
+export {myCommand} from './my-command/my-command.mjs';
```
### 2. Create the CLI wrapper
@@ -96,9 +111,9 @@ export {myCommand} from './my-command.mjs';
The CLI handler just parses args, calls the API function, and formats the result. No business logic here:
```javascript
-// src/commands/my-command.mjs
-import {jsonOut, jsonError} from '../lib/json.mjs';
-import {myCommand} from '../api/my-command.mjs';
+// cli/commands/my-command.mjs
+import {jsonOut, jsonError} from '../../lib/json.mjs';
+import {myCommand} from '../../api/my-command/my-command.mjs';
export function registerMyCommand(program) {
program
@@ -124,7 +139,7 @@ export function registerMyCommand(program) {
### 3. Define response types
-Create `src/types/my-command.d.ts`:
+Create `types/my-command.d.ts`:
```typescript
/** xds --json my-command */
@@ -147,13 +162,13 @@ export interface MyCommandDetailResponse {
### 4. Wire it up
-Add to `src/types/index.d.ts`:
+Add to `types/index.d.ts`:
```typescript
export * from './my-command';
```
-Add to `CLIAnyResponse` in `src/types/base.d.ts`:
+Add to `CLIAnyResponse` in `types/base.d.ts`:
```typescript
export type CLIAnyResponse =
@@ -207,17 +222,17 @@ packages/cli/templates/{name}/
### Adding a new option to an existing API function
-1. Add the option to the API function in `src/api/{command}.mjs`
-2. Pass it through from the CLI handler in `src/commands/{command}.mjs`
-3. Update the types in `src/types/api.d.ts` (add to the options interface)
-4. If it produces a new response type, also update `src/types/{command}.d.ts` and `src/types/base.d.ts`
+1. Add the option to the API function in `api/{command}/{command}.mjs`
+2. Pass it through from the CLI handler in `cli/commands/{command}.mjs`
+3. Update the types in `types/api.d.ts` (add to the options interface)
+4. If it produces a new response type, also update `types/{command}.d.ts` and `types/base.d.ts`
### Adding a new response type (e.g. `component.detail.variants`)
-1. Add the logic in `src/api/{command}.mjs` — return `{type: 'component.detail.variants', data: ...}`
-2. Add a TypeScript interface in `src/types/{command}.d.ts`
-3. Add it to `CLIAnyResponse` in `src/types/base.d.ts`
-4. Add it to the result union in `src/types/api.d.ts`
+1. Add the logic in `api/{command}/{command}.mjs` — return `{type: 'component.detail.variants', data: ...}`
+2. Add a TypeScript interface in `types/{command}.d.ts`
+3. Add it to `CLIAnyResponse` in `types/base.d.ts`
+4. Add it to the result union in `types/api.d.ts`
5. The parity test will auto-detect the new type and verify API=CLI
### Renaming or removing a response type
@@ -297,7 +312,8 @@ if (!json) p.log.step('Running...');
The CLI ships as hand-written `.mjs` (no build step) but is type-checked with
TypeScript's `checkJs` against the JSDoc annotations in the source. `tsconfig.strict.json`
-runs the compiler over the **whole package** — `src`, `bin`, `scripts`, `docs`, and the
+runs the compiler over the **whole package** — every pillar (`api`, `cli`, `codemods`,
+`authoring`, `lib`, `utils`, `types`, `schemas`), plus `bin`, `scripts`, `docs`, and the
emitted `templates` (including their `.tsx` source) — under full `strict`, including
`noImplicitAny`, so an un-annotated parameter is an error.
@@ -312,3 +328,73 @@ CLI must stay strict-clean — a new un-annotated parameter or type error fails
locally before pushing. (The emitted `templates/**/*.tsx` import built workspace packages,
so run `pnpm build` first or you'll see spurious "cannot find module" errors from unbuilt
`dist` output.)
+
+## Roadmap
+
+Two tracks of planned work. Both are intentionally sequenced _after_ the thin-CLI
+extraction settles, so each lands as a focused, fully-verified increment rather than a
+rushed one where a subtle behavior change could slip past the tests.
+
+Every increment must clear the same gate before commit: shape-lock IDENTICAL (the
+`--json` payloads and human text stay byte-for-byte the same), `typecheck:strict` at 0
+errors with the file count not shrinking, `typecheck:json-api`, the vitest suite, and the
+api↔cli parity + json-smoke scripts.
+
+### 1. Finish the thin-CLI / API coverage
+
+Goal: every command is scriptable and each CLI handler is `parse → one API call →
+render`. The reusable core lives in `api/`; the CLI only parses args, renders (`jsonOut`
+or human text), and sets the exit code. Side-effecting commands do the effect in the API
+and return a `{type, data}` receipt.
+
+Remaining commands, in order (largest / highest-risk deliberately taken one at a time):
+
+1. **`upgrade`** (~860 lines — codemod pipeline, ~10 outcomes). Extract to `api/upgrade`
+ returning an `upgrade.run` receipt. Use the **injected-logger** pattern: the API takes
+ an optional logger (default no-op) so the work runs identically whether or not the CLI
+ is rendering progress; all `term-log` calls stay in the CLI. Runs codemods + a
+ post-codemod hook via `execFile`, so preserve dry-run vs `--apply` exactly.
+ - Open decision to make explicit in that PR: two error sites currently pass a metadata
+ object (`{agentDocs}` / `{receipt}`) as `jsonError`'s _suggestions_ argument, which
+ `toErrorEnvelope` silently drops (it only forwards array-shaped suggestions). Either
+ preserve the drop (shape-lock stays identical) **or** fix it as a deliberate,
+ documented additive change that puts the metadata in the receipt `data`. Do not
+ change it silently either way.
+2. **`theme build`** (~1275 lines — theme→CSS/TS compiler, ~14 file-write sites). Extract
+ the compiler into `api/theme` returning a build receipt; keep all disk writes in the
+ API, keep rendering in the CLI. Large and side-effecting — its own pass.
+3. **`init`** (~195 lines). The interactive prompts stay CLI-side; extract the scaffolding
+ core into `api/init` so the non-interactive path is scriptable.
+4. **`blog --json`**: `blog` emits `blog.list` / `blog.detail` today but has **no
+ `blog.d.ts`** — enabling/locking its `--json` surface must _also_ add the response
+ types and register them in `CLIAnyResponse`. Small, low-risk, pure win.
+5. **Data-command audit** (`component`, `docs`, `hook`, `template`): confirm no residual
+ business logic remains CLI-side after the reorg. Mostly already thin.
+
+### 2. Replace hand-written `.d.ts` with generated declarations
+
+Today the API's public types are hand-written `.d.ts` files in `types/`, kept in sync with
+the `.mjs` implementation by convention + CI. The goal is to make the annotated `.mjs` the
+single source of truth so type drift becomes a compile error instead of a review catch.
+
+Proven feasible: a JSDoc `@typedef` in a `.mjs` file plus `tsc --emitDeclarationOnly`
+generates a correct `.d.ts`, and a shared `.ts` spine can `import type { XResult } from
+'./x.mjs'` and both type-check and emit correctly.
+
+Phased plan:
+
+- **Phase 0 (done):** each API function gets a precise `@returns
+{Promise<XResult>}` pointing at its exported result union, so an implementation that
+ stops matching its declared type fails `typecheck:strict`. `discover` and `docs` are the
+ reference pattern; `build`'s `search` result is already annotated.
+- **Phase 1 — generation harness:** wire `tsc --emitDeclarationOnly` → `dist/types/` and
+ prove the generated output is byte-identical to the current hand-written `.d.ts`. No
+ behavior change; this only establishes the generator.
+- **Phase 2 — migrate per-command:** move each command's types into a colocated
+ `api/<cmd>/<cmd>.types.ts` (or JSDoc typedefs in the `.mjs`), update `base.ts`'s imports,
+ and delete `types/<cmd>.d.ts` one at a time. Start with **`blog`** — it has no `.d.ts`
+ today, so it's a pure win with nothing to keep in sync.
+- **Phase 3 — flip the export:** point `exports.types` at the generated output and stop
+ committing generated `.d.ts` by hand.
+- **Phase 4 — lock it:** add a CI check so no hand-written per-command `.d.ts` can
+ reappear.
diff --git a/packages/cli/api/build/build.mjs b/packages/cli/api/build/build.mjs
new file mode 100644
index 0000000000..812239987c
--- /dev/null
+++ b/packages/cli/api/build/build.mjs
@@ -0,0 +1,92 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file build API — the "assemble a page" assistant, as data.
+ *
+ * `build()` with no query signals the workflow playbook (`build.help`). With a
+ * query it runs the unified search and groups the results into a composition
+ * KIT (`build.kit`): the closest page templates, the blocks that cover parts,
+ * and the domain components to fill gaps, plus the always-on frame + foundation.
+ *
+ * The kit carries RAW `SearchResultEntry` objects and static name arrays only —
+ * never pre-formatted command strings. All CLI prefixing (formatCliCommand /
+ * getCliInvocation) and the section prose live in the command renderer, so the
+ * JSON shape stays package-manager-agnostic and stable across environments.
+ */
+
+import {search} from '../search/search.mjs';
+
+/** A page at/above this score is a confident direct match. */
+const PAGE_DIRECT = 95;
+/** Below this a page is too weak to offer even as a layout reference. */
+const PAGE_FLOOR = 50;
+/** Below this a block/domain-component match is incidental noise. */
+const DOMAIN_FLOOR = 55;
+
+/**
+ * Always-surfaced primitives. Every page needs a shell + layout/typography/
+ * action atoms, but these never keyword-match an idea ("dashboard" != "Stack"),
+ * so search alone never returns them. Kept here (not the renderer) because they
+ * are ALSO used to exclude these names from the idea-specific `domain` group.
+ */
+const FRAME = ['AppShell', 'TopNav', 'SideNav', 'Layout'];
+const FOUNDATION = [
+ 'VStack', 'HStack', 'Grid', 'StackItem', 'Card', 'Section',
+ 'Text', 'Heading', 'Button', 'Icon', 'Badge', 'Divider',
+];
+const ALWAYS = new Set([...FRAME, ...FOUNDATION]);
+
+/**
+ * The page-building assistant. No query → the playbook signal; a query → the
+ * grouped composition kit.
+ *
+ * @param {string} [query] what you're building (e.g. "analytics dashboard")
+ * @param {{cwd?: string, type?: import('../../types/search').SearchDomain, limit?: number}} [options]
+ * @returns {Promise<import('../../types/build').BuildHelpResponse | import('../../types/build').BuildKitResponse>}
+ */
+export async function build(query, options = {}) {
+ if (!query || !String(query).trim()) {
+ return {type: 'build.help', data: {playbook: true}};
+ }
+
+ const {cwd = process.cwd(), type, limit = 60} = options;
+ // search()'s JSDoc @returns widens results to object[]; the SearchResponse
+ // shape is the contract (api.d.ts). Cast locally rather than tightening the
+ // search @returns (a separate follow-up).
+ const result = /** @type {import('../../types/search').SearchResponse} */ (
+ await search(query, {cwd, type, limit})
+ );
+ const results = result.data.results;
+
+ const pages = results
+ .filter(r => r.domain === 'template' && r.kind !== 'block' && r.score >= PAGE_FLOOR)
+ .slice(0, 3);
+ const blocks = results
+ .filter(r => r.domain === 'template' && r.kind === 'block' && r.score >= DOMAIN_FLOOR)
+ .slice(0, 5);
+ const domain = results
+ .filter(
+ r =>
+ (r.domain === 'component' || r.domain === 'hook') &&
+ r.score >= DOMAIN_FLOOR &&
+ !ALWAYS.has(r.name),
+ )
+ .slice(0, 6);
+ const directMatch = pages.length > 0 && pages[0].score >= PAGE_DIRECT;
+
+ return {
+ type: 'build.kit',
+ data: {
+ query: result.data.query,
+ // Distinguishes "search found nothing" (renderer shows "No matches")
+ // from a weak-but-non-empty result set (renderer still shows the kit).
+ hasResults: results.length > 0,
+ directMatch,
+ pages,
+ blocks,
+ domain,
+ frame: FRAME,
+ foundation: FOUNDATION,
+ },
+ };
+}
diff --git a/packages/cli/api/build/build.test.mjs b/packages/cli/api/build/build.test.mjs
new file mode 100644
index 0000000000..e47d0027ad
--- /dev/null
+++ b/packages/cli/api/build/build.test.mjs
@@ -0,0 +1,92 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Tests for the build API (playbook signal + composition kit).
+ */
+
+import {describe, it, expect, vi} from 'vitest';
+import * as path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {build} from './build.mjs';
+
+// api/build/ -> up 3 = packages/cli, up 4 = repo root (has packages/core).
+const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../..');
+
+// build() delegates to search(), whose first (cold) call is slow under vitest.
+vi.setConfig({testTimeout: 30000});
+
+describe('build API', () => {
+ it('no query → build.help playbook signal', async () => {
+ const r = await build();
+ expect(r.type).toBe('build.help');
+ expect(r.data).toEqual({playbook: true});
+ });
+
+ it('query → build.kit with raw entries + static frame/foundation', async () => {
+ const r = await build('dashboard', {cwd: REPO});
+ expect(r.type).toBe('build.kit');
+ if (r.type !== 'build.kit') return;
+ expect(r.data.query).toBe('dashboard');
+ expect(r.data.hasResults).toBe(true);
+ expect(r.data.frame).toContain('AppShell');
+ expect(r.data.foundation).toContain('Button');
+ expect(Array.isArray(r.data.pages)).toBe(true);
+
+ // Entries are RAW SearchResultEntry objects — never package-manager-prefixed
+ // command strings (that formatting is the CLI renderer's job).
+ for (const e of [...r.data.pages, ...r.data.blocks, ...r.data.domain]) {
+ expect(typeof e.name).toBe('string');
+ expect(typeof e.score).toBe('number');
+ expect(e.command).not.toMatch(/^(pnpm|npm|yarn|bun|npx)\b/);
+ }
+ });
+
+ it('excludes always-on frame/foundation names from the domain group', async () => {
+ const r = await build('dashboard', {cwd: REPO});
+ if (r.type !== 'build.kit') throw new Error('expected build.kit');
+ const names = r.data.domain.map(d => d.name);
+ expect(names).not.toContain('Button');
+ expect(names).not.toContain('AppShell');
+ });
+
+ it('applies grouping caps, score floors, and directMatch threshold', async () => {
+ const r = await build('dashboard', {cwd: REPO});
+ if (r.type !== 'build.kit') throw new Error('expected build.kit');
+ const {pages, blocks, domain, directMatch} = r.data;
+
+ // Caps: pages ≤ 3, blocks ≤ 5, domain ≤ 6.
+ expect(pages.length).toBeLessThanOrEqual(3);
+ expect(blocks.length).toBeLessThanOrEqual(5);
+ expect(domain.length).toBeLessThanOrEqual(6);
+
+ // Score floors: pages ≥ PAGE_FLOOR(50); blocks/domain ≥ DOMAIN_FLOOR(55).
+ for (const p of pages) expect(p.score).toBeGreaterThanOrEqual(50);
+ for (const b of blocks) expect(b.score).toBeGreaterThanOrEqual(55);
+ for (const d of domain) expect(d.score).toBeGreaterThanOrEqual(55);
+
+ // directMatch iff the top page is a confident match (PAGE_DIRECT = 95).
+ expect(directMatch).toBe(pages.length > 0 && pages[0].score >= 95);
+
+ // Domain partitioning: pages = non-block templates, blocks = block templates,
+ // domain = components/hooks.
+ for (const p of pages) {
+ expect(p.domain).toBe('template');
+ expect(p.kind).not.toBe('block');
+ }
+ for (const b of blocks) {
+ expect(b.domain).toBe('template');
+ expect(b.kind).toBe('block');
+ }
+ for (const d of domain) expect(['component', 'hook']).toContain(d.domain);
+ });
+
+ it('no matches → build.kit with hasResults=false and empty groups', async () => {
+ const r = await build('zzznomatch99', {cwd: REPO});
+ expect(r.type).toBe('build.kit');
+ if (r.type !== 'build.kit') return;
+ expect(r.data.hasResults).toBe(false);
+ expect(r.data.pages).toHaveLength(0);
+ expect(r.data.blocks).toHaveLength(0);
+ expect(r.data.domain).toHaveLength(0);
+ });
+});
diff --git a/packages/cli/api/index.mjs b/packages/cli/api/index.mjs
index 3fe2374c09..0acbcfeec1 100644
--- a/packages/cli/api/index.mjs
+++ b/packages/cli/api/index.mjs
@@ -27,5 +27,12 @@ export {template} from './template/template.mjs';
export {themeAdd, listThemes} from './theme/theme-add.mjs';
export {hook} from './hook/hook.mjs';
export {search} from './search/search.mjs';
+export {build} from './build/build.mjs';
+export {swizzle} from './swizzle/swizzle.mjs';
export {doctor} from './doctor/doctor.mjs';
+export {layoutExpand, layoutCheck, layoutGrammar} from './layout/layout.mjs';
+export {
+ validateIntegration,
+ summarizeIssues,
+} from './integration/validate-integration.mjs';
export {AstryxError} from './error.mjs';
diff --git a/packages/cli/api/integration/validate-integration.mjs b/packages/cli/api/integration/validate-integration.mjs
index 2f2b284b5a..d847a0382b 100644
--- a/packages/cli/api/integration/validate-integration.mjs
+++ b/packages/cli/api/integration/validate-integration.mjs
@@ -351,6 +351,34 @@ export async function validateInstalledIntegration(spec, cwd = process.cwd()) {
});
}
+/**
+ * Unified entry: validate the LOCAL integration (no `pkg`) or an INSTALLED one
+ * (`pkg` given) and return the `integration.validate` envelope. The no-manifest
+ * local case is guidance, not an error — it comes back with `name: null` and no
+ * issues so the CLI can print a hint and stay exit-0.
+ *
+ * This is the seam that keeps the CLI a thin wrapper: the command handler calls
+ * this and only chooses how to render (human vs --json) + the exit code.
+ *
+ * @param {string} [pkg] installed package name; omit to validate the cwd package
+ * @param {{cwd?: string}} [options]
+ * @returns {Promise<import('../../types/validate-integration').ValidateIntegrationResponse>}
+ */
+export async function validateIntegration(pkg, options = {}) {
+ const {cwd = process.cwd()} = options;
+ const result = pkg
+ ? await validateInstalledIntegration(pkg, cwd)
+ : await validateLocalIntegration(cwd);
+ return {
+ type: 'integration.validate',
+ data: {
+ name: result.found ? result.name ?? null : null,
+ version: result.found ? result.version ?? null : null,
+ issues: result.issues,
+ },
+ };
+}
+
/**
* Summarize issues by severity.
* @param {Issue[]} issues
diff --git a/packages/cli/api/swizzle/swizzle.mjs b/packages/cli/api/swizzle/swizzle.mjs
new file mode 100644
index 0000000000..6299bebce4
--- /dev/null
+++ b/packages/cli/api/swizzle/swizzle.mjs
@@ -0,0 +1,283 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file swizzle API — copy a component's source into the consumer project for
+ * customization, rewriting escaping relative imports to the OWNER package's
+ * subpaths.
+ *
+ * Side-effecting: `swizzle(name, ...)` writes files and returns a
+ * `swizzle.copy` receipt describing what it did; with no name (or `list`) it
+ * returns `swizzle.list`. Errors throw AstryxError (stable code + suggestions).
+ * All human prose / package-manager prefixing lives in the CLI renderer.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {findCoreDir, listComponents} from '../../utils/paths.mjs';
+import {assertWithin, PathSafetyError} from '../../utils/path-safety.mjs';
+import {checkGhCli} from '../../utils/github.mjs';
+import {Project} from '../../lib/project.mjs';
+import {
+ CORE_PACKAGE,
+ findIntegrationComponentDoc,
+ findIntegrationComponentSource,
+} from '../../lib/component-discovery.mjs';
+import {ERROR_CODES} from '../../lib/error-codes.mjs';
+import {AstryxError} from '../error.mjs';
+
+/** Default issue tracker for maintainer feedback after swizzling. */
+const DEFAULT_ISSUES_URL = 'https://github.com/facebook/astryx/issues/new';
+
+/**
+ * Rewrite relative imports that point outside the component directory to use
+ * the OWNER package's subpaths. Imports within the copied directory (./x) are
+ * left untouched.
+ *
+ * e.g. with ownerPackage '@astryxdesign/core':
+ * '../theme/tokens.stylex' -> '@astryxdesign/core/theme'
+ * '../utils/mergeProps' -> '@astryxdesign/core/utils'
+ *
+ * @param {string} content
+ * @param {string} [ownerPackage]
+ */
+export function rewriteImports(content, ownerPackage = CORE_PACKAGE) {
+ return content.replace(
+ /(from\s+['"])(\.\.\/.+?)(['"])/g,
+ (match, prefix, importPath, suffix) => {
+ const parts = importPath.replace(/^\.\.\//, '').split('/');
+ const topDir = parts[0];
+ return `${prefix}${ownerPackage}/${topDir}${suffix}`;
+ },
+ );
+}
+
+/**
+ * Build the maintainer feedback note for a swizzled component.
+ * @param {string} component
+ * @param {string|undefined} issuesUrl
+ * @returns {{issuesUrl: string, ghCommand?: string} | null}
+ */
+function buildFeedback(component, issuesUrl) {
+ if (!issuesUrl) return null;
+ /** @type {{issuesUrl: string, ghCommand?: string}} */
+ const feedback = {issuesUrl};
+ const match = issuesUrl.match(
+ /^https:\/\/github\.com\/([^/]+)\/([^/]+)\/issues(?:\/new)?\/?$/,
+ );
+ if (match && checkGhCli()) {
+ const [, owner, repo] = match;
+ feedback.ghCommand = `gh issue create --repo ${owner}/${repo} --title "[${component}] Swizzle feedback"`;
+ }
+ return feedback;
+}
+
+/**
+ * Load the configured integrations + core issues URL for `cwd`, swallowing any
+ * config errors so swizzle never hard-fails on a malformed/absent config.
+ * @param {string} cwd
+ * @returns {Promise<{loadedIntegrations: import('../../lib/integrations.mjs').LoadedIntegration[], issuesUrl: string|undefined, project: Project|null}>}
+ */
+async function loadConfigSafely(cwd) {
+ try {
+ const project = await Project.load(cwd);
+ return {
+ loadedIntegrations: project.loadedIntegrations,
+ issuesUrl: project.config.issuesUrl,
+ project,
+ };
+ } catch {
+ return {loadedIntegrations: [], issuesUrl: undefined, project: null};
+ }
+}
+
+/**
+ * Build the set of OWNER packages that provide a component named `name` across
+ * core + every loaded integration.
+ * @param {string} coreDir
+ * @param {Array<{name: string, components?: string, issuesUrl?: string}>} loadedIntegrations
+ * @param {string} name
+ * @param {string|undefined} coreIssuesUrl
+ * @returns {Array<{package: string, sourceDir: string|null, ownerPackage: string, issuesUrl: string|undefined}>}
+ */
+function resolveOwners(coreDir, loadedIntegrations, name, coreIssuesUrl) {
+ const owners = [];
+ const coreComponentDir = path.join(coreDir, 'src', name);
+ if (fs.existsSync(coreComponentDir)) {
+ owners.push({
+ package: CORE_PACKAGE,
+ sourceDir: coreComponentDir,
+ ownerPackage: CORE_PACKAGE,
+ issuesUrl: coreIssuesUrl || DEFAULT_ISSUES_URL,
+ });
+ }
+ for (const integration of loadedIntegrations) {
+ const docPath = findIntegrationComponentDoc(integration, name);
+ if (!docPath) continue;
+ const sourcePath = findIntegrationComponentSource(integration, name);
+ owners.push({
+ package: integration.name,
+ sourceDir: sourcePath ? path.dirname(sourcePath) : null,
+ ownerPackage: integration.name,
+ issuesUrl: integration.issuesUrl,
+ });
+ }
+ return owners;
+}
+
+/** @param {string} file */
+function isExcludedFromCopy(file) {
+ return (
+ file.includes('.test.') || file.includes('.doc.') || file === 'README.md'
+ );
+}
+
+/**
+ * List swizzlable components, or copy one component's source for customization.
+ *
+ * @param {string} [component] bare or XDS-prefixed component name; omit to list
+ * @param {{cwd?: string, output?: string, package?: string, list?: boolean, overwrite?: boolean}} [options]
+ * @returns {Promise<import('../../types/swizzle').SwizzleListResponse | import('../../types/swizzle').SwizzleCopyResponse>}
+ */
+export async function swizzle(component, options = {}) {
+ const {
+ cwd = process.cwd(),
+ output = './components/astryx',
+ package: pkg,
+ list = false,
+ overwrite = false,
+ } = options;
+
+ const coreDir = findCoreDir(cwd);
+ if (!coreDir) {
+ throw new AstryxError(
+ 'Could not find @astryxdesign/core package. Make sure you are inside the design system monorepo or have @astryxdesign/core installed.',
+ [],
+ ERROR_CODES.ERR_CORE_NOT_FOUND,
+ );
+ }
+
+ const components = listComponents(coreDir);
+
+ if (list || !component) {
+ return {type: 'swizzle.list', data: components};
+ }
+
+ const dirName = component.replace(/^XDS/, '');
+
+ const {loadedIntegrations, project} = await loadConfigSafely(cwd);
+ const coreIssuesUrl = project
+ ? project.issuesUrl({package: CORE_PACKAGE})
+ : undefined;
+ const allOwners = resolveOwners(coreDir, loadedIntegrations, dirName, coreIssuesUrl);
+
+ if (allOwners.length === 0) {
+ throw new AstryxError(
+ `Component "${component}" not found.`,
+ components.slice(0, 10).map(n => ({name: n})),
+ ERROR_CODES.ERR_UNKNOWN_COMPONENT,
+ );
+ }
+
+ let owner;
+ if (pkg) {
+ owner = allOwners.find(o => o.package === pkg);
+ if (!owner) {
+ throw new AstryxError(
+ `Component "${dirName}" is not provided by package "${pkg}".`,
+ allOwners.map(o => ({name: o.package, reason: 'provides this component'})),
+ ERROR_CODES.ERR_UNKNOWN_COMPONENT,
+ );
+ }
+ } else if (allOwners.length > 1) {
+ throw new AstryxError(
+ `Component "${dirName}" is provided by multiple packages. Re-run with --package <pkg> to choose one.`,
+ allOwners.map(o => ({name: o.package, reason: 'provides this component'})),
+ ERROR_CODES.ERR_AMBIGUOUS_COMPONENT,
+ );
+ } else {
+ owner = allOwners[0];
+ }
+
+ if (!owner.sourceDir || !fs.existsSync(owner.sourceDir)) {
+ throw new AstryxError(
+ `No source found for "${dirName}" in package "${owner.package}".`,
+ [],
+ ERROR_CODES.ERR_NO_SOURCE,
+ );
+ }
+
+ const componentDir = owner.sourceDir;
+
+ // Path-safety: --output must resolve inside cwd.
+ let outputBase;
+ try {
+ outputBase = assertWithin(output, cwd, {label: 'output directory'});
+ } catch (err) {
+ if (err instanceof PathSafetyError) {
+ throw new AstryxError(err.message, [], ERROR_CODES.ERR_PATH_TRAVERSAL);
+ }
+ throw err;
+ }
+ const outputDir = path.join(outputBase, dirName);
+
+ // Pre-flight overwrite check before any mkdir/writeFile.
+ const sourceFiles = fs.readdirSync(componentDir).filter(file => {
+ if (isExcludedFromCopy(file)) return false;
+ return fs.statSync(path.join(componentDir, file)).isFile();
+ });
+ const existingFiles = sourceFiles.filter(f =>
+ fs.existsSync(path.join(outputDir, f)),
+ );
+ if (existingFiles.length > 0 && !overwrite) {
+ const relOutputForMsg = path.relative(cwd, outputDir) || '.';
+ throw new AstryxError(
+ `Refusing to overwrite ${existingFiles.length} existing file(s) in ${relOutputForMsg}/. ` +
+ `Re-run with --overwrite (or -f) to replace them.`,
+ [],
+ ERROR_CODES.ERR_FILE_EXISTS,
+ );
+ }
+
+ fs.mkdirSync(outputDir, {recursive: true});
+
+ const files = fs.readdirSync(componentDir);
+ let copied = 0;
+ let usesStyleX = false;
+ for (const file of files) {
+ if (isExcludedFromCopy(file)) continue;
+ const srcPath = path.join(componentDir, file);
+ if (!fs.statSync(srcPath).isFile()) continue;
+ let content = fs.readFileSync(srcPath, 'utf-8');
+ if (file.endsWith('.ts') || file.endsWith('.tsx')) {
+ content = rewriteImports(content, owner.ownerPackage);
+ }
+ if (
+ (file.endsWith('.ts') || file.endsWith('.tsx')) &&
+ content.includes('@stylexjs/stylex')
+ ) {
+ usesStyleX = true;
+ }
+ fs.writeFileSync(path.join(outputDir, file), content);
+ copied++;
+ }
+
+ const relOutput = path.relative(cwd, outputDir);
+ const copiedFiles = files.filter(
+ f =>
+ !isExcludedFromCopy(f) &&
+ fs.statSync(path.join(componentDir, f)).isFile(),
+ );
+ const feedback = buildFeedback(dirName, owner.issuesUrl);
+
+ /** @type {import('../../types/swizzle').SwizzleCopyResponse['data']} */
+ const data = {
+ component: dirName,
+ package: owner.package,
+ outputDir: relOutput,
+ filesCopied: copied,
+ files: copiedFiles.map(f => f),
+ usesStyleX,
+ };
+ if (feedback) data.feedback = feedback;
+ return {type: 'swizzle.copy', data};
+}
diff --git a/packages/cli/cli/commands/swizzle.test.mjs b/packages/cli/api/swizzle/swizzle.test.mjs
similarity index 65%
rename from packages/cli/cli/commands/swizzle.test.mjs
rename to packages/cli/api/swizzle/swizzle.test.mjs
index e4cc472936..bea9cc33e6 100644
--- a/packages/cli/cli/commands/swizzle.test.mjs
+++ b/packages/cli/api/swizzle/swizzle.test.mjs
@@ -1,7 +1,12 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
import {describe, it, expect} from 'vitest';
-import {rewriteImports} from './swizzle.mjs';
+import * as path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {rewriteImports, swizzle} from './swizzle.mjs';
+
+// api/swizzle/ -> up 3 = packages/cli, up 4 = repo root (has packages/core).
+const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../..');
describe('rewriteImports', () => {
it('rewrites ../theme/tokens to @astryxdesign/core/theme', () => {
@@ -51,3 +56,23 @@ describe('rewriteImports', () => {
);
});
});
+
+describe('swizzle() API', () => {
+ it('no component → swizzle.list of core components', async () => {
+ const r = await swizzle(undefined, {cwd: REPO});
+ expect(r.type).toBe('swizzle.list');
+ expect(Array.isArray(r.data)).toBe(true);
+ expect(r.data).toContain('Button');
+ });
+
+ it('--list → swizzle.list even with a component arg', async () => {
+ const r = await swizzle('Button', {cwd: REPO, list: true});
+ expect(r.type).toBe('swizzle.list');
+ });
+
+ it('unknown component → AstryxError ERR_UNKNOWN_COMPONENT with suggestions', async () => {
+ await expect(swizzle('NotARealComponent99', {cwd: REPO})).rejects.toMatchObject({
+ code: 'ERR_UNKNOWN_COMPONENT',
+ });
+ });
+});
diff --git a/packages/cli/cli/commands/build.mjs b/packages/cli/cli/commands/build.mjs
index 67ba2af3b8..99d4d9c13e 100644
--- a/packages/cli/cli/commands/build.mjs
+++ b/packages/cli/cli/commands/build.mjs
@@ -1,44 +1,21 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file build command — the page-building assistant.
+ * @file build command — thin wrapper around api/build.
*
- * Two modes:
- * astryx build → the PLAYBOOK: how to build a page with Astryx
- * astryx build "<what>" → a COMPOSITION KIT for what you're building:
- * the closest page template (scaffold or layout
- * reference), the blocks that cover parts, and
- * the components to fill gaps, plus a one-line
- * "Compose:" suggestion.
+ * astryx build → the PLAYBOOK (how to build a page)
+ * astryx build "<what>" → a COMPOSITION KIT (closest page template,
+ * blocks, components) with a recommended START.
*
- * `build` is the opinionated "assemble a page" verb. For a neutral lookup across
- * the whole CLI, use `astryx search <query>` instead.
+ * All grouping/scoring lives in api/build; this file only parses flags and
+ * renders. Command strings are prefixed for the caller's package manager here
+ * (never in the API payload) via formatCliCommand/getCliInvocation.
*/
import {getCliInvocation, formatCliCommand} from '../../utils/package-manager.mjs';
import {jsonOut, humanLog} from '../../lib/json.mjs';
import {cliError} from '../../lib/cli-error.mjs';
-import {search as searchApi} from '../../api/search/search.mjs';
-
-/** A page scoring at/above this is confident enough to call a direct match. */
-const PAGE_DIRECT = 95;
-/** Below this a page is too weak to even offer as a layout reference. */
-const PAGE_FLOOR = 50;
-/** Below this a block/domain-component match is incidental noise, not surfaced. */
-const DOMAIN_FLOOR = 55;
-
-/**
- * Always-surfaced primitives. Every page needs a shell + layout/typography/
- * action atoms, but these never keyword-match an idea ("dashboard" != "Stack"),
- * so search alone never returns them. We list them unconditionally so an agent
- * composing from scratch has the whole kit (esp. off-template).
- */
-const FRAME = ['AppShell', 'TopNav', 'SideNav', 'Layout'];
-const FOUNDATION = [
- 'VStack', 'HStack', 'Grid', 'StackItem', 'Card', 'Section',
- 'Text', 'Heading', 'Button', 'Icon', 'Badge', 'Divider',
-];
-const ALWAYS = new Set([...FRAME, ...FOUNDATION]);
+import {build as buildApi} from '../../api/build/build.mjs';
/**
* Print the build playbook (shown when `build` is run with no query).
@@ -88,14 +65,15 @@ export function registerBuild(program) {
const run = getCliInvocation();
const json = program.opts().json || false;
- // No query → print the playbook (the "how to build" skill).
+ // No query → the playbook. Still routed through the API for the envelope.
if (!query || !String(query).trim()) {
- if (json) return jsonOut('build.help', {playbook: true});
+ const result = await buildApi(undefined, {cwd: process.cwd()});
+ if (json) return jsonOut(result.type, result.data);
printPlaybook(run);
return;
}
- // Default to a deep pool so each role section has candidates after grouping.
+ // Arg validation stays in the CLI.
let limit = 60;
if (options.limit != null) {
const parsed = Number.parseInt(options.limit, 10);
@@ -106,11 +84,11 @@ export function registerBuild(program) {
limit = parsed;
}
- /** @type {import('../../types/search').SearchResponse} */
+ /** @type {import('../../types/build').BuildKitResponse} */
let result;
try {
- result = /** @type {import('../../types/search').SearchResponse} */ (
- await searchApi(query, {cwd: process.cwd(), type: options.type, limit})
+ result = /** @type {import('../../types/build').BuildKitResponse} */ (
+ await buildApi(query, {cwd: process.cwd(), type: options.type, limit})
);
} catch (e) {
const err = /** @type {import('../../api/error.mjs').AstryxError} */ (e);
@@ -120,9 +98,10 @@ export function registerBuild(program) {
if (json) return jsonOut(result.type, result.data);
- const {query: q, results} = result.data;
+ const {query: q, hasResults, directMatch, pages, blocks, domain, frame, foundation} =
+ result.data;
- if (results.length === 0) {
+ if (!hasResults) {
humanLog('');
humanLog(`No matches for "${q}".`);
humanLog(`Try a broader term, or browse: ${run} component --list`);
@@ -130,19 +109,6 @@ export function registerBuild(program) {
return;
}
- // ── Group results by role (the build kit) ──────────────────────
- const pages = results
- .filter(r => r.domain === 'template' && r.kind !== 'block' && r.score >= PAGE_FLOOR)
- .slice(0, 3);
- const blocks = results
- .filter(r => r.domain === 'template' && r.kind === 'block' && r.score >= DOMAIN_FLOOR)
- .slice(0, 5);
- // Idea-specific atoms = matched components/hooks MINUS the always-on kit.
- const domain = results
- .filter(r => (r.domain === 'component' || r.domain === 'hook') && r.score >= DOMAIN_FLOOR && !ALWAYS.has(r.name))
- .slice(0, 6);
- const directMatch = pages.length > 0 && pages[0].score >= PAGE_DIRECT;
-
const printItem = (/** @type {import('../../types/search').SearchResultEntry} */ r, /** @type {string} */ label) => {
const display = r.domain === 'template' && r.displayName ? r.displayName : r.name;
humanLog('');
@@ -177,7 +143,7 @@ export function registerBuild(program) {
// FRAME — always (the page shell).
humanLog('');
- humanLog(`FRAME — page shell (always): ${FRAME.join(', ')}`);
+ humanLog(`FRAME — page shell (always): ${frame.join(', ')}`);
humanLog(` full-page → AppShell; or Layout + SideNav/TopNav. ${run} component AppShell`);
// BLOCKS — idea-specific composed patterns.
@@ -196,7 +162,7 @@ export function registerBuild(program) {
// FOUNDATION — always (layout/typography/actions).
humanLog('');
- humanLog(`FOUNDATION — always available (layout/text/actions): ${FOUNDATION.join(' ')}`);
+ humanLog(`FOUNDATION — always available (layout/text/actions): ${foundation.join(' ')}`);
// SETUP — so it renders / stays on-system.
humanLog('');
diff --git a/packages/cli/cli/commands/init.mjs b/packages/cli/cli/commands/init.mjs
index f9d65632e8..fbf5fa25f6 100644
--- a/packages/cli/cli/commands/init.mjs
+++ b/packages/cli/cli/commands/init.mjs
@@ -20,7 +20,7 @@ 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 './agent-docs.mjs';
+import {installAgentDocs, removeAgentDocs} from '../../lib/agent-docs/agent-docs.mjs';
import {listTemplates} from './template.mjs';
import {humanLog} from '../../lib/json.mjs';
import {cliError} from '../../lib/cli-error.mjs';
diff --git a/packages/cli/cli/commands/setup-nudge.test.mjs b/packages/cli/cli/commands/setup-nudge.test.mjs
index 514f343cd7..814aa91a54 100644
--- a/packages/cli/cli/commands/setup-nudge.test.mjs
+++ b/packages/cli/cli/commands/setup-nudge.test.mjs
@@ -18,7 +18,7 @@ import * as fs from 'node:fs';
import * as path from 'node:path';
import * as os from 'node:os';
import {fileURLToPath} from 'node:url';
-import {isAstryxInitialized} from './agent-docs.mjs';
+import {isAstryxInitialized} from '../../lib/agent-docs/agent-docs.mjs';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const CLI = path.resolve(__dirname, '..', '..', 'bin', 'astryx.mjs');
diff --git a/packages/cli/cli/commands/swizzle.mjs b/packages/cli/cli/commands/swizzle.mjs
index 6195dcec85..492886a154 100644
--- a/packages/cli/cli/commands/swizzle.mjs
+++ b/packages/cli/cli/commands/swizzle.mjs
@@ -1,177 +1,19 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
/**
- * @file swizzle command — Copy component source for customization
+ * @file swizzle command — thin wrapper around api/swizzle.
*
- * Resolves a component's owning package (core or a configured integration),
- * copies its non-test/non-doc source files to the output directory, and
- * rewrites escaping relative imports to use the OWNER package's subpaths.
- *
- * After swizzling, prints a short maintainer feedback note pointing users at
- * the owner's issue tracker so they can let the team know what gap led them to
- * customize the component. The core feedback URL is routed through app config
- * (`config.issuesUrl`); integration components use their manifest `issuesUrl`.
+ * Copies a component's source into the consumer project for customization
+ * (imports rewritten to the owner package's subpaths). All logic — owner
+ * resolution, copy, import rewriting, StyleX detection, maintainer feedback —
+ * lives in api/swizzle; this file only parses flags, prints, and prefixes
+ * commands for the caller's package manager.
*/
-import * as fs from 'node:fs';
-import * as path from 'node:path';
-import {findCoreDir, listComponents} from '../../utils/paths.mjs';
-import {
- assertWithin,
- PathSafetyError,
-} from '../../utils/path-safety.mjs';
import {jsonOut, humanLog} from '../../lib/json.mjs';
import {cliError} from '../../lib/cli-error.mjs';
-import {ERROR_CODES} from '../../lib/error-codes.mjs';
-import {checkGhCli} from '../../utils/github.mjs';
import {getCliInvocation} from '../../utils/package-manager.mjs';
-import {Project} from '../../lib/project.mjs';
-import {
- CORE_PACKAGE,
- findIntegrationComponentDoc,
- findIntegrationComponentSource,
-} from '../../lib/component-discovery.mjs';
-
-/** Default issue tracker for maintainer feedback after swizzling. */
-const DEFAULT_ISSUES_URL = 'https://github.com/facebook/astryx/issues/new';
-
-/**
- * Rewrite relative imports that point outside the component directory to use
- * the OWNER package's subpaths. Imports within the copied directory (./x) are
- * left untouched.
- *
- * e.g. with ownerPackage '@astryxdesign/core':
- * '../theme/tokens.stylex' -> '@astryxdesign/core/theme'
- * '../utils/mergeProps' -> '@astryxdesign/core/utils'
- *
- * `ownerPackage` defaults to '@astryxdesign/core' so existing core behavior is
- * unchanged; integration components pass their own owning package.
- *
- * @param {string} content
- * @param {string} [ownerPackage]
- */
-export function rewriteImports(content, ownerPackage = CORE_PACKAGE) {
- // Match import/export from statements with relative paths going up
- return content.replace(
- /(from\s+['"])(\.\.\/.+?)(['"])/g,
- (match, prefix, importPath, suffix) => {
- // Extract the top-level directory from the relative path
- // e.g. '../theme/tokens.stylex' -> 'theme'
- // e.g. '../utils/mergeProps' -> 'utils'
- const parts = importPath.replace(/^\.\.\//, '').split('/');
- const topDir = parts[0];
-
- // Map to the owner package subpath
- return `${prefix}${ownerPackage}/${topDir}${suffix}`;
- },
- );
-}
-
-/**
- * Build the maintainer feedback note for a swizzled component.
- *
- * Returns { issuesUrl, ghCommand? } or null when no issues URL is available
- * (an integration that ships no `issuesUrl`). When the issues URL is a GitHub
- * issues URL and the `gh` CLI is available, a ready-to-run `gh issue create`
- * command is included so the user can file feedback without leaving the
- * terminal.
- *
- * @param {string} component bare component name (used in the issue title)
- * @param {string|undefined} issuesUrl owner's issue tracker URL
- * @returns {{issuesUrl: string, ghCommand?: string} | null}
- */
-function buildFeedback(component, issuesUrl) {
- if (!issuesUrl) return null;
-
- /** @type {{issuesUrl: string, ghCommand?: string}} */
- const feedback = {issuesUrl};
-
- // Accept any github.com/<owner>/<repo>/issues(/new)? form.
- const match = issuesUrl.match(
- /^https:\/\/github\.com\/([^/]+)\/([^/]+)\/issues(?:\/new)?\/?$/,
- );
- if (match && checkGhCli()) {
- const [, owner, repo] = match;
- feedback.ghCommand = `gh issue create --repo ${owner}/${repo} --title "[${component}] Swizzle feedback"`;
- }
-
- return feedback;
-}
-
-/**
- * Load the configured integrations + core issues URL for `cwd`, swallowing any
- * config errors so swizzle never hard-fails on a malformed/absent config. An
- * empty list means "core only". The core issues URL is routed through the
- * Project (config.issuesUrl, falling back to the default core tracker).
- * @param {string} cwd
- * @returns {Promise<{loadedIntegrations: import('../../lib/integrations.mjs').LoadedIntegration[], issuesUrl: string|undefined, project: Project|null}>}
- */
-async function loadConfigSafely(cwd) {
- try {
- const project = await Project.load(cwd);
- return {
- loadedIntegrations: project.loadedIntegrations,
- issuesUrl: project.config.issuesUrl,
- project,
- };
- } catch {
- return {loadedIntegrations: [], issuesUrl: undefined, project: null};
- }
-}
-
-/**
- * Build the set of OWNER packages that provide a component with `name` across
- * core + every loaded integration.
- *
- * Core ownership is determined by the source directory existing on disk
- * (`coreDir/src/<name>`) so plain core components without a `.doc.mjs` still
- * resolve as today. Integration ownership is determined by a same-stem doc file
- * (`<name>.doc.{ts,mjs,js}`) via findIntegrationComponentDoc.
- *
- * @param {string} coreDir
- * @param {Array<{name: string, components?: string, issuesUrl?: string}>} loadedIntegrations
- * @param {string} name bare component name (no XDS/Astryx prefix)
- * @param {string|undefined} coreIssuesUrl
- * @returns {Array<{package: string, sourceDir: string|null, ownerPackage: string, issuesUrl: string|undefined}>}
- */
-function resolveOwners(coreDir, loadedIntegrations, name, coreIssuesUrl) {
- const owners = [];
-
- const coreComponentDir = path.join(coreDir, 'src', name);
- if (fs.existsSync(coreComponentDir)) {
- owners.push({
- package: CORE_PACKAGE,
- sourceDir: coreComponentDir,
- ownerPackage: CORE_PACKAGE,
- issuesUrl: coreIssuesUrl || DEFAULT_ISSUES_URL,
- });
- }
-
- for (const integration of loadedIntegrations) {
- const docPath = findIntegrationComponentDoc(integration, name);
- if (!docPath) continue;
- const sourcePath = findIntegrationComponentSource(integration, name);
- owners.push({
- package: integration.name,
- // The component's own folder — the directory containing its source.
- sourceDir: sourcePath ? path.dirname(sourcePath) : null,
- ownerPackage: integration.name,
- issuesUrl: integration.issuesUrl,
- });
- }
-
- return owners;
-}
-
-/**
- * Whether a filename should be excluded from the swizzle copy.
- * @param {string} file
- */
-function isExcludedFromCopy(file) {
- return (
- file.includes('.test.') || file.includes('.doc.') || file === 'README.md'
- );
-}
+import {swizzle as swizzleApi} from '../../api/swizzle/swizzle.mjs';
/**
* @param {import('commander').Command} program
@@ -185,209 +27,48 @@ export function registerSwizzle(program) {
.option('--list', 'List available components')
.option('-f, --overwrite', 'Overwrite existing files without prompting')
.action(async (/** @type {string | undefined} */ component, /** @type {{output: string, package?: string, list?: boolean, overwrite?: boolean}} */ options) => {
- const coreDir = findCoreDir(process.cwd());
const json = program.opts().json || false;
const run = getCliInvocation();
- if (!coreDir) {
- cliError(
- 'Could not find @astryxdesign/core package. Make sure you are inside the design system monorepo or have @astryxdesign/core installed.',
- {code: ERROR_CODES.ERR_CORE_NOT_FOUND},
- );
+ /** @type {import('../../types/swizzle').SwizzleListResponse | import('../../types/swizzle').SwizzleCopyResponse} */
+ let result;
+ try {
+ result = await swizzleApi(component, {
+ cwd: process.cwd(),
+ output: options.output,
+ package: options.package,
+ list: options.list,
+ overwrite: options.overwrite,
+ });
+ } catch (e) {
+ const err = /** @type {import('../../api/error.mjs').AstryxError} */ (e);
+ cliError(err.message, {suggestions: err.suggestions, code: err.code});
return;
}
- const components = listComponents(coreDir);
+ if (json) return jsonOut(result.type, result.data);
- if (options.list || !component) {
- if (json) return jsonOut('swizzle.list', components);
+ if (result.type === 'swizzle.list') {
+ const components = result.data;
humanLog('\nAvailable components:\n');
for (const name of components) {
humanLog(` ${name}`);
}
humanLog(`\nUsage: ${run} swizzle <component>\n`);
humanLog(`Example: ${run} swizzle Button`);
- humanLog(
- ` ${run} swizzle XDSButton (XDS prefix also works)\n`,
- );
+ humanLog(` ${run} swizzle XDSButton (XDS prefix also works)\n`);
return;
}
- const dirName = component.replace(/^XDS/, '');
-
- // Resolve the component's owning package(s) across core + integrations.
- const {loadedIntegrations, project} = await loadConfigSafely(
- process.cwd(),
- );
- // Core feedback URL is routed through the Project (config.issuesUrl,
- // falling back to the default core tracker). When config load failed,
- // resolveOwners applies the same default fallback.
- const coreIssuesUrl = project
- ? project.issuesUrl({package: CORE_PACKAGE})
- : undefined;
- const allOwners = resolveOwners(
- coreDir,
- loadedIntegrations,
- dirName,
- coreIssuesUrl,
- );
-
- if (allOwners.length === 0) {
- cliError(`Component "${component}" not found.`, {
- suggestions: components.slice(0, 10).map(n => ({name: n})),
- code: ERROR_CODES.ERR_UNKNOWN_COMPONENT,
- });
- return;
- }
-
- let owner;
- if (options.package) {
- owner = allOwners.find(o => o.package === options.package);
- if (!owner) {
- cliError(
- `Component "${dirName}" is not provided by package "${options.package}".`,
- {
- suggestions: allOwners.map(o => ({
- name: o.package,
- reason: 'provides this component',
- })),
- code: ERROR_CODES.ERR_UNKNOWN_COMPONENT,
- },
- );
- return;
- }
- } else if (allOwners.length > 1) {
- cliError(
- `Component "${dirName}" is provided by multiple packages. Re-run with --package <pkg> to choose one.`,
- {
- suggestions: allOwners.map(o => ({
- name: o.package,
- reason: 'provides this component',
- })),
- code: ERROR_CODES.ERR_AMBIGUOUS_COMPONENT,
- },
- );
- return;
- } else {
- owner = allOwners[0];
- }
-
- if (!owner.sourceDir || !fs.existsSync(owner.sourceDir)) {
- cliError(
- `No source found for "${dirName}" in package "${owner.package}".`,
- {code: ERROR_CODES.ERR_NO_SOURCE},
- );
- return;
- }
-
- const componentDir = owner.sourceDir;
-
- // Path-safety: --output must resolve inside cwd. Reject absolute
- // paths and `..` traversal up front, before any directory is created.
- let outputBase;
- try {
- outputBase = assertWithin(options.output, process.cwd(), {
- label: 'output directory',
- });
- } catch (err) {
- if (err instanceof PathSafetyError) {
- cliError(err.message, {code: ERROR_CODES.ERR_PATH_TRAVERSAL});
- return;
- }
- throw err;
- }
- const outputDir = path.join(outputBase, dirName);
-
- // Pre-flight overwrite check: collect files we'd write and detect
- // collisions before mkdir/writeFile so we never half-clobber.
- const sourceFiles = fs.readdirSync(componentDir).filter(file => {
- if (isExcludedFromCopy(file)) return false;
- const stat = fs.statSync(path.join(componentDir, file));
- return stat.isFile();
- });
-
- const existingFiles = sourceFiles.filter(f =>
- fs.existsSync(path.join(outputDir, f)),
- );
-
- if (existingFiles.length > 0 && !options.overwrite) {
- const relOutputForMsg = path.relative(process.cwd(), outputDir) || '.';
- const msg =
- `Refusing to overwrite ${existingFiles.length} existing file(s) in ${relOutputForMsg}/. ` +
- `Re-run with --overwrite (or -f) to replace them.`;
- cliError(msg, {code: ERROR_CODES.ERR_FILE_EXISTS});
- return;
- }
-
- fs.mkdirSync(outputDir, {recursive: true});
-
- // Copy all non-test, non-doc, non-README files
- const files = fs.readdirSync(componentDir);
- let copied = 0;
- // Track whether any copied source uses StyleX. Swizzled StyleX source
- // needs a build-time StyleX compiler in the consumer's app or it renders
- // unstyled with no error — so we surface a setup note after copying.
- let usesStyleX = false;
-
- for (const file of files) {
- // Skip test files, doc files, and README
- if (isExcludedFromCopy(file)) continue;
-
- const srcPath = path.join(componentDir, file);
- const stat = fs.statSync(srcPath);
- if (!stat.isFile()) continue;
-
- let content = fs.readFileSync(srcPath, 'utf-8');
-
- // Rewrite escaping imports for .ts/.tsx files to the owner package.
- if (file.endsWith('.ts') || file.endsWith('.tsx')) {
- content = rewriteImports(content, owner.ownerPackage);
- }
-
- if (
- (file.endsWith('.ts') || file.endsWith('.tsx')) &&
- content.includes('@stylexjs/stylex')
- ) {
- usesStyleX = true;
- }
-
- fs.writeFileSync(path.join(outputDir, file), content);
- copied++;
- }
-
- const relOutput = path.relative(process.cwd(), outputDir);
- const copiedFiles = files.filter(
- f =>
- !isExcludedFromCopy(f) &&
- fs.statSync(path.join(componentDir, f)).isFile(),
- );
-
- const feedback = buildFeedback(dirName, owner.issuesUrl);
-
- if (json) {
- /** @type {import('../../types/swizzle').SwizzleCopyResponse['data']} */
- const payload = {
- component: dirName,
- package: owner.package,
- outputDir: relOutput,
- filesCopied: copied,
- files: copiedFiles.map(f => f),
- usesStyleX,
- };
- if (feedback) payload.feedback = feedback;
- return jsonOut('swizzle.copy', payload);
- }
+ const {package: ownerPackage, outputDir, filesCopied, usesStyleX, feedback} =
+ result.data;
- humanLog(`\n✓ Copied ${copied} files to ${relOutput}/\n`);
- humanLog(
- `Relative imports have been rewritten to use ${owner.ownerPackage}.`,
- );
+ humanLog(`\n✓ Copied ${filesCopied} files to ${outputDir}/\n`);
+ humanLog(`Relative imports have been rewritten to use ${ownerPackage}.`);
humanLog('You can now customize the component source freely.\n');
- // StyleX build requirement. Swizzled components ship raw StyleX source,
- // which needs a build-time StyleX compiler in the consumer's app to
- // produce atomic CSS. Without it the component compiles but renders
- // unstyled, with no error — a confusing silent failure, so call it out.
+ // StyleX build requirement — swizzled StyleX source renders unstyled with
+ // no error unless the consumer's build runs a StyleX compiler.
if (usesStyleX) {
humanLog(
'⚠ These components use StyleX and require a StyleX compiler in your build.',
@@ -405,9 +86,7 @@ export function registerSwizzle(program) {
humanLog('');
}
- // Maintainer feedback note. If we couldn't swizzle cleanly, the team
- // wants to know — point users at the issue tracker. Skipped when the
- // owning package ships no issues URL.
+ // Maintainer feedback note (skipped when the owner ships no issues URL).
if (feedback) {
humanLog(
'Customizing a component often signals a gap in the design system.',
diff --git a/packages/cli/cli/commands/upgrade.mjs b/packages/cli/cli/commands/upgrade.mjs
index a81e3a9594..4840cc6a8d 100644
--- a/packages/cli/cli/commands/upgrade.mjs
+++ b/packages/cli/cli/commands/upgrade.mjs
@@ -49,7 +49,7 @@ import {
selectIntegrationCodemods,
} from '../../codemods/integration-discovery.mjs';
import {runIntegrationCodemods} from '../../codemods/integration-runner.mjs';
-import {installAgentDocs, inspectAgentDocs} from './agent-docs.mjs';
+import {installAgentDocs, inspectAgentDocs} from '../../lib/agent-docs/agent-docs.mjs';
import {getCliInvocation, formatCliCommand} from '../../utils/package-manager.mjs';
import {isValidSemver, semverGte} from '../../utils/semver.mjs';
import {jsonOut, jsonError} from '../../lib/json.mjs';
diff --git a/packages/cli/cli/commands/upgrade.test.mjs b/packages/cli/cli/commands/upgrade.test.mjs
index 7ff38b2348..b4f837cc6e 100644
--- a/packages/cli/cli/commands/upgrade.test.mjs
+++ b/packages/cli/cli/commands/upgrade.test.mjs
@@ -6,7 +6,7 @@ import * as path from 'node:path';
import * as os from 'node:os';
import {Command} from 'commander';
import {registerUpgrade} from './upgrade.mjs';
-import {generateCompressedIndex} from './agent-docs.mjs';
+import {generateCompressedIndex} from '../../lib/agent-docs/agent-docs.mjs';
let tmpDir;
let originalCwd;
diff --git a/packages/cli/cli/commands/validate-integration.mjs b/packages/cli/cli/commands/validate-integration.mjs
index d149342be1..617e5d2d28 100644
--- a/packages/cli/cli/commands/validate-integration.mjs
+++ b/packages/cli/cli/commands/validate-integration.mjs
@@ -16,35 +16,32 @@
import {jsonOut, humanLog} from '../../lib/json.mjs';
import {
- validateLocalIntegration,
- validateInstalledIntegration,
+ validateIntegration,
summarizeIssues,
} from '../../api/integration/validate-integration.mjs';
/**
* Render a validation result for humans.
- * @param {import('../../api/integration/validate-integration.mjs').ValidateResult} result
+ * @param {import('../../types/validate-integration').ValidateIntegrationResponse['data']} data
*/
-function printHuman(result) {
+function printHuman(data) {
const label =
- result.version != null
- ? `${result.name}@${result.version}`
- : result.name;
+ data.version != null ? `${data.name}@${data.version}` : data.name;
humanLog(`Validating integration: ${label}`);
- if (result.issues.length === 0) {
+ if (data.issues.length === 0) {
humanLog('\n\u2713 No issues found.');
return;
}
humanLog('');
- for (const issue of result.issues) {
+ for (const issue of data.issues) {
humanLog(` ${issue.severity} ${issue.code}: ${issue.message}`);
}
- const {errors, warnings} = summarizeIssues(result.issues);
+ const {errors, warnings} = summarizeIssues(data.issues);
humanLog(
- `\n${result.issues.length} issue(s): ${errors} error(s), ${warnings} warning(s)`,
+ `\n${data.issues.length} issue(s): ${errors} error(s), ${warnings} warning(s)`,
);
}
@@ -74,35 +71,18 @@ export function registerValidateIntegration(program) {
.action(async pkg => {
const json = program.opts().json || false;
- const result = pkg
- ? await validateInstalledIntegration(pkg)
- : await validateLocalIntegration();
-
- // No-arg + no local manifest: guidance, not an error.
- if (!result.found) {
- if (json) {
- jsonOut('integration.validate', {
- name: null,
- version: null,
- issues: [],
- });
- } else {
- humanLog(NO_MANIFEST_GUIDANCE);
- }
- return;
- }
+ const result = await validateIntegration(pkg);
if (json) {
- jsonOut('integration.validate', {
- name: result.name ?? null,
- version: result.version ?? null,
- issues: result.issues,
- });
+ jsonOut(result.type, result.data);
+ } else if (result.data.name === null) {
+ // No-arg + no local manifest: guidance, not an error.
+ humanLog(NO_MANIFEST_GUIDANCE);
} else {
- printHuman(result);
+ printHuman(result.data);
}
- const {errors} = summarizeIssues(result.issues);
+ const {errors} = summarizeIssues(result.data.issues);
if (errors > 0) {
process.exitCode = 1;
}
diff --git a/packages/cli/cli/index.mjs b/packages/cli/cli/index.mjs
index 1e23c31441..ca0cbbd0a9 100644
--- a/packages/cli/cli/index.mjs
+++ b/packages/cli/cli/index.mjs
@@ -19,7 +19,7 @@ import {cliError} from '../lib/cli-error.mjs';
import {ERROR_CODES} from '../lib/error-codes.mjs';
import {levenshteinDistance} from '../lib/string-utils.mjs';
import {installJsonShim} from '../lib/json-shim.mjs';
-import {isAstryxInitialized} from './commands/agent-docs.mjs';
+import {isAstryxInitialized} from '../lib/agent-docs/agent-docs.mjs';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -56,6 +56,7 @@ export const JSON_SUPPORTED = new Set([
'docs',
'discover',
'search',
+ 'build',
'swizzle',
'template',
'hook',
diff --git a/packages/cli/cli/commands/agent-docs.mjs b/packages/cli/lib/agent-docs/agent-docs.mjs
similarity index 100%
rename from packages/cli/cli/commands/agent-docs.mjs
rename to packages/cli/lib/agent-docs/agent-docs.mjs
diff --git a/packages/cli/cli/commands/agent-docs.path-safety.test.mjs b/packages/cli/lib/agent-docs/agent-docs.path-safety.test.mjs
similarity index 100%
rename from packages/cli/cli/commands/agent-docs.path-safety.test.mjs
rename to packages/cli/lib/agent-docs/agent-docs.path-safety.test.mjs
diff --git a/packages/cli/cli/commands/agent-docs.test.mjs b/packages/cli/lib/agent-docs/agent-docs.test.mjs
similarity index 100%
rename from packages/cli/cli/commands/agent-docs.test.mjs
rename to packages/cli/lib/agent-docs/agent-docs.test.mjs
diff --git a/packages/cli/lib/manifest.mjs b/packages/cli/lib/manifest.mjs
index 1b64dbdfe5..d1265b86d2 100644
--- a/packages/cli/lib/manifest.mjs
+++ b/packages/cli/lib/manifest.mjs
@@ -50,6 +50,7 @@ export const RESPONSE_TYPES = {
docs: ['docs.list', 'docs.detail', 'docs.detail.section'],
discover: ['discover.list', 'discover.detail', 'discover.detail.doc', 'discover.search'],
search: ['search'],
+ build: ['build.help', 'build.kit'],
swizzle: ['swizzle.list', 'swizzle.copy'],
template: [
'template.list',
@@ -79,6 +80,7 @@ const EXAMPLES = {
docs: ['astryx docs', 'astryx docs spacing --json'],
discover: ['astryx discover --json'],
search: ['astryx search modal --json', 'astryx search button --type component --json'],
+ build: ['astryx build', 'astryx build "analytics dashboard" --json'],
swizzle: ['astryx swizzle XDSButton'],
template: ['astryx template --json', 'astryx template dashboard ./src/app'],
hook: ['astryx hook', 'astryx hook useToggle --json'],
diff --git a/packages/cli/scripts/postinstall.mjs b/packages/cli/scripts/postinstall.mjs
index f339dc26ff..b3696cf136 100644
--- a/packages/cli/scripts/postinstall.mjs
+++ b/packages/cli/scripts/postinstall.mjs
@@ -41,7 +41,7 @@ export function shouldNudge({scriptPath, npmCommand, isSetUp} = {}) {
/** @param {string} root @returns {Promise<boolean>} */
async function projectIsSetUp(root) {
try {
- const {isAstryxInitialized} = await import('../cli/commands/agent-docs.mjs');
+ const {isAstryxInitialized} = await import('../lib/agent-docs/agent-docs.mjs');
return isAstryxInitialized(root);
} catch {
return false; // best-effort — if the check can't load, fall through and nudge
diff --git a/packages/cli/types/api.d.ts b/packages/cli/types/api.d.ts
index 2ccca60360..7bd6bfa4d6 100644
--- a/packages/cli/types/api.d.ts
+++ b/packages/cli/types/api.d.ts
@@ -44,6 +44,16 @@ import type {
import type {SearchResponse, SearchDomain} from './search';
import type {ErrorCode} from './error-codes';
import type {DoctorResponse} from './doctor';
+import type {
+ LayoutForm,
+ LayoutExpandResponse,
+ LayoutCheckResponse,
+ LayoutGrammarResponse,
+} from './layout';
+import type {ValidateIntegrationResponse} from './validate-integration';
+import type {AstryxIntegrationIssue} from './integration';
+import type {BuildHelpResponse, BuildKitResponse} from './build';
+import type {SwizzleListResponse, SwizzleCopyResponse} from './swizzle';
import type {Suggestion} from './base';
/** Structured API error with a stable machine-readable code. */
@@ -186,6 +196,47 @@ export declare function search(
options?: SearchOptions,
): Promise<SearchResponse>;
+// ── Build ────────────────────────────────────────────────────────────
+
+export interface BuildOptions {
+ cwd?: string;
+ type?: SearchDomain;
+ limit?: number;
+}
+
+/**
+ * Page-building assistant. No query → `build.help` (playbook signal); a query →
+ * `build.kit` (grouped composition kit of raw search entries + frame/foundation).
+ */
+export declare function build(
+ query?: string,
+ options?: BuildOptions,
+): Promise<BuildHelpResponse | BuildKitResponse>;
+
+// ── Swizzle ──────────────────────────────────────────────────────────
+
+export interface SwizzleOptions {
+ cwd?: string;
+ /** Output directory (must resolve inside cwd). Defaults to ./components/astryx. */
+ output?: string;
+ /** Scope to a specific owning package when a name is ambiguous. */
+ package?: string;
+ /** Force the list response even with a component argument. */
+ list?: boolean;
+ /** Overwrite existing files instead of erroring. */
+ overwrite?: boolean;
+}
+
+/**
+ * List swizzlable components (no name / `list`) or copy one component's source
+ * into the project (side effect) and return a `swizzle.copy` receipt. Errors
+ * throw AstryxError (ERR_UNKNOWN_COMPONENT, ERR_AMBIGUOUS_COMPONENT, …).
+ */
+export declare function swizzle(
+ component?: string,
+ options?: SwizzleOptions,
+): Promise<SwizzleListResponse | SwizzleCopyResponse>;
+
// ── Doctor ──────────────────────────────────
export interface DoctorOptions {
@@ -195,3 +246,58 @@ export interface DoctorOptions {
export declare function doctor(
options?: DoctorOptions,
): Promise<DoctorResponse>;
+
+// ── Layout ───────────────────────────────────────────────────────────
+
+export interface LayoutExpandOptions {
+ targetPath?: string;
+ form?: LayoutForm;
+ loose?: boolean;
+ name?: string;
+ cwd?: string;
+}
+
+export declare function layoutExpand(
+ expression: string,
+ options?: LayoutExpandOptions,
+): Promise<LayoutExpandResponse>;
+
+export interface LayoutCheckOptions {
+ form?: LayoutForm;
+ loose?: boolean;
+ cwd?: string;
+}
+
+export declare function layoutCheck(
+ expression: string,
+ options?: LayoutCheckOptions,
+): Promise<LayoutCheckResponse>;
+
+export interface LayoutGrammarOptions {
+ cwd?: string;
+}
+
+export declare function layoutGrammar(
+ options?: LayoutGrammarOptions,
+): Promise<LayoutGrammarResponse>;
+
+// ── Validate integration ─────────────────────────────────────────────
+
+export interface ValidateIntegrationOptions {
+ cwd?: string;
+}
+
+/**
+ * Validate the local integration (no `pkg`) or an installed one (`pkg` given).
+ * The no-manifest local case returns `{ name: null, version: null, issues: [] }`.
+ */
+export declare function validateIntegration(
+ pkg?: string,
+ options?: ValidateIntegrationOptions,
+): Promise<ValidateIntegrationResponse>;
+
+/** Count issues by severity. */
+export declare function summarizeIssues(issues: AstryxIntegrationIssue[]): {
+ errors: number;
+ warnings: number;
+};
diff --git a/packages/cli/types/base.d.ts b/packages/cli/types/base.d.ts
index aeec7d5343..37d8f0cff8 100644
--- a/packages/cli/types/base.d.ts
+++ b/packages/cli/types/base.d.ts
@@ -59,7 +59,7 @@ import type {
LayoutCheckResponse,
LayoutGrammarResponse,
} from './layout';
-import type {BuildHelpResponse} from './build';
+import type {BuildHelpResponse, BuildKitResponse} from './build';
import type {ErrorCode} from './error-codes';
import type {ManifestResponse} from './manifest';
import type {DoctorResponse} from './doctor';
@@ -135,6 +135,7 @@ export type CLIAnyResponse =
| LayoutCheckResponse
| LayoutGrammarResponse
| BuildHelpResponse
+ | BuildKitResponse
| ManifestResponse
| DoctorResponse
| ValidateIntegrationResponse;
diff --git a/packages/cli/types/build.d.ts b/packages/cli/types/build.d.ts
index 47da337679..dc38fee4f6 100644
--- a/packages/cli/types/build.d.ts
+++ b/packages/cli/types/build.d.ts
@@ -10,9 +10,11 @@
* Invocation -> type discriminator
* ---------------------------------------------------
* xds --json build -> build.help
- * xds --json build "<idea>" -> search
+ * xds --json build "<idea>" -> build.kit
*/
+import type {SearchResultEntry} from './search';
+
/** xds --json build (no query) — the "how to build a page" playbook signal. */
export interface BuildHelpResponse {
type: 'build.help';
@@ -21,3 +23,31 @@ export interface BuildHelpResponse {
playbook: true;
};
}
+
+/**
+ * xds --json build "<idea>" — the composition kit for what you're building.
+ *
+ * Entries are raw `SearchResultEntry` objects (no package-manager-prefixed
+ * command strings — the CLI adds those); `frame`/`foundation` are static
+ * component-name arrays surfaced on every kit.
+ */
+export interface BuildKitResponse {
+ type: 'build.kit';
+ data: {
+ query: string;
+ /** False when search returned nothing (renderer shows "No matches"). */
+ hasResults: boolean;
+ /** True when the top page template is a confident direct match. */
+ directMatch: boolean;
+ /** Closest page templates (≤3). */
+ pages: SearchResultEntry[];
+ /** Drop-in block patterns covering parts of the idea (≤5). */
+ blocks: SearchResultEntry[];
+ /** Idea-specific components/hooks (≤6), excluding frame/foundation. */
+ domain: SearchResultEntry[];
+ /** Always-on page-shell component names. */
+ frame: string[];
+ /** Always-on layout/typography/action component names. */
+ foundation: string[];
+ };
+}