An open source design system that's fully customizable and agent ready
TypeScript
Restore the `astryx layout` command removed before its deprecation (#6887)
Cindy Zhangebd939b66536
diff --git a/.changeset/cli-remove-layout-command.md b/.changeset/cli-remove-layout-command.mddeleted file mode 100644index d9a8f54745..0000000000--- a/.changeset/cli-remove-layout-command.md+++ /dev/null@@ -1,13 +0,0 @@-----'@astryxdesign/cli': minor------[breaking] Remove the `layout` command. `astryx layout expand`, `astryx layout check` and `astryx layout grammar` are gone, together with the `layoutExpand`, `layoutCheck` and `layoutGrammar` functions exported from `@astryxdesign/cli/api`, their `layout.expand`, `layout.check` and `layout.grammar` response types, and the command's docs. It was experimental and is not used.--There is no replacement and no codemod: a layout expression has no equivalent command to move to. Build the page from `astryx template <name>` and `astryx component <Name>` instead. The expression engine itself is unchanged and still public as `@astryxdesign/cli/xle` (`checkExpression`, `expandExpression`), so a caller that wants the expansion can keep it by calling that barrel with its own registry.--Two pieces of the surface deliberately stay. The `ERR_LAYOUT_PARSE` and `ERR_LAYOUT_INVALID` error codes remain registered, because a shipped code is never removed, and both still describe what the retained `@astryxdesign/cli/xle` engine reports.--The `experimental.xle.components` config key is still accepted, so existing configs keep loading, but **it has no effect**: its only reader was the deleted layout command. Delete it from `astryx.config.*`; the README and the config reference now say the same.--@josephfarinadiff --git a/.github/scripts/cli-api-types-verify.mjs b/.github/scripts/cli-api-types-verify.mjsindex 5c9a433634..4949281f2d 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,+ gapReport, upgrade, init, doctor, layoutExpand, layoutCheck, layoutGrammar,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, themeBuild, themeAdd, themeTemplate,+ doctor, layoutExpand, layoutCheck, layoutGrammar, themeBuild, themeAdd, themeTemplate,themeList, listThemes, validateIntegration, summarizeIssues, AstryxError, s];}void main;diff --git a/apps/docsite/src/content/blog/posts/the-astryx-cli.md b/apps/docsite/src/content/blog/posts/the-astryx-cli.mdindex 16509e7510..cda7e41b5b 100644--- a/apps/docsite/src/content/blog/posts/the-astryx-cli.md+++ b/apps/docsite/src/content/blog/posts/the-astryx-cli.md@@ -36,7 +36,7 @@ Here is the fun part. You do not really need any of it. Your agent will know it**Learn.** `astryx search` ranks results across components, hooks, docs, and templates at once. `astryx component` prints the props, examples, and source for a component. `astryx hook` does the same for hooks. `astryx docs` covers reference topics like tokens, color, type, motion, and our principles.-**Compose.** `astryx build` is going to be your best friend. Tell it what you are making. It points your agent at the closest template, the right blocks, and the components to fill the gaps. `astryx template` drops a page template straight into your project.+**Compose.** `astryx build` is going to be your best friend. Tell it what you are making. It points your agent at the closest template, the right blocks, and the components to fill the gaps. `astryx template` drops a page template straight into your project. `astryx layout` sketches a page's structure from a short expression before you fill it in.**Make it yours.** `astryx theme build` compiles a theme to production CSS and JS. `astryx swizzle` ejects a component's full source when you want to own it.diff --git a/docs/specs/AST-042-cli-command-admission/spec.md b/docs/specs/AST-042-cli-command-admission/spec.mdindex 66b41ae6b8..a67b1ade97 100644--- a/docs/specs/AST-042-cli-command-admission/spec.md+++ b/docs/specs/AST-042-cli-command-admission/spec.md@@ -140,12 +140,12 @@ restates FR4 and FR5 for contributors. It does not yet restate FR7, and CommandDhas no typed AST-053 eligibility field; projecting the rule there and adding therepository check are known enforcement gaps that land separately.-The CLI has 16 top-level commands. The command docs of 25 commands and+The CLI has 17 top-level commands. The command docs of 28 commands andsubcommands name the function they call. Known gaps, for which this record doesnot assign migrations:-- the component, discover, search, template, and theme handlers read project- state or files themselves (FR1);+- the component, discover, layout, search, template, and theme handlers read+ project state or files themselves (FR1);- the theme handler draws its target table from characters, and the docshandler renders authored headings and tables with its own code (FR3); bothare candidates for one shared block kind under FR3, not two commanddiff --git a/packages/cli/README.md b/packages/cli/README.mdindex 6f2303757b..a1b340b38a 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -90,6 +90,7 @@ Options:| `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) || `search` | Search components, hooks, docs, and templates in one ranked list || `swizzle` | Copy component source for customization || `template` | List, show, or scaffold page and block templates |@@ -478,6 +479,9 @@ Every response has a `type` discriminant. The full set is below (generated from| `integration.template-conflicts` | 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` | 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` | 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, and written (the output path, or null when nothing was written). |+| `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). |+| `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. |<!-- END GENERATED: response-types --><!-- Generated by scripts/generate-cli-readme.mjs from the response-types EnumDoc. Run `pnpm -F @astryxdesign/cli readme`. -->@@ -578,12 +582,12 @@ There is no factory: write a plain object. For editor autocomplete andtype-checking, annotate it with the `AstryxConfig` type exported from`@astryxdesign/cli/authoring`.-| Field | Type | Purpose |-| ----------------------------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------------ |-| `integrations` | `string[]` | Integration package names to load (see [Integrations](#integrations)). |-| `issuesUrl` | `string` | Where "report an issue" links point for your project. Defaults to the core issue tracker. |-| `hooks.postCodemod` | `PostCodemodHook[]` | Commands to run after `astryx upgrade` applies codemods (e.g. reinstall, rebuild, reformat). |-| `experimental.xle.components` | `Record<string, XleComponent>` | No effect. Its only reader was the removed `layout` command. Still accepted so existing configs keep loading; delete it. |+| Field | Type | Purpose |+| ----------------------------- | ------------------------------ | ----------------------------------------------------------------------------------------------- |+| `integrations` | `string[]` | Integration package names to load (see [Integrations](#integrations)). |+| `issuesUrl` | `string` | Where "report an issue" links point for your project. Defaults to the core issue tracker. |+| `hooks.postCodemod` | `PostCodemodHook[]` | Commands to run after `astryx upgrade` applies codemods (e.g. reinstall, rebuild, reformat). |+| `experimental.xle.components` | `Record<string, XleComponent>` | Register app-local components so layout (XLE) expressions can reference them by name. Unstable. |The config is validated against a strict schema when the CLI loads it, so anunknown field is a hard error rather than a silent no-op. `astryx doctor`diff --git a/packages/cli/api/index.mjs b/packages/cli/api/index.mjsindex b33d4839f2..f758a550bf 100644--- a/packages/cli/api/index.mjs+++ b/packages/cli/api/index.mjs@@ -44,6 +44,7 @@ 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,@@ -92,6 +93,7 @@ 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.tsindex fbcf04f397..2d36ad7302 100644--- a/packages/cli/api/json/index.ts+++ b/packages/cli/api/json/index.ts@@ -26,6 +26,7 @@ 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.mjsnew file mode 100644index 0000000000..42434cd9af--- /dev/null+++ b/packages/cli/api/layout/_adapter.mjs@@ -0,0 +1,148 @@+// 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.mjsnew file mode 100644index 0000000000..c69678446b--- /dev/null+++ b/packages/cli/api/layout/check/check.mjs@@ -0,0 +1,40 @@+// 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';++/**+ * `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.mjsnew file mode 100644index 0000000000..3363ed69aa--- /dev/null+++ b/packages/cli/api/layout/expand/expand.mjs@@ -0,0 +1,155 @@+// 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 {stripTemplateAssetRefs} 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.+ *+ * @param {import('../../../foundation/xle/xle-ast').XLEDoc} doc+ * @param {import('../_adapter.mjs').LayoutBlock[]} blocks+ * @returns {Map<string, import('../../../foundation/xle/xle-ast').BlockModule>}+ */+function buildBlockModules(doc, blocks) {+ const referenced = collectHintNames(doc);+ if (referenced.size === 0) return new Map();+ const byKey = new Map(blocks.map(b => [normKey(b.dirName), b]));+ /** @type {Map<string, import('../../../foundation/xle/xle-ast').BlockModule>} */+ const modules = new Map();+ 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)) {+ modules.set(name, /** @type {import('../../../foundation/xle/xle-ast').BlockModule} */ ({mode: 'splice', componentName: block.dirName, source: stripTemplateAssetRefs(fs.readFileSync(block.filePath, 'utf-8'))}));+ }+ }+ return modules;+}++/**+ * `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 blockModules = 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,+ },+ };+}diff --git a/packages/cli/api/layout/expand/expand.path-safety.test.mjs b/packages/cli/api/layout/expand/expand.path-safety.test.mjsnew file mode 100644index 0000000000..62d53f1ace--- /dev/null+++ b/packages/cli/api/layout/expand/expand.path-safety.test.mjs@@ -0,0 +1,53 @@+// 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/grammar/grammar.mjs b/packages/cli/api/layout/grammar/grammar.mjsnew file mode 100644index 0000000000..b7bc5f4cee--- /dev/null+++ b/packages/cli/api/layout/grammar/grammar.mjs@@ -0,0 +1,87 @@+// 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';++/**+ * `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.mjsnew file mode 100644index 0000000000..efcd135624--- /dev/null+++ b/packages/cli/api/layout/layout.mjs@@ -0,0 +1,17 @@+// 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.mjsnew file mode 100644index 0000000000..b3a5394ef6--- /dev/null+++ b/packages/cli/api/layout/layout.test.mjs@@ -0,0 +1,297 @@+// 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.mjsnew file mode 100644index 0000000000..5644026ec0--- /dev/null+++ b/packages/cli/api/layout/layout.type.mjs@@ -0,0 +1,103 @@+// 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+ */++/**+ * 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.mjsnew file mode 100644index 0000000000..c284854804--- /dev/null+++ b/packages/cli/api/layout/layoutCheck.doc.mjs@@ -0,0 +1,85 @@+// 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.',+ 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.mjsnew file mode 100644index 0000000000..806c9daf59--- /dev/null+++ b/packages/cli/api/layout/layoutExpand.doc.mjs@@ -0,0 +1,107 @@+// 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.',+ 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, and written (the relative output path, or null when nothing was written).',+ },+ ],+ 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.mjsnew file mode 100644index 0000000000..b68fe9d628--- /dev/null+++ b/packages/cli/api/layout/layoutGrammar.doc.mjs@@ -0,0 +1,57 @@+// 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.',+ 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.mjsindex 21ea8dcf08..7588e39802 100644--- a/packages/cli/api/template/template-integration.test.mjs+++ b/packages/cli/api/template/template-integration.test.mjs@@ -19,6 +19,7 @@ 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;@@ -517,7 +518,53 @@ describe('integration template discovery', () => {});});- it('resolves chained block aliases consistently in template', async () => {+ 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',);@@ -545,12 +592,29 @@ describe('integration template discovery', () => {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 () => {diff --git a/packages/cli/api/template/template.mjs b/packages/cli/api/template/template.mjsindex 71efe597ad..77afdef1c1 100644--- a/packages/cli/api/template/template.mjs+++ b/packages/cli/api/template/template.mjs@@ -8,7 +8,7 @@* the requested one, and routes to a leaf (list/show/skeleton/copy/cdn). The shared* discovery/IO + cross-command helpers live in `foundation/discovery/template-adapter.mjs` and are* RE-EXPORTED here so external import paths (`api/template/template.mjs`) —- * used by component, search, init, discover, Doctor integration, and+ * used by component, layout, search, init, discover, Doctor integration, and* lib/project — keep resolving unchanged.** @position api/template — the template dispatcher + barrel; leaves live underdiff --git a/packages/cli/api/upgrade/run/run.mjs b/packages/cli/api/upgrade/run/run.mjsindex d26bb6c385..12273ce6e8 100644--- a/packages/cli/api/upgrade/run/run.mjs+++ b/packages/cli/api/upgrade/run/run.mjs@@ -114,7 +114,7 @@ export async function run(options = {}, {cwd = process.cwd()} = {}) {// Resolve the source dir against the API's cwd (not process.cwd()) so a// programmatic caller in another directory scans the right tree. Confine it to// cwd: --apply rewrites files in place, so a `..`-escaping or out-of-tree- // absolute --path must be rejected (parity with template/theme/swizzle,+ // absolute --path must be rejected (parity with template/theme/swizzle/layout,// and this is the most destructive command). allowAbsolute permits an absolute// path that still resolves inside cwd.let path_;diff --git a/packages/cli/authoring/config/config.doc.mjs b/packages/cli/authoring/config/config.doc.mjsindex 1e916034bb..701a9606de 100644--- a/packages/cli/authoring/config/config.doc.mjs+++ b/packages/cli/authoring/config/config.doc.mjs@@ -77,7 +77,7 @@ export const doc = {name: 'experimental.xle.components',type: 'Record<string, XleComponent>',description:- 'No effect. Its only reader was the removed `layout` command. The key is still accepted so existing configs keep loading; delete it.',+ 'Custom components the layout expander (XLE) may emit, keyed by tag.',},],},diff --git a/packages/cli/authoring/config/type.ts b/packages/cli/authoring/config/type.tsindex efa8aa3759..0926d65ec8 100644--- a/packages/cli/authoring/config/type.ts+++ b/packages/cli/authoring/config/type.ts@@ -115,8 +115,8 @@ export interface AstryxConfig {/** Experimental XLE (layout expression) configuration. */xle?: {/**- * No effect. Its only reader was the removed `layout` command. Still- * accepted so existing configs keep loading; delete it.+ * Register app-local components so XLE layout expressions can+ * reference them by name via {hint}. Keyed by component name.*/components?: Record<string, XleComponent>;};diff --git a/packages/cli/authoring/doctypes/command/command.doc.mjs b/packages/cli/authoring/doctypes/command/command.doc.mjsindex fd38553e90..ae3949c295 100644--- a/packages/cli/authoring/doctypes/command/command.doc.mjs+++ b/packages/cli/authoring/doctypes/command/command.doc.mjs@@ -151,7 +151,7 @@ export const doc = {name: 'subcommands',type: 'string[]',description:- 'Subcommand names (for command groups like `theme`).',+ 'Subcommand names (for command groups like `theme` / `layout`).',},{name: 'examples',diff --git a/packages/cli/authoring/doctypes/command/type.ts b/packages/cli/authoring/doctypes/command/type.tsindex 5f670c441f..919e239518 100644--- a/packages/cli/authoring/doctypes/command/type.ts+++ b/packages/cli/authoring/doctypes/command/type.ts@@ -75,7 +75,7 @@ export interface CommandDoc extends AuthoredDocGraphFields {args?: CommandArgDoc[];/** Flags/options. */options?: CommandOptionDoc[];- /** Subcommand names (for command groups like `theme`). */+ /** Subcommand names (for command groups like `theme` / `layout`). */subcommands?: string[];/** Terminal examples. */examples?: CommandExampleDoc[];diff --git a/packages/cli/clients/cli/command-result-coverage.test.mjs b/packages/cli/clients/cli/command-result-coverage.test.mjsindex cc1d916269..dbd8479a73 100644--- a/packages/cli/clients/cli/command-result-coverage.test.mjs+++ b/packages/cli/clients/cli/command-result-coverage.test.mjs@@ -29,17 +29,17 @@ import {program} from './index.mjs';import {reportsResult, reportsResultVia} from './lib/define-command.mjs';/**- * Commands with no action of their own: a group that prints its subcommand- * list and does nothing else has no run to report on.+ * Commands with no action of their own: bare `astryx layout` prints its+ * subcommand list and does nothing else, so there is no run to report on.** Pinned as a SET rather than skipped silently — if a command joins this list,* that is a real change to what the CLI does and it should be read, not- * absorbed. Every group ships an action today: `theme`, for instance, HAS one- * — the one that rejects an unknown subcommand — so it goes through the- * converter like any other. Its bare form prints help and never returns from- * that action, which the recorder covers where help is recorded, not here.+ * absorbed. (`theme` is deliberately NOT here: it HAS an action — the one that+ * rejects an unknown subcommand — so it goes through the converter like any+ * 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 = [];+const NO_ACTION_OF_THEIR_OWN = ['layout'];/*** 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.mjsindex e42ac5a46e..5ffe768b09 100644--- a/packages/cli/clients/cli/commands/debug-result-summary.test.mjs+++ b/packages/cli/clients/cli/commands/debug-result-summary.test.mjs@@ -179,9 +179,9 @@ describe('DebugEvent result summary', () => {it('says so explicitly when a command has no result set',async () => {- // Bare `integration` prints its subcommand list: nothing was looked+ // `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(['integration']);+ const {event} = await runWithDebug(['layout', 'check', 'VStack>Text']);expect(event.output).toMatchObject({resultKind: 'none',resultCount: null,diff --git a/packages/cli/clients/cli/commands/layout-check.doc.mjs b/packages/cli/clients/cli/commands/layout-check.doc.mjsnew file mode 100644index 0000000000..c21672548d--- /dev/null+++ b/packages/cli/clients/cli/commands/layout-check.doc.mjs@@ -0,0 +1,65 @@+// 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',+ },+ ],+ 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.mjsnew file mode 100644index 0000000000..d164e43160--- /dev/null+++ b/packages/cli/clients/cli/commands/layout-expand.doc.mjs@@ -0,0 +1,83 @@+// 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.',+ 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',+ },+ ],+ 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.mjsnew file mode 100644index 0000000000..ea056e75e2--- /dev/null+++ b/packages/cli/clients/cli/commands/layout-grammar.doc.mjs@@ -0,0 +1,30 @@+// 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'},+ ],+ related: ['layout expand', 'layout check'],+};diff --git a/packages/cli/clients/cli/commands/layout.doc.mjs b/packages/cli/clients/cli/commands/layout.doc.mjsnew file mode 100644index 0000000000..2ee3ba0ab2--- /dev/null+++ b/packages/cli/clients/cli/commands/layout.doc.mjs@@ -0,0 +1,34 @@+// 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'},+ ],+ 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.mjsnew file mode 100644index 0000000000..bcc9c45c20--- /dev/null+++ b/packages/cli/clients/cli/commands/layout.error-codes.test.mjs@@ -0,0 +1,66 @@+// 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.mjsnew file mode 100644index 0000000000..767bf14cae--- /dev/null+++ b/packages/cli/clients/cli/commands/layout.exit-parity.test.mjs@@ -0,0 +1,41 @@+// 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.mjs b/packages/cli/clients/cli/commands/layout.mjsnew file mode 100644index 0000000000..1c316cfd99--- /dev/null+++ b/packages/cli/clients/cli/commands/layout.mjs@@ -0,0 +1,275 @@+// 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} 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]+ */++/** 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 ?? '';+}++/**+ * @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) => {+ 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(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));+ }+ emit(...out);+ return NO_RESULT_SET;+ },+ });++ defineCommand(layoutCmd, layoutCheckCommand, {+ fn: layoutCheckFn,+ action: async (/** @type {string} */ expression, /** @type {LayoutCheckOptions} */ options) => {+ 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(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 () => {+ 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(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.mjsnew file mode 100644index 0000000000..d0c782e8a7--- /dev/null+++ b/packages/cli/clients/cli/commands/layout.path-help.test.mjs@@ -0,0 +1,33 @@+// 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.mjsnew file mode 100644index 0000000000..a432645659--- /dev/null+++ b/packages/cli/clients/cli/commands/layout.stdin-cap.test.mjs@@ -0,0 +1,47 @@+// 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.mjsnew file mode 100644index 0000000000..fb64a0feef--- /dev/null+++ b/packages/cli/clients/cli/commands/layout.text-fields.test.mjs@@ -0,0 +1,39 @@+// 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.mjsindex b58c960942..6b0215e8cf 100644--- a/packages/cli/clients/cli/commands/text-json-parity.test.mjs+++ b/packages/cli/clients/cli/commands/text-json-parity.test.mjs@@ -383,6 +383,23 @@ 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.mjsindex 59e1f94d60..a1442822a1 100644--- a/packages/cli/clients/cli/index.mjs+++ b/packages/cli/clients/cli/index.mjs@@ -104,6 +104,9 @@ export const JSON_SUPPORTED = new Set(['doctor integration templates','doctor integration components','doctor integration docs',+ 'layout expand',+ 'layout check',+ 'layout grammar',]);/**@@ -262,6 +265,7 @@ 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.mjsindex 6ed1ef9b14..87c46d6283 100644--- a/packages/cli/clients/cli/lib/exit-codes.test.mjs+++ b/packages/cli/clients/cli/lib/exit-codes.test.mjs@@ -34,7 +34,7 @@ manifest.commands.forEach(walk);describe('command exit codes', () => {it('every CommandDoc documents its exit codes', () => {- expect(commandDocs.length).toBeGreaterThan(25);+ expect(commandDocs.length).toBeGreaterThan(30);for (const doc of commandDocs) {expect(doc.exitCodes?.length, doc.name).toBeGreaterThan(0);}@@ -70,6 +70,13 @@ 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.mjsindex f73106554c..6c10336719 100644--- a/packages/cli/clients/cli/lib/json-shim.test.mjs+++ b/packages/cli/clients/cli/lib/json-shim.test.mjs@@ -225,6 +225,23 @@ 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));@@ -240,9 +257,6 @@ describe('--json shim: help shown for a failed invocation is an error envelope',});it('a group added after install gets the same error envelope', () => {- // This is the only coverage of the no-subcommand path: every group the CLI- // ships has an action of its own (see command-result-coverage.test.mjs), so- // a group without one has to be built here.const program = new Command('astryx');installJsonShim(program);// Added later, so only the prototype-level patch covers its outputHelp.@@ -268,11 +282,11 @@ 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 theme --json still emits the help envelope, exit 0', async () => {- const {status, stdout} = await runCli(['help', 'theme', '--json']);+ 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 theme');+ expect(parsed.data.command).toBe('astryx layout');});});diff --git a/packages/cli/clients/cli/lib/manifest.mjs b/packages/cli/clients/cli/lib/manifest.mjsindex af72ad89bc..e58ba839d7 100644--- a/packages/cli/clients/cli/lib/manifest.mjs+++ b/packages/cli/clients/cli/lib/manifest.mjs@@ -102,6 +102,9 @@ export const RESPONSE_TYPES = {'doctor integration templates': ['integration.template-conflicts'],'doctor integration components': ['integration.component-conflicts'],'doctor integration docs': ['integration.doc-conflicts'],+ 'layout expand': ['layout.expand'],+ 'layout check': ['layout.check'],+ 'layout grammar': ['layout.grammar'],};/**@@ -190,6 +193,11 @@ const EXAMPLES = {'astryx doctor integration docs @acme/widgets --json',],init: ['astryx init', 'astryx init --all --json'],+ 'layout expand': [+ `astryx layout expand 'V[g6] > C{card-callout}*4' ./src/Page.tsx`,+ ],+ 'layout check': [`astryx layout check 'A[cp6] > L > LC > S[p6]' --json`],+ 'layout grammar': ['astryx layout grammar'],};/**diff --git a/packages/cli/foundation/discovery/template-adapter.mjs b/packages/cli/foundation/discovery/template-adapter.mjsindex eb7d2f818a..7762752c8a 100644--- a/packages/cli/foundation/discovery/template-adapter.mjs+++ b/packages/cli/foundation/discovery/template-adapter.mjs@@ -4,7 +4,7 @@* @file Shared template discovery + IO.** Owns everything the template leaves (list/show/skeleton/copy) AND other- * commands (component, search, init, discover, Doctor integration)+ * commands (component, layout, search, init, discover, Doctor integration)* share: template discovery across core/external/integration sources, the* template-spec loaders, and the cross-command helpers (stripTemplateAssetRefs,* findShowcase, findRelatedBlocks, extractComponents, listTemplates). Thediff --git a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs b/packages/cli/foundation/doc-compiler/doc-loads.test.mjsindex c0a8863326..928c107a0e 100644--- a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs+++ b/packages/cli/foundation/doc-compiler/doc-loads.test.mjs@@ -192,6 +192,18 @@ 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/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjsindex 8420310613..4fd8b3eca0 100644--- a/packages/cli/foundation/response/response-types.doc.mjs+++ b/packages/cli/foundation/response/response-types.doc.mjs@@ -337,5 +337,22 @@ export const doc = {description:'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, and written (the output path, or null when nothing was written).',+ },+ {+ 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).',+ },+ {+ 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.",+ },],};diff --git a/packages/cli/foundation/xle/browser.mjs b/packages/cli/foundation/xle/browser.mjsindex 8f431fdb48..3b4b50fa80 100644--- a/packages/cli/foundation/xle/browser.mjs+++ b/packages/cli/foundation/xle/browser.mjs@@ -44,8 +44,8 @@ function formatIssue(issue) {}/**- * Validate an expression and return both canonical surfaces. Never throws on- * invalid input; returns the errors.+ * Validate an expression and return both canonical surfaces — the browser+ * twin of `layout check`. 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.+ * Validate + expand to TSX — the browser twin of `layout expand`.* Returns either {code, ...} or {errors} (never writes files).** @param {string} expressiondiff --git a/packages/cli/foundation/xle/expand.mjs b/packages/cli/foundation/xle/expand.mjsindex 549167b2c5..7df2b8a2a2 100644--- a/packages/cli/foundation/xle/expand.mjs+++ b/packages/cli/foundation/xle/expand.mjs@@ -13,7 +13,7 @@** @input validated doc (nodes carry .bound) + registry* @output expand() → {code, componentsUsed, states, todos}- * @position lib/xle — last stage; the browser barrel orchestrates+ * @position lib/xle — last stage; api/layout.mjs orchestrates*/import {PAYLOAD_PROPS} from './validate.mjs';@@ -751,7 +751,7 @@ export function expand(doc, registry, options = {}) {: [];const code = [- `// Generated by the Astryx XLE expander — this file is the artifact; edit freely.`,+ `// Generated by \`astryx layout expand\` — this file is the artifact; edit freely.`,...importLines,...blockSection,'',diff --git a/packages/cli/foundation/xle/parse.mjs b/packages/cli/foundation/xle/parse.mjsindex 067257ea00..98504c07ea 100644--- a/packages/cli/foundation/xle/parse.mjs+++ b/packages/cli/foundation/xle/parse.mjs@@ -302,7 +302,7 @@ function parseAttrToken(token, line) {* Guard against unbounded recursion in the compact parser. A layout tree this* deep is never hand-authored; without the cap the recursive descent blows the* JS call stack and surfaces a raw RangeError (→ ERR_UNKNOWN, no line/col)- * instead of a located parse error. The counter is module-level so it+ * instead of a located ERR_LAYOUT_PARSE. The counter is module-level so it* spans group / attribute sub-streams; each parse entry point resets it.*/const MAX_COMPACT_DEPTH = 512;diff --git a/packages/cli/foundation/xle/print.mjs b/packages/cli/foundation/xle/print.mjsindex f2adc236fe..7ad3242df1 100644--- a/packages/cli/foundation/xle/print.mjs+++ b/packages/cli/foundation/xle/print.mjs@@ -3,8 +3,8 @@/*** @file XLE canonical printers — AST → compact (XLE) or outline (XLO) text.*- * Used by `checkExpression` so either party (agent or human) can request the- * other surface, and by round-trip conformance tests.+ * Used by `astryx layout check --form …` 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/foundation/xle/splice.mjs b/packages/cli/foundation/xle/splice.mjsindex af6c60b838..ae9a99b7c4 100644--- a/packages/cli/foundation/xle/splice.mjs+++ b/packages/cli/foundation/xle/splice.mjs@@ -18,7 +18,7 @@** @input block TSX source (splice) or a name+importPath (import)* @output prepareSpliceModule / parseImportStatements + import-merge helpers- * @position lib/xle — used by expand.mjs; sources gathered by the caller+ * @position lib/xle — used by expand.mjs; sources gathered in api/layout.mjs*/const IMPORT_RE =diff --git a/scripts/check-cli-structure.mjs b/scripts/check-cli-structure.mjsindex 4023ed91af..13ee856976 100644--- a/scripts/check-cli-structure.mjs+++ b/scripts/check-cli-structure.mjs@@ -27,8 +27,7 @@* *.test.mjs coverage (may be nested, e.g. api/theme/build/build.test.mjs)** Deliberately NOT checked here: command <-> CommandDoc pairing. That is not a- * filename convention — subcommand docs (theme-add, doctor-integration-validate,- * ...) live+ * filename convention — subcommand docs (layout-expand, theme-add, ...) live* inside their group's handler and `manifest` registers in index.mjs — and the* drift harness already validates it semantically against the live manifest,* which is strictly stronger than matching filenames.