Skip to content

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

TypeScript

feat(cli)!: remove the `astryx layout` command group (CLN-0006) (#7137)

Joey458ff35b179b
diff --git a/.changeset/remove-layout-command.md b/.changeset/remove-layout-command.md
new file mode 100644
index 0000000000..371d5fdefd
--- /dev/null
+++ b/.changeset/remove-layout-command.md
@@ -0,0 +1,17 @@
+---
+'@astryxdesign/cli': minor
+---
+
+[breaking] Remove the `astryx layout` command group (CLN-0006)
+
+Removes the deprecated `astryx layout` command group (`expand`, `check`, `grammar`),
+its three response types (`layout.expand`, `layout.check`, `layout.grammar`), and
+the programmatic API exports (`layoutExpand`, `layoutCheck`, `layoutGrammar`).
+Completes the `CLN-0006` cleanup of `DEP-0006`.
+
+Use `astryx build` to choose the template to start from, `astryx template` to scaffold
+it, and `astryx docs layout` for layout guidance. The layout guide is unaffected. The error codes `ERR_LAYOUT_PARSE` and `ERR_LAYOUT_INVALID` are retained (append-only contract).
+
+Removed JSON ids: `LayoutBlockReference.mode` `LayoutBlockReference.name` `LayoutCheckOptions.cwd` `LayoutCheckOptions.form` `LayoutCheckOptions.loose` `LayoutCheckResponse.data` `LayoutCheckResponse.data.compact` `LayoutCheckResponse.data.errors` `LayoutCheckResponse.data.form` `LayoutCheckResponse.data.outline` `LayoutCheckResponse.data.valid` `LayoutCheckResponse.data.warnings` `LayoutCheckResponse.type` `LayoutExpandOptions.cwd` `LayoutExpandOptions.form` `LayoutExpandOptions.loose` `LayoutExpandOptions.name` `LayoutExpandOptions.targetPath` `LayoutExpandResponse.data` `LayoutExpandResponse.data.blocksReferenced` `LayoutExpandResponse.data.code` `LayoutExpandResponse.data.componentsUsed` `LayoutExpandResponse.data.demoMediaReplaced` `LayoutExpandResponse.data.form` `LayoutExpandResponse.data.states` `LayoutExpandResponse.data.todos` `LayoutExpandResponse.data.warnings` `LayoutExpandResponse.data.written` `LayoutExpandResponse.type` `LayoutGrammarOptions.cwd` `LayoutGrammarResponse.data` `LayoutGrammarResponse.data.aliases` `LayoutGrammarResponse.data.text` `LayoutGrammarResponse.type` `LayoutIssue.col` `LayoutIssue.formatted` `LayoutIssue.line` `LayoutIssue.message` `LayoutIssue.suggestions`
+
+@josephfarina
diff --git a/.github/scripts/cli-api-types-verify.mjs b/.github/scripts/cli-api-types-verify.mjs
index 4949281f2d..5c9a433634 100644
--- a/.github/scripts/cli-api-types-verify.mjs
+++ b/.github/scripts/cli-api-types-verify.mjs
@@ -104,7 +104,7 @@ fs.writeFileSync(
const scenario = `
import {
component, docs, blog, discover, template, hook, search, build, swizzle,
- gapReport, upgrade, init, doctor, layoutExpand, layoutCheck, layoutGrammar,
+ gapReport, upgrade, init, doctor,
themeBuild, themeAdd, themeTemplate, themeList, listThemes,
integrationAdd, integrationAddComponent, integrationAddDoc,
integrationAddTemplate, integrationAddCodemod, integrationAddAgentDoc,
@@ -141,7 +141,7 @@ async function main() {
void ({} as ComponentDetailResponse); void ({} as SearchResponse); void ({} as UpgradeRunResponse);
void ({} as GapReportReceiptResponse); void ({} as GapReportCategoriesResponse);
void [docs, blog, discover, template, hook, search, build, swizzle, gapReport, upgrade, init,
- doctor, layoutExpand, layoutCheck, layoutGrammar, themeBuild, themeAdd, themeTemplate,
+ doctor, themeBuild, themeAdd, themeTemplate,
themeList, listThemes, validateIntegration, summarizeIssues, AstryxError, s];
}
void main;
diff --git a/packages/cli/README.md b/packages/cli/README.md
index de6708210d..f1ca0a095b 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -78,24 +78,23 @@ Options:
<!-- BEGIN GENERATED: commands -->
-| Command | Description |
-| ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `blog` | Read the Astryx blog from the published feed |
-| `build` | Build a page: the template to start from, or the workflow playbook (no query) |
-| `component` | List components or print component docs |
-| `discover` | Browse and search integrations: the ones you have and the ones you could add |
-| `docs` | Print reference docs |
-| `doctor` | Diagnose Astryx projects and integration packages |
-| `gap-report` | Report a missing component or feature to the package that owns it |
-| `hook` | List hooks or print hook docs |
-| `init` | Initialize the design system in your project |
-| `integration` | Author and verify an Astryx integration package |
-| `layout` | Generate XDS layouts from compressed expressions (XLE/XLO) [DEPRECATED: DEP-0006: Use `astryx build` to start from a template, `astryx template` to scaffold, and `astryx docs layout` for guidance.] |
-| `search` | Search components, hooks, docs, templates, and themes in one ranked list |
-| `swizzle` | Copy component source for customization |
-| `template` | List, show, or scaffold page and block templates |
-| `theme` | Add, switch, build, and author themes |
-| `upgrade` | Update your code after upgrading Astryx, and refresh ShadCN-copied components |
+| Command | Description |
+| ------------- | ----------------------------------------------------------------------------- |
+| `blog` | Read the Astryx blog from the published feed |
+| `build` | Build a page: the template to start from, or the workflow playbook (no query) |
+| `component` | List components or print component docs |
+| `discover` | Browse and search integrations: the ones you have and the ones you could add |
+| `docs` | Print reference docs |
+| `doctor` | Diagnose Astryx projects and integration packages |
+| `gap-report` | Report a missing component or feature to the package that owns it |
+| `hook` | List hooks or print hook docs |
+| `init` | Initialize the design system in your project |
+| `integration` | Author and verify an Astryx integration package |
+| `search` | Search components, hooks, docs, templates, and themes in one ranked list |
+| `swizzle` | Copy component source for customization |
+| `template` | List, show, or scaffold page and block templates |
+| `theme` | Add, switch, build, and author themes |
+| `upgrade` | Update your code after upgrading Astryx, and refresh ShadCN-copied components |
<!-- END GENERATED: commands -->
<!-- Generated by scripts/generate-cli-readme.mjs from `astryx manifest`. Run `pnpm -F @astryxdesign/cli readme`. -->
@@ -165,7 +164,7 @@ if (isError(result)) {
| `ERR_UNKNOWN` | Fallback for any error without a more specific code. |
| `ERR_UNKNOWN_COMMAND` | A top-level command name was not recognized (e.g. `astryx bogus`). |
| `ERR_UNKNOWN_SUBCOMMAND` | A subcommand under a command group was not recognized (e.g. `astryx theme bogus`). |
-| `ERR_INVALID_OPTION` | An unknown option was passed, --json was given to a command without JSON output, or layout --form got a value other than compact, outline, or auto. |
+| `ERR_INVALID_OPTION` | An unknown option was passed, --json was given to a command without JSON output. |
| `ERR_INVALID_ARGUMENT` | An argument or option value is invalid: wrong type, out of range, an unknown choice, an extra argument, or a conflicting combination. |
| `ERR_MISSING_ARGUMENT` | A required argument or option value was omitted. |
| `ERR_INVALID_LANG` | `--lang` was given a value outside its choices (en, zh, dense). |
@@ -481,9 +480,6 @@ Every response has a `type` discriminant. The full set is below (generated from
| `integration.template-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and non-blocking Core template-id conflicts as {id, severity: warning, integrationPackage, integrationType, integrationName, coreMatches, message, command}. |
| `integration.component-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and non-blocking conflicts where an integration component name is also owned by Core; each conflict includes the exact package-qualified command. |
| `integration.doc-conflicts` | validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and Core doc overlaps. Each finding includes `severity` (`info` \| `error`) and `relationship` (`replaces` \| `extends` \| `accidental`). |
-| `layout.expand` | The expansion: parsed form, generated TSX code, componentsUsed, states (count of useState hooks scaffolded), todos, blocksReferenced (each {name, mode}), warnings, written (the output path, or null when nothing was written), and demoMediaReplaced (count of demo media placeholders). Carries `meta.deprecations` with DEP-0006 and its replacement commands. |
-| `layout.check` | The validation result: a valid flag, the detected form, errors (each with line/col, message, formatted text, and suggestions), warnings, and the expression re-printed in both canonical surfaces (compact and outline). Carries `meta.deprecations` with DEP-0006 and its replacement commands. |
-| `layout.grammar` | The XLE/XLO grammar cheatsheet: a text field with the full reference plus an aliases map (short name → canonical component) generated from this install's registry. Carries `meta.deprecations` with DEP-0006 and its replacement commands. |
<!-- END GENERATED: response-types -->
<!-- Generated by scripts/generate-cli-readme.mjs from the response-types EnumDoc. Run `pnpm -F @astryxdesign/cli readme`. -->
diff --git a/packages/cli/api/index.mjs b/packages/cli/api/index.mjs
index b270b3e105..92c48be87c 100644
--- a/packages/cli/api/index.mjs
+++ b/packages/cli/api/index.mjs
@@ -48,7 +48,6 @@ export {gapReport} from './gap-report/gap-report.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 {
integrationAdd,
integrationAddAgentDoc,
@@ -97,7 +96,6 @@ export * from './gap-report/gap-report.type.mjs';
export * from './upgrade/upgrade.type.mjs';
export * from './init/init.type.mjs';
export * from './doctor/doctor.type.mjs';
-export * from './layout/layout.type.mjs';
export * from './integration/integration-authoring.type.mjs';
export * from './integration/pack-check.type.mjs';
export * from './integration/validate-integration.type.mjs';
diff --git a/packages/cli/api/json/index.ts b/packages/cli/api/json/index.ts
index 2d36ad7302..fbcf04f397 100644
--- a/packages/cli/api/json/index.ts
+++ b/packages/cli/api/json/index.ts
@@ -26,7 +26,6 @@ export type * from '../gap-report/gap-report.type.mjs';
export type * from '../upgrade/upgrade.type.mjs';
export type * from '../init/init.type.mjs';
export type * from '../doctor/doctor.type.mjs';
-export type * from '../layout/layout.type.mjs';
export type * from '../integration/validate-integration.type.mjs';
export type * from '../integration/authoring-checks.type.mjs';
export type * from '../integration/pack-check.type.mjs';
diff --git a/packages/cli/api/layout/_adapter.mjs b/packages/cli/api/layout/_adapter.mjs
deleted file mode 100644
index 42434cd9af..0000000000
--- a/packages/cli/api/layout/_adapter.mjs
+++ /dev/null
@@ -1,148 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * @file Shared analysis layer for the `layout` command's expand/check leaves.
- *
- * Loads the block catalog (template blocks + app-registered components), builds
- * the branch registry, and parses+validates a layout expression into a doc +
- * issues. Both the expand and check leaves sit on `analyze`; neither parses or
- * validates directly. (The grammar leaf needs none of this — it only reads the
- * registry alias table.)
- *
- * @input expression string (+ options)
- * @output analyze() -> {doc, registry, blocks, errors, warnings}; formatIssue()
- * @position api — shared core over lib/xle; leaves in expand/ + check/ project it
- */
-
-import {AstryxError} from '../error.mjs';
-import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
-import {parse, XLEParseError} from '../../foundation/xle/parse.mjs';
-import {validate} from '../../foundation/xle/validate.mjs';
-import {buildRegistry} from '../../foundation/xle/registry.mjs';
-import {discoverTemplates} from '../template/template.mjs';
-import {Project} from '../../foundation/config/project.mjs';
-
-/**
- * @typedef {object} LayoutBlock
- * @property {string} dirName
- * @property {string} name
- * @property {'template'|'component'} kind
- * @property {string} [type]
- * @property {string} [description]
- * @property {string} [category]
- * @property {string} [importPath]
- * @property {string} [filePath]
- * @property {boolean} [isDefault]
- */
-
-/**
- * The catalog a `{hint}` can resolve to: template blocks (spliced inline) plus
- * any app-registered local components from astryx.config.mjs
- * `experimental.xle.components` (imported by name). App components are how XLE
- * reaches domain pieces — the KpiCard/chart/drawer set that the
- * @astryxdesign/core registry can't see.
- *
- * @param {string} cwd
- * @returns {Promise<LayoutBlock[]>}
- */
-async function loadBlocks(cwd) {
- /** @type {LayoutBlock[]} */
- const blocks = [];
- try {
- const all = await discoverTemplates(cwd);
- const templates = all.filter(template => template.type === 'block');
- /** @type {Map<string, import('../../foundation/discovery/template-adapter.mjs').DiscoveredTemplate>} */
- const byId = new Map();
- // Exact ids are the fallback. Active replacement aliases override them in a
- // second pass, matching template() regardless of discovery/display order.
- for (const template of templates) byId.set(template.dirName, template);
- for (const template of templates) {
- if (template.replaces != null) byId.set(template.replaces, template);
- }
- for (const [id, template] of byId) {
- blocks.push({...template, dirName: id, kind: 'template'});
- }
- } catch {
- // discovery is best-effort
- }
- try {
- const project = await Project.load(cwd);
- /** @type {Record<string, {from?: string, description?: string, default?: boolean}>} */
- const components = project.config.experimental?.xle?.components ?? {};
- for (const [name, spec] of Object.entries(components)) {
- const importPath = spec.from;
- if (!importPath) continue;
- blocks.push({
- type: 'block',
- kind: 'component',
- dirName: name,
- name,
- description: spec.description ?? '',
- category: 'app',
- importPath,
- isDefault: Boolean(spec.default),
- });
- }
- } catch {
- // config is optional
- }
- return blocks;
-}
-
-/** @param {import('../../foundation/xle/xle-ast').RawIssue} issue */
-export function formatIssue(issue) {
- const where = issue.line != null ? `line ${issue.line}: ` : '';
- return `${where}${issue.message}`;
-}
-
-/**
- * Parse + validate, throwing structured XDSErrors on failure.
- * Returns {doc, registry, blocks, warnings}.
- *
- * @param {string} expression
- * @param {{form?: 'compact'|'outline'|'auto', loose?: boolean, cwd?: string}} [options]
- */
-export async function analyze(
- expression,
- {form = 'auto', loose = false, cwd = process.cwd()} = {},
-) {
- // Validate inputs in the API (not just the CLI): an empty expression or an
- // unknown --form must error, not silently parse as an empty/compact layout.
- if (typeof expression !== 'string' || expression.trim() === '') {
- throw new AstryxError(
- 'Layout expression is empty.',
- undefined,
- ERROR_CODES.ERR_INVALID_ARGUMENT,
- );
- }
- if (form !== 'compact' && form !== 'outline' && form !== 'auto') {
- throw new AstryxError(
- `Invalid form "${form}". Must be one of: compact, outline, auto.`,
- undefined,
- ERROR_CODES.ERR_INVALID_OPTION,
- );
- }
- const registry =
- /** @type {import('../../foundation/xle/xle-ast').Registry} */ (
- /** @type {unknown} */ (await buildRegistry({cwd}))
- );
- const blocks = await loadBlocks(cwd);
-
- /** @type {import('../../foundation/xle/xle-ast').XLEDoc} */
- let doc;
- try {
- doc = parse(expression, {form});
- } catch (e) {
- if (e instanceof XLEParseError) {
- throw new AstryxError(
- `Layout expression syntax error at line ${e.line}, col ${e.col}: ${e.message}`,
- undefined,
- ERROR_CODES.ERR_LAYOUT_PARSE,
- );
- }
- throw e;
- }
-
- const {errors, warnings} = validate(doc, registry, blocks, {loose});
- return {doc, registry, blocks, errors, warnings};
-}
diff --git a/packages/cli/api/layout/check/check.mjs b/packages/cli/api/layout/check/check.mjs
deleted file mode 100644
index 9b782ce1fa..0000000000
--- a/packages/cli/api/layout/check/check.mjs
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * @file `astryx layout check` leaf — validate a layout expression without
- * expanding, echoing both canonical surfaces (compact + outline). Resolution +
- * validation come from ../_adapter.mjs (analyze); this leaf projects the
- * `layout.check` envelope.
- *
- * @input expression string (+ options)
- * @output {type:'layout.check', data}
- * @position api — leaf over ../_adapter.mjs + lib/xle/print
- */
-
-import {toCompact, toOutline} from '../../../foundation/xle/print.mjs';
-import {analyze, formatIssue} from '../_adapter.mjs';
-
-/**
- * @deprecated DEP-0006: Use `build`, `template`, and `docs layout` instead. Removal in CLN-0006.
- * `astryx layout check "<expr>" [--form compact|outline]`
- * Validates without expanding; echoes both canonical surfaces.
- *
- * @param {string} expression
- * @param {{form?: 'compact'|'outline'|'auto', loose?: boolean, cwd?: string}} [options]
- * @returns {Promise<import('../layout.type.mjs').LayoutCheckResponse>}
- */
-export async function layoutCheck(expression, options = {}) {
- const {form = 'auto', loose = false, cwd = process.cwd()} = options;
- const {doc, errors, warnings} = await analyze(expression, {form, loose, cwd});
-
- return {
- type: 'layout.check',
- data: {
- valid: errors.length === 0,
- form: doc.form,
- errors: errors.map(e => ({...e, formatted: formatIssue(e)})),
- warnings: warnings.map(formatIssue),
- compact: toCompact(doc),
- outline: toOutline(doc),
- },
- };
-}
diff --git a/packages/cli/api/layout/expand/expand.mjs b/packages/cli/api/layout/expand/expand.mjs
deleted file mode 100644
index 9eff40d30a..0000000000
--- a/packages/cli/api/layout/expand/expand.mjs
+++ /dev/null
@@ -1,161 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * @file `astryx layout expand` leaf — expand a validated layout expression into
- * XDS TSX (optionally written to disk). Resolution + validation come from
- * ../_adapter.mjs (analyze); this leaf owns block-module assembly, code
- * generation, and the path-safe write, and projects the `layout.expand` envelope.
- *
- * @input expression string (+ options)
- * @output {type:'layout.expand', data}
- * @position api — leaf over ../_adapter.mjs + lib/xle/expand
- */
-
-import * as fs from 'node:fs';
-import * as path from 'node:path';
-import {AstryxError} from '../../error.mjs';
-import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
-import {assertWithin, isFilePathArg, PathSafetyError} from '../../../foundation/fs/path-safety.mjs';
-import {detectForm} from '../../../foundation/xle/parse.mjs';
-import {expand} from '../../../foundation/xle/expand.mjs';
-import {replaceDemoMedia} from '../../template/template.mjs';
-import {analyze, formatIssue} from '../_adapter.mjs';
-
-/** @param {string} name */
-const normKey = (name) => name.toLowerCase().replace(/[^a-z0-9]/g, '');
-
-/**
- * Collect the block names referenced by {hints} anywhere in the doc.
- * @param {import('../../../foundation/xle/xle-ast').XLEDoc} doc
- */
-function collectHintNames(doc) {
- /** @type {Set<string>} */
- const names = new Set();
- /** @param {import('../../../foundation/xle/xle-ast').XLEItem} node */
- const visitNode = (node) => {
- if (!node || node.kind === 'group') {
- (node?.children || []).forEach(visit);
- return;
- }
- if (node.hint?.block) names.add(node.hint.block.name);
- for (const slot of node.slots || []) {
- const value = slot.value;
- if (value && typeof value === 'object' && 'hint' in value && value.hint?.block) {
- names.add(value.hint.block.name);
- }
- if (value && typeof value === 'object' && 'subexpr' in value) {
- (value.subexpr || []).forEach(visit);
- }
- }
- (node.children || []).forEach(visit);
- };
- /** @param {import('../../../foundation/xle/xle-ast').XLEItem} item */
- const visit = (item) => (item?.kind === 'group' ? item.children.forEach(visit) : visitNode(item));
- doc.roots.forEach(visit);
- doc.overlays.forEach(visit);
- return names;
-}
-
-/**
- * Build the blockModules map expand() needs: import-mode for app components,
- * splice-mode (reading + asset-stripping the block source) for template blocks.
- * Only blocks actually referenced are read. Also returns how many demo media
- * references the splice-mode sources had replaced.
- *
- * @param {import('../../../foundation/xle/xle-ast').XLEDoc} doc
- * @param {import('../_adapter.mjs').LayoutBlock[]} blocks
- * @returns {{modules: Map<string, import('../../../foundation/xle/xle-ast').BlockModule>, demoMediaReplaced: number}}
- */
-function buildBlockModules(doc, blocks) {
- const referenced = collectHintNames(doc);
- if (referenced.size === 0) return {modules: new Map(), demoMediaReplaced: 0};
- const byKey = new Map(blocks.map(b => [normKey(b.dirName), b]));
- /** @type {Map<string, import('../../../foundation/xle/xle-ast').BlockModule>} */
- const modules = new Map();
- let demoMediaReplaced = 0;
- for (const name of referenced) {
- const block = byKey.get(normKey(name));
- if (!block) continue;
- if (block.kind === 'component') {
- modules.set(name, /** @type {import('../../../foundation/xle/xle-ast').BlockModule} */ (/** @type {unknown} */ ({mode: 'import', componentName: block.name, importPath: block.importPath, isDefault: block.isDefault})));
- } else if (block.filePath && fs.existsSync(block.filePath)) {
- const spliced = replaceDemoMedia(fs.readFileSync(block.filePath, 'utf-8'));
- demoMediaReplaced += spliced.demoMediaReplaced;
- modules.set(name, /** @type {import('../../../foundation/xle/xle-ast').BlockModule} */ ({mode: 'splice', componentName: block.dirName, source: spliced.source}));
- }
- }
- return {modules, demoMediaReplaced};
-}
-
-/**
- * @deprecated DEP-0006: Use `build`, `template`, and `docs layout` instead. Removal in CLN-0006.
- * `astryx layout expand "<expr>" [path]`
- *
- * @param {string} expression
- * @param {object} [options]
- * @param {string} [options.targetPath] - write TSX here (validated against cwd)
- * @param {'compact'|'outline'|'auto'} [options.form]
- * @param {boolean} [options.loose] - downgrade unknown {hints} to TODO warnings
- * @param {string} [options.name] - generated component name
- * @param {string} [options.cwd]
- * @returns {Promise<import('../layout.type.mjs').LayoutExpandResponse>}
- */
-export async function layoutExpand(expression, options = {}) {
- const {targetPath, form = 'auto', loose = false, name, cwd = process.cwd()} = options;
- const {doc, registry, blocks, errors, warnings} = await analyze(expression, {form, loose, cwd});
-
- if (errors.length > 0) {
- throw new AstryxError(
- `Layout expression is invalid:\n` + errors.map(e => ` - ${formatIssue(e)}`).join('\n'),
- errors.flatMap(e => (e.suggestions || []).map(s => ({name: s, reason: 'did you mean this?'}))),
- ERROR_CODES.ERR_LAYOUT_INVALID,
- );
- }
-
- const componentName = name || 'GeneratedLayout';
- if (!/^[A-Z][A-Za-z0-9]*$/.test(componentName)) {
- throw new AstryxError(
- `--name must be a PascalCase component name, got '${componentName}'`,
- undefined,
- ERROR_CODES.ERR_INVALID_ARGUMENT,
- );
- }
- const {modules: blockModules, demoMediaReplaced} = buildBlockModules(doc, blocks);
- const result = expand(doc, registry, {componentName, blockModules});
-
- let written = null;
- if (targetPath) {
- // The guard sees the file that will be written, not only its directory:
- // a symlink at that name would otherwise carry the write outside the root.
- const fileTarget = isFilePathArg(targetPath)
- ? targetPath
- : path.join(targetPath, `${componentName}.tsx`);
- let filePath;
- try {
- filePath = assertWithin(fileTarget, cwd, {label: 'layout target path'});
- } catch (err) {
- if (err instanceof PathSafetyError) {
- throw new AstryxError(err.message, undefined, ERROR_CODES.ERR_PATH_TRAVERSAL);
- }
- throw err;
- }
- fs.mkdirSync(path.dirname(filePath), {recursive: true});
- fs.writeFileSync(filePath, result.code);
- written = path.relative(cwd, filePath);
- }
-
- return {
- type: 'layout.expand',
- data: {
- form: form === 'auto' ? detectForm(expression) : form,
- code: result.code,
- componentsUsed: result.componentsUsed,
- states: result.states,
- todos: result.todos,
- blocksReferenced: [...blockModules.entries()].map(([name, m]) => ({name, mode: m.mode})),
- warnings: warnings.map(formatIssue),
- written,
- demoMediaReplaced,
- },
- };
-}
diff --git a/packages/cli/api/layout/expand/expand.path-safety.test.mjs b/packages/cli/api/layout/expand/expand.path-safety.test.mjs
deleted file mode 100644
index 62d53f1ace..0000000000
--- a/packages/cli/api/layout/expand/expand.path-safety.test.mjs
+++ /dev/null
@@ -1,53 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * @file Path-safety tests for the `layout.expand` write. The file written, not
- * only the directory it lands in, must stay inside the project root.
- */
-
-import {describe, it, expect, beforeAll} from 'vitest';
-import * as fs from 'node:fs';
-import * as os from 'node:os';
-import * as path from 'node:path';
-import {layoutExpand} from '../layout.mjs';
-import {buildRegistry} from '../../../foundation/xle/registry.mjs';
-
-const SLOW = 30_000;
-
-// The registry imports every component doc on first use; warm it once.
-beforeAll(async () => {
- await buildRegistry();
-}, 120_000);
-
-describe('layout.expand — write confinement', () => {
- it('rejects a directory target whose generated file is a symlink leading outside cwd', async () => {
- // Inside the workspace so @astryxdesign/core resolves.
- const cwd = fs.mkdtempSync(path.join(process.cwd(), '.xle-confine-test-'));
- const outside = fs.mkdtempSync(path.join(os.tmpdir(), 'xle-confine-outside-'));
- try {
- const victim = path.join(outside, 'victim.tsx');
- fs.writeFileSync(victim, 'OUTSIDE');
- fs.mkdirSync(path.join(cwd, 'out'));
- fs.symlinkSync(victim, path.join(cwd, 'out', 'GeneratedLayout.tsx'));
-
- await expect(
- layoutExpand('V > B', {targetPath: './out', cwd}),
- ).rejects.toMatchObject({code: 'ERR_PATH_TRAVERSAL'});
- expect(fs.readFileSync(victim, 'utf-8')).toBe('OUTSIDE');
- } finally {
- fs.rmSync(cwd, {recursive: true, force: true});
- fs.rmSync(outside, {recursive: true, force: true});
- }
- }, SLOW);
-
- it('still writes <Name>.tsx into a plain directory target', async () => {
- const cwd = fs.mkdtempSync(path.join(process.cwd(), '.xle-confine-test-'));
- try {
- const result = await layoutExpand('V > B', {targetPath: './out', name: 'Demo', cwd});
- expect(result.data.written).toBe(path.join('out', 'Demo.tsx'));
- expect(fs.existsSync(path.join(cwd, 'out', 'Demo.tsx'))).toBe(true);
- } finally {
- fs.rmSync(cwd, {recursive: true, force: true});
- }
- }, SLOW);
-});
diff --git a/packages/cli/api/layout/expand/expand.receipt.test.mjs b/packages/cli/api/layout/expand/expand.receipt.test.mjs
deleted file mode 100644
index 7b14ca7ae7..0000000000
--- a/packages/cli/api/layout/expand/expand.receipt.test.mjs
+++ /dev/null
@@ -1,74 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * @file The layout.expand receipt discloses demo media replaced in the template
- * blocks it splices. Blocks are picked by what their source contains, not by
- * name, so catalog renames do not break the suite.
- */
-
-import {describe, it, expect, beforeAll} from 'vitest';
-import * as fs from 'node:fs';
-import {layoutExpand} from '../layout.mjs';
-import {discoverTemplates} from '../../template/template.mjs';
-import {buildRegistry} from '../../../foundation/xle/registry.mjs';
-
-const SLOW = 60_000;
-const FIXTURE_REF = /\/template-assets\/[\w.-]+\.\w+/g;
-
-beforeAll(async () => {
- await buildRegistry();
-}, 120_000);
-
-/** @param {string} name */
-const hintKey = name => name.toLowerCase().replace(/[^a-z0-9]/g, '');
-
-/** @type {Promise<Array<{hint: string, refs: number}>> | undefined} */
-let catalog;
-
-/**
- * Template blocks a `{hint}` resolves to unambiguously, with the number of demo
- * media references in each one's source.
- * @returns {Promise<Array<{hint: string, refs: number}>>}
- */
-function catalogBlocks() {
- catalog ??= discoverTemplates().then(found => {
- const all = /** @type {Array<{dirName: string, type: string, filePath: string}>} */ (
- found
- ).filter(t => t.type === 'block' && t.filePath && fs.existsSync(t.filePath));
- const seen = new Map();
- for (const t of all) seen.set(hintKey(t.dirName), (seen.get(hintKey(t.dirName)) ?? 0) + 1);
- return all
- .filter(t => seen.get(hintKey(t.dirName)) === 1)
- .map(t => ({
- hint: hintKey(t.dirName),
- refs: (fs.readFileSync(t.filePath, 'utf-8').match(FIXTURE_REF) ?? []).length,
- }));
- });
- return catalog;
-}
-
-describe('layout.expand receipt - replaced demo media', () => {
- it('counts the demo media of a spliced block once, however often it is referenced', async () => {
- const block = (await catalogBlocks()).find(b => b.refs > 0);
- if (!block) throw new Error('no template block carries demo media');
- const res = await layoutExpand(`V > {${block.hint}}*3`);
- expect(res.type).toBe('layout.expand');
- expect(res.data.blocksReferenced).toHaveLength(1);
- expect(res.data.demoMediaReplaced).toBe(block.refs);
- expect(res.data.code).not.toContain('/template-assets/');
- }, SLOW);
-
- it('sums the demo media of every spliced block', async () => {
- const [a, b] = (await catalogBlocks()).filter(x => x.refs > 0);
- if (!b) throw new Error('fewer than two template blocks carry demo media');
- const res = await layoutExpand(`V > {${a.hint}} + {${b.hint}}`);
- expect(res.data.demoMediaReplaced).toBe(a.refs + b.refs);
- }, SLOW);
-
- it('reports 0 when nothing spliced carries demo media', async () => {
- const plain = (await catalogBlocks()).find(b => b.refs === 0);
- if (!plain) throw new Error('every template block carries demo media');
- expect((await layoutExpand(`V > {${plain.hint}}`)).data.demoMediaReplaced).toBe(0);
- expect((await layoutExpand('V > B"Save"')).data.demoMediaReplaced).toBe(0);
- }, SLOW);
-});
diff --git a/packages/cli/api/layout/grammar/grammar.mjs b/packages/cli/api/layout/grammar/grammar.mjs
deleted file mode 100644
index 214bb03e78..0000000000
--- a/packages/cli/api/layout/grammar/grammar.mjs
+++ /dev/null
@@ -1,88 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * @file `astryx layout grammar` leaf — the agent cheatsheet, with the alias
- * table generated from this branch's registry (never hand-maintained). Reads
- * only the registry; shares nothing with expand/check, so it has no adapter.
- *
- * @output {type:'layout.grammar', data}
- * @position api — leaf over lib/xle/registry
- */
-
-import {buildRegistry} from '../../../foundation/xle/registry.mjs';
-import {MAX_REPEAT} from '../../../foundation/xle/expand.mjs';
-
-/**
- * @deprecated DEP-0006: Use `build`, `template`, and `docs layout` instead. Removal in CLN-0006.
- * `astryx layout grammar` — the agent cheatsheet, with the alias table
- * generated from this branch's registry (never hand-maintained).
- *
- * @param {{cwd?: string}} [options]
- * @returns {Promise<import('../layout.type.mjs').LayoutGrammarResponse>}
- */
-export async function layoutGrammar(options = {}) {
- const {cwd = process.cwd()} = options;
- const registry = await buildRegistry({cwd});
-
- /** @type {string[]} */
- const aliasLines = [];
- /** @type {Map<string, string[]>} */
- const byTarget = new Map();
- for (const [alias, target] of registry.aliases) {
- if (!byTarget.has(target)) byTarget.set(target, []);
- byTarget.get(target)?.push(alias);
- }
- for (const [target, aliases] of [...byTarget.entries()].sort(([a], [b]) => a.localeCompare(b))) {
- aliasLines.push(`${aliases.join('/')}=${target}`);
- }
-
- const text = `XLE/XLO — XDS layout expressions (branch-generated; aliases reflect this install)
-
-WORKFLOW
- astryx layout check "<expr>" validate; echoes canonical compact + outline forms
- astryx layout expand "<expr>" [path] emit validated TSX (path optional; --name <Pascal>)
- Errors carry line/col + suggestions. Fix and resubmit; nothing is guessed.
-
-TWO SURFACES, ONE LANGUAGE (autodetected; --form to force)
- compact: A[cp6 @topNav=TN] > L > LC > S[p6] > (C{card-callout}*4) + T
- outline: indentation = nesting · same-indent = siblings · "repeat N:" block = (...)*N
- slot lines: topNav: TN (or a block: topNav:\\n TN ...)
-
-NODE ANATOMY Name#id.enum"payload"[attrs]{hint}*N > children
- .enum unique enum value of any prop: Bd.success Tx.lg B.primary
- "payload" primary text prop (label/title/heading) or text child: TI"Email" B"Save"
- {hint} kebab-case template/component reference (see TEMPLATE REFERENCING) — NEVER text
- *N / xN repeat, at most ${MAX_REPEAT} copies (use $ for the counter: Tk"item-$"*3)
- trailing ! initial selection for scaffolded state: Tab"Overview"!
-
-ATTRS [...] (outline: bare tokens after the name, no brackets)
- fused p6 g4 c4 w240 h2 cp2 mw960 rg2 cg2 (per-component: padding lives on Card/Section/AppShell.cp — p6 on AppShell/Layout/VStack errors with a correction)
- key=value t=email href='/x' c{min:340} dv=[top,bottom] — keys validated per component
- flags req opt dis striped hover divider … (isX/hasX props) · negate: !scroll
- align j= main axis, a= cross axis — expander picks hAlign/vAlign per stack direction
- slots @slotName=Node | @slotName=(sub > expr) | @slotName='text' | @slotName=#id
- trigger opens=#id (a plain attr, no @ — binds an onClick that opens the overlay)
- fill on a stack child → wraps in <StackItem size="fill">
-
-TEMPLATE REFERENCING ({hint} pulls in real content — this is how XLE reaches past the @astryxdesign/core shell)
- C{card-callout} splice a template block (astryx template --list --type block):
- the block is co-defined once in the file, referenced, imports merged
- {kpi-card} standalone reference (no wrapper element) — place a component directly
- {kpi-card}*4 repeat a reference; the definition/import is emitted once
- app components register local ones in astryx.config.mjs to import them by name:
- export default {experimental: {xle: {components: {KpiCard: {from: '@/components/KpiCard'}}}}}
- then {kpi-card} → import {KpiCard} + <KpiCard /> (kebab ↔ Pascal)
-
-STRUCTURE THE EXPANDER HANDLES
- Layout > LH + LC + LF + LP children auto-route into header/content/footer/start slots
- T > (TR>THC*4) + (TR>TC*4)*6 rows partition into TableHeader/TableBody automatically
- TabList/inputs required value+onChange scaffold typed useState automatically
- overlays compact: tree ;; Dlg#confirm[...] · outline: overlays: section
- trigger: B"Delete"[opens=#confirm]
-
-ALIASES (full component names always valid; XDS prefix optional)
- ${aliasLines.join(' ')}
-`;
-
- return {type: 'layout.grammar', data: {text, aliases: Object.fromEntries(registry.aliases)}};
-}
diff --git a/packages/cli/api/layout/layout.mjs b/packages/cli/api/layout/layout.mjs
deleted file mode 100644
index efcd135624..0000000000
--- a/packages/cli/api/layout/layout.mjs
+++ /dev/null
@@ -1,17 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * @file `layout` command barrel — re-exports the expand/check/grammar leaves so
- * the CLI (cli/commands/layout.mjs) and scripted callers import from one place.
- * Each leaf is also importable directly (e.g. api/layout/expand/expand.mjs). The
- * shared analysis core lives in ./_adapter.mjs. `layout` has real subcommands,
- * so there is no flag-dispatch here — the CLI calls the leaf it wants.
- *
- * @input layout expressions (+ options), per leaf
- * @output {type, data} envelopes: layout.expand / layout.check / layout.grammar
- * @position api — command barrel over the expand/check/grammar leaves
- */
-
-export {layoutExpand} from './expand/expand.mjs';
-export {layoutCheck} from './check/check.mjs';
-export {layoutGrammar} from './grammar/grammar.mjs';
diff --git a/packages/cli/api/layout/layout.test.mjs b/packages/cli/api/layout/layout.test.mjs
deleted file mode 100644
index b3a5394ef6..0000000000
--- a/packages/cli/api/layout/layout.test.mjs
+++ /dev/null
@@ -1,297 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * @file Integration tests for the layout API against the real @astryxdesign/core
- * registry and real template blocks. Every expansion is additionally
- * checked for TSX syntactic validity with the TypeScript parser, so the
- * "expansion emits compilable JSX" contract is enforced, not assumed.
- */
-
-import {describe, it, expect, beforeAll} from 'vitest';
-import {mkdtempSync, writeFileSync, rmSync} from 'node:fs';
-import {tmpdir} from 'node:os';
-import {join} from 'node:path';
-import ts from 'typescript';
-import {layoutExpand, layoutCheck, layoutGrammar} from './layout.mjs';
-import {buildRegistry} from '../../foundation/xle/registry.mjs';
-
-// The registry imports ~140 .doc.mjs modules on first use; under full-suite
-// parallel load that can exceed the default 5s test timeout. Warm it once.
-beforeAll(async () => {
- await buildRegistry();
-}, 120_000);
-
-const SLOW = 30_000;
-
-/** Assert TSX parses cleanly; returns the source file for inspection. */
-function expectValidTsx(code) {
- const sourceFile = ts.createSourceFile('generated.tsx', code, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX);
- const diagnostics = sourceFile.parseDiagnostics || [];
- const messages = diagnostics.map(d => ts.flattenDiagnosticMessageText(d.messageText, ' '));
- expect(messages).toEqual([]);
- return sourceFile;
-}
-
-const LOGIN_COMPACT =
- 'Ctr[h="100dvh"] > C[w=400 p8] > V[g6] > ' +
- '(V[g1] > Tx"Welcome back" + Tx[t=supporting]"Sign in to your account") + ' +
- '(F > TI"Email"[t=email req] + TI"Password"[t=password req]) + ' +
- '(H[j=between a=center] > CB"Remember me" + Lk[href="/forgot"]"Forgot password?") + ' +
- 'B.primary"Sign in"';
-
-const CHAT_OUTLINE = `
-AppShell
- topNav: TN
- Layout > LC !scroll
- ChL
- composer:
- ChC
- ChML
- ChS "Today"
- repeat 2:
- ChM
- ChB "Reply $"
- Tbar "Actions"
- B "Delete" opens=#confirm
-
-overlays:
- AD#confirm "Delete item?"
-`;
-
-const DASHBOARD_COMPACT =
- 'A[@topNav=TN @sideNav=SN] > L > V[g6] > ' +
- '(G[c4 g4] > C{card-callout}*4) + ' +
- '(C[p0] > T[striped] > (TR > THC"Name" + THC"Amount") + (TR > TC"Order $" + TC"\\$12.00")*3)';
-
-describe('layoutExpand', () => {
- it('expands the login card with typed state scaffolds', async () => {
- const result = await layoutExpand(LOGIN_COMPACT);
- expect(result.type).toBe('layout.expand');
- const {code} = result.data;
- expectValidTsx(code);
-
- expect(code).toContain(`const [email, setEmail] = useState('');`);
- expect(code).toContain(`const [rememberMe, setRememberMe] = useState(false);`);
- expect(code).toContain('<XDSCenter height="100dvh">');
- expect(code).toContain('variant="primary"');
- // axis-neutral j/a resolved onto the HStack's real props
- expect(code).toContain('hAlign="between"');
- expect(code).toContain('vAlign="center"');
- // payload routed to label props, not duplicated as children
- expect(code).not.toMatch(/label="Forgot password\?"[\s\S]{0,80}Forgot password\?/);
- }, SLOW);
-
- it('expands the outline chat page: slots, repeat blocks, overlays, triggers', async () => {
- const result = await layoutExpand(CHAT_OUTLINE);
- const {code, form} = result.data;
- expect(form).toBe('outline');
- expectValidTsx(code);
-
- expect(code).toContain('composer={');
- // slot satisfied required prop — no double assignment, no TODO for it
- expect(code.match(/composer=/g)).toHaveLength(1);
- expect(code).toContain('TODO(xle): open #confirm');
- expect(code).toContain('overlays — wire open state');
- expect((code.match(/<XDSChatMessage\b/g) || [])).toHaveLength(2);
- }, SLOW);
-
- it('expands the dashboard: table partition, repeats with $ counter and \\$ escape', async () => {
- const result = await layoutExpand(DASHBOARD_COMPACT);
- const {code} = result.data;
- expectValidTsx(code);
-
- expect(code).toContain('<XDSTableHeader>');
- expect(code).toContain('<XDSTableBody>');
- expect(code).toContain('Order 1');
- expect(code).toContain('Order 3');
- expect(code).toContain('$12.00');
- expect(code).not.toContain('112.00');
- // {card-callout} now splices: the block is co-defined once and referenced
- // four times — no TODO marker.
- expect((code.match(/^function CardCallout\(\)/gm) || [])).toHaveLength(1);
- expect((code.match(/<CardCallout \/>/g) || [])).toHaveLength(4);
- expect(code).not.toContain("TODO(xle): content block 'CardCallout'");
- }, SLOW);
-
- it('compact and outline surfaces expand to identical TSX', async () => {
- const check = await layoutCheck(LOGIN_COMPACT);
- const fromCompact = await layoutExpand(LOGIN_COMPACT);
- const fromOutline = await layoutExpand(check.data.outline, {form: 'outline'});
- expect(fromOutline.data.code).toEqual(fromCompact.data.code);
- }, SLOW);
-
- it('expansion is deterministic', async () => {
- const a = await layoutExpand(DASHBOARD_COMPACT);
- const b = await layoutExpand(DASHBOARD_COMPACT);
- expect(a.data.code).toEqual(b.data.code);
- }, SLOW);
-
- it('throws structured errors with suggestions on invalid expressions', async () => {
- await expect(layoutExpand('A[p6] > Grdi')).rejects.toMatchObject({
- code: 'ERR_LAYOUT_INVALID',
- message: expect.stringMatching(/AppShell has no prop 'padding'/),
- });
- });
-
- it('rejects non-PascalCase --name', async () => {
- await expect(layoutExpand('V > C', {name: 'not pascal'})).rejects.toMatchObject({
- code: 'ERR_INVALID_ARGUMENT',
- });
- });
-
- it('surfaces parse errors with positions', async () => {
- await expect(layoutExpand('V > > C')).rejects.toMatchObject({
- code: 'ERR_LAYOUT_PARSE',
- message: expect.stringMatching(/line 1/),
- });
- });
-
- it('maps pathologically deep nesting to a coded parse error, not ERR_UNKNOWN', async () => {
- await expect(layoutCheck('V > '.repeat(2000) + 'C')).rejects.toMatchObject({
- code: 'ERR_LAYOUT_PARSE',
- });
- });
-
- it('wraps top-level repeats and groups in a fragment (valid JSX)', async () => {
- for (const expr of ['B"Sign in"*3', '(B"a" + B"b")', '(B"a" + B"b")*2']) {
- const {data} = await layoutExpand(expr);
- expectValidTsx(data.code);
- expect(data.code).toContain('<>');
- }
- }, SLOW);
-
- it('wraps a top-level outline repeat block in a fragment', async () => {
- const {data} = await layoutExpand('repeat 3:\n B "x"', {form: 'outline'});
- expectValidTsx(data.code);
- }, SLOW);
-
- it('emits JSX-safe TSX for text payloads containing < and >', async () => {
- const result = await layoutExpand('Text"5 < 3 and 3 > 1"');
- expectValidTsx(result.data.code);
- }, SLOW);
-
- it('emits JSX-safe TSX for text payloads containing { and }', async () => {
- const result = await layoutExpand('Text"cost is {price}"');
- expectValidTsx(result.data.code);
- }, SLOW);
-
- it('emits JSX-safe TSX when a text payload looks like a closing tag', async () => {
- const result = await layoutExpand('Text"end</Text><img/>"');
- expectValidTsx(result.data.code);
- }, SLOW);
-
- it('emits JSX-safe TSX for JSX-special chars in outline form', async () => {
- const result = await layoutExpand('VStack\n Text "a < b"', {form: 'outline'});
- expectValidTsx(result.data.code);
- }, SLOW);
-});
-
-describe('layoutCheck', () => {
- it('returns both canonical surfaces for valid input', async () => {
- const result = await layoutCheck('V[g6] > C{card-callout}*2');
- expect(result.data.valid).toBe(true);
- expect(result.data.compact).toContain('{card-callout}');
- expect(result.data.outline).toContain('C {card-callout} x2');
- });
-
- it('collects all errors instead of stopping at the first', async () => {
- const result = await layoutCheck('A[p6] > V[g7] > Bd.sucess"x" + C{not-a-block}');
- expect(result.data.valid).toBe(false);
- expect(result.data.errors.length).toBeGreaterThanOrEqual(4);
- const all = result.data.errors.map(e => e.message).join('\n');
- expect(all).toMatch(/no prop 'padding'/);
- expect(all).toMatch(/must be one of/);
- expect(all).toMatch(/Unknown block/);
- });
-});
-
-describe('template referencing', () => {
- it('splices a template block: co-defined once, referenced, imports merged', async () => {
- const result = await layoutExpand('S[p6] > C{card-callout}*3', {name: 'Demo'});
- const {code} = result.data;
- expectValidTsx(code);
- // co-defined exactly once, referenced three times, no TODO
- expect((code.match(/^function CardCallout\(\)/gm) || [])).toHaveLength(1);
- expect((code.match(/<CardCallout \/>/g) || [])).toHaveLength(3);
- expect(code).not.toContain('TODO(xle)');
- // the block's own import is hoisted, and shared specifiers dedupe
- expect((code.match(/from '@astryxdesign\/core\/Card'/g) || [])).toHaveLength(1);
- // the block lost its export — it's a local declaration now
- expect(code).not.toContain('export default function CardCallout');
- expect(result.data.blocksReferenced).toEqual([{name: 'CardCallout', mode: 'splice'}]);
- }, SLOW);
-
- it('merges a stateful block useState into a single react import', async () => {
- const result = await layoutExpand(
- 'V > TI"Search"[t=text] + {table-column-settings-table}',
- {name: 'Demo'},
- );
- const {code} = result.data;
- expectValidTsx(code);
- // page TextInput scaffolds useState; block also uses useState → one import
- expect((code.match(/^import \{useState\} from 'react';$/gm) || [])).toHaveLength(1);
- expect(code).toContain('function TableColumnSettingsTable()');
- }, SLOW);
-
- it('imports app-registered local components (the local-component bridge)', async () => {
- // Inside the workspace so @astryxdesign/core resolves; cleaned up after.
- // A package.json beside the config makes Project.load resolve it as the
- // sibling-of-nearest-package.json (the standard config resolution).
- const cwd = mkdtempSync(join(process.cwd(), '.xle-imp-test-'));
- try {
- writeFileSync(join(cwd, 'package.json'), '{"name": "xle-imp-fixture"}\n');
- writeFileSync(
- join(cwd, 'astryx.config.mjs'),
- `export default {experimental: {xle: {components: {KpiCard: {from: '@/components/KpiCard'}, TimeRangePicker: {from: '@/components/TimeRangePicker'}}}}};\n`,
- );
- const result = await layoutExpand('S[p6] > (G[c4 g4] > {kpi-card}*4) + {time-range-picker}', {
- name: 'Demo',
- cwd,
- });
- const {code} = result.data;
- expectValidTsx(code);
- expect(code).toContain("import {KpiCard} from '@/components/KpiCard';");
- expect(code).toContain("import {TimeRangePicker} from '@/components/TimeRangePicker';");
- expect((code.match(/<KpiCard \/>/g) || [])).toHaveLength(4);
- expect(code).toContain('<TimeRangePicker />');
- expect(result.data.blocksReferenced).toContainEqual({name: 'KpiCard', mode: 'import'});
- } finally {
- rmSync(cwd, {recursive: true, force: true});
- }
- }, SLOW);
-
- it('parses a standalone {block} in both surfaces', async () => {
- const check = await layoutCheck('G[c4 g4] > {card-callout}*2');
- expect(check.data.valid).toBe(true);
- expect(check.data.compact).toContain('{card-callout}*2');
- expect(check.data.outline).toMatch(/\{card-callout\} x2/);
- });
-});
-
-describe('layoutGrammar', () => {
- it('emits the cheatsheet with branch-generated aliases', async () => {
- const result = await layoutGrammar();
- expect(result.data.text).toContain('TWO SURFACES');
- expect(result.data.aliases.V).toBe('VStack');
- expect(result.data.aliases.TB).toBe('TableBody');
- // every alias target must exist — the table is registry-filtered
- expect(Object.values(result.data.aliases)).not.toContain(undefined);
- });
-});
-
-
-describe('layout — input validation (API matches CLI)', () => {
- it('rejects an invalid --form value instead of silently parsing as compact', async () => {
- await expect(layoutCheck('V > C', {form: /** @type {any} */ ('xml')})).rejects.toMatchObject({
- code: 'ERR_INVALID_OPTION',
- });
- await expect(layoutExpand('V > C', {form: /** @type {any} */ ('nonsense')})).rejects.toMatchObject({
- code: 'ERR_INVALID_OPTION',
- });
- });
-
- it('rejects an empty expression at the API layer', async () => {
- await expect(layoutCheck('')).rejects.toMatchObject({code: 'ERR_INVALID_ARGUMENT'});
- await expect(layoutExpand(' ')).rejects.toMatchObject({code: 'ERR_INVALID_ARGUMENT'});
- });
-});
diff --git a/packages/cli/api/layout/layout.type.mjs b/packages/cli/api/layout/layout.type.mjs
deleted file mode 100644
index 57a29fb0cd..0000000000
--- a/packages/cli/api/layout/layout.type.mjs
+++ /dev/null
@@ -1,104 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * @file Colocated types for the `layout` command — source of truth for its JSON
- * responses. `astryx layout expand|check|grammar` turn compressed XLE/XLO
- * expressions into validated XDS TSX (or echo canonical surfaces / a grammar
- * cheatsheet). The `types/layout.d.ts` barrel re-exports from here.
- *
- * Invocation -> type discriminator
- * -----------------------------------------------------------------
- * astryx --json layout expand "<expr>" -> layout.expand
- * astryx --json layout check "<expr>" -> layout.check
- * astryx --json layout grammar -> layout.grammar
- */
-
-/**
- * The input surface an expression was parsed as.
- * @typedef {'compact' | 'outline' | 'auto'} LayoutForm
- */
-
-/**
- * A validation issue with its formatted, human-readable rendering.
- * @typedef {object} LayoutIssue
- * @property {number} [line]
- * @property {number} [col]
- * @property {string} message
- * @property {string} formatted
- * @property {string[]} [suggestions]
- */
-
-/**
- * A block referenced by a layout expression and how it was spliced in.
- * @typedef {object} LayoutBlockReference
- * @property {string} name
- * @property {string} mode
- */
-
-/**
- * astryx --json layout expand "<expr>" [path]
- * @typedef {object} LayoutExpandResponse
- * @property {'layout.expand'} type
- * @property {object} data
- * @property {LayoutForm} data.form
- * @property {string} data.code
- * @property {string[]} data.componentsUsed
- * @property {number} data.states Number of useState hooks the expansion scaffolded.
- * @property {string[]} data.todos
- * @property {LayoutBlockReference[]} data.blocksReferenced
- * @property {string[]} data.warnings
- * @property {string | null} data.written
- * @property {number} data.demoMediaReplaced Astryx demo media references (images, posters, videos) replaced in the spliced template blocks: images with a neutral placeholder, videos with an empty source. Swap in your own media at those points in the code; no media is installed. 0 when no spliced block carried any.
- */
-
-/**
- * astryx --json layout check "<expr>"
- * @typedef {object} LayoutCheckResponse
- * @property {'layout.check'} type
- * @property {object} data
- * @property {boolean} data.valid
- * @property {LayoutForm} data.form
- * @property {LayoutIssue[]} data.errors
- * @property {string[]} data.warnings
- * @property {string} data.compact
- * @property {string} data.outline
- */
-
-/**
- * astryx --json layout grammar
- * @typedef {object} LayoutGrammarResponse
- * @property {'layout.grammar'} type
- * @property {object} data
- * @property {string} data.text
- * @property {Record<string, string>} data.aliases Alias table (short name -> canonical component), from the registry.
- */
-
-/**
- * @typedef {LayoutExpandResponse | LayoutCheckResponse | LayoutGrammarResponse} LayoutResponse
- */
-
-/**
- * Options for `layoutExpand()`.
- * @typedef {object} LayoutExpandOptions
- * @property {string} [targetPath]
- * @property {LayoutForm} [form]
- * @property {boolean} [loose]
- * @property {string} [name]
- * @property {string} [cwd]
- */
-
-/**
- * Options for `layoutCheck()`.
- * @typedef {object} LayoutCheckOptions
- * @property {LayoutForm} [form]
- * @property {boolean} [loose]
- * @property {string} [cwd]
- */
-
-/**
- * Options for `layoutGrammar()`.
- * @typedef {object} LayoutGrammarOptions
- * @property {string} [cwd]
- */
-
-export {};
diff --git a/packages/cli/api/layout/layoutCheck.doc.mjs b/packages/cli/api/layout/layoutCheck.doc.mjs
deleted file mode 100644
index 1fd1b3e03d..0000000000
--- a/packages/cli/api/layout/layoutCheck.doc.mjs
+++ /dev/null
@@ -1,85 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * @file FunctionDoc for `layoutCheck()` / `astryx layout check`. Colocated with
- * the API function it documents; the response-shape source of truth stays in
- * `layout.type.mjs`.
- * @position packages/cli/api/layout — function documentation
- */
-
-/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */
-export const doc = {
- type: 'function',
- kind: 'api',
- name: 'layoutCheck',
- namespace: 'cli/api',
- displayName: 'layoutCheck()',
- summary: 'Validate a layout expression without expanding it.',
- description:
- 'The validator behind `astryx layout check`. Parses and validates a compressed XLE/XLO ' +
- 'expression without generating any TSX, and echoes it back in both canonical surfaces ' +
- '(compact and outline). Validation failures are reported in the layout.check envelope ' +
- '(valid: false) with line/col and suggestions (not thrown) so callers can lint an ' +
- 'expression and surface fixes. **Deprecated (DEP-0006).** Use `build`, `template`, and `docs layout` instead. This function will be removed in a future minor release.',
- importPath: '@astryxdesign/cli/api',
- signature:
- 'layoutCheck(expression: string, options?: LayoutCheckOptions): Promise<LayoutCheckResponse>',
- keywords: ['layout', 'check', 'validate', 'xle', 'xlo', 'lint'],
- params: [
- {
- name: 'expression',
- type: 'string',
- description: 'The layout expression to validate.',
- required: true,
- },
- {
- name: 'options.form',
- type: "'compact' | 'outline' | 'auto'",
- description:
- 'Force which input surface the expression is parsed as, or auto-detect it.',
- default: "'auto'",
- },
- {
- name: 'options.loose',
- type: 'boolean',
- description:
- 'Treat unknown {hint} references as warnings instead of errors.',
- default: 'false',
- },
- {
- name: 'options.cwd',
- type: 'string',
- description: 'Directory the block catalog and registry resolve against.',
- },
- ],
- returns: [
- {
- type: 'layout.check',
- description:
- 'The validation result: a valid flag, the detected form, errors (each with line/col, message, formatted text, and suggestions), warnings, and the expression re-printed in both canonical surfaces (compact and outline).',
- },
- ],
- throws: [
- {code: 'ERR_INVALID_ARGUMENT', when: 'the expression is empty'},
- {
- code: 'ERR_INVALID_OPTION',
- when: 'form is not one of "compact", "outline", or "auto"',
- },
- {
- code: 'ERR_LAYOUT_PARSE',
- when: 'the expression has a syntax error (reported with line/col)',
- },
- ],
- examples: [
- {
- label: 'Validate an expression',
- code: 'const r = await layoutCheck(\'VStack[g4] > Text"Hi"\');',
- },
- {
- label: 'Read the canonical forms',
- code: 'const {data} = await layoutCheck(\'Card > Text"Hi"\');',
- },
- ],
- command: 'layout check',
- related: ['layoutExpand', 'layoutGrammar'],
-};
diff --git a/packages/cli/api/layout/layoutExpand.doc.mjs b/packages/cli/api/layout/layoutExpand.doc.mjs
deleted file mode 100644
index f36039714b..0000000000
--- a/packages/cli/api/layout/layoutExpand.doc.mjs
+++ /dev/null
@@ -1,107 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * @file FunctionDoc for `layoutExpand()` / `astryx layout expand`. Colocated
- * with the API function it documents; the response-shape source of truth stays
- * in `layout.type.mjs`.
- * @position packages/cli/api/layout — function documentation
- */
-
-/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */
-export const doc = {
- type: 'function',
- kind: 'api',
- name: 'layoutExpand',
- namespace: 'cli/api',
- displayName: 'layoutExpand()',
- summary: 'Expand a validated layout expression into XDS TSX.',
- description:
- 'The generator behind `astryx layout expand`. Parses and validates a compressed XLE/XLO ' +
- 'expression, then expands it into ready-to-use XDS TSX, auto-routing structural children ' +
- 'into the right slots, scaffolding typed useState for interactive controls, and splicing or ' +
- 'importing any referenced template blocks. Returns the code (and metadata) in a layout.expand ' +
- 'envelope, optionally writing it to a path within cwd. **Deprecated (DEP-0006).** Use `build`, `template`, and `docs layout` instead. This function will be removed in a future minor release.',
- importPath: '@astryxdesign/cli/api',
- signature:
- 'layoutExpand(expression: string, options?: LayoutExpandOptions): Promise<LayoutExpandResponse>',
- keywords: ['layout', 'expand', 'xle', 'xlo', 'tsx', 'scaffold', 'generate'],
- params: [
- {
- name: 'expression',
- type: 'string',
- description:
- 'The layout expression to expand (XLE compact or XLO outline form).',
- required: true,
- },
- {
- name: 'options.targetPath',
- type: 'string',
- description:
- 'Write the generated TSX here (validated to stay within cwd). A path that ends in .tsx, .ts, .jsx, .js, .mjs, .cjs, .css, .scss, .json, .md or .html is used as-is; any other path is a directory that gets <name>.tsx. An existing file is replaced. Omit to return the code without writing.',
- },
- {
- name: 'options.form',
- type: "'compact' | 'outline' | 'auto'",
- description:
- 'Force which input surface the expression is parsed as, or auto-detect it.',
- default: "'auto'",
- },
- {
- name: 'options.loose',
- type: 'boolean',
- description:
- 'Downgrade unknown {hint} references to TODO warnings instead of hard errors.',
- default: 'false',
- },
- {
- name: 'options.name',
- type: 'string',
- description: 'PascalCase name for the generated component.',
- default: "'GeneratedLayout'",
- },
- {
- name: 'options.cwd',
- type: 'string',
- description:
- 'Directory the block catalog, registry, and target path resolve against.',
- },
- ],
- returns: [
- {
- type: 'layout.expand',
- description:
- 'The expansion: the parsed form, the generated TSX code, componentsUsed, states (count of useState hooks scaffolded), todos, blocksReferenced (each {name, mode}), warnings, written (the relative output path, or null when nothing was written), and demoMediaReplaced (how many Astryx demo media references in the spliced template blocks, such as images, posters and videos, were replaced with placeholders for you to swap for your own media).',
- },
- ],
- throws: [
- {
- code: 'ERR_INVALID_ARGUMENT',
- when: 'the expression is empty, or name is not a PascalCase identifier',
- },
- {
- code: 'ERR_INVALID_OPTION',
- when: 'form is not one of "compact", "outline", or "auto"',
- },
- {
- code: 'ERR_LAYOUT_PARSE',
- when: 'the expression has a syntax error (reported with line/col)',
- },
- {
- code: 'ERR_LAYOUT_INVALID',
- when: 'the expression parses but fails validation (unknown component/prop/enum/block)',
- },
- {code: 'ERR_PATH_TRAVERSAL', when: 'the target path escapes cwd'},
- ],
- examples: [
- {
- label: 'Expand to TSX',
- code: 'const r = await layoutExpand(\'VStack[g4] > Heading"Title" + Text"Body"\');',
- },
- {
- label: 'Write to a file',
- code: "await layoutExpand('Card > Text\"Hi\"', {targetPath: 'src/Generated.tsx', name: 'Generated'});",
- },
- ],
- command: 'layout expand',
- related: ['layoutCheck', 'layoutGrammar'],
-};
diff --git a/packages/cli/api/layout/layoutGrammar.doc.mjs b/packages/cli/api/layout/layoutGrammar.doc.mjs
deleted file mode 100644
index 0d9e9f2c67..0000000000
--- a/packages/cli/api/layout/layoutGrammar.doc.mjs
+++ /dev/null
@@ -1,57 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * @file FunctionDoc for `layoutGrammar()` / `astryx layout grammar`. Colocated
- * with the API function it documents; the response-shape source of truth stays
- * in `layout.type.mjs`.
- * @position packages/cli/api/layout — function documentation
- */
-
-/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */
-export const doc = {
- type: 'function',
- kind: 'api',
- name: 'layoutGrammar',
- namespace: 'cli/api',
- displayName: 'layoutGrammar()',
- summary: 'Return the XLE/XLO grammar cheatsheet for this install.',
- description:
- 'The reference behind `astryx layout grammar`: the agent cheatsheet for writing XLE/XLO ' +
- "layout expressions, with the alias table generated from this branch's registry rather than " +
- 'hand-maintained, so short names always reflect the components actually installed. **Deprecated (DEP-0006).** Use `build`, `template`, and `docs layout` instead. This function will be removed in a future minor release.',
- importPath: '@astryxdesign/cli/api',
- signature:
- 'layoutGrammar(options?: LayoutGrammarOptions): Promise<LayoutGrammarResponse>',
- keywords: [
- 'layout',
- 'grammar',
- 'cheatsheet',
- 'xle',
- 'xlo',
- 'aliases',
- 'reference',
- ],
- params: [
- {
- name: 'options.cwd',
- type: 'string',
- description:
- 'Directory the component registry (and its alias table) resolves against.',
- },
- ],
- returns: [
- {
- type: 'layout.grammar',
- description:
- "The cheatsheet: a text field with the full grammar reference, plus an aliases map (short name → canonical component) generated from this install's registry.",
- },
- ],
- examples: [
- {
- label: 'Get the cheatsheet',
- code: 'const {data} = await layoutGrammar();',
- },
- ],
- command: 'layout grammar',
- related: ['layoutExpand', 'layoutCheck'],
-};
diff --git a/packages/cli/api/template/template-integration.test.mjs b/packages/cli/api/template/template-integration.test.mjs
index 434b486e6a..99f1ec4daa 100644
--- a/packages/cli/api/template/template-integration.test.mjs
+++ b/packages/cli/api/template/template-integration.test.mjs
@@ -19,7 +19,6 @@ import {
} from './template.mjs';
import {search} from '../search/search.mjs';
import {build} from '../build/build.mjs';
-import {layoutExpand} from '../layout/layout.mjs';
import {runCli} from '../../test-utils/run-cli.mjs';
let tmpDir;
@@ -532,105 +531,6 @@ describe('integration template discovery', () => {
});
});
- it('resolves a replacement block through the layout alias', async () => {
- const pkgDir = installWidgets(tmpDir);
- writeTemplate(pkgDir, 'acme-card-callout', {
- kind: 'block',
- source:
- 'export default function AcmeCardCallout() { return <span>Acme replacement block</span>; }\n',
- });
- declareReplaces(pkgDir, {
- 'acme-card-callout': 'CardCallout',
- });
-
- const accidental = path.join(tmpDir, 'node_modules', '@acme', 'extra');
- fs.mkdirSync(path.join(accidental, 'templates'), {recursive: true});
- fs.writeFileSync(
- path.join(accidental, 'package.json'),
- JSON.stringify({name: '@acme/extra', version: '1.0.0'}),
- );
- fs.writeFileSync(
- path.join(accidental, 'astryx.integration.mjs'),
- `export default {templates: './templates'};\n`,
- );
- writeTemplate(accidental, 'CardCallout', {
- kind: 'block',
- body: `export default {type: 'block', name: 'ZZZ accidental block', description: 'collision'};\n`,
- source:
- 'export default function Accidental() { return <span>Accidental block</span>; }\n',
- });
- fs.writeFileSync(
- path.join(tmpDir, 'astryx.config.mjs'),
- `export default { integrations: ['@acme/widgets', '@acme/extra'] };\n`,
- );
-
- const result = await layoutExpand('C{card-callout}', {
- name: 'ReplacementLayout',
- cwd: tmpDir,
- });
-
- expect(result.data.code).toContain('Acme replacement block');
- expect(result.data.code).not.toContain('Accidental block');
- expect(result.data.blocksReferenced).toEqual(
- expect.arrayContaining([
- expect.objectContaining({name: 'CardCallout', mode: 'splice'}),
- ]),
- );
- }, 30_000);
-
- it('resolves chained block aliases consistently in template and layout', async () => {
- const [firstTarget, secondTarget] = (await discoverCoreTemplates()).filter(
- candidate => candidate.type === 'block',
- );
- expect(firstTarget).toBeDefined();
- expect(secondTarget).toBeDefined();
-
- const pkgDir = installWidgets(tmpDir);
- writeTemplate(pkgDir, secondTarget.dirName, {
- kind: 'block',
- source:
- 'export default function FirstReplacement() { return <span>First chain replacement</span>; }\n',
- });
- writeTemplate(pkgDir, 'acme-final-block', {
- kind: 'block',
- source:
- 'export default function FinalReplacement() { return <span>Final chain replacement</span>; }\n',
- });
- declareReplaces(pkgDir, {
- [secondTarget.dirName]: firstTarget.dirName,
- 'acme-final-block': secondTarget.dirName,
- });
-
- const firstTemplate = await template(firstTarget.dirName, {
- show: true,
- cwd: tmpDir,
- });
- expect(firstTemplate.data.source).toContain('First chain replacement');
- const layoutId = id =>
- id.replace(/([a-z0-9])([A-Z])/gu, '$1-$2').toLowerCase();
- const firstLayout = await layoutExpand(
- `C{${layoutId(firstTarget.dirName)}}`,
- {
- cwd: tmpDir,
- },
- );
- expect(firstLayout.data.code).toContain('First chain replacement');
- expect(firstLayout.data.code).not.toContain('Final chain replacement');
-
- const secondTemplate = await template(secondTarget.dirName, {
- show: true,
- cwd: tmpDir,
- });
- expect(secondTemplate.data.source).toContain('Final chain replacement');
- const secondLayout = await layoutExpand(
- `C{${layoutId(secondTarget.dirName)}}`,
- {
- cwd: tmpDir,
- },
- );
- expect(secondLayout.data.code).toContain('Final chain replacement');
- }, 30_000);
-
it('keeps the old discovery behavior when no replacement is declared', async () => {
const pkgDir = installWidgets(tmpDir);
writeTemplate(pkgDir, 'acme-app-shell', {kind: 'page'});
@@ -1334,4 +1234,41 @@ describe('build names a start its command selects', () => {
template('contact-form', {show: true, cwd: tmpDir}),
).rejects.toMatchObject({code: 'ERR_AMBIGUOUS_TEMPLATE'});
});
+
+ it('resolves chained template aliases without the layout command', async () => {
+ const [firstTarget, secondTarget] = (await discoverCoreTemplates()).filter(
+ candidate => candidate.type === 'block',
+ );
+ expect(firstTarget).toBeDefined();
+ expect(secondTarget).toBeDefined();
+
+ const pkgDir = installWidgets(tmpDir);
+ writeTemplate(pkgDir, secondTarget.dirName, {
+ kind: 'block',
+ source:
+ 'export default function FirstReplacement() { return <span>First chain replacement</span>; }\n',
+ });
+ writeTemplate(pkgDir, 'acme-final-block', {
+ kind: 'block',
+ source:
+ 'export default function FinalReplacement() { return <span>Final chain replacement</span>; }\n',
+ });
+ declareReplaces(pkgDir, {
+ [secondTarget.dirName]: firstTarget.dirName,
+ 'acme-final-block': secondTarget.dirName,
+ });
+
+ const firstTemplate = await template(firstTarget.dirName, {
+ show: true,
+ cwd: tmpDir,
+ });
+ expect(firstTemplate.data.source).toContain('First chain replacement');
+
+ const secondTemplate = await template(secondTarget.dirName, {
+ show: true,
+ cwd: tmpDir,
+ });
+ expect(secondTemplate.data.source).toContain('Final chain replacement');
+ }, 30_000);
+
});
diff --git a/packages/cli/clients/cli/command-result-coverage.test.mjs b/packages/cli/clients/cli/command-result-coverage.test.mjs
index dbd8479a73..ab457839e4 100644
--- a/packages/cli/clients/cli/command-result-coverage.test.mjs
+++ b/packages/cli/clients/cli/command-result-coverage.test.mjs
@@ -39,7 +39,7 @@ import {reportsResult, reportsResultVia} from './lib/define-command.mjs';
* other. Its bare form prints help and never returns from that action, which
* the recorder covers where help is recorded, not here.)
*/
-const NO_ACTION_OF_THEIR_OWN = ['layout'];
+const NO_ACTION_OF_THEIR_OWN = [];
/**
* Commands that record for themselves instead of returning a descriptor.
diff --git a/packages/cli/clients/cli/commands/debug-result-summary.test.mjs b/packages/cli/clients/cli/commands/debug-result-summary.test.mjs
index 5ffe768b09..660923e9c6 100644
--- a/packages/cli/clients/cli/commands/debug-result-summary.test.mjs
+++ b/packages/cli/clients/cli/commands/debug-result-summary.test.mjs
@@ -176,22 +176,6 @@ describe('DebugEvent result summary', () => {
SLOW,
);
- it(
- 'says so explicitly when a command has no result set',
- async () => {
- // `layout check` returns a verdict on one expression: nothing was looked
- // up, and the run says that rather than leaving four ambiguous nulls.
- const {event} = await runWithDebug(['layout', 'check', 'VStack>Text']);
- expect(event.output).toMatchObject({
- resultKind: 'none',
- resultCount: null,
- emptyResult: null,
- directMatch: null,
- });
- },
- SLOW,
- );
-
it(
'only claims a direct match when the filter resolved one component',
async () => {
diff --git a/packages/cli/clients/cli/commands/layout-check.doc.mjs b/packages/cli/clients/cli/commands/layout-check.doc.mjs
deleted file mode 100644
index d0efbd34d2..0000000000
--- a/packages/cli/clients/cli/commands/layout-check.doc.mjs
+++ /dev/null
@@ -1,67 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * @file CommandDoc for `astryx layout check`. The terminal binding of the
- * `layoutCheck()` function (referenced via `fn`); its args/flags map to that
- * function's params so a converter can build Commander config + --help from one
- * source of truth.
- * @position packages/cli/clients/cli/commands — command documentation
- */
-
-/** @type {import('@astryxdesign/cli/authoring').CommandDoc} */
-export const doc = {
- type: 'command',
- name: 'layout check',
- displayName: 'astryx layout check',
- namespace: 'cli/commands',
- summary:
- 'Validate a layout expression and echo canonical compact/outline forms',
- description:
- 'Parses and validates a compressed XLE/XLO expression without generating any TSX, and ' +
- 'echoes it back in both canonical surfaces (compact and outline). An invalid but ' +
- 'parseable expression is reported with line/col and suggestions, and exits non-zero.',
- fn: 'layoutCheck',
- args: [
- {
- name: 'expression',
- param: 'expression',
- required: false,
- description:
- 'The XLE/XLO expression. Pass - to read it from stdin; --file reads it from a file instead.',
- },
- ],
- options: [
- {
- flag: '--file <file>',
- description: 'Read the expression from a file (used instead of the argument when both are given)',
- },
- {
- flag: '--form <form>',
- param: 'options.form',
- choices: ['compact', 'outline', 'auto'],
- default: 'auto',
- description: 'Input surface: compact, outline, or auto',
- },
- {
- flag: '--loose',
- param: 'options.loose',
- description: 'Downgrade unknown {block} hints to TODO placeholders',
- },
- ],
- examples: [
- {
- label: 'Validate an expression',
- cli: "astryx layout check 'A[cp6] > L > LC > S[p6]' --json",
- },
- ],
- exitCodes: [
- {code: 0, when: 'the expression is valid'},
- {
- code: 1,
- when: 'the expression is invalid, empty or over 5 MB (from stdin or --file), has a syntax error, or a bad --form',
- },
- ],
- deprecated: 'DEP-0006: Use `astryx build` to start from a template, `astryx template` to scaffold, and `astryx docs layout` for guidance.',
- notes: [{"type": "prose", "text": "**Deprecated (DEP-0006).** Use `astryx build` to choose the template to start from, `astryx template` to scaffold it, and `astryx docs layout` for layout guidance. This command will be removed in a future minor release."}],
- related: ['layout expand', 'layout grammar'],
-};
diff --git a/packages/cli/clients/cli/commands/layout-expand.doc.mjs b/packages/cli/clients/cli/commands/layout-expand.doc.mjs
deleted file mode 100644
index 3a29e66147..0000000000
--- a/packages/cli/clients/cli/commands/layout-expand.doc.mjs
+++ /dev/null
@@ -1,87 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * @file CommandDoc for `astryx layout expand`. The terminal binding of the
- * `layoutExpand()` function (referenced via `fn`); its args/flags map to that
- * function's params so a converter can build Commander config + --help from one
- * source of truth.
- * @position packages/cli/clients/cli/commands — command documentation
- */
-
-/** @type {import('@astryxdesign/cli/authoring').CommandDoc} */
-export const doc = {
- type: 'command',
- name: 'layout expand',
- displayName: 'astryx layout expand',
- namespace: 'cli/commands',
- summary: 'Expand a layout expression into validated XDS TSX',
- description:
- 'Parses and validates a compressed XLE/XLO expression, then expands it into ' +
- 'ready-to-use XDS TSX, routing children into slots, scaffolding typed useState for ' +
- 'interactive controls, and splicing referenced blocks. Writes to a path, or returns the code. ' +
- 'Astryx demo media in a spliced block becomes a placeholder, and the output says how many ' +
- 'references were replaced (as a closing line comment when it prints the code).',
- fn: 'layoutExpand',
- args: [
- {
- name: 'expression',
- param: 'expression',
- required: false,
- description:
- 'The XLE/XLO expression. Pass - to read it from stdin; --file reads it from a file instead.',
- },
- {
- name: 'path',
- param: 'options.targetPath',
- required: false,
- description:
- 'Where to write the TSX, relative to the project root. A path that ends in .tsx, .ts, .jsx, .js, .mjs, .cjs, .css, .scss, .json, .md or .html is the file to write; ' +
- 'any other path is a directory, which receives <Name>.tsx (see --name). An existing file there is replaced. ' +
- 'Omit it to print the code.',
- },
- ],
- options: [
- {
- flag: '--file <file>',
- description: 'Read the expression from a file (used instead of the argument when both are given)',
- },
- {
- flag: '--form <form>',
- param: 'options.form',
- choices: ['compact', 'outline', 'auto'],
- default: 'auto',
- description: 'Input surface: compact, outline, or auto',
- },
- {
- flag: '--name <name>',
- param: 'options.name',
- default: 'GeneratedLayout',
- description: 'Generated component name (PascalCase)',
- },
- {
- flag: '--loose',
- param: 'options.loose',
- description: 'Downgrade unknown {block} hints to TODO placeholders',
- },
- ],
- examples: [
- {
- label: 'Expand to a file',
- cli: "astryx layout expand 'V[g6] > C{card-callout}*4' ./src/Page.tsx",
- },
- {
- label: 'From a file, named',
- cli: 'astryx layout expand --file layout.xlo --name Dashboard',
- },
- ],
- exitCodes: [
- {code: 0, when: 'success'},
- {
- code: 1,
- when: 'a missing, empty or over-5 MB expression (from stdin or --file), a bad --name or --form, a parse/validation error, or a path escape',
- },
- ],
- deprecated: 'DEP-0006: Use `astryx build` to start from a template, `astryx template` to scaffold, and `astryx docs layout` for guidance.',
- notes: [{"type": "prose", "text": "**Deprecated (DEP-0006).** Use `astryx build` to choose the template to start from, `astryx template` to scaffold it, and `astryx docs layout` for layout guidance. This command will be removed in a future minor release."}],
- related: ['layout check', 'layout grammar'],
-};
diff --git a/packages/cli/clients/cli/commands/layout-grammar.doc.mjs b/packages/cli/clients/cli/commands/layout-grammar.doc.mjs
deleted file mode 100644
index 89c8ec55e9..0000000000
--- a/packages/cli/clients/cli/commands/layout-grammar.doc.mjs
+++ /dev/null
@@ -1,32 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * @file CommandDoc for `astryx layout grammar`. The terminal binding of the
- * `layoutGrammar()` function (referenced via `fn`); it carries only CLI-surface
- * facts so a converter can build Commander config + --help from one source of
- * truth.
- * @position packages/cli/clients/cli/commands — command documentation
- */
-
-/** @type {import('@astryxdesign/cli/authoring').CommandDoc} */
-export const doc = {
- type: 'command',
- name: 'layout grammar',
- displayName: 'astryx layout grammar',
- namespace: 'cli/commands',
- summary:
- 'Print the XLE/XLO cheatsheet (alias table generated from this branch)',
- description:
- 'Prints the XLE/XLO grammar cheatsheet for writing layout expressions, with the alias ' +
- "table generated from this install's registry so short names always reflect the " +
- 'components actually available.',
- fn: 'layoutGrammar',
- examples: [{label: 'Get the cheatsheet', cli: 'astryx layout grammar'}],
- exitCodes: [
- {code: 0, when: 'success'},
- {code: 1, when: 'the component registry cannot be read'},
- ],
- deprecated: 'DEP-0006: Use `astryx build` to start from a template, `astryx template` to scaffold, and `astryx docs layout` for guidance.',
- notes: [{"type": "prose", "text": "**Deprecated (DEP-0006).** Use `astryx build` to choose the template to start from, `astryx template` to scaffold it, and `astryx docs layout` for layout guidance. This command will be removed in a future minor release."}],
- related: ['layout expand', 'layout check'],
-};
diff --git a/packages/cli/clients/cli/commands/layout.deprecation-lifecycle.test.mjs b/packages/cli/clients/cli/commands/layout.deprecation-lifecycle.test.mjs
deleted file mode 100644
index 8c250116f1..0000000000
--- a/packages/cli/clients/cli/commands/layout.deprecation-lifecycle.test.mjs
+++ /dev/null
@@ -1,140 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * @file Deprecation lifecycle coverage for the layout command group (DEP-0006).
- *
- * Mirrors the DEP-0005 theme-add-lifecycle tests: pins the JSON
- * `meta.deprecations` entry, the human-mode stderr warning, the help label,
- * and the docs reference pages.
- */
-
-import {describe, it, expect} from 'vitest';
-import {runCli} from '../../../test-utils/run-cli.mjs';
-
-const SLOW = 30_000;
-
-describe('layout DEP-0006 lifecycle', () => {
- it('JSON mode carries meta.deprecations with DEP-0006 and its replacements', async () => {
- const result = await runCli(['layout', 'grammar', '--json']);
- expect(result.status).toBe(0);
- const envelope = JSON.parse(result.stdout);
- expect(envelope.meta).toBeDefined();
- expect(envelope.meta.deprecations).toEqual([
- {
- id: 'DEP-0006',
- replacements: ['build', 'template', 'docs layout'],
- },
- ]);
- // Canonical data is unchanged
- expect(envelope.type).toBe('layout.grammar');
- expect(envelope.data.text).toBeDefined();
- expect(envelope.data.aliases).toBeDefined();
- }, SLOW);
-
- it('human mode emits one stderr deprecation warning', async () => {
- const result = await runCli(['layout', 'grammar']);
- expect(result.status).toBe(0);
- expect(result.stderr).toContain('[DEP-0006]');
- expect(result.stderr).toContain('astryx layout is deprecated');
- expect(result.stderr).toContain('astryx build');
- expect(result.stderr).toContain('astryx template');
- expect(result.stderr).toContain('astryx docs layout');
- }, SLOW);
-
- it('JSON mode does NOT emit the stderr warning', async () => {
- const result = await runCli(['layout', 'grammar', '--json']);
- expect(result.stderr).not.toContain('[DEP-0006]');
- }, SLOW);
-
- it('layout --help labels the command as deprecated', async () => {
- const result = await runCli(['layout', '--help']);
- expect(result.stdout).toContain('DEPRECATED');
- expect(result.stdout).toContain('DEP-0006');
- });
-
- it('layout expand --json carries the same meta.deprecations', async () => {
- const result = await runCli([
- 'layout', 'expand', 'V[g6] > C*2', '--json',
- ]);
- expect(result.status).toBe(0);
- const envelope = JSON.parse(result.stdout);
- expect(envelope.meta.deprecations).toEqual([
- {
- id: 'DEP-0006',
- replacements: ['build', 'template', 'docs layout'],
- },
- ]);
- expect(envelope.type).toBe('layout.expand');
- }, SLOW);
-
- it('layout check --json carries the same meta.deprecations', async () => {
- const result = await runCli([
- 'layout', 'check', 'V[g6] > C*2', '--json',
- ]);
- expect(result.status).toBe(0);
- const envelope = JSON.parse(result.stdout);
- expect(envelope.meta.deprecations).toEqual([
- {
- id: 'DEP-0006',
- replacements: ['build', 'template', 'docs layout'],
- },
- ]);
- expect(envelope.type).toBe('layout.check');
- }, SLOW);
-
- // FR29d: every reference page names DEP-0006 and the replacements.
- // Removing the label from any single page must fail this test.
- describe('docs reference pages name DEP-0006', () => {
- const COMMAND_PAGES = [
- 'cli/commands/layout',
- 'cli/commands/layout-expand',
- 'cli/commands/layout-check',
- 'cli/commands/layout-grammar',
- ];
-
- const FUNCTION_PAGES = [
- 'cli/api/functions/layout-expand',
- 'cli/api/functions/layout-check',
- 'cli/api/functions/layout-grammar',
- ];
-
- for (const page of COMMAND_PAGES) {
- it(`${page} names DEP-0006 and replacements`, async () => {
- const result = await runCli(['docs', page, '--json']);
- expect(result.status, result.stderr).toBe(0);
- const body = result.stdout;
- expect(body).toContain('DEP-0006');
- expect(body).toContain('build');
- expect(body).toContain('template');
- expect(body).toContain('docs layout');
- }, SLOW);
- }
-
- for (const page of FUNCTION_PAGES) {
- it(`${page} names DEP-0006 and replacements`, async () => {
- const result = await runCli(['docs', page, '--json']);
- expect(result.status, result.stderr).toBe(0);
- const body = result.stdout;
- expect(body).toContain('DEP-0006');
- expect(body).toContain('build');
- expect(body).toContain('template');
- expect(body).toContain('docs layout');
- }, SLOW);
- }
- });
-
- it('response-types reference names DEP-0006 in each layout entry description', async () => {
- const result = await runCli(['docs', 'cli/api/enums/response-types', '--json']);
- expect(result.status, result.stderr).toBe(0);
- const envelope = JSON.parse(result.stdout);
- // The enum page has a table in its content; each row is [value, description].
- const tables = envelope.data.content.filter(b => b.type === 'table');
- const rows = tables.flatMap(t => t.rows || []);
- for (const type of ['layout.expand', 'layout.check', 'layout.grammar']) {
- const row = rows.find(r => r[0] && r[0].includes(type));
- expect(row, `${type} not found in response-types table`).toBeDefined();
- expect(row[1], `${type} description missing DEP-0006`).toContain('DEP-0006');
- expect(row[1], `${type} description missing replacements`).toContain('replacement');
- }
- }, SLOW);
-});
diff --git a/packages/cli/clients/cli/commands/layout.doc.mjs b/packages/cli/clients/cli/commands/layout.doc.mjs
deleted file mode 100644
index 62256cd6f4..0000000000
--- a/packages/cli/clients/cli/commands/layout.doc.mjs
+++ /dev/null
@@ -1,36 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * @file CommandDoc for the `astryx layout` command group. A parent group with no
- * behavior of its own; it dispatches to the expand/check/grammar subcommands,
- * which carry the actual args, flags, and wrapped functions.
- * @position packages/cli/clients/cli/commands — command documentation
- */
-
-/** @type {import('@astryxdesign/cli/authoring').CommandDoc} */
-export const doc = {
- type: 'command',
- name: 'layout',
- displayName: 'astryx layout',
- namespace: 'cli/commands',
- summary: 'Generate XDS layouts from compressed expressions (XLE/XLO)',
- description:
- 'The layout command group. Running astryx layout with no subcommand prints the ' +
- 'subcommand list; the work happens in the subcommands: expand an expression into ' +
- 'TSX (expand), validate one (check), or print the grammar cheatsheet (grammar).',
- subcommands: ['expand', 'check', 'grammar'],
- examples: [
- {label: 'Print the grammar', cli: 'astryx layout grammar'},
- {
- label: 'Expand to TSX',
- cli: "astryx layout expand 'V[g6] > C{card-callout}*4' ./src/Page.tsx",
- },
- ],
- exitCodes: [
- {code: 0, when: 'a subcommand succeeded, or --help'},
- {code: 1, when: 'no subcommand (help is printed) or an unknown subcommand'},
- ],
- deprecated: 'DEP-0006: Use `astryx build` to start from a template, `astryx template` to scaffold, and `astryx docs layout` for guidance.',
- notes: [{"type": "prose", "text": "**Deprecated (DEP-0006).** Use `astryx build` to choose the template to start from, `astryx template` to scaffold it, and `astryx docs layout` for layout guidance. This command will be removed in a future minor release."}],
- related: ['template', 'build'],
-};
diff --git a/packages/cli/clients/cli/commands/layout.error-codes.test.mjs b/packages/cli/clients/cli/commands/layout.error-codes.test.mjs
deleted file mode 100644
index bcc9c45c20..0000000000
--- a/packages/cli/clients/cli/commands/layout.error-codes.test.mjs
+++ /dev/null
@@ -1,66 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * @file Error-code contract tests for the layout command wrapper. Locks the
- * two foreseeable input errors to STABLE ERR_* codes (never ERR_UNKNOWN or a
- * raw fs errno) and asserts --json/human exit parity:
- * - empty expression → ERR_MISSING_ARGUMENT
- * - --file <missing> → ERR_FILE_NOT_FOUND (not raw ENOENT), no stack leak
- * Spawns the real binary so the bin error boundary is exercised faithfully.
- */
-
-import {describe, it, expect} from 'vitest';
-import {spawnSync} from 'node:child_process';
-import * as path from 'node:path';
-import {fileURLToPath} from 'node:url';
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url));
-const CLI_BIN = path.resolve(__dirname, '../bin/astryx.mjs');
-
-function run(args) {
- const res = spawnSync('node', [CLI_BIN, ...args], {
- encoding: 'utf-8',
- timeout: 20_000,
- });
- return {status: res.status, stdout: res.stdout || '', stderr: res.stderr || ''};
-}
-
-describe('layout --json error codes', () => {
- for (const sub of ['expand', 'check']) {
- it(`layout ${sub} "" → ERR_MISSING_ARGUMENT (not ERR_UNKNOWN)`, () => {
- const r = run(['--json', 'layout', sub, '']);
- expect(r.status).toBe(1);
- const env = JSON.parse(r.stdout);
- expect(env.code).toBe('ERR_MISSING_ARGUMENT');
- expect(r.stderr).toBe('');
- expect(r.stdout).not.toMatch(/\n\s+at /); // no stack frames
- });
-
- it(`layout ${sub} --file <missing> → ERR_FILE_NOT_FOUND (not ENOENT)`, () => {
- const r = run([
- '--json',
- 'layout',
- sub,
- '--file',
- '/tmp/definitely-missing-astryx-xyz.mjs',
- ]);
- expect(r.status).toBe(1);
- const env = JSON.parse(r.stdout);
- expect(env.code).toBe('ERR_FILE_NOT_FOUND');
- expect(r.stderr).toBe('');
- });
-
- it(`layout ${sub}: --json and human agree on exit code (empty input)`, () => {
- const human = run(['layout', sub, '']);
- const json = run(['--json', 'layout', sub, '']);
- expect(json.status).toBe(human.status);
- expect(json.status).toBe(1);
- });
-
- it(`layout ${sub} --file <missing> in human mode leaks no stack trace`, () => {
- const r = run(['layout', sub, '--file', '/tmp/definitely-missing-astryx-xyz.mjs']);
- expect(r.status).toBe(1);
- expect(r.stderr).not.toMatch(/\n\s+at /);
- });
- }
-});
diff --git a/packages/cli/clients/cli/commands/layout.exit-parity.test.mjs b/packages/cli/clients/cli/commands/layout.exit-parity.test.mjs
deleted file mode 100644
index 767bf14cae..0000000000
--- a/packages/cli/clients/cli/commands/layout.exit-parity.test.mjs
+++ /dev/null
@@ -1,41 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * @file CLI-level tests for `astryx layout check` exit-code parity.
- *
- * The exit code is the contract and must NOT depend on --json vs human mode:
- * an invalid (but parseable) layout exits 1 in BOTH modes so `layout check`
- * works as a CI gate / agent check without parsing stdout. Runs the real
- * program in-process via the shared runCli harness.
- */
-
-import {describe, it, expect} from 'vitest';
-import {runCli} from '../../../test-utils/run-cli.mjs';
-
-const SLOW = 30_000;
-// Parses fine, but references an unknown component -> data.valid: false
-// (a semantic error, surfaced as data, not a thrown ERR_LAYOUT_PARSE).
-const INVALID = 'ZzzUnknownComponent[foo=bar]';
-const VALID = 'K';
-
-describe('layout check — exit-code parity (--json vs human)', () => {
- it('human mode exits 1 for an invalid (parseable) expression', async () => {
- const {status} = await runCli(['layout', 'check', INVALID]);
- expect(status).toBe(1);
- }, SLOW);
-
- it('--json exits 1 for the SAME invalid expression (modes agree)', async () => {
- const {status, stdout} = await runCli(['layout', 'check', INVALID, '--json']);
- const env = JSON.parse(stdout);
- expect(env.type).toBe('layout.check');
- expect(env.data.valid).toBe(false);
- expect(status).toBe(1);
- }, SLOW);
-
- it('a valid expression exits 0 in both modes', async () => {
- expect((await runCli(['layout', 'check', VALID])).status).toBe(0);
- const {status, stdout} = await runCli(['layout', 'check', VALID, '--json']);
- expect(JSON.parse(stdout).data.valid).toBe(true);
- expect(status).toBe(0);
- }, SLOW);
-});
diff --git a/packages/cli/clients/cli/commands/layout.expand-receipt.test.mjs b/packages/cli/clients/cli/commands/layout.expand-receipt.test.mjs
deleted file mode 100644
index ca809866ef..0000000000
--- a/packages/cli/clients/cli/commands/layout.expand-receipt.test.mjs
+++ /dev/null
@@ -1,94 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * @file `astryx layout expand` tells the caller, in JSON and in text, when demo
- * media in a spliced template block was replaced with placeholders. Printed
- * code stays verbatim and valid TSX: the disclosure follows it as a comment.
- */
-
-import {describe, it, expect, beforeEach, afterEach} from 'vitest';
-import * as fs from 'node:fs';
-import * as path from 'node:path';
-import ts from 'typescript';
-import {runCli} from '../../../test-utils/run-cli.mjs';
-import {discoverTemplates} from '../../../api/template/template.mjs';
-
-const SLOW = 60_000;
-const DISCLOSURE = /demo media/i;
-
-/** @param {string} name */
-const hintKey = name => name.toLowerCase().replace(/[^a-z0-9]/g, '');
-
-/** @param {string} source */
-const tsxErrors = source =>
- /** @type {any} */ (
- ts.createSourceFile('out.tsx', source, ts.ScriptTarget.Latest, true, ts.ScriptKind.TSX)
- ).parseDiagnostics.map((/** @type {ts.Diagnostic} */ d) =>
- ts.flattenDiagnosticMessageText(d.messageText, ' '),
- );
-
-/** A `{hint}` for a template block whose source carries demo media. */
-async function mediaBlockHint() {
- const blocks = /** @type {Array<{dirName: string, type: string, filePath: string}>} */ (
- await discoverTemplates()
- ).filter(t => t.type === 'block' && t.filePath && fs.existsSync(t.filePath));
- const seen = new Map();
- for (const t of blocks) seen.set(hintKey(t.dirName), (seen.get(hintKey(t.dirName)) ?? 0) + 1);
- const found = blocks.find(
- t =>
- seen.get(hintKey(t.dirName)) === 1 &&
- /\/template-assets\/[\w.-]+\.\w+/.test(fs.readFileSync(t.filePath, 'utf-8')),
- );
- if (!found) throw new Error('no template block carries demo media');
- return hintKey(found.dirName);
-}
-
-describe('layout expand discloses replaced demo media', () => {
- let cwd;
- beforeEach(() => {
- // Inside the workspace so @astryxdesign/core resolves.
- cwd = fs.mkdtempSync(path.join(process.cwd(), '.xle-media-receipt-'));
- });
- afterEach(() => fs.rmSync(cwd, {recursive: true, force: true}));
-
- it('--json carries demoMediaReplaced; the text receipt states it for the written file', async () => {
- const expr = `V > {${await mediaBlockHint()}}`;
- const json = await runCli(['layout', 'expand', expr, './a', '--json'], cwd);
- expect(json.status).toBe(0);
- const {data} = JSON.parse(json.stdout);
- expect(data.demoMediaReplaced).toBeGreaterThan(0);
-
- const human = await runCli(['layout', 'expand', expr, './b'], cwd);
- expect(human.status).toBe(0);
- expect(human.stdout).toContain(
- `Replaced ${data.demoMediaReplaced} Astryx demo media reference`,
- );
- expect(human.stdout).toContain(path.join('b', 'GeneratedLayout.tsx'));
- }, SLOW);
-
- it('prints the code verbatim, then states the count in a comment that keeps it valid TSX', async () => {
- const expr = `V > {${await mediaBlockHint()}}`;
- const {data} = JSON.parse((await runCli(['layout', 'expand', expr, '--json'], cwd)).stdout);
-
- const human = await runCli(['layout', 'expand', expr], cwd);
- expect(human.status).toBe(0);
- expect(human.stdout.startsWith(data.code)).toBe(true);
- expect(human.stdout.slice(data.code.length).trim()).toMatch(
- new RegExp(`^// Replaced ${data.demoMediaReplaced} Astryx demo media references? in the code above: [^\\n]+$`),
- );
- expect(tsxErrors(human.stdout)).toEqual([]);
- }, SLOW);
-
- it('says nothing about demo media when none was replaced', async () => {
- const json = await runCli(['layout', 'expand', 'V > B"Save"', '--json'], cwd);
- const {data} = JSON.parse(json.stdout);
- expect(data.demoMediaReplaced).toBe(0);
-
- const written = await runCli(['layout', 'expand', 'V > B"Save"', './a'], cwd);
- expect(written.status).toBe(0);
- expect(written.stdout).not.toMatch(DISCLOSURE);
- const printed = await runCli(['layout', 'expand', 'V > B"Save"'], cwd);
- expect(printed.status).toBe(0);
- expect(printed.stdout).toBe(`${data.code}\n`);
- }, SLOW);
-});
diff --git a/packages/cli/clients/cli/commands/layout.mjs b/packages/cli/clients/cli/commands/layout.mjs
deleted file mode 100644
index ac82f1eebe..0000000000
--- a/packages/cli/clients/cli/commands/layout.mjs
+++ /dev/null
@@ -1,327 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * @file layout command — thin CLI wrapper around api/layout.mjs.
- *
- * Subcommands:
- * astryx layout expand "<expr>" [path] compressed expression → validated TSX
- * astryx layout check "<expr>" validate + echo both canonical surfaces
- * astryx layout grammar agent cheatsheet (alias table is branch-generated)
- *
- * The expression argument may also come from --file or stdin (`-`),
- * which is how multi-line outline (XLO) input usually arrives.
- *
- * The command surface (group + subcommand descriptions, args, flags) is sourced
- * from the colocated CommandDocs via `defineCommand`; this file supplies only the
- * actions.
- */
-
-import * as fs from 'node:fs';
-import * as path from 'node:path';
-import {jsonOut, isJsonMode} from '../../../foundation/response/json.mjs';
-import {emit, section, text, list, record, code, WARN} from '../formatters/index.mjs';
-import {cliError} from '../lib/cli-error.mjs';
-import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
-import {layoutExpand, layoutCheck, layoutGrammar} from '../../../api/layout/layout.mjs';
-import {defineCommand} from '../lib/define-command.mjs';
-import {doc as layoutGroup} from './layout.doc.mjs';
-import {doc as layoutExpandCommand} from './layout-expand.doc.mjs';
-import {doc as layoutCheckCommand} from './layout-check.doc.mjs';
-import {doc as layoutGrammarCommand} from './layout-grammar.doc.mjs';
-import {doc as layoutExpandFn} from '../../../api/layout/layoutExpand.doc.mjs';
-import {doc as layoutCheckFn} from '../../../api/layout/layoutCheck.doc.mjs';
-import {doc as layoutGrammarFn} from '../../../api/layout/layoutGrammar.doc.mjs';
-import {NO_RESULT_SET, resultSet} from '../../../foundation/debug/index.mjs';
-
-/**
- * The api layer's @returns for these functions widen the `type` discriminator
- * to `string`, so annotate the command-local result with the precise response
- * shapes from the colocated api/layout/layout.type.mjs so narrowing + jsonOut
- * typecheck.
- *
- * @typedef {import('../../../api/layout/layout.type.mjs').LayoutExpandResponse} LayoutExpandResponse
- * @typedef {import('../../../api/layout/layout.type.mjs').LayoutCheckResponse} LayoutCheckResponse
- * @typedef {import('../../../api/layout/layout.type.mjs').LayoutGrammarResponse} LayoutGrammarResponse
- */
-
-/**
- * @typedef {object} LayoutExpandOptions
- * @property {string} [file]
- * @property {'compact'|'outline'|'auto'} [form]
- * @property {string} [name]
- * @property {boolean} [loose]
- */
-
-/**
- * @typedef {object} LayoutCheckOptions
- * @property {string} [file]
- * @property {'compact'|'outline'|'auto'} [form]
- * @property {boolean} [loose]
- */
-
-/**
- * DEP-0006: the `astryx layout` command group is deprecated.
- *
- * Human mode: one stderr warning per invocation.
- * JSON mode: `meta.deprecations` array in the response envelope.
- */
-const LAYOUT_DEPRECATION = Object.freeze({
- id: 'DEP-0006',
- replacements: ['build', 'template', 'docs layout'],
-});
-
-function warnDeprecated() {
- if (!isJsonMode()) {
- console.error(
- '[DEP-0006] astryx layout is deprecated and will be removed in a future minor release.\n' +
- ' Use instead:\n' +
- ' astryx build "<idea>" choose the template to start from\n' +
- ' astryx template <name> scaffold it\n' +
- ' astryx docs layout layout guidance\n',
- );
- }
-}
-
-/**
- * Add deprecation metadata to a JSON response before output.
- * Canonical stdout (type, data) is unchanged; the metadata sits in `meta`.
- * @param {{type: string, data: unknown}} result
- * @returns {{type: string, data: unknown, meta: {deprecations: [typeof LAYOUT_DEPRECATION]}}}
- */
-function withDeprecation(result) {
- return {...result, meta: {deprecations: [LAYOUT_DEPRECATION]}};
-}
-
-/** The largest layout expression read from --file or stdin. */
-const MAX_EXPRESSION_BYTES = 5 * 1024 * 1024; // 5 MB
-
-/**
- * Resolve the expression from arg, --file, or stdin ('-').
- * @param {string} [expr]
- * @param {{file?: string}} [options]
- * @returns {Promise<string>}
- */
-async function readExpression(expr, options = {}) {
- if (options.file) {
- // Validate the file exists + is a regular file + is reasonably sized.
- // We intentionally do NOT confine the read path (the user running the CLI
- // controls --file; this is a read, not a write). The size cap prevents OOM
- // from infinite streams like /dev/zero.
- const filePath = path.resolve(process.cwd(), options.file);
- const stat = fs.statSync(filePath, {throwIfNoEntry: false});
- if (!stat || !stat.isFile()) {
- cliError(`File not found: ${options.file}`, {
- code: ERROR_CODES.ERR_FILE_NOT_FOUND,
- });
- }
- if (stat.size > MAX_EXPRESSION_BYTES) {
- cliError(
- `File "${options.file}" is too large (${(stat.size / 1024 / 1024).toFixed(1)} MB, max 5 MB)`,
- {code: ERROR_CODES.ERR_FILE_NOT_FOUND},
- );
- }
- try {
- return fs.readFileSync(filePath, 'utf-8');
- } catch (e) {
- const errno = /** @type {NodeJS.ErrnoException} */ (e);
- if (errno && errno.code === 'ENOENT') {
- // A --file pointing at a missing file is foreseeable — surface a
- // stable code, not the raw ENOENT errno (and no stack in human mode).
- cliError(`File not found: ${options.file}`, {
- code: ERROR_CODES.ERR_FILE_NOT_FOUND,
- });
- }
- throw e;
- }
- }
- if (expr === '-') {
- // Capped like --file: an endless stream must not be buffered whole.
- /** @type {Buffer[]} */
- const chunks = [];
- let size = 0;
- for await (const chunk of process.stdin) {
- size += /** @type {Buffer} */ (chunk).length;
- if (size > MAX_EXPRESSION_BYTES) {
- cliError('The layout expression on stdin is too large (max 5 MB)', {
- code: ERROR_CODES.ERR_INVALID_ARGUMENT,
- });
- }
- chunks.push(/** @type {Buffer} */ (chunk));
- }
- return Buffer.concat(chunks).toString('utf-8');
- }
- return expr ?? '';
-}
-
-/**
- * The disclosure for demo media replaced in spliced template blocks, or '' when
- * none was. After printed code it is a line comment, so piped output stays TSX.
- * @param {LayoutExpandResponse['data']} data
- * @returns {string}
- */
-function demoMediaNotice({demoMediaReplaced, written}) {
- if (demoMediaReplaced === 0) return '';
- const notice =
- `Replaced ${demoMediaReplaced} Astryx demo media reference${demoMediaReplaced === 1 ? '' : 's'} in ${written ?? 'the code above'}: ` +
- 'images now show a neutral placeholder and videos have an empty source. Supply your own media there.';
- return written ? notice : `// ${notice}`;
-}
-
-/**
- * @param {import('commander').Command} program
- */
-export function registerLayout(program) {
- const layoutCmd = defineCommand(program, layoutGroup);
-
- defineCommand(layoutCmd, layoutExpandCommand, {
- fn: layoutExpandFn,
- action: async (/** @type {string} */ expression, /** @type {string} */ targetPath, /** @type {LayoutExpandOptions} */ options) => {
- warnDeprecated();
- const json = program.opts().json || false;
- const source = await readExpression(expression, options);
- if (!source || source.trim() === '') {
- return cliError(
- 'No layout expression given — pass it as an argument, via --file, or on stdin',
- {code: ERROR_CODES.ERR_MISSING_ARGUMENT},
- );
- }
- /** @type {LayoutExpandResponse} */
- let result;
- try {
- result = /** @type {LayoutExpandResponse} */ (await layoutExpand(source, {
- targetPath,
- form: options.form,
- loose: options.loose || false,
- name: options.name,
- cwd: process.cwd(),
- }));
- } catch (e) {
- const err = /** @type {import('../../../api/error.mjs').AstryxError} */ (e);
- return cliError(err.message, {suggestions: err.suggestions || [], code: err.code});
- }
- // Expanding turns an expression into TSX — a transformation, not a
- // lookup. What it produced is in the output; there is no set to count.
- if (json) {
- jsonOut(withDeprecation(result));
- return NO_RESULT_SET;
- }
-
- /** @type {import('../formatters/index.mjs').Block[]} */
- const out = [];
- if (result.data.warnings.length > 0) {
- out.push(text(result.data.warnings.map(w => `${WARN} ${w}`).join('\n')));
- }
- if (result.data.written) {
- out.push(
- text(`[ok] Expanded to ${result.data.written}`),
- // Field names are the JSON keys; todos are summarised, not listed.
- record(
- {componentsUsed: result.data.componentsUsed, todos: result.data.todos},
- {
- format: {
- todos: (/** @type {string[]} */ todos) =>
- `${todos.length} (search for "TODO(xle)")`,
- },
- },
- ),
- );
- } else {
- // Raw expanded TSX (no target path) — preformatted, emitted verbatim.
- out.push(code(result.data.code));
- }
- const mediaNotice = demoMediaNotice(result.data);
- if (mediaNotice) out.push(text(mediaNotice));
- emit(...out);
- return NO_RESULT_SET;
- },
- });
-
- defineCommand(layoutCmd, layoutCheckCommand, {
- fn: layoutCheckFn,
- action: async (/** @type {string} */ expression, /** @type {LayoutCheckOptions} */ options) => {
- warnDeprecated();
- const json = program.opts().json || false;
- const source = await readExpression(expression, options);
- if (!source || source.trim() === '') {
- return cliError(
- 'No layout expression given — pass it as an argument, via --file, or on stdin',
- {code: ERROR_CODES.ERR_MISSING_ARGUMENT},
- );
- }
- /** @type {LayoutCheckResponse} */
- let result;
- try {
- result = /** @type {LayoutCheckResponse} */ (await layoutCheck(source, {
- form: options.form,
- loose: options.loose || false,
- cwd: process.cwd(),
- }));
- } catch (e) {
- const err = /** @type {import('../../../api/error.mjs').AstryxError} */ (e);
- return cliError(err.message, {suggestions: err.suggestions || [], code: err.code});
- }
- // Exit code is the contract and must NOT depend on --json vs human: an
- // invalid (but parseable) layout exits 1 in BOTH modes so `layout check`
- // works as a CI gate / agent check without parsing stdout. Decide it
- // before the JSON return (parity with doctor integration validate).
- if (!result.data.valid) process.exitCode = 1;
-
- // A verdict on one expression: valid or not, with the errors that made
- // it so. Nothing was looked up.
- if (json) {
- jsonOut(withDeprecation(result));
- return NO_RESULT_SET;
- }
-
- const {valid, form, errors, warnings, compact, outline} = result.data;
- if (!valid) {
- // Each error: the formatted issue, with a hanging "did you mean" line.
- const items = errors.map(e =>
- e.suggestions && e.suggestions.length > 0
- ? [e.formatted, `did you mean: ${e.suggestions.join(', ')}?`]
- : [e.formatted],
- );
- emit(
- text(`[fail] Invalid (${errors.length} error${errors.length === 1 ? '' : 's'}):`),
- list(items),
- );
- return NO_RESULT_SET;
- }
-
- /** @type {import('../formatters/index.mjs').Block[]} */
- const out = [text(`[ok] Valid (parsed as ${form})`)];
- if (warnings.length > 0) {
- out.push(text(warnings.map(w => `${WARN} ${w}`).join('\n')));
- }
- // The canonical compact/outline surfaces are preformatted — emit verbatim.
- out.push(section('compact'), code(compact), section('outline'), code(outline));
- emit(...out);
- return NO_RESULT_SET;
- },
- });
-
- defineCommand(layoutCmd, layoutGrammarCommand, {
- fn: layoutGrammarFn,
- action: async () => {
- warnDeprecated();
- const json = program.opts().json || false;
- /** @type {LayoutGrammarResponse} */
- let result;
- try {
- result = /** @type {LayoutGrammarResponse} */ (await layoutGrammar({cwd: process.cwd()}));
- } catch (e) {
- const err = /** @type {import('../../../api/error.mjs').AstryxError} */ (e);
- return cliError(err.message, {suggestions: err.suggestions || [], code: err.code});
- }
- // One document, the same one every time: the grammar cheatsheet.
- const answered = resultSet({count: 1, resultKind: 'doc'});
- if (json) {
- jsonOut(withDeprecation(result));
- return answered;
- }
- // The cheatsheet is a preformatted document — emit verbatim.
- emit(code(result.data.text));
- return answered;
- },
- });
-}
diff --git a/packages/cli/clients/cli/commands/layout.path-help.test.mjs b/packages/cli/clients/cli/commands/layout.path-help.test.mjs
deleted file mode 100644
index d0c782e8a7..0000000000
--- a/packages/cli/clients/cli/commands/layout.path-help.test.mjs
+++ /dev/null
@@ -1,33 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * @file `layout expand` and `layout check` document their input modes (the
- * argument, `-` for stdin, --file) and where `layout expand` writes.
- */
-
-import {describe, it, expect} from 'vitest';
-import {runCli} from '../../../test-utils/run-cli.mjs';
-import {isFilePathArg} from '../../../foundation/fs/path-safety.mjs';
-
-const SLOW = 30_000;
-
-describe('layout argument behavior is documented', () => {
- it('layout expand help covers stdin, --file precedence and the output path rule', async () => {
- const {status, stdout} = await runCli(['layout', 'expand', '--help']);
- expect(status).toBe(0);
- expect(stdout).toMatch(/Pass - to read it from stdin/);
- expect(stdout).toMatch(/instead of the argument/);
- expect(stdout).toContain('<Name>.tsx');
- expect(stdout).toMatch(/existing file there is replaced/);
- const exts = [...(stdout.match(/ends in ([.\w, ]+ or \.\w+)/)?.[1] ?? '').matchAll(/\.\w+/g)];
- expect(exts.length).toBeGreaterThan(0);
- for (const [ext] of exts) expect(isFilePathArg(`src/Page${ext}`)).toBe(true);
- }, SLOW);
-
- it('layout check help covers stdin and --file precedence', async () => {
- const {status, stdout} = await runCli(['layout', 'check', '--help']);
- expect(status).toBe(0);
- expect(stdout).toMatch(/Pass - to read it from stdin/);
- expect(stdout).toMatch(/instead of the argument/);
- }, SLOW);
-});
diff --git a/packages/cli/clients/cli/commands/layout.stdin-cap.test.mjs b/packages/cli/clients/cli/commands/layout.stdin-cap.test.mjs
deleted file mode 100644
index a432645659..0000000000
--- a/packages/cli/clients/cli/commands/layout.stdin-cap.test.mjs
+++ /dev/null
@@ -1,47 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * @file `layout check -` reads the expression from stdin under the same 5 MB
- * cap as --file, instead of buffering whatever the pipe delivers. Spawns the
- * real bin, since the in-process harness has no stdin.
- */
-
-import {describe, it, expect} from 'vitest';
-import {spawnSync} from 'node:child_process';
-import * as path from 'node:path';
-import {fileURLToPath} from 'node:url';
-
-const HERE = path.dirname(fileURLToPath(import.meta.url));
-const BIN = path.resolve(HERE, '../bin/astryx.mjs');
-// Run against the monorepo root so @astryxdesign/core is discoverable.
-const REPO = path.resolve(HERE, '../../../..');
-const SLOW = 60_000;
-
-/** @param {string} input @param {string[]} [extra] */
-function checkFromStdin(input, extra = []) {
- return spawnSync(process.execPath, [BIN, 'layout', 'check', '-', ...extra], {
- cwd: REPO,
- input,
- encoding: 'utf-8',
- maxBuffer: 16 * 1024 * 1024,
- });
-}
-
-describe('layout check - (stdin)', () => {
- it('refuses more than 5 MB with ERR_INVALID_ARGUMENT, in both modes', () => {
- // Valid once trimmed, so only the cap can reject it.
- const big = ' '.repeat(5 * 1024 * 1024 + 1) + 'V';
- const json = checkFromStdin(big, ['--json']);
- expect(json.status).toBe(1);
- expect(JSON.parse(json.stdout).code).toBe('ERR_INVALID_ARGUMENT');
- const human = checkFromStdin(big);
- expect(human.status).toBe(1);
- expect(human.stderr + human.stdout).toMatch(/too large/);
- }, SLOW);
-
- it('still reads a normal expression', () => {
- const r = checkFromStdin('V > B', ['--json']);
- expect(r.status).toBe(0);
- expect(JSON.parse(r.stdout).data.valid).toBe(true);
- }, SLOW);
-});
diff --git a/packages/cli/clients/cli/commands/layout.text-fields.test.mjs b/packages/cli/clients/cli/commands/layout.text-fields.test.mjs
deleted file mode 100644
index fb64a0feef..0000000000
--- a/packages/cli/clients/cli/commands/layout.text-fields.test.mjs
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
-/**
- * @file `layout expand` text output names its fields after the JSON keys, so
- * the two views stay greppable against each other.
- */
-
-import {describe, it, expect, beforeEach, afterEach} from 'vitest';
-import * as fs from 'node:fs';
-import * as path from 'node:path';
-import {runCli} from '../../../test-utils/run-cli.mjs';
-
-const SLOW = 60_000;
-
-describe('layout expand text fields mirror the JSON keys', () => {
- let cwd;
- beforeEach(() => {
- // Inside the workspace so @astryxdesign/core resolves.
- cwd = fs.mkdtempSync(path.join(process.cwd(), '.xle-text-fields-'));
- });
- afterEach(() => fs.rmSync(cwd, {recursive: true, force: true}));
-
- it('labels every record field with a key of the layout.expand data', async () => {
- const expr = 'V > B + {not-a-real-block}';
- const json = await runCli(['layout', 'expand', expr, './a', '--loose', '--json'], cwd);
- expect(json.status).toBe(0);
- const {data} = JSON.parse(json.stdout);
- expect(data.todos.length).toBeGreaterThan(0);
-
- const human = await runCli(['layout', 'expand', expr, './b', '--loose'], cwd);
- expect(human.status).toBe(0);
- const fields = human.stdout
- .split('\n')
- .map(line => /^([A-Za-z]+):\s/.exec(line)?.[1])
- .filter(Boolean);
- expect(fields).toEqual(['componentsUsed', 'todos']);
- for (const field of fields) expect(Object.keys(data)).toContain(field);
- }, SLOW);
-});
diff --git a/packages/cli/clients/cli/commands/text-json-parity.test.mjs b/packages/cli/clients/cli/commands/text-json-parity.test.mjs
index 560994bd69..ac73647826 100644
--- a/packages/cli/clients/cli/commands/text-json-parity.test.mjs
+++ b/packages/cli/clients/cli/commands/text-json-parity.test.mjs
@@ -394,23 +394,6 @@ const CASES = [
args: ['integration', 'pack', '--check'],
skipFieldChecks: true,
},
- // ── Layout command: remove these cases when the layout command is deleted ──
- {
- name: 'layout check',
- args: ['layout', 'check', 'Button'],
- skipFieldChecks: true,
- },
- {
- name: 'layout expand',
- args: ['layout', 'expand', 'Button'],
- skipFieldChecks: true,
- },
- {
- name: 'layout grammar',
- args: ['layout', 'grammar'],
- skipFieldChecks: true,
- },
- // ── End layout cases ──
{
name: 'manifest',
args: ['manifest'],
diff --git a/packages/cli/clients/cli/index.mjs b/packages/cli/clients/cli/index.mjs
index d0e8bb62d8..d23160456a 100644
--- a/packages/cli/clients/cli/index.mjs
+++ b/packages/cli/clients/cli/index.mjs
@@ -107,9 +107,6 @@ export const JSON_SUPPORTED = new Set([
'doctor integration templates',
'doctor integration components',
'doctor integration docs',
- 'layout expand',
- 'layout check',
- 'layout grammar',
]);
/**
@@ -268,7 +265,6 @@ const commands = [
{name: 'gap-report', path: './commands/gap-report.mjs', register: 'registerGapReport'},
// agent-docs folded into init — functions still importable from agent-docs.mjs
{name: 'template', path: './commands/template.mjs', register: 'registerTemplate'},
- {name: 'layout', path: './commands/layout.mjs', register: 'registerLayout'},
{name: 'upgrade', path: './commands/upgrade.mjs', register: 'registerUpgrade'},
{name: 'theme', path: './commands/build-theme.mjs', register: 'registerTheme'},
{name: 'integration', path: './commands/integration.mjs', register: 'registerIntegration'},
diff --git a/packages/cli/clients/cli/lib/exit-codes.test.mjs b/packages/cli/clients/cli/lib/exit-codes.test.mjs
index 87c46d6283..c2ec796256 100644
--- a/packages/cli/clients/cli/lib/exit-codes.test.mjs
+++ b/packages/cli/clients/cli/lib/exit-codes.test.mjs
@@ -70,13 +70,6 @@ describe('command exit codes', () => {
},
);
- it('bare `astryx layout` exits 1 in both modes, as documented', async () => {
- const doc = commandDocs.find((d) => d.name === 'layout');
- expect(doc.exitCodes.find((e) => e.code === 1)?.when).toMatch(/^no subcommand/);
- expect((await runCli(['layout'])).status).toBe(1);
- expect((await runCli(['layout', '--json'])).status).toBe(1);
- });
-
it('`astryx discover` with a blank query exits 1 only when packages are discovered', async () => {
const doc = commandDocs.find((d) => d.name === 'discover');
expect(doc.exitCodes.find((e) => e.code === 1)?.when).toMatch(/blank query when packages are discovered/);
diff --git a/packages/cli/clients/cli/lib/json-shim.test.mjs b/packages/cli/clients/cli/lib/json-shim.test.mjs
index 6c10336719..d92233f1d9 100644
--- a/packages/cli/clients/cli/lib/json-shim.test.mjs
+++ b/packages/cli/clients/cli/lib/json-shim.test.mjs
@@ -225,23 +225,6 @@ describe('--json shim: help shown for a failed invocation is an error envelope',
expect(parsed.error).toMatch(/bogus/);
});
- it('astryx layout --json (group, no subcommand) emits ERR_MISSING_ARGUMENT, exit 1', async () => {
- const {status, stdout, stderr} = await runCli(['layout', '--json']);
- expect(status).toBe(1);
- expect(stderr).toBe('');
- const parsed = parseJson(stdout);
- expect(parsed).not.toHaveProperty('type');
- expect(parsed.code).toBe('ERR_MISSING_ARGUMENT');
- expect(parsed.suggestions.map((s) => s.name)).toContain('layout expand');
- });
-
- it('astryx layout (no --json) still prints help to stderr, exit 1', async () => {
- const {status, stdout, stderr} = await runCli(['layout']);
- expect(status).toBe(1);
- expect(stdout).toBe('');
- expect(stderr).toMatch(/Usage: astryx layout/);
- });
-
it('the real binary emits the same envelope for help bogus --json', () => {
// One program per process, so the root's own outputHelp patch is used here.
const bin = fileURLToPath(new URL('../bin/astryx.mjs', import.meta.url));
@@ -282,11 +265,4 @@ describe('--json shim: help shown for a failed invocation is an error envelope',
expect(parsed.suggestions).toEqual([{name: 'late child', reason: 'available subcommand'}]);
});
- it('astryx help layout --json still emits the help envelope, exit 0', async () => {
- const {status, stdout} = await runCli(['help', 'layout', '--json']);
- expect(status).toBe(0);
- const parsed = parseJson(stdout);
- expect(parsed.type).toBe('help');
- expect(parsed.data.command).toBe('astryx layout');
- });
});
diff --git a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs b/packages/cli/foundation/doc-compiler/doc-loads.test.mjs
index 2f6354e78d..ff61a1698c 100644
--- a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs
+++ b/packages/cli/foundation/doc-compiler/doc-loads.test.mjs
@@ -202,18 +202,6 @@ const RUNNERS = {
'import ./integration.doc.mjs',
],
},
- 'clients/cli/commands/layout.mjs': {
- runs: SELF_DOCS,
- sites: [
- 'import ../../../api/layout/layoutCheck.doc.mjs',
- 'import ../../../api/layout/layoutExpand.doc.mjs',
- 'import ../../../api/layout/layoutGrammar.doc.mjs',
- 'import ./layout-check.doc.mjs',
- 'import ./layout-expand.doc.mjs',
- 'import ./layout-grammar.doc.mjs',
- 'import ./layout.doc.mjs',
- ],
- },
'clients/cli/commands/search.mjs': {
runs: SELF_DOCS,
sites: [
diff --git a/packages/cli/foundation/response/error-codes.doc.mjs b/packages/cli/foundation/response/error-codes.doc.mjs
index 1a180fb0ad..da31640431 100644
--- a/packages/cli/foundation/response/error-codes.doc.mjs
+++ b/packages/cli/foundation/response/error-codes.doc.mjs
@@ -36,7 +36,7 @@ export const doc = {
{
value: 'ERR_INVALID_OPTION',
description:
- 'An unknown option was passed, --json was given to a command without JSON output, or layout --form got a value other than compact, outline, or auto.',
+ 'An unknown option was passed, --json was given to a command without JSON output.',
},
{
value: 'ERR_INVALID_ARGUMENT',
diff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjs
index 5e8740c766..deb95eb533 100644
--- a/packages/cli/foundation/response/response-types.doc.mjs
+++ b/packages/cli/foundation/response/response-types.doc.mjs
@@ -350,21 +350,5 @@ export const doc = {
'validated (false when no integration manifest was found, so nothing was inspected), the integration identity, structural issues, and Core doc overlaps. Each finding includes `severity` (`info` | `error`) and `relationship` (`replaces` | `extends` | `accidental`).',
},
- // layout (XLE/XLO)
- {
- value: 'layout.expand',
- description:
- 'The expansion: parsed form, generated TSX code, componentsUsed, states (count of useState hooks scaffolded), todos, blocksReferenced (each {name, mode}), warnings, written (the output path, or null when nothing was written), and demoMediaReplaced (count of demo media placeholders). Carries `meta.deprecations` with DEP-0006 and its replacement commands.',
- },
- {
- value: 'layout.check',
- description:
- 'The validation result: a valid flag, the detected form, errors (each with line/col, message, formatted text, and suggestions), warnings, and the expression re-printed in both canonical surfaces (compact and outline). Carries `meta.deprecations` with DEP-0006 and its replacement commands.',
- },
- {
- value: 'layout.grammar',
- description:
- "The XLE/XLO grammar cheatsheet: a text field with the full reference plus an aliases map (short name → canonical component) generated from this install's registry. Carries `meta.deprecations` with DEP-0006 and its replacement commands.",
- },
],
};
diff --git a/packages/cli/foundation/response/response.doc.mjs b/packages/cli/foundation/response/response.doc.mjs
index 6a6e9c0c8e..aa1a61600f 100644
--- a/packages/cli/foundation/response/response.doc.mjs
+++ b/packages/cli/foundation/response/response.doc.mjs
@@ -166,7 +166,7 @@ export const doc = {
text:
'The process exit code is part of the contract too. Exit 0 means success, ' +
'and every error envelope exits 1. Some commands also exit 1 with a success ' +
- 'envelope when what they report failed: a failed check (layout check, doctor ' +
+ 'envelope when what they report failed: a failed check (doctor ' +
'and its integration subcommands, integration verify, theme build ' +
'--check), a gap report that was not delivered, an upgrade left incomplete, ' +
'or init agent docs refused for a path outside the project. Read the ' +
diff --git a/packages/cli/foundation/xle/browser.mjs b/packages/cli/foundation/xle/browser.mjs
index 3b4b50fa80..b870d1777c 100644
--- a/packages/cli/foundation/xle/browser.mjs
+++ b/packages/cli/foundation/xle/browser.mjs
@@ -45,7 +45,7 @@ function formatIssue(issue) {
/**
* Validate an expression and return both canonical surfaces — the browser
- * twin of `layout check`. Never throws on invalid input; returns the errors.
+ * browser twin of the XLE validator. Never throws on invalid input; returns the errors.
*
* @param {string} expression
* @param {import('./xle-ast').Registry | import('./browser').SerializedRegistry | object} registry - serialized or hydrated
@@ -85,7 +85,7 @@ export function checkExpression(expression, registry, opts = {}) {
}
/**
- * Validate + expand to TSX — the browser twin of `layout expand`.
+ * Validate + expand to TSX — the browser twin of the XLE expander.
* Returns either {code, ...} or {errors} (never writes files).
*
* @param {string} expression
diff --git a/packages/cli/foundation/xle/expand.mjs b/packages/cli/foundation/xle/expand.mjs
index 7df2b8a2a2..9935f016c0 100644
--- a/packages/cli/foundation/xle/expand.mjs
+++ b/packages/cli/foundation/xle/expand.mjs
@@ -751,7 +751,7 @@ export function expand(doc, registry, options = {}) {
: [];
const code = [
- `// Generated by \`astryx layout expand\` — this file is the artifact; edit freely.`,
+ `// Generated by the Astryx XLE expander — this file is the artifact; edit freely.`,
...importLines,
...blockSection,
'',
diff --git a/packages/cli/foundation/xle/print.mjs b/packages/cli/foundation/xle/print.mjs
index 7ad3242df1..1537a26283 100644
--- a/packages/cli/foundation/xle/print.mjs
+++ b/packages/cli/foundation/xle/print.mjs
@@ -3,7 +3,7 @@
/**
* @file XLE canonical printers — AST → compact (XLE) or outline (XLO) text.
*
- * Used by `astryx layout check --form …` so either party (agent or human)
+ * Used by the XLE validator so either party (agent or human)
* can request the other surface, and by round-trip conformance tests.
* Printing is best-effort canonical: spelling variants the lexer
* normalized are emitted in canonical form.
diff --git a/packages/cli/test/doc-routes.ids.json b/packages/cli/test/doc-routes.ids.json
index 20b7879769..4a82e0495c 100644
--- a/packages/cli/test/doc-routes.ids.json
+++ b/packages/cli/test/doc-routes.ids.json
@@ -969,13 +969,27 @@
"VStackBasic",
"VStackShowcase"
],
- "@astryxdesign/theme-butter/theme": ["butter"],
- "@astryxdesign/theme-chocolate/theme": ["chocolate"],
- "@astryxdesign/theme-gothic/theme": ["gothic"],
- "@astryxdesign/theme-matcha/theme": ["matcha"],
- "@astryxdesign/theme-neutral/theme": ["neutral"],
- "@astryxdesign/theme-stone/theme": ["stone"],
- "@astryxdesign/theme-y2k/theme": ["y2k"],
+ "@astryxdesign/theme-butter/theme": [
+ "butter"
+ ],
+ "@astryxdesign/theme-chocolate/theme": [
+ "chocolate"
+ ],
+ "@astryxdesign/theme-gothic/theme": [
+ "gothic"
+ ],
+ "@astryxdesign/theme-matcha/theme": [
+ "matcha"
+ ],
+ "@astryxdesign/theme-neutral/theme": [
+ "neutral"
+ ],
+ "@astryxdesign/theme-stone/theme": [
+ "stone"
+ ],
+ "@astryxdesign/theme-y2k/theme": [
+ "y2k"
+ ],
"@astryxdesign/cli/command": [
"blog",
"build",
@@ -995,10 +1009,6 @@
"integration add",
"integration pack",
"integration verify",
- "layout",
- "layout check",
- "layout expand",
- "layout grammar",
"manifest",
"search",
"swizzle",
@@ -1040,9 +1050,6 @@
"integrationPackCheck",
"integrationTemplateConflicts",
"isError",
- "layoutCheck",
- "layoutExpand",
- "layoutGrammar",
"listThemes",
"parseResponse",
"search",
@@ -1083,5 +1090,8 @@
"template-doc",
"theme-doc"
],
- "@astryxdesign/cli/enum": ["error-codes", "response-types"]
+ "@astryxdesign/cli/enum": [
+ "error-codes",
+ "response-types"
+ ]
}
diff --git a/packages/cli/test/doc-routes.json b/packages/cli/test/doc-routes.json
index 2f6278f5ba..19433f0bcf 100644
--- a/packages/cli/test/doc-routes.json
+++ b/packages/cli/test/doc-routes.json
@@ -4532,7 +4532,7 @@
"kind": "command",
"id": "@astryxdesign/cli/command",
"provider": "@astryxdesign/cli",
- "count": 38,
+ "count": 34,
"oldCliRoute": "astryx <id> --help",
"oldDocsiteUrl": null,
"placement": "namespace:cli/commands",
@@ -4545,7 +4545,7 @@
"kind": "function",
"id": "@astryxdesign/cli/function",
"provider": "@astryxdesign/cli",
- "count": 44,
+ "count": 41,
"oldCliRoute": null,
"oldDocsiteUrl": null,
"placement": "namespace:cli/api/functions",