Skip to content

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

TypeScript

feat(cli): self-documenting CLI — colocated typed docs for every command, API function, and schema (#4714)

Joey2d2dba1de5ff
diff --git a/.changeset/cli-self-documenting-docs.md b/.changeset/cli-self-documenting-docs.md
new file mode 100644
index 0000000000..eb0f5de20b
--- /dev/null
+++ b/.changeset/cli-self-documenting-docs.md
@@ -0,0 +1,12 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] Add a self-documenting layer to the CLI: typed, colocated `.doc.mjs` for every command, every `@astryxdesign/cli/api` function, and every authored schema (config, integration, codemod, the response envelope, and the doc-types themselves). Adds the `FunctionDoc`, `SchemaDoc`, `CommandDoc`, and `EnumDoc` authoring types with sealed parsers.
+
+Every command's `--help` and its `astryx manifest` entry are now built from that command's colocated `CommandDoc` via a `defineCommand` converter, so the docs and the CLI can no longer describe different things. The migration is behavior-preserving: help text, command output, error paths, and exit codes are byte-identical.
+
+The CLI README's command, error-code, and response-type tables are now generated from the manifest and the `EnumDoc`s, correcting real drift — the error-code table listed two codes that do not exist and omitted several that do, and the command table was missing `blog`, `build`, `layout`, and `validate-integration`.
+
+Kept honest by a drift harness (docs vs the live CLI), `check:cli-structure` (each doc-type and `api/` leaf ships its full file set), and lint rules for the CLI's layering.
+@josephfarina
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 9186f9ed07..0eefb3ebc6 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -317,6 +317,73 @@ Two repo-side rules worth restating here:
keyboard behavior, focus management, and announcement timing are exactly
what the checklist and the component's unit tests cover.
+## Working on the `astryx` CLI
+
+The CLI (`packages/cli/`) is layered so behavior, presentation, and contracts stay separable:
+
+- **`clients/cli/`** — the Commander program and per-command handlers. A handler is a _thin wrapper_: parse flags → call the matching `api/` function → render (JSON via `jsonOut`, or text via the formatter kit in `clients/cli/formatters/`).
+- **`api/`** — the programmatic API (`@astryxdesign/cli/api`). Each command maps to `api/<name>/`, whose functions return a typed `{ type, data }` envelope. This is the behavior source of truth, so `astryx --json` and the imported function return identical data.
+- **`authoring/`** — the pure data contracts (`@astryxdesign/cli/authoring`): the TypeScript types you author objects against (config, integration, codemod, and the doc-types) plus the sealed zod parsers the CLI runs at the load boundary.
+- **`foundation/`** — cross-cutting infra: the `{ type, data }` JSON contract, the stable `ERROR_CODES`, discovery, and path-safety.
+
+### The CLI documents itself
+
+Every CLI surface has a colocated, typed `.doc.mjs` next to what it describes, annotated with a `@type` from `@astryxdesign/cli/authoring`:
+
+| Surface | Doc-type | Lives next to |
+| --------------------------------------------------------------------------------------- | ---------------------------------------------------- | ---------------------------------------------------------- |
+| An API function (a hook or an `api/` export) | `FunctionDoc` | `api/<name>/<fn>.doc.mjs` |
+| A CLI command | `CommandDoc` (references its `FunctionDoc` via `fn`) | `clients/cli/commands/<name>.doc.mjs` |
+| An authored object (config, integration, codemod, the doc-types, the response envelope) | `SchemaDoc` | beside the schema (`authoring/**`, `foundation/response/`) |
+| A closed vocabulary (error codes, response types) | `EnumDoc` | `foundation/response/` |
+| A long-form topic (tokens, principles, theming, …) | `ReferenceDoc` | `assets/docs/<topic>.doc.mjs` |
+
+These are not free-form. `parseDoc` validates each at load, and a **drift harness** (`packages/cli/test/drift/`) enforces that they mirror their source of truth: every `CommandDoc`'s `fn`/args/options match the live CLI, and the `EnumDoc`s equal `ERROR_CODES` / the manifest's response-type set exactly. A doc that drifts fails CI.
+
+### What's enforced for you
+
+Most of the conventions above are mechanical, so they're checked rather than reviewed:
+
+| Rule | Enforced by |
+| ------------------------------------------------------------------------------------------------------------- | -------------------------------- |
+| `authoring/` imports no other layer; `api/` never imports `clients/` | ESLint (`no-restricted-imports`) |
+| zod stays sealed behind the `authoring/` parsers | ESLint (`no-restricted-imports`) |
+| commands register via `defineCommand`, never straight onto Commander | ESLint (`no-restricted-syntax`) |
+| each doc-type ships `type.ts` + `parse.mjs` + `parse.d.mts` + `<kind>.doc.mjs`, and its parser is re-exported | `pnpm check:cli-structure` |
+| each `api/<name>/` ships its typedefs, a `FunctionDoc`, and a test | `pnpm check:cli-structure` |
+| every `CommandDoc`/`EnumDoc` matches the live CLI | the drift harness |
+
+The declaration file (`parse.d.mts`) is the easiest one to forget and the most expensive to miss: `authoring/index.d.ts` re-exports each parser, so without it a strict consumer of the published package resolves that parser as `any` — and local typechecks won't catch it, because they run with `checkJs` and never exercise the packed `./api` surface. A hand-written declaration shadows the JSDoc in its `.mjs`, so it can also go stale while still compiling; `check:cli-structure` therefore asserts that every doc kind appears in the `parseDoc` return union too.
+
+### Adding a command
+
+Author the docs _before_ the handler: `defineCommand` builds the Commander command from the `CommandDoc`, so the handler needs it to exist.
+
+1. Add the behavior under `api/<name>/`, with a colocated `<name>.type.mjs` (the `Options` + `{ type, data }` response typedefs — the shape source of truth) and a test.
+2. Author the docs — a `FunctionDoc` at `api/<name>/<fn>.doc.mjs` and a `CommandDoc` at `clients/cli/commands/<name>.doc.mjs`. Copy the `search` pair as a template.
+3. Write the thin handler in `clients/cli/commands/<name>.mjs`, registering it with `defineCommand(program, <name>Command, {fn: <name>Fn, action})` so `--help` and the manifest come from the doc. Call its `register<Name>` from `clients/cli/index.mjs`.
+4. Run the checks below. The drift harness catches a doc that disagrees with the live command, and `check:cli-structure` catches a missing typedef, doc, or test.
+
+### Testing the CLI
+
+```bash
+# Run the CLI locally (no build needed)
+node packages/cli/clients/cli/bin/astryx.mjs --help
+
+# Validate every colocated doc parses + mirrors its source of truth
+pnpm -F @astryxdesign/cli test # includes the drift suite
+pnpm -F @astryxdesign/cli typecheck:authoring
+
+# Structural conventions (doc-type quartets, api/ leaf contents). Also runs as
+# part of `pnpm lint` via check:repo, and in the pre-commit hook.
+pnpm check:cli-structure
+
+# Keep the generated CLI README tables (commands, error codes, response types)
+# in sync with the manifest + EnumDocs. After an intended change, refresh + review:
+pnpm -F @astryxdesign/cli readme # regenerate the tables
+pnpm -F @astryxdesign/cli readme:check # CI gate: fails on any un-refreshed drift
+```
+
## Testing
### Run Tests
diff --git a/eslint.config.js b/eslint.config.js
index c756bdd2cf..a14dab4c7c 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -406,6 +406,75 @@ export default defineConfig(
'@astryx/copyright-header': 'error',
},
},
+ // ── CLI architecture invariants ────────────────────────────────────────
+ // Enforces the layering documented in CONTRIBUTING > "Working on the astryx
+ // CLI". Every rule below is already clean across packages/cli, so they are
+ // errors: they exist to prevent regressions, not to flag a backlog.
+ //
+ // NOTE: flat config *overrides* (does not merge) a same-named rule, so the
+ // `no-restricted-imports` blocks are kept disjoint — one per layer.
+
+ // authoring/ is pure data contracts + sealed parsers: it sits below every
+ // other layer and imports none of them.
+ {
+ files: ["packages/cli/authoring/**/*.mjs"],
+ rules: {
+ "no-restricted-imports": ["error", {
+ patterns: [{
+ group: ["**/api/**", "**/clients/**", "**/foundation/**"],
+ message:
+ "authoring/ is pure data contracts (types + sealed parsers) and must not import api/, clients/, or foundation/. Move shared behavior down into the contract, or invert the dependency.",
+ }],
+ }],
+ },
+ },
+ // api/ is the behavior source of truth — it must never reach up into the
+ // CLI presentation layer (that's what keeps `astryx --json` and the imported
+ // function returning identical data).
+ {
+ files: ["packages/cli/api/**/*.mjs"],
+ rules: {
+ "no-restricted-imports": ["error", {
+ patterns: [{
+ group: ["**/clients/**"],
+ message:
+ "api/ is the behavior source of truth and must not import clients/ (the CLI presentation layer). Return data in the { type, data } envelope and let the command handler render it.",
+ }],
+ paths: [{
+ name: "zod",
+ message:
+ "zod is sealed behind the authoring/ parsers. Validate at the load boundary (parseDoc/parseConfig/parseIntegration) and pass typed data inward.",
+ }],
+ }],
+ },
+ },
+ // Everything above the contracts consumes already-parsed, typed data.
+ {
+ files: ["packages/cli/clients/**/*.mjs", "packages/cli/foundation/**/*.mjs"],
+ rules: {
+ "no-restricted-imports": ["error", {
+ paths: [{
+ name: "zod",
+ message:
+ "zod is sealed behind the authoring/ parsers. Validate at the load boundary (parseDoc/parseConfig/parseIntegration) and pass typed data inward.",
+ }],
+ }],
+ },
+ },
+ // A command's --help and its manifest entry are generated from its colocated
+ // CommandDoc via defineCommand. Registering straight onto Commander bypasses
+ // the doc, so the docs silently stop describing the real CLI.
+ {
+ files: ["packages/cli/clients/cli/commands/**/*.mjs"],
+ rules: {
+ "no-restricted-syntax": ["error", {
+ selector:
+ "CallExpression[callee.type='MemberExpression'][callee.property.name='command']",
+ message:
+ "Register commands with defineCommand(parent, doc, {fn, action}) so --help and the manifest come from the colocated CommandDoc. See CONTRIBUTING > Working on the astryx CLI.",
+ }],
+ },
+ },
// CLI tests — relax author-ergonomics rules (test files emit freely and may
// keep intentionally-unused fixtures). Must come after the CLI block above.
{
@@ -413,6 +482,9 @@ export default defineConfig(
rules: {
"@astryx/no-raw-console-cli": "off",
"@typescript-eslint/no-unused-vars": "off",
+ // Tests build fixtures directly against zod and Commander.
+ "no-restricted-imports": "off",
+ "no-restricted-syntax": "off",
},
},
);
diff --git a/package.json b/package.json
index cc5f748d9f..8141f09b5d 100644
--- a/package.json
+++ b/package.json
@@ -11,8 +11,9 @@
"test:watch": "vitest",
"test:coverage": "vitest --coverage",
"check:package-boundaries": "node scripts/check-package-boundaries.js",
- "check:repo": "pnpm check:sync && pnpm check:package-boundaries && pnpm check:changesets && pnpm check:demo-media && pnpm check:executable-bits",
+ "check:repo": "pnpm check:sync && pnpm check:package-boundaries && pnpm check:changesets && pnpm check:demo-media && pnpm check:executable-bits && pnpm check:cli-structure",
"check:changesets": "node scripts/check-changesets.mjs",
+ "check:cli-structure": "node scripts/check-cli-structure.mjs",
"check:executable-bits": "node scripts/check-executable-bits.mjs",
"check:demo-media": "node scripts/check-demo-media.mjs",
"check:sync": "node scripts/check-sync.js",
diff --git a/packages/cli/README.md b/packages/cli/README.md
index b43e47c592..bd6be5ad9c 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -56,19 +56,28 @@ Options:
## Commands
-| Command | Description |
-| ------------- | ---------------------------------------------------------------------------------------------------- |
-| `init` | Initialize the design system in your project: installs packages, sets up theming, adds AI agent docs |
-| `component` | List components or print detailed docs, props, usage examples, and source |
-| `search` | Find components, hooks, docs, and templates in one ranked, cross-domain result set |
-| `docs` | Print reference documentation (tokens, theme, color, typography, spacing, etc.) |
-| `template` | Inject page or block templates into your project |
-| `hook` | List hooks and print hook documentation |
-| `swizzle` | Copy component source into your project for deep customization |
-| `upgrade` | Run codemods to migrate between versions |
-| `theme build` | Compile a defineTheme file to production CSS and JS |
-| `discover` | Discover external packages and components |
-| `doctor` | Diagnose your Astryx setup and report problems with fixes (CI-friendly via exit code) |
+<!-- BEGIN GENERATED: commands -->
+
+| Command | Description |
+| ---------------------- | ----------------------------------------------------------------------------- |
+| `blog` | Read the Astryx blog from the published feed |
+| `build` | Build a page: composition kit for an idea, or the workflow playbook (no args) |
+| `component` | List components or print component docs |
+| `discover` | Discover external packages and components |
+| `docs` | Print reference docs |
+| `doctor` | Diagnose your XDS setup and report problems with fixes |
+| `hook` | List hooks or print hook docs |
+| `init` | Initialize the design system in your project |
+| `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` | Inject a page or block template |
+| `theme` | Theme tools — build, export, and manage themes |
+| `upgrade` | Run codemods to migrate between versions |
+| `validate-integration` | Validate an Astryx integration package (manifest + contributions) |
+
+<!-- END GENERATED: commands -->
+<!-- Generated by scripts/generate-cli-readme.mjs from `astryx manifest`. Run `pnpm -F @astryxdesign/cli readme`. -->
### Global options
@@ -127,45 +136,56 @@ if (isError(result)) {
### Error codes
-| Code | Meaning |
-| ------------------------ | -------------------------------------------------------------------------------------- |
-| `ERR_UNKNOWN` | Generic fallback for any error without a more specific code. |
-| `ERR_UNKNOWN_COMMAND` | A top-level command name was not recognized (e.g. `astryx bogus`). |
-| `ERR_UNKNOWN_SUBCOMMAND` | A subcommand under a group was not recognized (e.g. `astryx theme bogus`). |
-| `ERR_INVALID_OPTION` | An unknown flag was passed, or `--json` was used on a command that doesn't support it. |
-| `ERR_INVALID_ARGUMENT` | An option/argument value was rejected, or required flags were missing. |
-| `ERR_MISSING_ARGUMENT` | A required positional argument was omitted (e.g. `astryx theme build` with no file). |
-| `ERR_INVALID_LANG` | `--lang` was given a value outside its choices (`en`, `zh`, `dense`). |
-| `ERR_INVALID_DETAIL` | `--detail` was given a value outside its choices (`full`, `compact`, `brief`). |
-| `ERR_NODE_VERSION` | The running Node.js version is below the supported minimum. |
-| `ERR_CORE_NOT_FOUND` | `@astryxdesign/core` could not be located (not installed / not in a monorepo). |
-| `ERR_UNKNOWN_COMPONENT` | No component matched the requested name. |
-| `ERR_UNKNOWN_HOOK` | No hook matched the requested name. |
-| `ERR_UNKNOWN_TOPIC` | No docs topic matched the requested name. |
-| `ERR_UNKNOWN_SECTION` | A docs topic exists but the requested section within it does not. |
-| `ERR_UNKNOWN_CATEGORY` | A `--category` filter value did not match any known category. |
-| `ERR_UNKNOWN_TEMPLATE` | No template matched the requested name. |
-| `ERR_UNKNOWN_PACKAGE` | No package matched the requested name (discover). |
-| `ERR_UNKNOWN_AGENT` | An unrecognized `--agent` value was passed (agent docs / init). |
-| `ERR_UNKNOWN_FEATURE` | An unrecognized `--features` value was passed to `init`. |
-| `ERR_UNKNOWN_CODEMOD` | A `--codemod` value did not match any registered codemod (upgrade). |
-| `ERR_NOT_FOUND` | A discover/lookup query matched nothing in any package. |
-| `ERR_NO_DOC` | A component exists but has no typed `.doc.mjs` file. |
-| `ERR_NO_SHOWCASE` | No showcase exists for the requested component. |
-| `ERR_NO_SOURCE` | No source file could be located for the component/template. |
-| `ERR_INVALID_DOC` | A component's docs failed validation (malformed `.doc.mjs`). |
-| `ERR_FILE_NOT_FOUND` | A required input file did not exist. |
-| `ERR_FILE_EXISTS` | Refused to overwrite an existing file in non-interactive mode. |
-| `ERR_PATH_TRAVERSAL` | A path escaped its allowed root, or a name contained traversal markers. |
-| `ERR_WRITE_FAILED` | Writing output files failed (and was rolled back). |
-| `ERR_THEME_INVALID` | A theme definition was missing a required property (e.g. `name`). |
-| `ERR_THEME_LOAD` | A theme file could not be loaded / parsed into a `defineTheme` result. |
-| `ERR_TEMPLATE_CONFIG` | `template.get` is not configured in `astryx.config.mjs` (fetch-by-id). |
-| `ERR_TEMPLATE_GET` | A configured `template.get` threw or returned an invalid value. |
-| `ERR_VERSION_DETECT` | The current `@astryxdesign/core` version could not be detected. |
-| `ERR_INVALID_VERSION` | A `--from`/`--to` value was not a valid semver string. |
-| `ERR_DEP_MISSING` | A required external dependency (e.g. jscodeshift) is missing. |
-| `ERR_GH_CLI` | GitHub CLI (`gh`) is not installed or not authenticated. |
+<!-- BEGIN GENERATED: error-codes -->
+
+| Code | Meaning |
+| ------------------------- | ------------------------------------------------------------------------------------- |
+| `ERR_UNKNOWN` | Fallback for any error without a more specific code. |
+| `ERR_UNKNOWN_COMMAND` | A top-level command name was not recognized (e.g. `astryx bogus`). |
+| `ERR_UNKNOWN_SUBCOMMAND` | A subcommand under a command group was not recognized (e.g. `astryx theme bogus`). |
+| `ERR_INVALID_OPTION` | An unknown flag/option was passed (Commander `unknownOption`). |
+| `ERR_INVALID_ARGUMENT` | An option/argument had a value Commander's parser rejected. |
+| `ERR_MISSING_ARGUMENT` | A required positional argument was omitted (Commander `missingArgument`). |
+| `ERR_INVALID_LANG` | `--lang` was given a value outside its choices (en, zh, dense). |
+| `ERR_INVALID_DETAIL` | `--detail` was given a value outside its choices (full, compact, brief). |
+| `ERR_NODE_VERSION` | The running Node.js version is below the supported minimum. |
+| `ERR_CORE_NOT_FOUND` | `@astryxdesign/core` could not be located (not installed / not in a monorepo). |
+| `ERR_UNKNOWN_COMPONENT` | No component matched the requested name. |
+| `ERR_UNKNOWN_HOOK` | No hook matched the requested name. |
+| `ERR_UNKNOWN_TOPIC` | No docs topic matched the requested name. |
+| `ERR_UNKNOWN_SECTION` | A docs topic exists but the requested section within it does not. |
+| `ERR_UNKNOWN_CATEGORY` | A `--category` filter value did not match any known category. |
+| `ERR_UNKNOWN_TEMPLATE` | No template matched the requested name. |
+| `ERR_AMBIGUOUS_TEMPLATE` | A template id matched more than one template (narrow with --type/--package). |
+| `ERR_AMBIGUOUS_COMPONENT` | A component name is owned by more than one package (narrow with --package). |
+| `ERR_UNKNOWN_THEME` | No theme matched the requested slug (theme add). |
+| `ERR_UNKNOWN_PACKAGE` | No package matched the requested name (discover). |
+| `ERR_UNKNOWN_AGENT` | An unrecognized `--agent` value was passed to agent-docs/init. |
+| `ERR_UNKNOWN_FEATURE` | An unrecognized `--features` value was passed to init. |
+| `ERR_UNKNOWN_CODEMOD` | A `--codemod` value did not match any registered codemod (upgrade). |
+| `ERR_CODEMOD_FAILED` | One or more codemods failed during an upgrade run. |
+| `ERR_NOT_FOUND` | A generic discover/lookup query matched nothing in any package. |
+| `ERR_NO_DOC` | A component exists but has no typed `.doc.mjs` file. |
+| `ERR_NO_SHOWCASE` | No showcase exists for the requested component. |
+| `ERR_NO_SOURCE` | No source file could be located for the requested component/template. |
+| `ERR_INVALID_DOC` | A component's docs failed validation (malformed `.doc.mjs`). |
+| `ERR_FILE_NOT_FOUND` | A required input file did not exist. |
+| `ERR_FILE_EXISTS` | Refused to overwrite an existing file in non-interactive mode. |
+| `ERR_PATH_TRAVERSAL` | A path escaped its allowed root, or a name contained traversal markers. |
+| `ERR_WRITE_FAILED` | Writing output files failed (and was rolled back). |
+| `ERR_THEME_INVALID` | A theme definition was missing a required property (e.g. `name`). |
+| `ERR_THEME_LOAD` | A theme file could not be loaded / parsed into a defineTheme result. |
+| `ERR_VERSION_DETECT` | The current `@astryxdesign/core` version could not be detected. |
+| `ERR_INVALID_VERSION` | A `--from`/`--to` value was not a valid semver string. |
+| `ERR_DEP_MISSING` | A required external dependency (e.g. jscodeshift) is missing. |
+| `ERR_GH_CLI` | GitHub CLI (`gh`) is not installed or not authenticated. |
+| `ERR_UNKNOWN_POST` | No blog post matched the requested slug in the feed. |
+| `ERR_FETCH_FAILED` | A network fetch (RSS feed or post text) failed. |
+| `ERR_LAYOUT_PARSE` | A layout expression failed to parse (syntax error, with line/col). |
+| `ERR_LAYOUT_INVALID` | A layout expression parsed but failed validation (unknown component/prop/enum/block). |
+
+<!-- END GENERATED: error-codes -->
+<!-- Generated by scripts/generate-cli-readme.mjs from the error-codes EnumDoc (== ERROR_CODES). Run `pnpm -F @astryxdesign/cli readme`. -->
## Capability manifest (agent discovery)
@@ -359,39 +379,55 @@ detail.data.name; // narrowed
### Type discriminators
-Every response has a `type` string that uniquely identifies it:
-
-| Command | Type | Response |
-| ------------------------------------------------------------------ | ------------------------------------ | --------------------------------- |
-| `astryx --json component [--list] [--detail names\|compact\|full]` | `component.list` (see `data.detail`) | `ComponentListResponse` |
-| `astryx --json component <name>` | `component.detail` | `ComponentDetailResponse` |
-| `astryx --json component <name> --props` | `component.detail.props` | `ComponentDetailPropsResponse` |
-| `astryx --json component <name> --source` | `component.detail.source` | `ComponentDetailSourceResponse` |
-| `astryx --json component <name> --showcase` | `component.detail.showcase` | `ComponentDetailShowcaseResponse` |
-| `astryx --json component <name> --blocks` | `component.detail.blocks` | `ComponentDetailBlocksResponse` |
-| `astryx --json discover` | `discover.list` | `DiscoverListResponse` |
-| `astryx --json discover @scope/name` | `discover.detail` | `DiscoverDetailResponse` |
-| `astryx --json discover @scope/name/Comp` | `discover.detail.doc` | `DiscoverDetailDocResponse` |
-| `astryx --json discover <search>` | `discover.search` | `DiscoverSearchResponse` |
-| `astryx --json docs` | `docs.list` | `DocsListResponse` |
-| `astryx --json docs <topic>` | `docs.detail` | `DocsDetailResponse` |
-| `astryx --json docs <topic> <section>` | `docs.detail.section` | `DocsDetailSectionResponse` |
-| `astryx --json template [--list]` | `template.list` | `TemplateListResponse` |
-| `astryx --json template <name>` | `template.show` | `TemplateShowResponse` |
-| `astryx --json template <name> --skeleton` | `template.skeleton` | `TemplateSkeletonResponse` |
-| `astryx --json template <name> [path]` | `template.copy` | `TemplateCopyResponse` |
-| `astryx --json hook [--list] [--detail names\|compact\|full]` | `hook.list` (see `data.detail`) | `HookListResponse` |
-| `astryx --json hook <name>` | `hook.detail` | `HookDetailResponse` |
-| `astryx --json hook <name> --params` | `hook.detail.params` | `HookDetailParamsResponse` |
-| `astryx --json search <query>` | `search` | `SearchResponse` |
-| `astryx --json swizzle [--list]` | `swizzle.list` | `SwizzleListResponse` |
-| `astryx --json swizzle <component>` | `swizzle.copy` | `SwizzleCopyResponse` |
-| `astryx --json theme build <file>` | `theme.build` | `ThemeBuildResponse` |
-| `astryx --json upgrade --list` | `upgrade.list` | `UpgradeListResponse` |
-| `astryx --json upgrade [--apply]` | `upgrade.run` | `UpgradeRunResponse` |
-| `astryx --json doctor` | `doctor` | `DoctorResponse` |
-| any error | — | `CLIError` |
-| unsupported command | — | `CLIUnsupportedError` |
+Every response has a `type` discriminant. The full set is below (generated from the manifest). Each command's `type`s are also listed in `astryx manifest --json`, and the matching `*Response` TypeScript types (e.g. `ComponentDetailResponse`) are exported from `@astryxdesign/cli/json`. Errors use `CLIError`, and unsupported commands use `CLIUnsupportedError`.
+
+<!-- BEGIN GENERATED: response-types -->
+
+| Type | What `data` carries |
+| --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `component.list` | The component catalog grouped by category: `detail` (the level — names \| compact \| full) and `components`, the grouped map of names+package, brief entries, or a full ComponentDoc per entry. |
+| `component.detail` | One component's authored ComponentDoc plus ownership metadata (owner package, import specifier, and whether source is available). |
+| `component.detail.props` | Just one component's props table (ComponentPropDoc[]). |
+| `component.detail.source` | One component's source file, as {component, source}. |
+| `component.detail.showcase` | One component's showcase example, as {component, aspectRatio, source}. |
+| `component.detail.blocks` | One component's example blocks, as {component, showcase, examples, related} of BlockEntry. |
+| `docs.list` | All reference-doc topics as DocsListEntry[] ({topic, description}), in discovery order. |
+| `docs.detail` | One topic's full ReferenceDoc, with token-ref blocks inlined. |
+| `docs.detail.section` | A single ReferenceSection of a topic — the first whose title contains the section query. |
+| `blog.list` | The feed URL plus every post parsed from the RSS feed — each with slug, title, description, date, type, authors, link, and plaintext URL. |
+| `blog.detail` | One post's metadata plus the feed URL and the post's full plaintext body. |
+| `discover.list` | The configured external packages (name, category, components, version, description); when empty it carries meta.configured to tell "nothing configured" from "nothing discovered". |
+| `discover.detail` | A single external package entry, for an @scope/name query. |
+| `discover.detail.doc` | The validated ComponentDoc for one external component — an @scope/name/Component query, or a free-text term resolving to exactly one component. |
+| `discover.search` | The echoed query plus the matching {package, component} pairs, when a free-text term matches several components. |
+| `search` | The echoed query plus a ranked SearchResultEntry[] (domain, name, score, reason, description, follow-up command, and import path where relevant). |
+| `build.help` | A marker (`playbook: true`) that the renderer expands into the how-to-build-a-page workflow; emitted when no query is given. |
+| `build.kit` | The grouped composition kit: echoed query, hasResults/directMatch flags, the closest page templates, drop-in block patterns, idea-specific components/hooks, and the always-on frame + foundation component-name arrays. |
+| `swizzle.list` | The names of swizzlable components discoverable from cwd's @astryxdesign/core. |
+| `swizzle.copy` | An eject receipt: component name, owning package, output directory, files-copied count, the written file names, whether any file uses StyleX, and an optional maintainer note. |
+| `template.list` | Every discovered template (page + block); each entry carries id, name, description, kind, owning package, optional category and componentsUsed, and readiness flags. |
+| `template.show` | The resolved template's raw source plus its description, kind, and the component names it composes. |
+| `template.skeleton` | A layout skeleton (structural tags with spatial annotations) plus the template's description and the components it composes. |
+| `template.copy` | A scaffold receipt: template id, output directory, written file name, and file count. |
+| `hook.list` | The hook catalog grouped by category: `detail` (the level — names \| compact \| full) and `components`, the grouped map of hook names, brief entries, or a full HookDoc per entry. |
+| `hook.detail` | One hook's full authored HookDoc. |
+| `hook.detail.params` | Just one hook's parameters table (HookParamDoc[]). |
+| `theme.build` | A theme build receipt: name, token- and component-override counts, output size, the written outputs {css, js, dts, and variantsDts when applicable}, and any validation warnings. |
+| `theme.build.check` | The --check receipt: theme name, an upToDate flag, the stale outputs (each {path, reason: missing \| outdated}), and the full list of checked paths. Writes nothing. |
+| `theme.list` | Every bundled theme as a ThemeListEntry[] — each with slug, displayName, description, and a maintained flag. |
+| `theme.add` | A scaffold receipt: resolved slug, displayName, maintained flag, outputDir (relative to cwd), the theme entry file, its exportName, and the files written. |
+| `upgrade.list` | Every available codemod, oldest→newest, as {name, title, version, optional}; returned for --list without running anything. |
+| `upgrade.status` | A short-circuit outcome with no codemods run — up_to_date, no_codemods, or config_fixable — each carrying the agent-docs summary. |
+| `upgrade.run` | The run receipt: from/to versions, codemod count, integrations processed, the agent-docs summary, and (apply mode) filesChanged, transformsApplied, and per-codemod errors. |
+| `manifest` | The self-describing CLI capability manifest: name, version, apiVersion, global options, the command tree (args, options, json flag, response types, examples), the jsonSupported allowlist, and the flat responseTypes index. |
+| `doctor` | The health-check report: `checks` (each with id, label, status: pass \| warn \| fail \| info, a message, and a fix when not passing) plus a `summary` of counts per status. |
+| `integration.validate` | The validation result: the package name and version (both null when no local manifest is found) plus issues, an AstryxIntegrationIssue[] of {code, severity: warning \| error, message}. |
+| `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`. -->
## Doctor
diff --git a/packages/cli/api/api-docs-parse.test.mjs b/packages/cli/api/api-docs-parse.test.mjs
new file mode 100644
index 0000000000..7d79c03255
--- /dev/null
+++ b/packages/cli/api/api-docs-parse.test.mjs
@@ -0,0 +1,47 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Validates every colocated FunctionDoc under `api/**` — each `*.doc.mjs`
+ * must export a `doc` that passes `parseDoc` (stamped `type: 'function'`). This
+ * is the safety net for the hand-authored API function docs.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {fileURLToPath, pathToFileURL} from 'node:url';
+import {describe, it, expect} from 'vitest';
+import {parseDoc} from '../authoring/index.mjs';
+
+const API_DIR = path.dirname(fileURLToPath(import.meta.url));
+
+/** @param {string} dir @returns {string[]} */
+function findDocs(dir) {
+ /** @type {string[]} */
+ const out = [];
+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {
+ const p = path.join(dir, entry.name);
+ if (entry.isDirectory()) out.push(...findDocs(p));
+ else if (entry.name.endsWith('.doc.mjs')) out.push(p);
+ }
+ return out;
+}
+
+describe('api FunctionDocs', () => {
+ const files = findDocs(API_DIR);
+
+ it('discovers colocated function docs', () => {
+ expect(files.length).toBeGreaterThan(0);
+ });
+
+ for (const file of files) {
+ const rel = path.relative(API_DIR, file);
+ it(`parses ${rel}`, async () => {
+ const mod = await import(pathToFileURL(file).href);
+ const doc = mod.doc ?? mod.docs;
+ expect(doc, `${rel} must export \`doc\``).toBeTruthy();
+ expect(doc.type, `${rel} should be a function doc`).toBe('function');
+ const parsed = parseDoc(doc);
+ expect(parsed.name, `${rel} needs a name`).toBeTruthy();
+ });
+ }
+});
diff --git a/packages/cli/api/blog/blog.doc.mjs b/packages/cli/api/blog/blog.doc.mjs
new file mode 100644
index 0000000000..99b1fd4a2c
--- /dev/null
+++ b/packages/cli/api/blog/blog.doc.mjs
@@ -0,0 +1,66 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file FunctionDoc for `blog()` / `astryx blog`. Colocated with the API
+ * function it documents; the shape source of truth stays in `blog.type.mjs`.
+ * @position packages/cli/api/blog — function documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */
+export const doc = {
+ type: 'function',
+ kind: 'api',
+ name: 'blog',
+ displayName: 'blog()',
+ summary: 'List blog posts, or read one, from the published RSS feed.',
+ description:
+ 'Reads the design system blog the same way any feed reader does — over the ' +
+ "published RSS feed, never the blog's source files. With no slug it lists every " +
+ "post parsed from the feed; with a slug it reads that post's full plaintext body " +
+ 'via the .txt alternate the feed advertises. Both envelopes carry feedUrl so a ' +
+ 'caller can hit the RSS feed directly.',
+ importPath: '@astryxdesign/cli/api',
+ signature:
+ 'blog(slug?: string): Promise<BlogListResponse | BlogDetailResponse>',
+ keywords: ['blog', 'posts', 'rss', 'feed', 'news', 'article'],
+ params: [
+ {
+ name: 'slug',
+ type: 'string',
+ description:
+ 'Post slug (matched case-insensitively) to read in full. Omit to list every post.',
+ },
+ ],
+ returns: [
+ {
+ type: 'blog.list',
+ description:
+ 'The feed URL plus every post parsed from the feed — each with slug, title, description, date, type, authors, link, and its plaintext URL.',
+ },
+ {
+ type: 'blog.detail',
+ description:
+ "One post's metadata plus the feed URL and the post's full plaintext body.",
+ },
+ ],
+ throws: [
+ {
+ code: 'ERR_INVALID_ARGUMENT',
+ when: 'the slug is provided but is not a string',
+ },
+ {
+ code: 'ERR_UNKNOWN_POST',
+ when: 'no post in the feed matches the requested slug',
+ },
+ {
+ code: 'ERR_FETCH_FAILED',
+ when: 'the RSS feed or post text cannot be fetched (network error, timeout, non-2xx, or oversized), or the post has no plaintext alternate in the feed',
+ },
+ ],
+ examples: [
+ {label: 'List posts', code: 'const {data} = await blog();'},
+ {label: 'Read one post', code: "await blog('introducing-astryx');"},
+ ],
+ command: 'blog',
+ related: ['docs', 'search'],
+};
diff --git a/packages/cli/api/build/build.doc.mjs b/packages/cli/api/build/build.doc.mjs
new file mode 100644
index 0000000000..b3061992ca
--- /dev/null
+++ b/packages/cli/api/build/build.doc.mjs
@@ -0,0 +1,81 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file FunctionDoc for `build()` / `astryx build`. Colocated with the API
+ * function it documents; the shape source of truth stays in `build.type.mjs`.
+ * @position packages/cli/api/build — function documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */
+export const doc = {
+ type: 'function',
+ kind: 'api',
+ name: 'build',
+ displayName: 'build()',
+ summary:
+ 'Page-building assistant: the how-to-build playbook, or a composition kit for an idea.',
+ description:
+ 'The "assemble a page" entry point. Called with no query it returns the ' +
+ 'playbook signal that the renderer expands into the how-to-build-a-page ' +
+ 'workflow. Called with a query it runs the unified search and groups the ' +
+ 'hits into a composition KIT: the closest page templates, drop-in blocks, ' +
+ 'and idea-specific components/hooks, plus the always-on frame + foundation.',
+ importPath: '@astryxdesign/cli/api',
+ signature:
+ 'build(query?: string, options?: BuildOptions): Promise<BuildHelpResponse | BuildKitResponse>',
+ keywords: ['build', 'compose', 'assemble', 'page', 'kit', 'scaffold'],
+ params: [
+ {
+ name: 'query',
+ type: 'string',
+ description:
+ 'What you\'re building (e.g. "analytics dashboard"). Omit for the how-to-build playbook.',
+ },
+ {
+ name: 'options.cwd',
+ type: 'string',
+ description:
+ 'Directory to resolve @astryxdesign/core and templates from.',
+ },
+ {
+ name: 'options.type',
+ type: "'component' | 'hook' | 'doc' | 'template'",
+ description: 'Restrict the underlying search to a single domain.',
+ },
+ {
+ name: 'options.limit',
+ type: 'number',
+ description:
+ 'Max results pulled from search before grouping into the kit.',
+ default: '60',
+ },
+ ],
+ returns: [
+ {
+ type: 'build.help',
+ description:
+ 'Emitted when the query is omitted — a pure marker (`data.playbook: true`) that the command renderer expands into the page-building workflow prose.',
+ },
+ {
+ type: 'build.kit',
+ description:
+ 'The grouped composition kit: the echoed query, hasResults/directMatch flags, the closest page templates (≤3), drop-in block patterns (≤5), idea-specific components/hooks (≤6), and the always-on frame + foundation component-name arrays.',
+ },
+ ],
+ throws: [
+ {
+ code: 'ERR_INVALID_ARGUMENT',
+ when: 'options.type is not a known domain, or options.limit is not a positive integer',
+ },
+ ],
+ examples: [
+ {label: 'Get the playbook', code: 'const r = await build();'},
+ {label: 'Compose a page', code: "await build('analytics dashboard');"},
+ {
+ label: 'Restrict + limit',
+ code: "await build('pricing', {type: 'template', limit: 10});",
+ },
+ ],
+ command: 'build',
+ related: ['search', 'template', 'component', 'hook', 'init'],
+};
diff --git a/packages/cli/api/component/component.doc.mjs b/packages/cli/api/component/component.doc.mjs
new file mode 100644
index 0000000000..ffe40cd302
--- /dev/null
+++ b/packages/cli/api/component/component.doc.mjs
@@ -0,0 +1,180 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file FunctionDoc for `component()` / `astryx component`. Colocated with the
+ * API function it documents; the shape source of truth stays in
+ * `component.type.mjs`.
+ * @position packages/cli/api/component — function documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */
+export const doc = {
+ type: 'function',
+ kind: 'api',
+ name: 'component',
+ displayName: 'component()',
+ summary:
+ 'Resolve a component by name, or list the catalog, with optional focused slices (props, source, showcase, blocks).',
+ description:
+ 'Routes on its arguments: a name resolves that component across core and ' +
+ 'integration packages and returns its authored ComponentDoc plus ownership ' +
+ 'metadata; no name (or `list`/`category`) returns the catalog grouped by ' +
+ 'category. Boolean flags narrow a single component to just its props, ' +
+ 'source, showcase, or example blocks.',
+ importPath: '@astryxdesign/cli/api',
+ signature:
+ 'component(name?: string, options?: ComponentOptions): Promise<ComponentListResponse | ComponentDetailResponse | ComponentDetailPropsResponse | ComponentDetailSourceResponse | ComponentDetailShowcaseResponse | ComponentDetailBlocksResponse>',
+ keywords: [
+ 'component',
+ 'components',
+ 'props',
+ 'source',
+ 'showcase',
+ 'blocks',
+ 'catalog',
+ ],
+ params: [
+ {
+ name: 'name',
+ type: 'string',
+ description:
+ "Component name to resolve (e.g. 'Button'). Omit to list the catalog.",
+ },
+ {
+ name: 'options.cwd',
+ type: 'string',
+ description: 'Directory to resolve @astryxdesign/core from.',
+ },
+ {
+ name: 'options.list',
+ type: 'boolean',
+ description: 'Return the grouped catalog instead of a single component.',
+ },
+ {
+ name: 'options.category',
+ type: 'string',
+ description: 'List only components in this category.',
+ },
+ {
+ name: 'options.package',
+ type: 'string',
+ description:
+ "Scope lookup to a specific external package (e.g. '@acme/xds-widgets').",
+ },
+ {
+ name: 'options.props',
+ type: 'boolean',
+ description: "Return only the component's props table.",
+ },
+ {
+ name: 'options.source',
+ type: 'boolean',
+ description: "Return the component's source file.",
+ },
+ {
+ name: 'options.showcase',
+ type: 'boolean',
+ description: "Return the component's showcase example.",
+ },
+ {
+ name: 'options.blocks',
+ type: 'boolean',
+ description:
+ "Return the component's example blocks (showcase, examples, related).",
+ },
+ {
+ name: 'options.detail',
+ type: "'full' | 'compact' | 'brief'",
+ description: 'Detail level for list views.',
+ default: "'full' for a named component, 'brief' for list views",
+ },
+ {
+ name: 'options.lang',
+ type: 'string',
+ description: 'Language code for localized doc content.',
+ },
+ {
+ name: 'options.zh',
+ type: 'boolean',
+ description: 'Shorthand for Chinese (zh) doc content.',
+ },
+ {
+ name: 'options.dense',
+ type: 'boolean',
+ description: 'Return the token-efficient dense doc variant.',
+ },
+ ],
+ returns: [
+ {
+ type: 'component.list',
+ description:
+ "The catalog grouped by category. data.detail is the level ('names' | 'compact' | 'full') and data.components is the grouped map — names+package, brief entries, or full ComponentDoc per entry.",
+ },
+ {
+ type: 'component.detail',
+ description:
+ "One component's authored ComponentDoc plus ownership metadata (owner package, import specifier, whether source is available).",
+ },
+ {
+ type: 'component.detail.props',
+ description: "Just the component's props table (ComponentPropDoc[]).",
+ },
+ {
+ type: 'component.detail.source',
+ description: "The component's source file, as {component, source}.",
+ },
+ {
+ type: 'component.detail.showcase',
+ description:
+ "The component's showcase example, as {component, aspectRatio, source}.",
+ },
+ {
+ type: 'component.detail.blocks',
+ description:
+ "The component's example blocks, as {component, showcase, examples, related} of BlockEntry.",
+ },
+ ],
+ throws: [
+ {
+ code: 'ERR_CORE_NOT_FOUND',
+ when: '@astryxdesign/core cannot be resolved from cwd',
+ },
+ {
+ code: 'ERR_UNKNOWN_CATEGORY',
+ when: 'options.category is not a string or matches no known category',
+ },
+ {
+ code: 'ERR_UNKNOWN_COMPONENT',
+ when: 'name is not a string, resolves to no known component, is provided by multiple packages (pass options.package), or is absent from the requested options.package',
+ },
+ {
+ code: 'ERR_UNKNOWN_PACKAGE',
+ when: 'options.package names a legacy external package that cannot be found',
+ },
+ {
+ code: 'ERR_NO_DOC',
+ when: 'the resolved component has no .doc.mjs typed doc file',
+ },
+ {
+ code: 'ERR_NO_SOURCE',
+ when: 'options.source is set but the component has no source file',
+ },
+ {
+ code: 'ERR_NO_SHOWCASE',
+ when: 'options.showcase is set but the component has no showcase',
+ },
+ ],
+ examples: [
+ {
+ label: 'Look up a component',
+ code: "const r = await component('Button');",
+ },
+ {label: 'Props only', code: "await component('Button', {props: true});"},
+ {
+ label: 'Browse a category',
+ code: "await component(undefined, {category: 'Form', detail: 'compact'});",
+ },
+ ],
+ command: 'component',
+ related: ['search', 'hook', 'docs', 'template', 'swizzle'],
+};
diff --git a/packages/cli/api/discover/discover.doc.mjs b/packages/cli/api/discover/discover.doc.mjs
new file mode 100644
index 0000000000..56dafe06cf
--- /dev/null
+++ b/packages/cli/api/discover/discover.doc.mjs
@@ -0,0 +1,109 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file FunctionDoc for `discover()` / `astryx discover`. Colocated with the API
+ * function it documents; the shape source of truth stays in `discover.type.mjs`.
+ * @position packages/cli/api/discover — function documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */
+export const doc = {
+ type: 'function',
+ kind: 'api',
+ name: 'discover',
+ displayName: 'discover()',
+ summary: 'Browse and search components from configured external packages.',
+ description:
+ 'Explores components contributed by configured external packages and integrations ' +
+ '— the ones that declare a components root. With no query it lists those packages; ' +
+ 'an @scope/name query browses one package; @scope/name/Component (or a free-text ' +
+ "term that resolves to a single component) returns that component's validated doc; " +
+ 'a free-text term with several matches returns the candidate list.',
+ importPath: '@astryxdesign/cli/api',
+ signature:
+ 'discover(query?: string, options?: DiscoverOptions): Promise<DiscoverListResponse | DiscoverDetailResponse | DiscoverDetailDocResponse | DiscoverSearchResponse>',
+ keywords: [
+ 'discover',
+ 'packages',
+ 'integrations',
+ 'external',
+ 'components',
+ 'search',
+ ],
+ params: [
+ {
+ name: 'query',
+ type: 'string',
+ description:
+ 'An @scope/name package, an @scope/name/Component path, or a free-text term. Omit to list all configured packages.',
+ },
+ {
+ name: 'options.components',
+ type: 'boolean',
+ description:
+ 'List components only. A CLI display flag consumed by the renderer; the programmatic response shape is unchanged.',
+ },
+ {
+ name: 'options.lang',
+ type: 'string',
+ description: 'Language code to translate a resolved component doc into.',
+ },
+ {
+ name: 'options.zh',
+ type: 'boolean',
+ description: 'Return a resolved component doc in Chinese.',
+ default: 'false',
+ },
+ ],
+ returns: [
+ {
+ type: 'discover.list',
+ description:
+ 'The configured external packages (name, category, components, version, description). When empty it carries meta.configured to distinguish "nothing configured" from "configured but nothing discovered".',
+ },
+ {
+ type: 'discover.detail',
+ description: 'A single package entry, for an @scope/name query.',
+ },
+ {
+ type: 'discover.detail.doc',
+ description:
+ 'The validated ComponentDoc for one external component — an @scope/name/Component query, or a free-text term that resolves to exactly one component.',
+ },
+ {
+ type: 'discover.search',
+ description:
+ 'The query echoed back plus the matching {package, component} pairs, when a free-text term matches several components.',
+ },
+ ],
+ throws: [
+ {
+ code: 'ERR_INVALID_ARGUMENT',
+ when: 'the query is a non-string value, or a free-text search is run with an empty query',
+ },
+ {
+ code: 'ERR_UNKNOWN_PACKAGE',
+ when: 'the @scope/name package is not among the configured packages',
+ },
+ {
+ code: 'ERR_UNKNOWN_COMPONENT',
+ when: 'the component is not found in the named @scope/name package',
+ },
+ {
+ code: 'ERR_NOT_FOUND',
+ when: 'a free-text term matches no component in any package',
+ },
+ {
+ code: 'ERR_INVALID_DOC',
+ when: "the resolved component's docs fail to load or are malformed",
+ },
+ ],
+ examples: [
+ {label: 'List packages', code: 'const {data} = await discover();'},
+ {label: 'Browse a package', code: "await discover('@acme/ui');"},
+ {label: 'Show a component doc', code: "await discover('@acme/ui/Button');"},
+ {label: 'Free-text search', code: "await discover('button');"},
+ ],
+ command: 'discover',
+ related: ['component', 'search', 'template'],
+};
diff --git a/packages/cli/api/docs/docs.doc.mjs b/packages/cli/api/docs/docs.doc.mjs
new file mode 100644
index 0000000000..8c92a32779
--- /dev/null
+++ b/packages/cli/api/docs/docs.doc.mjs
@@ -0,0 +1,98 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file FunctionDoc for `docs()` / `astryx docs`. Colocated with the API
+ * function it documents; the shape source of truth stays in `docs.type.mjs`.
+ * @position packages/cli/api/docs — function documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */
+export const doc = {
+ type: 'function',
+ kind: 'api',
+ name: 'docs',
+ displayName: 'docs()',
+ summary:
+ 'Read the reference docs — list every topic, one topic, or a single section of a topic.',
+ description:
+ 'Routes on its arguments: no topic lists every reference-doc topic; a topic ' +
+ 'returns that full ReferenceDoc (with token-ref blocks inlined); a topic ' +
+ 'plus a section returns the first section whose title contains the ' +
+ '(case-insensitive) query. Overlay options select localized or dense variants.',
+ importPath: '@astryxdesign/cli/api',
+ signature:
+ 'docs(topic?: string, section?: string, options?: DocsOptions): Promise<DocsListResponse | DocsDetailResponse | DocsDetailSectionResponse>',
+ keywords: [
+ 'docs',
+ 'documentation',
+ 'reference',
+ 'guide',
+ 'topic',
+ 'section',
+ 'principles',
+ 'tokens',
+ ],
+ params: [
+ {
+ name: 'topic',
+ type: 'string',
+ description:
+ "Doc topic to load (e.g. 'principles'). Omit to list all topics.",
+ },
+ {
+ name: 'section',
+ type: 'string',
+ description:
+ 'Section within the topic to return; matches the first section title that contains this (case-insensitive).',
+ },
+ {
+ name: 'options.lang',
+ type: 'string',
+ description: 'Language code for localized doc content.',
+ },
+ {
+ name: 'options.zh',
+ type: 'boolean',
+ description: 'Shorthand for Chinese (zh) doc content.',
+ },
+ {
+ name: 'options.dense',
+ type: 'boolean',
+ description: 'Return the token-efficient dense doc variant.',
+ },
+ ],
+ returns: [
+ {
+ type: 'docs.list',
+ description:
+ 'All available reference-doc topics as DocsListEntry[] ({topic, description}), in discovery order.',
+ },
+ {
+ type: 'docs.detail',
+ description:
+ "One topic's full ReferenceDoc, with token-ref blocks inlined.",
+ },
+ {
+ type: 'docs.detail.section',
+ description:
+ 'A single ReferenceSection of the topic — the first whose title contains the section query.',
+ },
+ ],
+ throws: [
+ {
+ code: 'ERR_UNKNOWN_TOPIC',
+ when: 'the topic is not a string or matches no known doc topic',
+ },
+ {
+ code: 'ERR_UNKNOWN_SECTION',
+ when: 'a section is requested but is empty or matches no section title in the topic',
+ },
+ ],
+ examples: [
+ {label: 'List topics', code: 'const r = await docs();'},
+ {label: 'Load a topic', code: "await docs('principles');"},
+ {label: 'One section', code: "await docs('tokens', 'spacing');"},
+ ],
+ command: 'docs',
+ related: ['search', 'component', 'hook', 'template'],
+};
diff --git a/packages/cli/api/doctor/doctor.doc.mjs b/packages/cli/api/doctor/doctor.doc.mjs
new file mode 100644
index 0000000000..c99b4c4c74
--- /dev/null
+++ b/packages/cli/api/doctor/doctor.doc.mjs
@@ -0,0 +1,49 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file FunctionDoc for `doctor()` / `astryx doctor`. Colocated with the API
+ * function it documents; the shape source of truth stays in `doctor.type.mjs`.
+ * @position packages/cli/api/doctor — function documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */
+export const doc = {
+ type: 'function',
+ kind: 'api',
+ name: 'doctor',
+ displayName: 'doctor()',
+ summary: 'Read-only project + environment health check.',
+ description:
+ 'Runs a series of side-effect-free diagnostics — Node version, ' +
+ '@astryxdesign/core install and version alignment with the CLI, installed ' +
+ 'themes and wiring, astryx.config validity, agent docs, core peer ' +
+ 'dependencies, and the detected package manager — and returns a structured ' +
+ 'report. It only reads (never installs, writes, or mutates), so it is safe ' +
+ 'as a CI gate and for agents to invoke.',
+ importPath: '@astryxdesign/cli/api',
+ signature: 'doctor(options?: DoctorOptions): Promise<DoctorResponse>',
+ keywords: ['doctor', 'diagnose', 'health', 'check', 'verify', 'environment'],
+ params: [
+ {
+ name: 'options.cwd',
+ type: 'string',
+ description: 'Directory to diagnose.',
+ },
+ ],
+ returns: [
+ {
+ type: 'doctor',
+ description:
+ 'The diagnostic report: `data.checks` — each with a stable id, label, `status` (`pass` | `warn` | `fail` | `info`), a one-line message, and a `fix` when the status is not `pass` — plus `data.summary` with counts per status.',
+ },
+ ],
+ examples: [
+ {label: 'Run diagnostics', code: 'const r = await doctor();'},
+ {
+ label: 'Diagnose a directory',
+ code: "await doctor({cwd: '/path/to/app'});",
+ },
+ ],
+ command: 'doctor',
+ related: ['init', 'upgrade'],
+};
diff --git a/packages/cli/api/hook/hook.doc.mjs b/packages/cli/api/hook/hook.doc.mjs
new file mode 100644
index 0000000000..bb516fea4d
--- /dev/null
+++ b/packages/cli/api/hook/hook.doc.mjs
@@ -0,0 +1,111 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file FunctionDoc for `hook()` / `astryx hook`. Colocated with the API
+ * function it documents; the shape source of truth stays in `hook.type.mjs`.
+ * @position packages/cli/api/hook — function documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */
+export const doc = {
+ type: 'function',
+ kind: 'api',
+ name: 'hook',
+ displayName: 'hook()',
+ summary:
+ 'Resolve a hook by name, or list the catalog, with an optional params-only slice.',
+ description:
+ "Routes on its arguments: a name returns that hook's full authored HookDoc; " +
+ 'no name (or `list`/`category`) returns the catalog grouped by category. The ' +
+ '`params` flag narrows a single hook to just its parameters table.',
+ importPath: '@astryxdesign/cli/api',
+ signature:
+ 'hook(name?: string, options?: HookOptions): Promise<HookListResponse | HookDetailResponse | HookDetailParamsResponse>',
+ keywords: ['hook', 'hooks', 'params', 'react', 'catalog'],
+ params: [
+ {
+ name: 'name',
+ type: 'string',
+ description:
+ "Hook name to resolve (e.g. 'useMediaQuery'). Omit to list the catalog.",
+ },
+ {
+ name: 'options.cwd',
+ type: 'string',
+ description: 'Directory to resolve @astryxdesign/core from.',
+ },
+ {
+ name: 'options.list',
+ type: 'boolean',
+ description: 'Return the grouped catalog instead of a single hook.',
+ },
+ {
+ name: 'options.category',
+ type: 'string',
+ description: 'List only hooks in this category.',
+ },
+ {
+ name: 'options.params',
+ type: 'boolean',
+ description: "Return only the hook's parameters table.",
+ },
+ {
+ name: 'options.detail',
+ type: "'full' | 'compact' | 'brief'",
+ description: 'Detail level for list views.',
+ default: "'full' for a named hook, 'brief' for list views",
+ },
+ {
+ name: 'options.lang',
+ type: 'string',
+ description: 'Language code for localized doc content.',
+ },
+ {
+ name: 'options.zh',
+ type: 'boolean',
+ description: 'Shorthand for Chinese (zh) doc content.',
+ },
+ ],
+ returns: [
+ {
+ type: 'hook.list',
+ description:
+ "The catalog grouped by category. data.detail is the level ('names' | 'compact' | 'full') and data.components is the grouped map — hook names, brief entries, or full HookDoc per entry.",
+ },
+ {
+ type: 'hook.detail',
+ description: "One hook's full authored HookDoc.",
+ },
+ {
+ type: 'hook.detail.params',
+ description: "Just the hook's parameters table (HookParamDoc[]).",
+ },
+ ],
+ throws: [
+ {
+ code: 'ERR_CORE_NOT_FOUND',
+ when: '@astryxdesign/core cannot be resolved from cwd',
+ },
+ {
+ code: 'ERR_UNKNOWN_CATEGORY',
+ when: 'options.category is not a string or matches no known category',
+ },
+ {
+ code: 'ERR_UNKNOWN_HOOK',
+ when: 'name is not a string or resolves to no known hook',
+ },
+ ],
+ examples: [
+ {label: 'Look up a hook', code: "const r = await hook('useMediaQuery');"},
+ {
+ label: 'Params only',
+ code: "await hook('useMediaQuery', {params: true});",
+ },
+ {
+ label: 'Browse a category',
+ code: "await hook(undefined, {category: 'State', detail: 'compact'});",
+ },
+ ],
+ command: 'hook',
+ related: ['search', 'component', 'docs', 'template'],
+};
diff --git a/packages/cli/api/init/init.doc.mjs b/packages/cli/api/init/init.doc.mjs
new file mode 100644
index 0000000000..0c247e341e
--- /dev/null
+++ b/packages/cli/api/init/init.doc.mjs
@@ -0,0 +1,100 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file FunctionDoc for `init()` / `astryx init`. Colocated with the API
+ * function it documents; the shape source of truth stays in `init.type.mjs`.
+ * @position packages/cli/api/init — function documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */
+export const doc = {
+ type: 'function',
+ kind: 'api',
+ name: 'init',
+ displayName: 'init()',
+ summary:
+ 'Non-interactive project setup: install agent docs and point at the theme + build workflows.',
+ description:
+ 'Sets a project up with NO prompts, so it behaves identically for humans, ' +
+ 'agents, CI, and piped I/O. By default it installs the AGENTS.md/CLAUDE.md ' +
+ 'agent-docs cheat sheet and prints getting-started guidance; `features` / ' +
+ '`all` add theme and page-building guidance and can scaffold a starter ' +
+ 'template. With `removeAgents` it removes the managed agent-docs block ' +
+ 'instead of installing.',
+ importPath: '@astryxdesign/cli/api',
+ signature:
+ 'init(options?: InitOptions, ctx?: {cwd?: string}): Promise<InitRunResponse | InitRemoveResponse>',
+ keywords: ['init', 'setup', 'install', 'scaffold', 'agents', 'bootstrap'],
+ params: [
+ {
+ name: 'options.features',
+ type: 'string',
+ description:
+ 'Comma-separated features to install: agents, theme, template.',
+ },
+ {
+ name: 'options.all',
+ type: 'boolean',
+ description: 'Install all features (agents, theme, template).',
+ },
+ {
+ name: 'options.removeAgents',
+ type: 'boolean',
+ description: 'Remove the managed agent-docs block instead of installing.',
+ },
+ {
+ name: 'options.agent',
+ type: 'string',
+ description: 'Agent preset: claude, cursor, codex, hermes, all.',
+ },
+ {
+ name: 'options.agentDocsPath',
+ type: 'string | string[]',
+ description: 'Explicit agent-docs file path(s) to write.',
+ },
+ {
+ name: 'options.templateName',
+ type: 'string',
+ description:
+ 'Scaffold a named page template (programmatic only; the CLI never sets it).',
+ },
+ {name: 'ctx.cwd', type: 'string', description: 'Directory to set up.'},
+ ],
+ returns: [
+ {
+ type: 'init.run',
+ description:
+ 'The install receipt: the `mode` (`default` | `features`), the features run, agent-doc files written, any soft docsError, whether theme guidance was emitted, the template outcome (`workflow` | `created` | `skipped`) plus its path, and whether the next-steps were emitted.',
+ },
+ {
+ type: 'init.remove',
+ description:
+ 'Confirmation that the managed agent-docs block was removed (`data.removed: true`) — returned when `removeAgents` is set.',
+ },
+ ],
+ throws: [
+ {
+ code: 'ERR_UNKNOWN_AGENT',
+ when: '`agent` is not one of claude, cursor, codex, hermes, all',
+ },
+ {
+ code: 'ERR_UNKNOWN_FEATURE',
+ when: '`features` contains a name other than agents, theme, or template',
+ },
+ {
+ code: 'ERR_UNKNOWN_TEMPLATE',
+ when: '`templateName` matches no bundled template',
+ },
+ {
+ code: 'ERR_FILE_EXISTS',
+ when: 'scaffolding a template would overwrite an existing page.tsx',
+ },
+ ],
+ examples: [
+ {label: 'Default setup', code: 'const r = await init();'},
+ {label: 'All features', code: 'await init({all: true});'},
+ {label: 'Remove agent docs', code: 'await init({removeAgents: true});'},
+ ],
+ command: 'init',
+ related: ['doctor', 'upgrade', 'build', 'theme'],
+};
diff --git a/packages/cli/api/integration/summarizeIssues.doc.mjs b/packages/cli/api/integration/summarizeIssues.doc.mjs
new file mode 100644
index 0000000000..a658c57332
--- /dev/null
+++ b/packages/cli/api/integration/summarizeIssues.doc.mjs
@@ -0,0 +1,59 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file FunctionDoc for `summarizeIssues()` — the severity-tally helper paired
+ * with `validateIntegration`. Colocated with the API function it documents; the
+ * source of truth is the function in `validate-integration.mjs`.
+ * @position packages/cli/api/integration — function documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */
+export const doc = {
+ type: 'function',
+ kind: 'api',
+ name: 'summarizeIssues',
+ displayName: 'summarizeIssues()',
+ summary:
+ 'Tally integration issues by severity into error and warning counts.',
+ description:
+ 'A synchronous helper that reduces an AstryxIntegrationIssue[] (as returned ' +
+ 'by validateIntegration) to counts of errors and warnings — the seam a ' +
+ 'caller uses to decide an exit code or print a summary line. Issues of any ' +
+ 'other severity are ignored.',
+ importPath: '@astryxdesign/cli/api',
+ signature:
+ 'summarizeIssues(issues: AstryxIntegrationIssue[]): {errors: number, warnings: number}',
+ keywords: ['integration', 'issues', 'summarize', 'count', 'severity'],
+ params: [
+ {
+ name: 'issues',
+ type: 'AstryxIntegrationIssue[]',
+ description:
+ 'The issues to tally (e.g. `data.issues` from validateIntegration).',
+ required: true,
+ },
+ ],
+ returns: [
+ {
+ name: 'errors',
+ type: 'number',
+ description: 'Count of issues with severity "error".',
+ },
+ {
+ name: 'warnings',
+ type: 'number',
+ description: 'Count of issues with severity "warning".',
+ },
+ ],
+ examples: [
+ {
+ label: 'Tally issues',
+ code: 'const {errors, warnings} = summarizeIssues(issues);',
+ },
+ {
+ label: 'Gate on errors',
+ code: 'const {errors} = summarizeIssues(result.data.issues);',
+ },
+ ],
+ related: ['validateIntegration'],
+};
diff --git a/packages/cli/api/integration/validateIntegration.doc.mjs b/packages/cli/api/integration/validateIntegration.doc.mjs
new file mode 100644
index 0000000000..911c7dc8a7
--- /dev/null
+++ b/packages/cli/api/integration/validateIntegration.doc.mjs
@@ -0,0 +1,63 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file FunctionDoc for `validateIntegration()` / `astryx validate-integration`.
+ * Colocated with the API function it documents; the shape source of truth stays
+ * in `validate-integration.type.mjs`.
+ * @position packages/cli/api/integration — function documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */
+export const doc = {
+ type: 'function',
+ kind: 'api',
+ name: 'validateIntegration',
+ displayName: 'validateIntegration()',
+ summary:
+ 'Validate a single Astryx integration package and report its issues.',
+ description:
+ 'Validates exactly ONE integration at a time: the local package rooted at ' +
+ 'cwd (no `pkg`), or an installed package resolved from cwd/node_modules ' +
+ '(`pkg` given). It loads and schema-checks the manifest, verifies each ' +
+ 'declared contribution root exists, and runs the codemod/template/component ' +
+ 'validators, returning every finding as an AstryxIntegrationIssue. A missing ' +
+ 'local manifest is guidance (name null, no issues), not an error, so callers ' +
+ 'can stay exit-0 in a non-integration directory.',
+ importPath: '@astryxdesign/cli/api',
+ signature:
+ 'validateIntegration(pkg?: string, options?: ValidateIntegrationOptions): Promise<ValidateIntegrationResponse>',
+ keywords: ['integration', 'validate', 'manifest', 'lint', 'check'],
+ params: [
+ {
+ name: 'pkg',
+ type: 'string',
+ description:
+ 'Installed package name to validate; omit to validate the package rooted at cwd.',
+ },
+ {
+ name: 'options.cwd',
+ type: 'string',
+ description:
+ 'Directory to resolve the local package / node_modules from.',
+ },
+ ],
+ returns: [
+ {
+ type: 'integration.validate',
+ description:
+ 'The result envelope: `data.name` and `data.version` of the validated package (both null when no local manifest is found), plus `data.issues` — an AstryxIntegrationIssue[] of {code, severity: `warning` | `error`, message}.',
+ },
+ ],
+ examples: [
+ {
+ label: 'Validate the local package',
+ code: 'const r = await validateIntegration();',
+ },
+ {
+ label: 'Validate an installed package',
+ code: "await validateIntegration('@acme/astryx-integration');",
+ },
+ ],
+ command: 'validate-integration',
+ related: ['summarizeIssues', 'doctor', 'upgrade'],
+};
diff --git a/packages/cli/api/json/assertResponse.doc.mjs b/packages/cli/api/json/assertResponse.doc.mjs
new file mode 100644
index 0000000000..08f582778a
--- /dev/null
+++ b/packages/cli/api/json/assertResponse.doc.mjs
@@ -0,0 +1,62 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file FunctionDoc for `assertResponse()`. Colocated with the consumer helper it
+ * documents; the response shapes it asserts are re-exported from `index.ts`.
+ * @position packages/cli/api/json — function documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */
+export const doc = {
+ type: 'function',
+ kind: 'api',
+ name: 'assertResponse',
+ displayName: 'assertResponse()',
+ summary:
+ 'Parse and assert one expected response type, throwing on an error or a mismatch.',
+ description:
+ 'The strict alternative to parseResponse + manual narrowing: it parses, rethrows a ' +
+ 'CLIError as an Error carrying the CLI message, and rejects any envelope whose `type` ' +
+ 'is not the one you asked for. Use it when a call site expects exactly one response ' +
+ 'type and any other outcome is a bug worth failing on.',
+ importPath: '@astryxdesign/cli/json',
+ signature: 'assertResponse(raw: unknown, expectedType: string): any',
+ keywords: ['json', 'assert', 'narrow', 'subprocess', 'envelope'],
+ params: [
+ {
+ name: 'raw',
+ type: 'unknown',
+ description:
+ 'The CLI stdout to parse — a JSON string, or an object that was already parsed.',
+ required: true,
+ },
+ {
+ name: 'expectedType',
+ type: 'string',
+ description:
+ "The response discriminant the caller requires (e.g. 'component.detail').",
+ required: true,
+ },
+ ],
+ returns: [
+ {
+ type: 'any',
+ description:
+ 'The parsed envelope, guaranteed at runtime to carry the requested `type`. The published signature is untyped — cast to the matching *Response type for typed access.',
+ },
+ ],
+ throws: [
+ {
+ code: 'Error',
+ when: 'the CLI returned an error envelope (the CLI message is rethrown), or the response `type` is not expectedType',
+ },
+ ],
+ examples: [
+ {
+ label: 'Require one type',
+ code:
+ "const r = assertResponse(stdout, 'component.detail');\nr.data.name; // safe: any other outcome threw",
+ },
+ ],
+ related: ['parseResponse', 'isError'],
+};
diff --git a/packages/cli/api/json/isError.doc.mjs b/packages/cli/api/json/isError.doc.mjs
new file mode 100644
index 0000000000..a76e4bf2c9
--- /dev/null
+++ b/packages/cli/api/json/isError.doc.mjs
@@ -0,0 +1,47 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file FunctionDoc for `isError()`. Colocated with the consumer helper it
+ * documents; the CLIError shape is re-exported from `index.ts`.
+ * @position packages/cli/api/json — function documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */
+export const doc = {
+ type: 'function',
+ kind: 'api',
+ name: 'isError',
+ displayName: 'isError()',
+ summary: 'Did the CLI return an error envelope?',
+ description:
+ 'Tests a parsed response for an `error` key. Branch on this before touching `data` — ' +
+ 'and prefer the stable `code` field over matching the human-readable message, which is ' +
+ 'not a contract. Note this returns a plain boolean, not a TypeScript type predicate, so ' +
+ 'it does not narrow on its own: cast to the matching *Response type to get typed access.',
+ importPath: '@astryxdesign/cli/json',
+ signature: 'isError(result: unknown): boolean',
+ keywords: ['json', 'error', 'guard', 'narrow', 'subprocess'],
+ params: [
+ {
+ name: 'result',
+ type: 'unknown',
+ description: 'A parsed response envelope, typically from parseResponse().',
+ required: true,
+ },
+ ],
+ returns: [
+ {
+ type: 'boolean',
+ description:
+ 'True when the value is a non-null object carrying an `error` key (a CLIError envelope).',
+ },
+ ],
+ examples: [
+ {
+ label: 'Branch on the stable code',
+ code:
+ "const result = parseResponse(stdout);\nif (isError(result)) {\n if (result.code === 'ERR_UNKNOWN_COMPONENT') suggest(result.suggestions);\n}",
+ },
+ ],
+ related: ['parseResponse', 'assertResponse'],
+};
diff --git a/packages/cli/api/json/parseResponse.doc.mjs b/packages/cli/api/json/parseResponse.doc.mjs
new file mode 100644
index 0000000000..2113887c7b
--- /dev/null
+++ b/packages/cli/api/json/parseResponse.doc.mjs
@@ -0,0 +1,54 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file FunctionDoc for `parseResponse()`. Colocated with the consumer helper it
+ * documents; the response shapes it yields are re-exported from `index.ts`.
+ * @position packages/cli/api/json — function documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */
+export const doc = {
+ type: 'function',
+ kind: 'api',
+ name: 'parseResponse',
+ displayName: 'parseResponse()',
+ summary: 'Parse `astryx --json` stdout into the structural response envelope.',
+ description:
+ 'The entry point for consuming the CLI as a subprocess. A JSON string is parsed; ' +
+ 'an already-parsed object is passed through unchanged, so it is safe to call on ' +
+ 'either. It returns the structural { type, data, meta? } envelope without narrowing: ' +
+ '`data` stays unknown until you discriminate on `type` (or use assertResponse).',
+ importPath: '@astryxdesign/cli/json',
+ signature: 'parseResponse(raw: unknown): any',
+ keywords: ['json', 'parse', 'subprocess', 'envelope', 'stdout'],
+ params: [
+ {
+ name: 'raw',
+ type: 'unknown',
+ description:
+ 'The CLI stdout to parse — a JSON string, or an object that was already parsed.',
+ required: true,
+ },
+ ],
+ returns: [
+ {
+ type: 'any',
+ description:
+ 'The { type, data, meta? } envelope, or a CLIError envelope. The published signature is intentionally untyped — narrow it by casting to the matching *Response type exported from @astryxdesign/cli/json.',
+ },
+ ],
+ throws: [
+ {
+ code: 'SyntaxError',
+ when: 'raw is a string that is not valid JSON (surfaced from JSON.parse)',
+ },
+ ],
+ examples: [
+ {
+ label: 'Parse then narrow',
+ code:
+ "const result = parseResponse(stdout);\nif (isError(result)) throw new Error(result.error);",
+ },
+ ],
+ related: ['isError', 'assertResponse'],
+};
diff --git a/packages/cli/api/layout/layoutCheck.doc.mjs b/packages/cli/api/layout/layoutCheck.doc.mjs
new file mode 100644
index 0000000000..724cff169c
--- /dev/null
+++ b/packages/cli/api/layout/layoutCheck.doc.mjs
@@ -0,0 +1,84 @@
+// 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',
+ 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.mjs
new file mode 100644
index 0000000000..41afe6948a
--- /dev/null
+++ b/packages/cli/api/layout/layoutExpand.doc.mjs
@@ -0,0 +1,106 @@
+// 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',
+ 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 directory gets <name>.tsx; a file path is used as-is. 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.mjs
new file mode 100644
index 0000000000..f062a1763e
--- /dev/null
+++ b/packages/cli/api/layout/layoutGrammar.doc.mjs
@@ -0,0 +1,56 @@
+// 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',
+ 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/search/search.doc.mjs b/packages/cli/api/search/search.doc.mjs
new file mode 100644
index 0000000000..bfa197776b
--- /dev/null
+++ b/packages/cli/api/search/search.doc.mjs
@@ -0,0 +1,71 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file FunctionDoc for `search()` / `astryx search`. Colocated with the API
+ * function it documents; the shape source of truth stays in `search.type.mjs`.
+ * @position packages/cli/api/search — function documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */
+export const doc = {
+ type: 'function',
+ kind: 'api',
+ name: 'search',
+ displayName: 'search()',
+ summary:
+ 'Unified ranked search across components, hooks, docs, and templates.',
+ description:
+ 'The single "I\'m looking for X" entry point across every content domain. ' +
+ 'Ranking is keyword + fuzzy (not embeddings); name and keyword signals outrank ' +
+ 'incidental prose mentions, so an exact match always sorts first.',
+ importPath: '@astryxdesign/cli/api',
+ signature:
+ 'search(query: string, options?: SearchOptions): Promise<SearchResponse>',
+ keywords: ['search', 'find', 'lookup', 'discover'],
+ params: [
+ {
+ name: 'query',
+ type: 'string',
+ description: 'Free-text search term.',
+ required: true,
+ },
+ {
+ name: 'options.type',
+ type: "'component' | 'hook' | 'doc' | 'template'",
+ description: 'Restrict results to a single domain.',
+ },
+ {
+ name: 'options.limit',
+ type: 'number',
+ description: 'Maximum number of results.',
+ default: '20',
+ },
+ {
+ name: 'options.cwd',
+ type: 'string',
+ description: 'Directory to resolve @astryxdesign/core from.',
+ },
+ ],
+ returns: [
+ {
+ type: 'search',
+ description:
+ 'The query echoed back plus a ranked SearchResultEntry[] (domain, name, score, reason, description, follow-up command, and import path where relevant).',
+ },
+ ],
+ throws: [
+ {
+ code: 'ERR_INVALID_ARGUMENT',
+ when: 'the query is empty, --type is unknown, or --limit is not a positive integer',
+ },
+ ],
+ examples: [
+ {label: 'Find a component', code: "const r = await search('button');"},
+ {
+ label: 'Restrict + limit',
+ code: "await search('data table', {type: 'template', limit: 5});",
+ },
+ ],
+ command: 'search',
+ related: ['component', 'hook', 'docs', 'template', 'build'],
+};
diff --git a/packages/cli/api/swizzle/swizzle.doc.mjs b/packages/cli/api/swizzle/swizzle.doc.mjs
new file mode 100644
index 0000000000..598bb13923
--- /dev/null
+++ b/packages/cli/api/swizzle/swizzle.doc.mjs
@@ -0,0 +1,119 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file FunctionDoc for `swizzle()` / `astryx swizzle`. Colocated with the API
+ * function it documents; the shape source of truth stays in `swizzle.type.mjs`.
+ * @position packages/cli/api/swizzle — function documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */
+export const doc = {
+ type: 'function',
+ kind: 'api',
+ name: 'swizzle',
+ displayName: 'swizzle()',
+ summary: "Eject a component's source into your project for customization.",
+ description:
+ "Ejects a component's source into the consumer project for deep customization. " +
+ 'It copies from the locally resolved @astryxdesign/core (or the owning integration) ' +
+ 'package source, rewriting imports that escape the component directory to the owner ' +
+ "package's subpaths and flagging whether any copied file uses StyleX. With no name " +
+ '(or list) it returns the swizzlable component names instead.',
+ importPath: '@astryxdesign/cli/api',
+ signature:
+ 'swizzle(component?: string, options?: SwizzleOptions): Promise<SwizzleListResponse | SwizzleCopyResponse>',
+ keywords: ['swizzle', 'eject', 'copy', 'customize', 'source', 'override'],
+ params: [
+ {
+ name: 'component',
+ type: 'string',
+ description:
+ 'Bare or XDS-prefixed component name to copy. Omit to list the swizzlable components.',
+ },
+ {
+ name: 'options.cwd',
+ type: 'string',
+ description: 'Directory to resolve @astryxdesign/core from.',
+ },
+ {
+ name: 'options.output',
+ type: 'string',
+ description: 'Output directory; must resolve inside cwd.',
+ default: "'./components/astryx'",
+ },
+ {
+ name: 'options.package',
+ type: 'string',
+ description:
+ 'Owning package to copy from when the name is provided by more than one.',
+ },
+ {
+ name: 'options.list',
+ type: 'boolean',
+ description:
+ 'Force the list response even when a component argument is given.',
+ default: 'false',
+ },
+ {
+ name: 'options.overwrite',
+ type: 'boolean',
+ description: 'Overwrite existing files instead of erroring.',
+ default: 'false',
+ },
+ ],
+ returns: [
+ {
+ type: 'swizzle.list',
+ description:
+ "The names of swizzlable components discoverable from cwd's @astryxdesign/core.",
+ },
+ {
+ type: 'swizzle.copy',
+ description:
+ 'A receipt after copying the component into the project: the component name, owning package, output directory, files-copied count, the written file names, whether any file uses StyleX, and an optional maintainer-feedback note.',
+ },
+ ],
+ throws: [
+ {
+ code: 'ERR_CORE_NOT_FOUND',
+ when: '@astryxdesign/core cannot be located from cwd',
+ },
+ {
+ code: 'ERR_PATH_TRAVERSAL',
+ when: 'the component name contains a path separator or traversal, or output resolves outside cwd',
+ },
+ {
+ code: 'ERR_UNKNOWN_COMPONENT',
+ when: 'no package provides the component, or the named package does not provide it',
+ },
+ {
+ code: 'ERR_AMBIGUOUS_COMPONENT',
+ when: 'more than one package provides the component — choose one with package',
+ },
+ {
+ code: 'ERR_NO_SOURCE',
+ when: 'the owning package has no source directory for the component on disk',
+ },
+ {
+ code: 'ERR_FILE_EXISTS',
+ when: 'copying would overwrite existing files and overwrite is not set',
+ },
+ ],
+ examples: [
+ {
+ label: 'List swizzlable components',
+ code: 'const {data} = await swizzle();',
+ },
+ {label: 'Eject a component', code: "await swizzle('Button');"},
+ {
+ label: 'Disambiguate by package',
+ code: "await swizzle('Button', {package: '@astryxdesign/core'});",
+ },
+ {
+ label: 'Custom output directory',
+ code: "await swizzle('Card', {output: './src/ui', overwrite: true});",
+ },
+ ],
+ command: 'swizzle',
+ related: ['component', 'discover', 'upgrade'],
+};
diff --git a/packages/cli/api/template/template.doc.mjs b/packages/cli/api/template/template.doc.mjs
new file mode 100644
index 0000000000..f6375f027a
--- /dev/null
+++ b/packages/cli/api/template/template.doc.mjs
@@ -0,0 +1,142 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file FunctionDoc for `template()` / `astryx template`. Colocated with the API
+ * function it documents; the shape source of truth stays in `template.type.mjs`.
+ * @position packages/cli/api/template — function documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */
+export const doc = {
+ type: 'function',
+ kind: 'api',
+ name: 'template',
+ displayName: 'template()',
+ summary: 'List, inspect, or scaffold page and block templates.',
+ description:
+ 'One entry point for the template family: with no name it lists the discovered ' +
+ "templates; with a name it returns that template's source, a layout skeleton, or " +
+ 'scaffolds it into the project. Templates are discovered across core, external ' +
+ 'packages, and integrations, so the same id can appear in more than one place — ' +
+ 'narrow an ambiguous name with type and/or package.',
+ importPath: '@astryxdesign/cli/api',
+ signature:
+ 'template(name?: string, options?: TemplateOptions): Promise<TemplateListResponse | TemplateShowResponse | TemplateSkeletonResponse | TemplateCopyResponse>',
+ keywords: ['template', 'scaffold', 'page', 'block', 'skeleton', 'starter'],
+ params: [
+ {
+ name: 'name',
+ type: 'string',
+ description:
+ 'Template id to resolve. Omit to list every discovered template.',
+ },
+ {
+ name: 'options.list',
+ type: 'boolean',
+ description: 'Force the list response even when a name is given.',
+ default: 'false',
+ },
+ {
+ name: 'options.skeleton',
+ type: 'boolean',
+ description:
+ 'Return a compact layout skeleton (structural tags with spatial annotations) instead of the full source.',
+ default: 'false',
+ },
+ {
+ name: 'options.show',
+ type: 'boolean',
+ description:
+ 'Return the template source. This is the default for a named lookup with no target path.',
+ default: 'false',
+ },
+ {
+ name: 'options.type',
+ type: "'page' | 'block'",
+ description:
+ 'Filter list views, or narrow an ambiguous name, to a single template kind.',
+ },
+ {
+ name: 'options.package',
+ type: 'string',
+ description:
+ 'Narrow lookups to templates from a specific owning package (core templates report @astryxdesign/core).',
+ },
+ {
+ name: 'options.targetPath',
+ type: 'string',
+ description:
+ 'Destination (relative to cwd) to scaffold the template into. Its presence switches a named lookup into a copy.',
+ },
+ {
+ name: 'options.overwrite',
+ type: 'boolean',
+ description: 'Overwrite an existing target file instead of erroring.',
+ default: 'false',
+ },
+ {
+ name: 'options.cwd',
+ type: 'string',
+ description:
+ 'Directory to discover templates and resolve the target path from.',
+ },
+ ],
+ returns: [
+ {
+ type: 'template.list',
+ description:
+ 'Every discovered template (page + block); each entry carries id, name, description, kind, owning package, optional category and componentsUsed, and readiness flags. Filtered by type/package when provided.',
+ },
+ {
+ type: 'template.show',
+ description:
+ "The resolved template's raw source plus its description, kind, and the component names it composes.",
+ },
+ {
+ type: 'template.skeleton',
+ description:
+ "A layout skeleton — structural tags with spatial annotations — plus the template's description and the components it composes.",
+ },
+ {
+ type: 'template.copy',
+ description:
+ 'A receipt after scaffolding the template into the project: the template id, output directory, written file name, and file count.',
+ },
+ ],
+ throws: [
+ {
+ code: 'ERR_UNKNOWN_TEMPLATE',
+ when: 'the named template does not exist, or --skeleton is run without a name',
+ },
+ {
+ code: 'ERR_AMBIGUOUS_TEMPLATE',
+ when: 'the name matches more than one template across kinds/packages — narrow it with type and/or package',
+ },
+ {
+ code: 'ERR_NO_SOURCE',
+ when: 'the resolved template has no source file on disk',
+ },
+ {
+ code: 'ERR_PATH_TRAVERSAL',
+ when: 'the copy target path is absolute or escapes the project root',
+ },
+ {
+ code: 'ERR_FILE_EXISTS',
+ when: 'the copy target already exists and overwrite is not set',
+ },
+ ],
+ examples: [
+ {label: 'List templates', code: 'const {data} = await template();'},
+ {label: 'Show source', code: "await template('dashboard');"},
+ {
+ label: 'Layout skeleton',
+ code: "await template('dashboard', {skeleton: true});",
+ },
+ {
+ label: 'Scaffold into the project',
+ code: "await template('dashboard', {targetPath: './app/page.tsx'});",
+ },
+ ],
+ command: 'template',
+ related: ['component', 'search', 'discover', 'init'],
+};
diff --git a/packages/cli/api/theme/listThemes.doc.mjs b/packages/cli/api/theme/listThemes.doc.mjs
new file mode 100644
index 0000000000..89567f131c
--- /dev/null
+++ b/packages/cli/api/theme/listThemes.doc.mjs
@@ -0,0 +1,44 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file FunctionDoc for the `listThemes()` helper. Colocated with the theme
+ * command's shared data layer (`_adapter.mjs`); the BundledTheme shape lives
+ * there. This helper has no CLI command of its own — themeList and themeAdd
+ * sit on it.
+ * @position packages/cli/api/theme — function documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */
+export const doc = {
+ type: 'function',
+ kind: 'api',
+ name: 'listThemes',
+ displayName: 'listThemes()',
+ summary: 'Read the bundled-theme manifest and return its raw entries.',
+ description:
+ "The shared data layer behind theme list/add — reads the CLI's bundled-theme manifest " +
+ '(templates/themes/manifest.json, generated by scripts/generate-cli-themes.mjs) and returns ' +
+ 'the parsed entries. themeList() projects this into the theme.list envelope; themeAdd() ' +
+ 'resolves a slug against it. Returns synchronously.',
+ importPath: '@astryxdesign/cli/api',
+ signature: 'listThemes(): BundledTheme[]',
+ keywords: ['theme', 'themes', 'manifest', 'bundled', 'adapter', 'list'],
+ params: [],
+ returns: [
+ {
+ type: 'BundledTheme[]',
+ description:
+ 'The parsed themes array from the bundle manifest — each BundledTheme has slug, displayName, description, maintained, entry, exportName, and files. Empty when the manifest has not been generated.',
+ },
+ ],
+ throws: [
+ {
+ code: 'ERR_NO_SOURCE',
+ when: 'the manifest file exists but cannot be read or parsed as JSON',
+ },
+ ],
+ examples: [
+ {label: 'Read the manifest', code: 'const themes = listThemes();'},
+ ],
+ related: ['themeList', 'themeAdd', 'themeBuild'],
+};
diff --git a/packages/cli/api/theme/themeAdd.doc.mjs b/packages/cli/api/theme/themeAdd.doc.mjs
new file mode 100644
index 0000000000..b2a1051cc0
--- /dev/null
+++ b/packages/cli/api/theme/themeAdd.doc.mjs
@@ -0,0 +1,92 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file FunctionDoc for `themeAdd()` / `astryx theme add`. Colocated with the
+ * API function it documents; the response-shape source of truth stays in
+ * `theme.type.mjs`.
+ * @position packages/cli/api/theme — function documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */
+export const doc = {
+ type: 'function',
+ kind: 'api',
+ name: 'themeAdd',
+ displayName: 'themeAdd()',
+ summary: 'Scaffold a bundled theme into a project as editable source.',
+ description:
+ "Copies a bundled theme's source (from the CLI's templates/themes/<slug>) into the " +
+ "consumer's project so they own it — no theme package needed. Writes are staged to temp " +
+ 'files then renamed, rolling back partials on failure so a failed write never leaves a ' +
+ 'half-written theme. Returns a theme.add receipt describing where the files landed and how ' +
+ 'to import them.',
+ importPath: '@astryxdesign/cli/api',
+ signature:
+ 'themeAdd(slug: string, options?: {targetPath?: string, overwrite?: boolean, cwd?: string}): Promise<ThemeAddResponse>',
+ keywords: ['theme', 'add', 'scaffold', 'copy', 'eject', 'starter'],
+ params: [
+ {
+ name: 'slug',
+ type: 'string',
+ description:
+ 'Slug of the bundled theme to scaffold (matched case-insensitively).',
+ required: true,
+ },
+ {
+ name: 'options.targetPath',
+ type: 'string',
+ description:
+ 'Destination directory for the copied files. Must resolve within cwd.',
+ default: "'src/themes/<slug>'",
+ },
+ {
+ name: 'options.overwrite',
+ type: 'boolean',
+ description:
+ 'Replace existing files instead of refusing when a destination file already exists.',
+ default: 'false',
+ },
+ {
+ name: 'options.cwd',
+ type: 'string',
+ description: 'Directory the target path resolves against.',
+ },
+ ],
+ returns: [
+ {
+ type: 'theme.add',
+ description:
+ 'Scaffold receipt: the resolved slug, displayName, whether the theme is maintained, the outputDir the copy landed in (relative to cwd), the theme entry file, its exportName, and the list of files written.',
+ },
+ {
+ type: 'theme.list',
+ description:
+ 'The `theme add` command also lists: a bare `astryx theme add` (no slug) or `--list` routes to themeList() and returns every bundled theme (slug, displayName, description, maintained).',
+ },
+ ],
+ throws: [
+ {code: 'ERR_UNKNOWN_THEME', when: 'no bundled theme matches the slug'},
+ {code: 'ERR_PATH_TRAVERSAL', when: 'the target path escapes cwd'},
+ {
+ code: 'ERR_NO_SOURCE',
+ when: 'a bundled file for the theme is missing from this CLI build',
+ },
+ {
+ code: 'ERR_FILE_EXISTS',
+ when: 'a destination file already exists and overwrite is not set',
+ },
+ {
+ code: 'ERR_WRITE_FAILED',
+ when: 'writing the files fails (staged temp files are rolled back)',
+ },
+ ],
+ examples: [
+ {label: 'Scaffold a theme', code: "const r = await themeAdd('ocean');"},
+ {
+ label: 'Custom target + overwrite',
+ code: "await themeAdd('ocean', {targetPath: 'src/theme', overwrite: true});",
+ },
+ ],
+ command: 'theme add',
+ related: ['themeList', 'listThemes', 'themeBuild'],
+};
diff --git a/packages/cli/api/theme/themeBuild.doc.mjs b/packages/cli/api/theme/themeBuild.doc.mjs
new file mode 100644
index 0000000000..5fd556d821
--- /dev/null
+++ b/packages/cli/api/theme/themeBuild.doc.mjs
@@ -0,0 +1,108 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file FunctionDoc for `themeBuild()` / `astryx theme build`. Colocated with
+ * the API function it documents; the response-shape source of truth stays in
+ * `theme.type.mjs`.
+ * @position packages/cli/api/theme — function documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */
+export const doc = {
+ type: 'function',
+ kind: 'api',
+ name: 'themeBuild',
+ displayName: 'themeBuild()',
+ summary: 'Compile a defineTheme file to CSS + JS + type declarations.',
+ description:
+ 'The compiler behind `astryx theme build`. Reads a file that calls defineTheme() and, ' +
+ "via @astryxdesign/core's shared generator (the single source of truth, so the build " +
+ 'emits the exact CSS the <Theme> runtime does), writes a scoped CSS file, a JS module ' +
+ 'that re-exports the built theme, and a .d.ts (plus an optional .variants.d.ts when the ' +
+ 'theme adds custom prop values). With {check: true} it writes nothing and instead compares ' +
+ 'each output against disk, returning the drift — the CI guard for committed, generated theme CSS.',
+ importPath: '@astryxdesign/cli/api',
+ signature:
+ 'themeBuild(file: string, options?: {out?: string, check?: boolean}, ctx?: {cwd?: string}): Promise<ThemeBuildResponse | ThemeBuildCheckResponse | null>',
+ keywords: [
+ 'theme',
+ 'build',
+ 'compile',
+ 'css',
+ 'defineTheme',
+ 'check',
+ 'drift',
+ ],
+ params: [
+ {
+ name: 'file',
+ type: 'string',
+ description:
+ 'Path to a theme file that calls defineTheme(), resolved against cwd.',
+ required: true,
+ },
+ {
+ name: 'options.out',
+ type: 'string',
+ description:
+ 'Override the output CSS path; the sibling .js and .d.ts derive from it. A relative path must stay within cwd.',
+ },
+ {
+ name: 'options.check',
+ type: 'boolean',
+ description:
+ 'Compile in memory and compare each output against what is on disk instead of writing — the CI drift guard.',
+ default: 'false',
+ },
+ {
+ name: 'ctx.cwd',
+ type: 'string',
+ description:
+ 'Directory the theme file and @astryxdesign/core resolve against.',
+ },
+ ],
+ returns: [
+ {
+ type: 'theme.build',
+ description:
+ 'Build receipt: theme name, token- and component-override counts, output size in KB, the written outputs {css, js, dts, and variantsDts when custom prop values were augmented}, and any validation warnings. Resolves to null instead when the theme produced no CSS (nothing to build).',
+ },
+ {
+ type: 'theme.build.check',
+ description:
+ 'The {check: true} receipt: theme name, an upToDate flag, the stale outputs (each {path, reason: "missing" | "outdated"}), and the full list of checked paths. Writes nothing.',
+ },
+ ],
+ throws: [
+ {code: 'ERR_FILE_NOT_FOUND', when: 'the theme file does not exist'},
+ {
+ code: 'ERR_THEME_LOAD',
+ when: 'the file cannot be loaded or parsed into a defineTheme() result',
+ },
+ {code: 'ERR_THEME_INVALID', when: 'the resolved theme has no name'},
+ {
+ code: 'ERR_PATH_TRAVERSAL',
+ when: 'the theme name contains a path separator or traversal marker',
+ },
+ {
+ code: 'ERR_CORE_NOT_FOUND',
+ when: '@astryxdesign/core/theme cannot be imported — a built, resolvable @astryxdesign/core is required',
+ },
+ {
+ code: 'ERR_WRITE_FAILED',
+ when: 'writing the outputs fails (staged temp files are rolled back)',
+ },
+ ],
+ examples: [
+ {
+ label: 'Build a theme',
+ code: "const r = await themeBuild('src/themes/ocean.ts');",
+ },
+ {
+ label: 'Check for drift (CI)',
+ code: "const r = await themeBuild('src/themes/ocean.ts', {check: true});",
+ },
+ ],
+ command: 'theme build',
+ related: ['themeAdd', 'themeList', 'listThemes'],
+};
diff --git a/packages/cli/api/theme/themeList.doc.mjs b/packages/cli/api/theme/themeList.doc.mjs
new file mode 100644
index 0000000000..763e98a6fb
--- /dev/null
+++ b/packages/cli/api/theme/themeList.doc.mjs
@@ -0,0 +1,43 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file FunctionDoc for `themeList()` / `astryx theme list`. Colocated with the
+ * API function it documents; the response-shape source of truth stays in
+ * `theme.type.mjs`.
+ * @position packages/cli/api/theme — function documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */
+export const doc = {
+ type: 'function',
+ kind: 'api',
+ name: 'themeList',
+ displayName: 'themeList()',
+ summary: 'List the themes bundled with this CLI build.',
+ description:
+ 'Projects the bundled-theme manifest into the theme.list envelope — the themes that themeAdd ' +
+ 'can scaffold. A pure projection of the manifest read by listThemes(); no I/O beyond that read, ' +
+ 'and it returns synchronously.',
+ importPath: '@astryxdesign/cli/api',
+ signature: 'themeList(): ThemeListResponse',
+ keywords: ['theme', 'list', 'themes', 'bundled', 'available'],
+ params: [],
+ returns: [
+ {
+ type: 'theme.list',
+ description:
+ 'Every bundled theme as a ThemeListEntry[] — each entry has slug, displayName, description, and a maintained flag.',
+ },
+ ],
+ throws: [
+ {
+ code: 'ERR_NO_SOURCE',
+ when: 'the bundled-theme manifest exists but cannot be read or parsed',
+ },
+ ],
+ examples: [
+ {label: 'List bundled themes', code: 'const {data} = themeList();'},
+ ],
+ command: 'theme list',
+ related: ['themeAdd', 'listThemes', 'themeBuild'],
+};
diff --git a/packages/cli/api/upgrade/upgrade.doc.mjs b/packages/cli/api/upgrade/upgrade.doc.mjs
new file mode 100644
index 0000000000..9ea3ce7e45
--- /dev/null
+++ b/packages/cli/api/upgrade/upgrade.doc.mjs
@@ -0,0 +1,139 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file FunctionDoc for `upgrade()` / `astryx upgrade`. Colocated with the API
+ * function it documents; the shape source of truth stays in `upgrade.type.mjs`.
+ * @position packages/cli/api/upgrade — function documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */
+export const doc = {
+ type: 'function',
+ kind: 'api',
+ name: 'upgrade',
+ displayName: 'upgrade()',
+ summary:
+ 'Run version-migration codemods and refresh the managed agent-docs block.',
+ description:
+ 'Migrates project source from a previous Astryx version to the currently ' +
+ 'installed one by running the registered codemods, and refreshes the managed ' +
+ 'agent-docs block on every path. Dry-run by default (previews without ' +
+ 'writing); pass `apply` to write changes to disk. Core codemods run before ' +
+ 'the config is loaded so a config codemod can repair an otherwise-invalid ' +
+ 'astryx.config.',
+ importPath: '@astryxdesign/cli/api',
+ signature:
+ 'upgrade(options?: UpgradeOptions, ctx?: {cwd?: string}): Promise<UpgradeListResponse | UpgradeStatusResponse | UpgradeRunResponse>',
+ keywords: ['upgrade', 'migrate', 'codemod', 'migration', 'version'],
+ params: [
+ {
+ name: 'options.from',
+ type: 'string',
+ description:
+ 'Version before the dependency bump. Required unless `list` is set.',
+ },
+ {
+ name: 'options.apply',
+ type: 'boolean',
+ description: 'Write changes to disk; otherwise a dry-run preview.',
+ default: 'false',
+ },
+ {
+ name: 'options.force',
+ type: 'boolean',
+ description:
+ 'Run codemods even when `from` is at/after the installed version.',
+ },
+ {
+ name: 'options.codemod',
+ type: 'string',
+ description: 'Run a single named transform instead of the full set.',
+ },
+ {
+ name: 'options.skipCodemod',
+ type: 'string[]',
+ description: 'Codemod names to exclude (e.g. to re-run past a failure).',
+ },
+ {
+ name: 'options.integration',
+ type: 'string[]',
+ description:
+ 'Explicit integration package names / file paths to process.',
+ },
+ {
+ name: 'options.path',
+ type: 'string',
+ description: 'Source directory to scan.',
+ default: './src',
+ },
+ {
+ name: 'options.installDeps',
+ type: 'boolean',
+ description: 'Auto-install jscodeshift without prompting.',
+ },
+ {
+ name: 'options.list',
+ type: 'boolean',
+ description: 'Return the available codemods instead of running any.',
+ },
+ {
+ name: 'ctx.cwd',
+ type: 'string',
+ description: 'Directory to run the upgrade in.',
+ },
+ ],
+ returns: [
+ {
+ type: 'upgrade.list',
+ description:
+ 'Every available codemod, oldest→newest, as {name, title, version, optional} — returned when `list` is set; nothing is run.',
+ },
+ {
+ type: 'upgrade.status',
+ description:
+ 'A short-circuit outcome (no codemods executed): `up_to_date` (`from` is at/after the installed target and no `force`), `no_codemods` (none apply to the range), or `config_fixable` (dry-run preview that a pending config codemod would repair an invalid astryx.config). Each carries the agent-docs summary.',
+ },
+ {
+ type: 'upgrade.run',
+ description:
+ 'The terminal run receipt: from/to versions, the codemod count, integrations processed, the agent-docs summary, and (apply mode) filesChanged, transformsApplied, and any per-codemod errors.',
+ },
+ ],
+ throws: [
+ {
+ code: 'ERR_INVALID_ARGUMENT',
+ when: '`from` is missing (and `list` is not set), or the project config fails strict validation and no pending config codemod can repair it',
+ },
+ {code: 'ERR_INVALID_VERSION', when: '`from` is not a valid semver string'},
+ {code: 'ERR_PATH_TRAVERSAL', when: '`path` resolves outside cwd'},
+ {
+ code: 'ERR_VERSION_DETECT',
+ when: 'the installed @astryxdesign/core version cannot be detected',
+ },
+ {
+ code: 'ERR_DEP_MISSING',
+ when: 'jscodeshift is required but could not be installed',
+ },
+ {
+ code: 'ERR_UNKNOWN_CODEMOD',
+ when: 'a `codemod` name matches no registered codemod',
+ },
+ {
+ code: 'ERR_CODEMOD_FAILED',
+ when: 'one or more codemods failed, or a post-codemod hook failed',
+ },
+ ],
+ examples: [
+ {
+ label: 'List available codemods',
+ code: 'const r = await upgrade({list: true});',
+ },
+ {label: 'Preview (dry-run)', code: "await upgrade({from: '0.0.5'});"},
+ {
+ label: 'Apply changes',
+ code: "await upgrade({from: '0.0.5', apply: true});",
+ },
+ ],
+ command: 'upgrade',
+ related: ['init', 'doctor'],
+};
diff --git a/packages/cli/authoring/codemod/codemod.doc.mjs b/packages/cli/authoring/codemod/codemod.doc.mjs
new file mode 100644
index 0000000000..d4139b0e08
--- /dev/null
+++ b/packages/cli/authoring/codemod/codemod.doc.mjs
@@ -0,0 +1,155 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file SchemaDoc for an Astryx codemod module (AstryxCodemod /
+ * AstryxConfigCodemod). Colocated with the schema (`type.ts` + `parse.mjs`)
+ * it documents.
+ * @position packages/cli/authoring/codemod — schema documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').SchemaDoc} */
+export const doc = {
+ type: 'schema',
+ name: 'codemod',
+ displayName: 'Astryx Codemod',
+ namespace: 'cli',
+ description:
+ 'A codemod module the CLI runs during `astryx upgrade`. Default-export a ' +
+ "plain object with a `type` discriminant: 'code' rewrites source files, " +
+ "'config' rewrites the astryx.config.* file. There is no factory to call.",
+ appliesTo: 'the codemods/ dir of an integration',
+ fields: [
+ {
+ name: 'title',
+ type: 'string',
+ description: 'Short, human-readable title shown in upgrade output.',
+ required: true,
+ example: "'Rename Button prop kind to variant'",
+ },
+ {
+ name: 'description',
+ type: 'string',
+ description: 'Optional longer description.',
+ },
+ {
+ name: 'isOptional',
+ type: 'boolean',
+ description:
+ 'When true, the codemod runs only when explicitly requested.',
+ default: 'false',
+ },
+ {
+ name: 'fileExtensions',
+ type: 'string[]',
+ description:
+ 'File extensions this codemod applies to. Code codemods only — a ' +
+ 'config codemod always targets astryx.config.*.',
+ example: "['.tsx', '.ts']",
+ },
+ {
+ name: 'transform',
+ type: '(file: AstryxCodemodFile, api: AstryxCodemodApi) => string | null | undefined',
+ description:
+ 'The transform. Return the new source to rewrite the file, or ' +
+ 'null/undefined to leave it unchanged.',
+ required: true,
+ fields: [
+ {
+ name: 'file',
+ type: 'AstryxCodemodFile',
+ description: 'The source file presented to the transform.',
+ fields: [
+ {
+ name: 'file.path',
+ type: 'string',
+ description: 'Absolute path to the file being transformed.',
+ },
+ {
+ name: 'file.source',
+ type: 'string',
+ description: 'The current source contents of the file.',
+ },
+ ],
+ },
+ {
+ name: 'api',
+ type: 'AstryxCodemodApi',
+ description: 'Helpers and context passed as the second argument.',
+ fields: [
+ {
+ name: 'api.jscodeshift',
+ type: 'unknown',
+ description:
+ 'A jscodeshift instance configured with a parser for the file.',
+ },
+ {
+ name: 'api.stats',
+ type: '(...args: unknown[]) => void',
+ description:
+ 'Report a statistic (no-op-friendly; provided for jscodeshift parity).',
+ },
+ {
+ name: 'api.report',
+ type: '(...args: unknown[]) => void',
+ description:
+ 'Report progress (no-op-friendly; provided for jscodeshift parity).',
+ },
+ ],
+ },
+ ],
+ },
+ {
+ name: 'type',
+ type: "'code'",
+ description:
+ "Discriminant for the file-transforming variant. Use 'config' for a " +
+ 'codemod that rewrites astryx.config.* instead (see notes).',
+ required: true,
+ example: "'code'",
+ },
+ ],
+ examples: [
+ {
+ label: 'Code codemod (type: code)',
+ code: `export default {
+ type: 'code',
+ title: 'Rename Button prop kind to variant',
+ fileExtensions: ['.tsx', '.ts'],
+ transform(file, api) {
+ const j = api.jscodeshift;
+ const root = j(file.source);
+ // ...rewrite the AST...
+ return root.toSource();
+ },
+};`,
+ },
+ {
+ label: 'Config codemod (type: config)',
+ code: `export default {
+ type: 'config',
+ title: 'Move issuesUrl into astryx.config',
+ transform(file, api) {
+ // Rewrite the astryx.config.* source; return null to skip.
+ return null;
+ },
+};`,
+ },
+ ],
+ notes: [
+ {
+ type: 'prose',
+ text:
+ "The config-codemod variant (type: 'config') carries the same fields " +
+ 'as a code codemod except fileExtensions — it always targets the ' +
+ 'astryx.config.* file rather than a set of source files.',
+ },
+ {
+ type: 'prose',
+ text:
+ 'Authors write a plain object and default-export it with the `type` ' +
+ 'discriminant; there is no factory. The CLI validates it at the load ' +
+ 'boundary via parseCodemod with a strict schema, and isOptional ' +
+ 'defaults to false.',
+ },
+ ],
+};
diff --git a/packages/cli/authoring/config/config.doc.mjs b/packages/cli/authoring/config/config.doc.mjs
new file mode 100644
index 0000000000..4fe1e54ea5
--- /dev/null
+++ b/packages/cli/authoring/config/config.doc.mjs
@@ -0,0 +1,72 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file SchemaDoc for the `astryx.config.*` file (AstryxConfig). Colocated with
+ * the schema (`type.ts` + `parse.mjs`) it documents.
+ * @position packages/cli/authoring/config — schema documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').SchemaDoc} */
+export const doc = {
+ type: 'schema',
+ name: 'config',
+ displayName: 'Astryx Config',
+ namespace: 'cli',
+ description:
+ 'The optional astryx.config.* file at your project root. Declares which ' +
+ 'integrations to load, where to route issue links, post-codemod hooks, and ' +
+ 'experimental layout components. All fields are optional; {} is valid.',
+ appliesTo: 'astryx.config.{ts,mjs,js}',
+ fields: [
+ {
+ name: 'integrations',
+ type: 'string[]',
+ description:
+ 'Package names of Astryx integrations to load alongside core.',
+ example: "['@acme/astryx-widgets']",
+ },
+ {
+ name: 'issuesUrl',
+ type: 'string',
+ description: 'URL that "report an issue" affordances link to.',
+ },
+ {
+ name: 'hooks',
+ type: '{ postCodemod?: PostCodemodHook[] }',
+ description: 'Lifecycle hooks.',
+ fields: [
+ {
+ name: 'hooks.postCodemod',
+ type: 'PostCodemodHook[]',
+ description:
+ 'Commands run after an upgrade applies codemods (e.g. re-run your formatter). Each hook returns a command to execute, or null to skip.',
+ },
+ ],
+ },
+ {
+ name: 'experimental',
+ type: '{ xle?: { components?: Record<string, XleComponent> } }',
+ description: 'Unstable features — may change without a breaking bump.',
+ fields: [
+ {
+ name: 'experimental.xle.components',
+ type: 'Record<string, XleComponent>',
+ description:
+ 'Custom components the layout expander (XLE) may emit, keyed by tag.',
+ },
+ ],
+ },
+ ],
+ examples: [
+ {
+ label: 'Minimal',
+ code: "export default {\n integrations: ['@acme/astryx-widgets'],\n};",
+ },
+ ],
+ notes: [
+ {
+ type: 'prose',
+ text: 'The config is validated at load with a strict schema: unknown keys are errors, so a typo fails fast rather than being silently ignored.',
+ },
+ ],
+};
diff --git a/packages/cli/authoring/doctypes/_schema.mjs b/packages/cli/authoring/doctypes/_schema.mjs
index 505482e7d3..10b979143b 100644
--- a/packages/cli/authoring/doctypes/_schema.mjs
+++ b/packages/cli/authoring/doctypes/_schema.mjs
@@ -67,13 +67,25 @@ export const ComponentDocKindSchema = z
})
.passthrough();
-/** New-format stamped function/hook doc (`type: 'function'`). */
+/** Return entry for the generalized function doc: `name` is optional so CLI/API
+ * functions can document their `{type, data}` envelope entries (which have no
+ * field name), while hooks keep listing named return fields. */
+const FunctionReturnSchema = z
+ .object({
+ name: z.string().min(1).optional(),
+ type: z.string().min(1, 'return type is required'),
+ description: z.string(),
+ })
+ .passthrough();
+
+/** New-format stamped function doc (`type: 'function'`) — hooks and CLI/API
+ * functions alike (the discriminant and schema are shared). */
export const FunctionDocKindSchema = z
.object({
...BaseDocFields,
type: z.literal('function'),
params: z.array(ParamSchema),
- returns: z.array(ReturnSchema),
+ returns: z.array(FunctionReturnSchema),
})
.passthrough();
@@ -85,6 +97,132 @@ export const GenericDocKindSchema = z
})
.passthrough();
+/** Recursive field descriptor for a SchemaDoc (objects nest via `fields`). The
+ * explicit cast breaks the self-referential type inference (TS7022) that the
+ * authoring-contract `checkJs` pass would otherwise flag. */
+const SchemaFieldSchema =
+ /** @type {import('zod').ZodType<import('./schema/type').SchemaFieldDoc>} */ (
+ z.lazy(() =>
+ z
+ .object({
+ name: z.string().min(1, 'field name is required'),
+ // `{error}` covers a missing (undefined) type; `.min(1)` covers an
+ // empty string — both give the same author-friendly message.
+ type: z
+ .string({error: 'field type is required'})
+ .min(1, 'field type is required'),
+ description: z.string(),
+ required: z.boolean().optional(),
+ default: z.string().optional(),
+ example: z.string().optional(),
+ deprecated: z.string().optional(),
+ fields: z.array(SchemaFieldSchema).optional(),
+ })
+ .passthrough(),
+ )
+ );
+
+/** New stamped schema doc (`type: 'schema'`) — documents an authored object. */
+export const SchemaDocKindSchema = z
+ .object({
+ type: z.literal('schema'),
+ name: z.string().min(1, 'name is required'),
+ displayName: z.string().min(1, 'displayName is required'),
+ description: z.string(),
+ namespace: z.string().optional(),
+ aliases: z.array(z.string()).optional(),
+ appliesTo: z.string().optional(),
+ fields: z.array(SchemaFieldSchema),
+ examples: z
+ .array(z.object({label: z.string().optional(), code: z.string()}).passthrough())
+ .optional(),
+ notes: z.array(z.unknown()).optional(),
+ })
+ .passthrough();
+
+/** New stamped command doc (`type: 'command'`) — a function's terminal binding;
+ * references a FunctionDoc via `fn`. */
+export const CommandDocKindSchema = z
+ .object({
+ type: z.literal('command'),
+ name: z.string().min(1, 'name is required'),
+ displayName: z.string().min(1, 'displayName is required'),
+ summary: z.string(),
+ description: z.string().optional(),
+ namespace: z.string().optional(),
+ aliases: z.array(z.string()).optional(),
+ fn: z.string().optional(),
+ args: z
+ .array(
+ z
+ .object({
+ name: z.string().min(1),
+ param: z.string().optional(),
+ description: z.string().optional(),
+ required: z.boolean().optional(),
+ variadic: z.boolean().optional(),
+ })
+ .passthrough(),
+ )
+ .optional(),
+ options: z
+ .array(
+ z
+ .object({
+ flag: z.string().min(1),
+ param: z.string().optional(),
+ description: z.string().optional(),
+ choices: z.array(z.string()).optional(),
+ default: z
+ .union([z.string(), z.boolean(), z.array(z.string())])
+ .optional(),
+ cliOnly: z.boolean().optional(),
+ })
+ .passthrough(),
+ )
+ .optional(),
+ subcommands: z.array(z.string()).optional(),
+ examples: z
+ .array(
+ z
+ .object({
+ label: z.string().optional(),
+ cli: z.string(),
+ output: z.string().optional(),
+ })
+ .passthrough(),
+ )
+ .optional(),
+ exitCodes: z
+ .array(z.object({code: z.number(), when: z.string()}).passthrough())
+ .optional(),
+ related: z.array(z.string()).optional(),
+ notes: z.array(z.unknown()).optional(),
+ })
+ .passthrough();
+
+/** New stamped enum doc (`type: 'enum'`) — a closed vocabulary (error codes,
+ * response-type discriminants). */
+export const EnumDocKindSchema = z
+ .object({
+ type: z.literal('enum'),
+ name: z.string().min(1, 'name is required'),
+ displayName: z.string().min(1, 'displayName is required'),
+ description: z.string(),
+ namespace: z.string().optional(),
+ aliases: z.array(z.string()).optional(),
+ members: z.array(
+ z
+ .object({
+ value: z.string().min(1, 'member value is required'),
+ description: z.string(),
+ deprecated: z.string().optional(),
+ })
+ .passthrough(),
+ ),
+ })
+ .passthrough();
+
// ── Legacy loose format (unchanged, kept for back-compat) ─────────────
const LegacyBaseDocSchema = z.object({
name: z.string().min(1, 'name is required'),
diff --git a/packages/cli/authoring/doctypes/command/command.doc.mjs b/packages/cli/authoring/doctypes/command/command.doc.mjs
new file mode 100644
index 0000000000..56fd89fb37
--- /dev/null
+++ b/packages/cli/authoring/doctypes/command/command.doc.mjs
@@ -0,0 +1,241 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file SchemaDoc for the `CommandDoc` doc-type — how to author the TERMINAL
+ * binding of an operation. A command is a FunctionDoc exposed on the CLI, so it
+ * references the function via `fn` and only carries CLI-surface facts. Colocated
+ * with the type it describes (`type.ts`).
+ * @position packages/cli/authoring/doctypes/command — doc-type documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').SchemaDoc} */
+export const doc = {
+ type: 'schema',
+ name: 'command-doc',
+ displayName: 'CommandDoc',
+ namespace: 'authoring',
+ description:
+ 'The doc-type for a CLI command — the terminal binding of an operation. A command ' +
+ 'is not its own behavior; it is a FunctionDoc exposed on the CLI, referenced via `fn`, ' +
+ 'carrying only CLI-surface facts (args, flags, subcommands, examples, exit codes). ' +
+ 'A `defineCommand` converter turns it into Commander config + `--help`.',
+ appliesTo: 'clients/cli/commands/<name>.doc.mjs',
+ fields: [
+ {
+ name: 'type',
+ type: "'command'",
+ description: 'Doc-kind discriminant. Marks the file as a command doc.',
+ },
+ {
+ name: 'name',
+ type: 'string',
+ description: "Command path, e.g. 'search' | 'theme build'.",
+ required: true,
+ },
+ {
+ name: 'displayName',
+ type: 'string',
+ description: "Human-readable display name, e.g. 'astryx search'.",
+ required: true,
+ },
+ {
+ name: 'summary',
+ type: 'string',
+ description:
+ 'One-line summary → Commander `.description()` + the docs listing.',
+ required: true,
+ },
+ {
+ name: 'description',
+ type: 'string',
+ description: 'Longer help body / when-to-use.',
+ },
+ {
+ name: 'namespace',
+ type: 'string',
+ description:
+ "Docs namespace path. Defaults to 'cli' when applied by the docs index.",
+ },
+ {
+ name: 'aliases',
+ type: 'string[]',
+ description: 'Alternate slugs that also resolve to this doc.',
+ },
+ {
+ name: 'fn',
+ type: 'string',
+ description:
+ 'Name of the FunctionDoc (and `@astryxdesign/cli/api` export) this command wraps.',
+ example: "'search'",
+ },
+ {
+ name: 'args',
+ type: 'CommandArgDoc[]',
+ description: 'Positional arguments.',
+ fields: [
+ {
+ name: 'args[].name',
+ type: 'string',
+ description: 'Argument name.',
+ required: true,
+ },
+ {
+ name: 'args[].param',
+ type: 'string',
+ description:
+ 'FunctionDoc param this arg binds to (inherits its description).',
+ },
+ {
+ name: 'args[].description',
+ type: 'string',
+ description:
+ 'Override description (else inherited from the referenced param).',
+ },
+ {
+ name: 'args[].required',
+ type: 'boolean',
+ description: 'Whether the positional argument must be supplied.',
+ },
+ {
+ name: 'args[].variadic',
+ type: 'boolean',
+ description:
+ 'Whether the argument collects a variable number of values.',
+ },
+ ],
+ },
+ {
+ name: 'options',
+ type: 'CommandOptionDoc[]',
+ description: 'Flags/options.',
+ fields: [
+ {
+ name: 'options[].flag',
+ type: 'string',
+ description:
+ "Commander flag spec, e.g. '-l, --limit <n>' | '--json'.",
+ required: true,
+ },
+ {
+ name: 'options[].param',
+ type: 'string',
+ description:
+ 'FunctionDoc param this flag maps to (inherits its description).',
+ },
+ {
+ name: 'options[].description',
+ type: 'string',
+ description:
+ 'Override/explicit description (required when `cliOnly`).',
+ },
+ {
+ name: 'options[].choices',
+ type: 'string[]',
+ description: 'Allowed values for the flag.',
+ },
+ {
+ name: 'options[].default',
+ type: 'string',
+ description: 'Default value as a string.',
+ },
+ {
+ name: 'options[].cliOnly',
+ type: 'boolean',
+ description:
+ 'True for CLI-only flags with no function param (e.g. --json).',
+ },
+ ],
+ },
+ {
+ name: 'subcommands',
+ type: 'string[]',
+ description:
+ 'Subcommand names (for command groups like `theme` / `layout`).',
+ },
+ {
+ name: 'examples',
+ type: 'CommandExampleDoc[]',
+ description: 'Terminal examples.',
+ fields: [
+ {
+ name: 'examples[].label',
+ type: 'string',
+ description: 'Optional heading shown above the invocation.',
+ },
+ {
+ name: 'examples[].cli',
+ type: 'string',
+ description:
+ "A full terminal invocation, e.g. 'astryx search button --json'.",
+ required: true,
+ },
+ {
+ name: 'examples[].output',
+ type: 'string',
+ description: 'Optional sample output.',
+ },
+ ],
+ },
+ {
+ name: 'exitCodes',
+ type: '{ code: number; when: string }[]',
+ description: 'Documented exit codes.',
+ fields: [
+ {
+ name: 'exitCodes[].code',
+ type: 'number',
+ description: 'The process exit code.',
+ required: true,
+ },
+ {
+ name: 'exitCodes[].when',
+ type: 'string',
+ description: 'The condition that produces this exit code.',
+ required: true,
+ },
+ ],
+ },
+ {
+ name: 'related',
+ type: 'string[]',
+ description: 'Related command names.',
+ },
+ {
+ name: 'notes',
+ type: 'ReferenceContentBlock[]',
+ description: 'Freeform prose/notes.',
+ },
+ ],
+ examples: [
+ {
+ label: 'A command that wraps the search() function',
+ code: `/** @type {import('@astryxdesign/cli/authoring').CommandDoc} */
+export const doc = {
+ type: 'command',
+ name: 'search',
+ displayName: 'astryx search',
+ summary: 'Find components, hooks, docs, and templates.',
+ namespace: 'cli',
+ fn: 'search',
+ args: [{name: 'query', param: 'query', required: true}],
+ options: [
+ {flag: '--type <domain>', param: 'options.type', choices: ['component', 'hook', 'doc', 'template']},
+ {flag: '--json', cliOnly: true, description: 'Emit the typed JSON envelope.'},
+ ],
+ examples: [{label: 'Terminal', cli: 'astryx search button --json'}],
+ exitCodes: [{code: 1, when: 'The --type value is not a known domain.'}],
+ related: ['discover'],
+};`,
+ },
+ ],
+ notes: [
+ {
+ type: 'prose',
+ text: 'A command carries only CLI-surface facts. Behavior, parameters, returns, and thrown errors live in the FunctionDoc it points at via `fn` — the function does not know it has a CLI.',
+ },
+ {
+ type: 'prose',
+ text: "Bind an arg/option to a function param via `param` so it inherits that param's description. Use `cliOnly: true` for flags with no function param (e.g. `--json`); those must supply their own `description`.",
+ },
+ ],
+};
diff --git a/packages/cli/authoring/doctypes/command/parse.d.mts b/packages/cli/authoring/doctypes/command/parse.d.mts
new file mode 100644
index 0000000000..866d67283c
--- /dev/null
+++ b/packages/cli/authoring/doctypes/command/parse.d.mts
@@ -0,0 +1,4 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import type {CommandDoc} from '../types';
+export function parseCommand(input: unknown, label?: string): CommandDoc;
diff --git a/packages/cli/authoring/doctypes/command/parse.mjs b/packages/cli/authoring/doctypes/command/parse.mjs
new file mode 100644
index 0000000000..98b3af9801
--- /dev/null
+++ b/packages/cli/authoring/doctypes/command/parse.mjs
@@ -0,0 +1,26 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Command doc parser (stamped `type: 'command'`). Zod is sealed in
+ * `../_schema.mjs`; consumers call `parseCommand` or use `parseDoc`.
+ */
+
+import {CommandDocKindSchema} from '../_schema.mjs';
+import {formatZodError} from '../../_shared/errors.mjs';
+
+/** @typedef {import('../types').CommandDoc} CommandDoc */
+
+/**
+ * Validate an unknown value as a stamped command doc, or throw.
+ *
+ * @param {unknown} input
+ * @param {string} [label]
+ * @returns {CommandDoc}
+ */
+export function parseCommand(input, label = 'command doc') {
+ const result = CommandDocKindSchema.safeParse(input);
+ if (!result.success) {
+ throw new Error(formatZodError(label, result.error));
+ }
+ return /** @type {CommandDoc} */ (/** @type {unknown} */ (result.data));
+}
diff --git a/packages/cli/authoring/doctypes/command/type.ts b/packages/cli/authoring/doctypes/command/type.ts
new file mode 100644
index 0000000000..457e229275
--- /dev/null
+++ b/packages/cli/authoring/doctypes/command/type.ts
@@ -0,0 +1,87 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Command doc types — the TERMINAL binding of an operation. A command is
+ * not its own kind of behavior; it is a FunctionDoc exposed on the CLI, so this
+ * doc references the function via `fn` and only carries CLI-surface facts (args,
+ * flags, subcommands, terminal examples, exit codes). It is designed to be the
+ * single source that a `defineCommand` converter turns into Commander config +
+ * `--help`. Colocated at `clients/cli/commands/<name>.doc.mjs`.
+ */
+
+import type {ReferenceContentBlock} from '../reference/type';
+
+/** A positional argument. `param` links it to a FunctionDoc param for its description. */
+export interface CommandArgDoc {
+ name: string;
+ /** FunctionDoc param this arg binds to (inherits its description). */
+ param?: string;
+ /** Override description (else inherited from the referenced param). */
+ description?: string;
+ required?: boolean;
+ variadic?: boolean;
+}
+
+/** A flag/option. `param` links it to a FunctionDoc param; `cliOnly` for flags
+ * with no function param (e.g. --json). */
+export interface CommandOptionDoc {
+ /** Commander flag spec, e.g. '-l, --limit <n>' | '--json'. */
+ flag: string;
+ /** FunctionDoc param this flag maps to (inherits its description). */
+ param?: string;
+ /** Override/explicit description (required when cliOnly). */
+ description?: string;
+ choices?: string[];
+ /** Default value applied via Commander `.default()` (shown in --help). A
+ * boolean flag defaults to `false`; a repeatable value flag to `string[]`. */
+ default?: string | boolean | string[];
+ /** True for CLI-only flags with no function param. */
+ cliOnly?: boolean;
+}
+
+export interface CommandExampleDoc {
+ label?: string;
+ /** A full terminal invocation, e.g. 'astryx search button --json'. */
+ cli: string;
+ /** Optional sample output. */
+ output?: string;
+}
+
+/**
+ * A CLI command documentation file (.doc.mjs).
+ *
+ * /\*\* @type {import('@astryxdesign/cli/authoring').CommandDoc} \*\/
+ * export const doc = { type: 'command', name: 'search', fn: 'search', ... };
+ */
+export interface CommandDoc {
+ /** Doc-kind discriminant. */
+ type?: 'command';
+ /** Command path, e.g. 'search' | 'theme build'. */
+ name: string;
+ /** Human-readable display name, e.g. 'astryx search'. */
+ displayName: string;
+ /** One-line summary → Commander `.description()` + the docs listing. */
+ summary: string;
+ /** Longer help body / when-to-use. */
+ description?: string;
+ /** Docs namespace path. Defaults to 'cli' when applied by the docs index. */
+ namespace?: string;
+ /** Alternate slugs that also resolve to this doc. */
+ aliases?: string[];
+ /** Name of the FunctionDoc (and `@astryxdesign/cli/api` export) this wraps. */
+ fn?: string;
+ /** Positional arguments. */
+ args?: CommandArgDoc[];
+ /** Flags/options. */
+ options?: CommandOptionDoc[];
+ /** Subcommand names (for command groups like `theme` / `layout`). */
+ subcommands?: string[];
+ /** Terminal examples. */
+ examples?: CommandExampleDoc[];
+ /** Documented exit codes. */
+ exitCodes?: {code: number; when: string}[];
+ /** Related command names. */
+ related?: string[];
+ /** Freeform prose/notes. */
+ notes?: ReferenceContentBlock[];
+}
diff --git a/packages/cli/authoring/doctypes/component/component.doc.mjs b/packages/cli/authoring/doctypes/component/component.doc.mjs
new file mode 100644
index 0000000000..d2550f9a2c
--- /dev/null
+++ b/packages/cli/authoring/doctypes/component/component.doc.mjs
@@ -0,0 +1,254 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file SchemaDoc for the `ComponentDoc` doc-type — how to author a component
+ * directory's `{Name}.doc.mjs`. A discriminated union (Single/Multi/Sub) that
+ * shares ComponentBaseDoc. Colocated with the type it describes (`type.ts`).
+ * @position packages/cli/authoring/doctypes/component — doc-type documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').SchemaDoc} */
+export const doc = {
+ type: 'schema',
+ name: 'component-doc',
+ displayName: 'ComponentDoc',
+ namespace: 'authoring',
+ description:
+ "The doc-type for a component directory's {Name}.doc.mjs. A discriminated union of " +
+ 'SingleComponentDoc (props on the doc), MultiComponentDoc (a `components` array), and ' +
+ 'SubComponentDoc (a `subComponentOf` pointer). All three share the ComponentBaseDoc ' +
+ 'fields below; the variant is chosen by which of props / components / subComponentOf you set.',
+ appliesTo: '{Name}.doc.mjs',
+ fields: [
+ {
+ name: 'type',
+ type: "'component'",
+ description:
+ 'Doc-kind discriminant for the stamped default-export format. Optional: legacy `export const docs = {...}` docs omit it and the parser falls back to shape-sniffing.',
+ },
+ {
+ name: 'name',
+ type: 'string',
+ description:
+ "Directory name without the Astryx prefix, PascalCase. e.g. 'Button', 'TextInput', 'AppShell'.",
+ required: true,
+ },
+ {
+ name: 'displayName',
+ type: 'string',
+ description:
+ "Human-readable display name with spaces between words ('AppShell' → 'App Shell'). Drives the docsite gallery and sidebar label.",
+ required: true,
+ },
+ {
+ name: 'keywords',
+ type: 'string[]',
+ description:
+ 'Search keywords for CLI discovery: synonyms and related UI concepts from other design systems (MUI, Chakra, Radix, shadcn). Lowercase. Used by `astryx component <term>` fuzzy matching.',
+ },
+ {
+ name: 'hiddenComponents',
+ type: 'string[]',
+ description:
+ 'Sub-component names to hide from human-facing UI (CLI listings, docs catalogs). They stay public and importable — agents and tooling can still discover them via source.',
+ },
+ {
+ name: 'hidden',
+ type: 'boolean',
+ description:
+ 'Hide this entire component from human-facing UI. It stays public and importable. Use for shared primitives (NavIcon, NavMenu) that only make sense inside their parent.',
+ },
+ {
+ name: 'group',
+ type: 'string',
+ description:
+ 'Optional sidebar/docs group. Clusters related components; ungrouped components appear flat in alphabetical order.',
+ },
+ {
+ name: 'category',
+ type: "'Action' | 'Chat' | 'Container' | 'Content' | 'Data Input' | 'Data Visualization' | 'Feedback & Status' | 'Layout' | 'Navigation' | 'Overlay' | 'Table & List' | 'Utility'",
+ description:
+ "Overview-gallery category representing the component's functional role. Independent of `group` (which is for the sidebar).",
+ },
+ {
+ name: 'isHiddenFromOverview',
+ type: 'boolean',
+ description:
+ 'Exclude from the categorized overview page while keeping the component in the sidebar and CLI. Use for sub-components or internal primitives.',
+ },
+ {
+ name: 'theming',
+ type: '{ container?: boolean; targets: ComponentThemingTarget[]; vars?: ComponentThemingVar[]; derived?: ComponentThemingDerivedVar[] }',
+ description:
+ 'Theming configuration: the stable selector surface (xds-* classes + data-attribute reflections) that themes target via @scope selectors in defineTheme.',
+ fields: [
+ {
+ name: 'theming.container',
+ type: 'boolean',
+ description:
+ 'When true, container `padding` props are mapped to container tokens by the theme pipeline instead of emitting raw CSS.',
+ },
+ {
+ name: 'theming.targets',
+ type: 'ComponentThemingTarget[]',
+ description:
+ 'Selector targets rendered by this component. Each entry corresponds to a themeProps() call in the source.',
+ required: true,
+ },
+ {
+ name: 'theming.vars',
+ type: 'ComponentThemingVar[]',
+ description: 'CSS custom properties exposed for theming.',
+ },
+ {
+ name: 'theming.derived',
+ type: 'ComponentThemingDerivedVar[]',
+ description:
+ 'Maps standard CSS properties to internal vars for theme-pipeline expansion. Ordered by priority — earlier entries emit first.',
+ },
+ ],
+ },
+ {
+ name: 'usage',
+ type: 'UsageDoc',
+ description:
+ 'Component usage documentation: concise summary, best practices, and optional visual anatomy. (Optional on SubComponentDoc, where the sub-component description is used instead.)',
+ required: true,
+ fields: [
+ {
+ name: 'usage.description',
+ type: 'string',
+ description:
+ 'What the component is and when to use it, in 2-3 short sentences.',
+ required: true,
+ },
+ {
+ name: 'usage.bestPractices',
+ type: 'ComponentBestPractice[]',
+ description:
+ "3-4 do/don't design-guidance items ({guidance: boolean, description: string}). Never start the description with 'Do' or 'Don't'.",
+ },
+ {
+ name: 'usage.anatomy',
+ type: 'ComponentAnatomyElement[]',
+ description:
+ 'Structural/visual parts in reading order ({name, required, description}).',
+ },
+ ],
+ },
+ {
+ name: 'examples',
+ type: 'ComponentExampleDoc[]',
+ description:
+ 'Short code examples ({label?, code}) rendered by the CLI after the props table.',
+ },
+ {
+ name: 'playground',
+ type: 'ComponentPlaygroundConfig',
+ description:
+ 'Interactive-preview config: initial prop `defaults`, `overlay` for modal-only components, and a `wrapper` for context-dependent sub-components.',
+ },
+ {
+ name: 'props',
+ type: 'ComponentPropDoc[]',
+ description:
+ 'SingleComponentDoc variant (required there): all public props for the one primary component. Each prop is {name, type, description, default?, required?, slotElements?}. Skip styling props like xstyle/className/style. Also present on SubComponentDoc.',
+ },
+ {
+ name: 'components',
+ type: '(ComponentEntry | ComponentRef)[]',
+ description:
+ 'MultiComponentDoc variant (required there): one entry per public component/hook exported from the directory. Each entry is a full ComponentEntry (inline: name, displayName, description, props | params+returns) or a name-only ComponentRef pointing at a sibling {Name}.doc.mjs.',
+ },
+ {
+ name: 'subComponentOf',
+ type: 'string',
+ description:
+ "SubComponentDoc variant (required there): the parent component's `name` (e.g. 'Chat'). Marks this file as a sub-component doc that inherits family fields (group, category, keywords, theming, playground) from the parent.",
+ },
+ {
+ name: 'description',
+ type: 'string',
+ description:
+ "SubComponentDoc variant (required there): one-sentence description of the sub-component's role within the parent composition. Single/Multi docs have no top-level description — they derive their summary from `usage`.",
+ },
+ ],
+ examples: [
+ {
+ label: 'SingleComponentDoc (props on the doc)',
+ code: `/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */
+export const docs = {
+ name: 'Switch',
+ displayName: 'Switch',
+ category: 'Data Input',
+ keywords: ['toggle', 'switch', 'on off'],
+ usage: {
+ description:
+ 'A Switch toggles a single setting on or off. Use it for instant, binary preferences that apply immediately without a submit step.',
+ bestPractices: [
+ {guidance: true, description: 'Apply the change immediately when toggled.'},
+ {guidance: false, description: 'Use a Switch for actions that need confirmation — prefer a Checkbox in a form.'},
+ ],
+ },
+ props: [
+ {name: 'isSelected', type: 'boolean', description: 'Whether the switch is on.', required: true},
+ {name: 'onChange', type: '(isSelected: boolean) => void', description: 'Called when the user toggles the switch.'},
+ {name: 'isDisabled', type: 'boolean', description: 'Prevents interaction and dims the control.', default: 'false'},
+ ],
+};`,
+ },
+ {
+ label: 'MultiComponentDoc (a components array)',
+ code: `/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */
+export const docs = {
+ name: 'Table',
+ displayName: 'Table',
+ category: 'Table & List',
+ usage: {description: 'Displays rows and columns of data. Compose the sub-components to build headers, rows, and cells.'},
+ components: [
+ {name: 'Table', displayName: 'Table', description: 'The table container.', props: []},
+ {name: 'TableRow', displayName: 'Table Row', description: 'A row within the table body.', props: [
+ {name: 'isSelected', type: 'boolean', description: 'Highlights the row as selected.'},
+ ]},
+ {name: 'useTableSelection', displayName: 'useTableSelection', description: 'Manages row selection state.',
+ params: [{name: 'rows', type: 'T[]', description: 'The rows to track.', required: true}],
+ returns: [{name: 'selectedIds', type: 'Set<string>', description: 'Currently selected row ids.'}]},
+ ],
+};`,
+ },
+ ],
+ notes: [
+ {
+ type: 'prose',
+ text: 'ComponentDoc is a discriminated union of three shapes that all extend ComponentBaseDoc. Pick the variant by which key you set: `props` (single), `components` (multi), or `subComponentOf` (sub).',
+ },
+ {
+ type: 'list',
+ style: 'unordered',
+ items: [
+ 'SingleComponentDoc — one primary component; put props directly on the doc via `props`. Use for Switch, Badge, Spinner, TextInput.',
+ 'MultiComponentDoc — a directory exporting several components/hooks; list them in `components` (inline ComponentEntry or name-only ComponentRef). Use for Table, Dialog, TabList.',
+ 'SubComponentDoc — a single sub-component in its own {Name}.doc.mjs inside the parent directory; set `subComponentOf` to the parent name. It inherits family fields and may omit `usage`.',
+ ],
+ },
+ {
+ type: 'code',
+ lang: 'js',
+ label: 'SubComponentDoc',
+ code: `/** @type {import('@astryxdesign/cli/authoring').ComponentDoc} */
+export const docs = {
+ name: 'ChatComposer',
+ displayName: 'Chat Composer',
+ subComponentOf: 'Chat',
+ description: 'The message input row within a Chat, with an editor and send affordance.',
+ props: [
+ {name: 'onSend', type: '(text: string) => void', description: 'Called when the user submits a message.', required: true},
+ ],
+};`,
+ },
+ {
+ type: 'prose',
+ text: "The stamped format is `export default { type: 'component', ... }`; legacy docs use `export const docs = {...}` and omit `type` (the parser shape-sniffs). A hook that is part of a component API is documented as a ComponentEntry in a MultiComponentDoc `components` array (with `params`/`returns`), not as a standalone HookDoc.",
+ },
+ ],
+};
diff --git a/packages/cli/authoring/doctypes/doctypes-new.test.mjs b/packages/cli/authoring/doctypes/doctypes-new.test.mjs
new file mode 100644
index 0000000000..2b57659a13
--- /dev/null
+++ b/packages/cli/authoring/doctypes/doctypes-new.test.mjs
@@ -0,0 +1,120 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Tests for the new authoring doc-types (schema/command/enum) and the
+ * generalized `function` doc (hooks + CLI/API functions sharing the schema).
+ */
+
+import {describe, it, expect} from 'vitest';
+import {
+ parseDoc,
+ parseSchema,
+ parseCommand,
+ parseEnum,
+ parseFunction,
+} from '../index.mjs';
+
+describe('SchemaDoc', () => {
+ const doc = {
+ type: 'schema',
+ name: 'config',
+ displayName: 'Astryx Config',
+ description: 'Project config.',
+ appliesTo: 'astryx.config.{ts,mjs,js}',
+ fields: [
+ {name: 'integrations', type: 'string[]', description: 'Packages to load.'},
+ {
+ name: 'hooks',
+ type: 'object',
+ description: 'Lifecycle hooks.',
+ fields: [
+ {name: 'hooks.postCodemod', type: 'PostCodemodHook[]', description: 'Runs after codemods.'},
+ ],
+ },
+ ],
+ };
+
+ it('accepts a valid schema doc with nested fields', () => {
+ const parsed = parseSchema(doc);
+ expect(parsed.name).toBe('config');
+ expect(parsed.fields[1].fields?.[0].name).toBe('hooks.postCodemod');
+ expect(parseDoc(doc).type).toBe('schema');
+ });
+
+ it('throws when a field is missing its type', () => {
+ expect(() =>
+ parseSchema({
+ type: 'schema',
+ name: 'x',
+ displayName: 'X',
+ description: '',
+ fields: [{name: 'a', description: 'no type'}],
+ }),
+ ).toThrow(/type is required/);
+ });
+});
+
+describe('CommandDoc', () => {
+ const doc = {
+ type: 'command',
+ name: 'search',
+ displayName: 'astryx search',
+ summary: 'Find components, hooks, docs, and templates.',
+ fn: 'search',
+ args: [{name: 'query', param: 'query', required: true}],
+ options: [
+ {flag: '--type <domain>', param: 'options.type', choices: ['component', 'hook']},
+ {flag: '--json', cliOnly: true, description: 'Emit the typed JSON envelope.'},
+ ],
+ examples: [{label: 'Terminal', cli: 'astryx search button --json'}],
+ exitCodes: [{code: 1, when: 'invalid --type'}],
+ };
+
+ it('accepts a command doc that references a function', () => {
+ expect(parseCommand(doc).fn).toBe('search');
+ expect(parseDoc(doc).type).toBe('command');
+ });
+});
+
+describe('EnumDoc', () => {
+ it('accepts a closed vocabulary', () => {
+ const doc = {
+ type: 'enum',
+ name: 'error-codes',
+ displayName: 'Error Codes',
+ description: 'Stable CLI error codes.',
+ members: [{value: 'ERR_UNKNOWN', description: 'Fallback code.'}],
+ };
+ expect(parseEnum(doc).members).toHaveLength(1);
+ expect(parseDoc(doc).type).toBe('enum');
+ });
+});
+
+describe('generalized FunctionDoc', () => {
+ it('accepts an API function whose returns are envelope entries (no field name)', () => {
+ const apiFn = {
+ type: 'function',
+ kind: 'api',
+ name: 'search',
+ displayName: 'search()',
+ importPath: '@astryxdesign/cli/api',
+ params: [{name: 'query', type: 'string', description: 'Term.', required: true}],
+ returns: [{type: 'search', description: 'query + ranked results[]'}],
+ throws: [{code: 'ERR_INVALID_ARGUMENT', when: 'empty query'}],
+ };
+ expect(() => parseFunction(apiFn)).not.toThrow();
+ expect(parseDoc(apiFn).name).toBe('search');
+ });
+
+ it('still accepts a hook whose returns are named fields', () => {
+ const hook = {
+ type: 'function',
+ name: 'useThing',
+ displayName: 'useThing',
+ params: [{name: 'opts', type: 'Opts', description: 'Options.'}],
+ returns: [{name: 'value', type: 'string', description: 'The value.'}],
+ usage: {description: 'Use it.'},
+ };
+ expect(() => parseFunction(hook)).not.toThrow();
+ });
+});
diff --git a/packages/cli/authoring/doctypes/enum/enum.doc.mjs b/packages/cli/authoring/doctypes/enum/enum.doc.mjs
new file mode 100644
index 0000000000..7380c83fa4
--- /dev/null
+++ b/packages/cli/authoring/doctypes/enum/enum.doc.mjs
@@ -0,0 +1,114 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file SchemaDoc for the `EnumDoc` doc-type — how to author a doc for a closed
+ * vocabulary (error codes, response-type discriminants). Colocated with the
+ * type it describes (`type.ts`).
+ * @position packages/cli/authoring/doctypes/enum — doc-type documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').SchemaDoc} */
+export const doc = {
+ type: 'schema',
+ name: 'enum-doc',
+ displayName: 'EnumDoc',
+ namespace: 'authoring',
+ description:
+ 'The doc-type for a closed vocabulary — a fixed set of literal values such as ' +
+ 'error codes or response-type discriminants. Colocated as a `.doc.mjs` next to ' +
+ 'the source of truth it documents.',
+ appliesTo: '<enum>.doc.mjs',
+ fields: [
+ {
+ name: 'type',
+ type: "'enum'",
+ description: 'Doc-kind discriminant. Marks the file as an enum doc.',
+ },
+ {
+ name: 'name',
+ type: 'string',
+ description:
+ 'URL-safe identifier, used as the docs slug within its namespace.',
+ required: true,
+ example: "'error-codes'",
+ },
+ {
+ name: 'displayName',
+ type: 'string',
+ description: 'Human-readable title.',
+ required: true,
+ example: "'Error Codes'",
+ },
+ {
+ name: 'description',
+ type: 'string',
+ description: 'One-line summary shown in listings.',
+ required: true,
+ },
+ {
+ name: 'namespace',
+ type: 'string',
+ description:
+ "Docs namespace path. Defaults to 'cli' when applied by the docs index.",
+ },
+ {
+ name: 'aliases',
+ type: 'string[]',
+ description: 'Alternate slugs that also resolve to this doc.',
+ },
+ {
+ name: 'members',
+ type: 'EnumMemberDoc[]',
+ description: 'The enumerated members — one entry per literal value.',
+ required: true,
+ fields: [
+ {
+ name: 'members[].value',
+ type: 'string',
+ description:
+ "The literal value, e.g. 'ERR_UNKNOWN_TOPIC' | 'component.list'.",
+ required: true,
+ },
+ {
+ name: 'members[].description',
+ type: 'string',
+ description: 'What the value means / when it occurs.',
+ required: true,
+ },
+ {
+ name: 'members[].deprecated',
+ type: 'string',
+ description: 'Deprecation reason, if deprecated.',
+ },
+ ],
+ },
+ ],
+ examples: [
+ {
+ label: 'Error-codes enum doc',
+ code: `/** @type {import('@astryxdesign/cli/authoring').EnumDoc} */
+export const doc = {
+ type: 'enum',
+ name: 'error-codes',
+ displayName: 'Error Codes',
+ namespace: 'cli',
+ description: 'Stable error codes thrown by the CLI/API and surfaced in the JSON envelope.',
+ members: [
+ {value: 'ERR_UNKNOWN_TOPIC', description: 'The requested docs topic does not exist.'},
+ {value: 'ERR_INVALID_ARGUMENT', description: 'A required argument was missing or malformed.'},
+ {value: 'ERR_LEGACY', description: 'Old alias.', deprecated: 'Use ERR_INVALID_ARGUMENT.'},
+ ],
+};`,
+ },
+ ],
+ notes: [
+ {
+ type: 'prose',
+ text: 'An enum doc is the human-readable mirror of a closed vocabulary defined elsewhere in source (e.g. an ERROR_CODES map or a response-type union). Keep the members in sync with that source of truth.',
+ },
+ {
+ type: 'prose',
+ text: 'Mark a value with `deprecated` (a migration hint) rather than deleting it, so old codes stay documented while readers are pointed at the replacement.',
+ },
+ ],
+};
diff --git a/packages/cli/authoring/doctypes/enum/parse.d.mts b/packages/cli/authoring/doctypes/enum/parse.d.mts
new file mode 100644
index 0000000000..99bc85aa20
--- /dev/null
+++ b/packages/cli/authoring/doctypes/enum/parse.d.mts
@@ -0,0 +1,4 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import type {EnumDoc} from '../types';
+export function parseEnum(input: unknown, label?: string): EnumDoc;
diff --git a/packages/cli/authoring/doctypes/enum/parse.mjs b/packages/cli/authoring/doctypes/enum/parse.mjs
new file mode 100644
index 0000000000..83a6d6f20d
--- /dev/null
+++ b/packages/cli/authoring/doctypes/enum/parse.mjs
@@ -0,0 +1,26 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Enum doc parser (stamped `type: 'enum'`). Zod is sealed in
+ * `../_schema.mjs`; consumers call `parseEnum` or use `parseDoc`.
+ */
+
+import {EnumDocKindSchema} from '../_schema.mjs';
+import {formatZodError} from '../../_shared/errors.mjs';
+
+/** @typedef {import('../types').EnumDoc} EnumDoc */
+
+/**
+ * Validate an unknown value as a stamped enum doc, or throw.
+ *
+ * @param {unknown} input
+ * @param {string} [label]
+ * @returns {EnumDoc}
+ */
+export function parseEnum(input, label = 'enum doc') {
+ const result = EnumDocKindSchema.safeParse(input);
+ if (!result.success) {
+ throw new Error(formatZodError(label, result.error));
+ }
+ return /** @type {EnumDoc} */ (/** @type {unknown} */ (result.data));
+}
diff --git a/packages/cli/authoring/doctypes/enum/type.ts b/packages/cli/authoring/doctypes/enum/type.ts
new file mode 100644
index 0000000000..5fba25721d
--- /dev/null
+++ b/packages/cli/authoring/doctypes/enum/type.ts
@@ -0,0 +1,39 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Enum doc types — a closed vocabulary (error codes, response-type
+ * discriminants). Colocated next to the source of truth it documents.
+ */
+
+/** One member of an enumerated vocabulary. */
+export interface EnumMemberDoc {
+ /** The literal value, e.g. 'ERR_UNKNOWN_TOPIC' | 'component.list'. */
+ value: string;
+ /** What the value means / when it occurs. */
+ description: string;
+ /** Deprecation reason, if deprecated. */
+ deprecated?: string;
+}
+
+/**
+ * An enumeration documentation file (.doc.mjs).
+ *
+ * /\*\* @type {import('@astryxdesign/cli/authoring').EnumDoc} \*\/
+ * export const doc = { type: 'enum', name: 'error-codes', ... };
+ */
+export interface EnumDoc {
+ /** Doc-kind discriminant. */
+ type?: 'enum';
+ /** URL-safe identifier, used as the docs slug within its namespace. */
+ name: string;
+ /** Human-readable title. */
+ displayName: string;
+ /** One-line summary shown in listings. */
+ description: string;
+ /** Docs namespace path. Defaults to 'cli' when applied by the docs index. */
+ namespace?: string;
+ /** Alternate slugs that also resolve to this doc. */
+ aliases?: string[];
+ /** The enumerated members. */
+ members: EnumMemberDoc[];
+}
diff --git a/packages/cli/authoring/doctypes/function/function.doc.mjs b/packages/cli/authoring/doctypes/function/function.doc.mjs
new file mode 100644
index 0000000000..02fd00e380
--- /dev/null
+++ b/packages/cli/authoring/doctypes/function/function.doc.mjs
@@ -0,0 +1,266 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file SchemaDoc for the `FunctionDoc` doc-type — the generalized
+ * `type: 'function'` doc that covers BOTH React hooks and CLI/programmatic API
+ * functions. Colocated with the type it describes (`type.ts`).
+ * @position packages/cli/authoring/doctypes/function — doc-type documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').SchemaDoc} */
+export const doc = {
+ type: 'schema',
+ name: 'function-doc',
+ displayName: 'FunctionDoc',
+ namespace: 'authoring',
+ description:
+ "The generalized `type: 'function'` doc-type covering both React hooks and CLI/API " +
+ 'functions. A hook (HookDoc) is the hook-flavored view of this same kind; FunctionDoc ' +
+ 'adds the fields an API function needs (a {type, data} return envelope, thrown error ' +
+ 'codes, the wrapping CLI command). The CLI binding itself lives in a separate CommandDoc.',
+ appliesTo: 'api/<name>/<name>.doc.mjs',
+ fields: [
+ {
+ name: 'type',
+ type: "'function'",
+ description: 'Doc-kind discriminant (shared with hooks).',
+ },
+ {
+ name: 'name',
+ type: 'string',
+ description: "Export name, e.g. 'search' | 'useMediaQuery'.",
+ required: true,
+ },
+ {
+ name: 'displayName',
+ type: 'string',
+ description: "Human-readable display name, e.g. 'search()'.",
+ required: true,
+ },
+ {
+ name: 'kind',
+ type: "'hook' | 'api'",
+ description:
+ 'Which flavor — drives docsite sectioning; inferred from importPath if omitted.',
+ },
+ {
+ name: 'summary',
+ type: 'string',
+ description: 'One-line summary.',
+ },
+ {
+ name: 'description',
+ type: 'string',
+ description: 'Longer description.',
+ },
+ {
+ name: 'namespace',
+ type: 'string',
+ description:
+ "Docs namespace path. Defaults (e.g. 'cli/api') applied by the docs index.",
+ },
+ {
+ name: 'aliases',
+ type: 'string[]',
+ description: 'Alternate slugs that also resolve to this doc.',
+ },
+ {
+ name: 'keywords',
+ type: 'string[]',
+ description: 'Search keywords for discovery.',
+ },
+ {
+ name: 'importPath',
+ type: 'string',
+ description:
+ "Import path, e.g. '@astryxdesign/cli/api' | '@astryxdesign/core/hooks'.",
+ },
+ {
+ name: 'signature',
+ type: 'string',
+ description:
+ "Full signature as a string, e.g. 'search(query, options?): Promise<SearchResponse>'.",
+ },
+ {
+ name: 'params',
+ type: 'HookParamDoc[]',
+ description: 'Parameters / options-object fields.',
+ required: true,
+ fields: [
+ {
+ name: 'params[].name',
+ type: 'string',
+ description: 'Parameter or option field name.',
+ required: true,
+ },
+ {
+ name: 'params[].type',
+ type: 'string',
+ description: 'TypeScript type signature as a string.',
+ required: true,
+ },
+ {
+ name: 'params[].description',
+ type: 'string',
+ description: 'What this parameter does. 1-2 sentences.',
+ required: true,
+ },
+ {
+ name: 'params[].default',
+ type: 'string',
+ description: 'Default value as a string, if optional with a default.',
+ },
+ {
+ name: 'params[].required',
+ type: 'boolean',
+ description: 'True if required. Omit if optional.',
+ },
+ ],
+ },
+ {
+ name: 'returns',
+ type: 'FunctionReturnDoc[]',
+ description:
+ 'Return documentation. Hooks list named return fields (`name` set); API functions list {type, data} envelope entries where `type` is the response discriminant and `name` is omitted.',
+ required: true,
+ fields: [
+ {
+ name: 'returns[].name',
+ type: 'string',
+ description: 'Field name (hooks) — omit for API envelope entries.',
+ },
+ {
+ name: 'returns[].type',
+ type: 'string',
+ description:
+ 'TS type (hooks) or response-type discriminant (API), as a string.',
+ required: true,
+ },
+ {
+ name: 'returns[].description',
+ type: 'string',
+ description: 'What this return value / envelope entry provides.',
+ required: true,
+ },
+ ],
+ },
+ {
+ name: 'throws',
+ type: 'FunctionThrowsDoc[]',
+ description:
+ 'Errors the function throws (API functions), keyed to ERROR_CODES.',
+ fields: [
+ {
+ name: 'throws[].code',
+ type: 'string',
+ description: 'The ERROR_CODES member thrown.',
+ required: true,
+ },
+ {
+ name: 'throws[].when',
+ type: 'string',
+ description: 'The condition under which it is thrown.',
+ required: true,
+ },
+ ],
+ },
+ {
+ name: 'examples',
+ type: 'FunctionExampleDoc[]',
+ description: 'Usage examples.',
+ fields: [
+ {
+ name: 'examples[].label',
+ type: 'string',
+ description: 'Optional heading shown above the snippet.',
+ },
+ {
+ name: 'examples[].code',
+ type: 'string',
+ description: 'Language-level usage, e.g. "await search(\'button\')".',
+ required: true,
+ },
+ {
+ name: 'examples[].result',
+ type: 'string',
+ description: 'Optional sample result.',
+ },
+ ],
+ },
+ {
+ name: 'usage',
+ type: 'UsageDoc',
+ description:
+ 'Usage documentation (hooks) — description, best practices, anatomy. Same shape as HookDoc.usage.',
+ },
+ {
+ name: 'command',
+ type: 'string',
+ description: "The CLI command that wraps this function, e.g. 'search'.",
+ },
+ {
+ name: 'related',
+ type: 'string[]',
+ description: 'Related function/command names.',
+ },
+ {
+ name: 'relatedComponents',
+ type: 'string[]',
+ description: 'Component names this is commonly used with (hooks).',
+ },
+ {
+ name: 'relatedHooks',
+ type: 'string[]',
+ description: 'Other hook names this is commonly used with (hooks).',
+ },
+ {
+ name: 'category',
+ type: 'string',
+ description: 'Category for grouping in listings.',
+ },
+ ],
+ examples: [
+ {
+ label: 'An API function doc (envelope return, no field name)',
+ code: `/** @type {import('@astryxdesign/cli/authoring').FunctionDoc} */
+export const doc = {
+ type: 'function',
+ kind: 'api',
+ name: 'search',
+ displayName: 'search()',
+ namespace: 'cli/api',
+ importPath: '@astryxdesign/cli/api',
+ summary: 'Find components, hooks, docs, and templates by term.',
+ signature: 'search(query, options?): Promise<SearchResponse>',
+ params: [
+ {name: 'query', type: 'string', description: 'The search term.', required: true},
+ {name: 'options.type', type: "'component' | 'hook' | 'doc' | 'template'", description: 'Restrict results to one domain.'},
+ ],
+ returns: [
+ {type: 'search', description: 'Envelope with the query and ranked results[].'},
+ ],
+ throws: [
+ {code: 'ERR_INVALID_ARGUMENT', when: 'query is empty.'},
+ ],
+ examples: [
+ {label: 'Basic', code: "await search('button')", result: "{ type: 'search', data: { results: [...] } }"},
+ ],
+ command: 'search',
+};`,
+ },
+ ],
+ notes: [
+ {
+ type: 'prose',
+ text: "The `type` discriminant is 'function' for both flavors. Set `kind: 'hook'` or `kind: 'api'` to drive docsite sectioning; it is inferred from `importPath` when omitted.",
+ },
+ {
+ type: 'prose',
+ text: 'The two flavors differ in `returns`: a hook lists named fields (`name` set), while an API function lists {type, data} envelope entries whose `type` is the response discriminant and whose `name` is omitted. `throws` (keyed to ERROR_CODES) applies to API functions.',
+ },
+ {
+ type: 'prose',
+ text: 'The function does not know it has a CLI. The terminal binding (args, flags, exit codes) lives in a separate CommandDoc that references this function via `fn`; here you only note the wrapping command name via `command`.',
+ },
+ ],
+};
diff --git a/packages/cli/authoring/doctypes/function/parse.d.mts b/packages/cli/authoring/doctypes/function/parse.d.mts
new file mode 100644
index 0000000000..d65e0149a8
--- /dev/null
+++ b/packages/cli/authoring/doctypes/function/parse.d.mts
@@ -0,0 +1,4 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import type {FunctionDoc} from '../types';
+export function parseFunction(input: unknown, label?: string): FunctionDoc;
diff --git a/packages/cli/authoring/doctypes/function/parse.mjs b/packages/cli/authoring/doctypes/function/parse.mjs
new file mode 100644
index 0000000000..aec4faf77b
--- /dev/null
+++ b/packages/cli/authoring/doctypes/function/parse.mjs
@@ -0,0 +1,10 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Function doc parser (stamped `type: 'function'`). Hooks and CLI/API
+ * functions share the discriminant and the sealed schema, so this is the same
+ * validator as `parseHook`, exported under the general name. Consumers call
+ * `parseFunction` or use `parseDoc`.
+ */
+
+export {parseHook as parseFunction} from '../hook/parse.mjs';
diff --git a/packages/cli/authoring/doctypes/function/type.ts b/packages/cli/authoring/doctypes/function/type.ts
new file mode 100644
index 0000000000..962ffff207
--- /dev/null
+++ b/packages/cli/authoring/doctypes/function/type.ts
@@ -0,0 +1,91 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Function doc types — the generalized `type: 'function'` doc that covers
+ * BOTH React hooks and CLI/programmatic API functions. A hook (`HookDoc`) is the
+ * hook-flavored view of this same kind; `FunctionDoc` adds the fields an API
+ * function needs (a `{type,data}` return envelope, thrown error codes, the CLI
+ * command that wraps it). Colocated at `api/<name>/<name>.doc.mjs` (API) or with
+ * the hook source (hooks). The CLI binding lives in a separate CommandDoc, not
+ * here — the function does not know it has a CLI.
+ */
+
+import type {HookParamDoc, UsageDoc} from '../base/type';
+
+/**
+ * A documented return. Hooks list named return fields (`name` set); CLI/API
+ * functions list `{type, data}` envelope entries where `type` is the response
+ * discriminant and `name` is omitted.
+ */
+export interface FunctionReturnDoc {
+ /** Field name (hooks) — omit for API envelope entries. */
+ name?: string;
+ /** TS type (hooks) or response-type discriminant (API), as a string. */
+ type: string;
+ description: string;
+}
+
+/** An error the function can throw, keyed to an ERROR_CODES member. */
+export interface FunctionThrowsDoc {
+ code: string;
+ when: string;
+}
+
+export interface FunctionExampleDoc {
+ label?: string;
+ /** Language-level usage, e.g. "await search('button')". */
+ code: string;
+ /** Optional sample result. */
+ result?: string;
+}
+
+/**
+ * A function documentation file (.doc.mjs).
+ *
+ * /\*\* @type {import('@astryxdesign/cli/authoring').FunctionDoc} \*\/
+ * export const doc = { type: 'function', kind: 'api', name: 'search', ... };
+ */
+export interface FunctionDoc {
+ /** Doc-kind discriminant (shared with hooks). */
+ type?: 'function';
+ /** Export name, e.g. 'search' | 'useMediaQuery'. */
+ name: string;
+ /** Human-readable display name, e.g. 'search()'. */
+ displayName: string;
+ /** Which flavor — drives docsite sectioning; inferred from importPath if omitted. */
+ kind?: 'hook' | 'api';
+ /** One-line summary. */
+ summary?: string;
+ /** Longer description. */
+ description?: string;
+ /** Docs namespace path. Defaults (e.g. 'cli/api') applied by the docs index. */
+ namespace?: string;
+ /** Alternate slugs that also resolve to this doc. */
+ aliases?: string[];
+ /** Search keywords for discovery. */
+ keywords?: string[];
+ /** Import path, e.g. '@astryxdesign/cli/api' | '@astryxdesign/core/hooks'. */
+ importPath?: string;
+ /** Full signature as a string, e.g. 'search(query, options?): Promise<SearchResponse>'. */
+ signature?: string;
+ /** Parameters / options-object fields. */
+ params: HookParamDoc[];
+ /** Return documentation (named fields for hooks; envelope entries for API). */
+ returns: FunctionReturnDoc[];
+ /** Errors the function throws (API functions), keyed to ERROR_CODES. */
+ throws?: FunctionThrowsDoc[];
+ /** Usage examples. */
+ examples?: FunctionExampleDoc[];
+ /** Usage documentation (hooks) — description, best practices, anatomy. */
+ usage?: UsageDoc;
+ /** The CLI command that wraps this function, e.g. 'search'. */
+ command?: string;
+ /** Related function/command names. */
+ related?: string[];
+ /** Component names this is commonly used with (hooks). */
+ relatedComponents?: string[];
+ /** Other hook names this is commonly used with (hooks). */
+ relatedHooks?: string[];
+ /** Category for grouping in listings. */
+ category?: string;
+}
diff --git a/packages/cli/authoring/doctypes/hook/hook.doc.mjs b/packages/cli/authoring/doctypes/hook/hook.doc.mjs
new file mode 100644
index 0000000000..f04fdcd7d3
--- /dev/null
+++ b/packages/cli/authoring/doctypes/hook/hook.doc.mjs
@@ -0,0 +1,200 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file SchemaDoc for the `HookDoc` doc-type — how to author a standalone
+ * React hook's `.doc.mjs`. Colocated with the type it describes (`type.ts`).
+ * @position packages/cli/authoring/doctypes/hook — doc-type documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').SchemaDoc} */
+export const doc = {
+ type: 'schema',
+ name: 'hook-doc',
+ displayName: 'HookDoc',
+ namespace: 'authoring',
+ description:
+ 'The doc-type for a standalone React hook (e.g. useMediaQuery, useFocusTrap, ' +
+ 'useOverflow) that gets its own `.doc.mjs`. Hooks that are part of a component API ' +
+ "(e.g. useImperativeDialog) belong in that component's MultiComponentDoc `components` " +
+ "array instead. `HookDoc` is the hook-flavored view of the shared `type: 'function'` kind.",
+ appliesTo: '{useX}.doc.mjs',
+ fields: [
+ {
+ name: 'type',
+ type: "'function'",
+ description:
+ 'Doc-kind discriminant (shared with FunctionDoc). Legacy `export const docs = {...}` docs omit it.',
+ },
+ {
+ name: 'name',
+ type: 'string',
+ description:
+ "Hook name exactly as exported, e.g. 'useMediaQuery', 'useFocusTrap'.",
+ required: true,
+ },
+ {
+ name: 'displayName',
+ type: 'string',
+ description:
+ "Human-readable display name. Hooks read better as the raw identifier ('useMediaQuery') than spaced, so keep the identifier verbatim.",
+ required: true,
+ },
+ {
+ name: 'group',
+ type: 'string',
+ description:
+ 'Optional group for sidebar/docs organization — same as ComponentDoc.group.',
+ },
+ {
+ name: 'keywords',
+ type: 'string[]',
+ description: 'Search keywords for CLI discovery.',
+ },
+ {
+ name: 'params',
+ type: 'HookParamDoc[]',
+ description: 'Hook parameters or options-object fields.',
+ required: true,
+ fields: [
+ {
+ name: 'params[].name',
+ type: 'string',
+ description: 'Parameter or option field name.',
+ required: true,
+ },
+ {
+ name: 'params[].type',
+ type: 'string',
+ description: 'TypeScript type signature as a string.',
+ required: true,
+ },
+ {
+ name: 'params[].description',
+ type: 'string',
+ description: 'What this parameter does. 1-2 sentences.',
+ required: true,
+ },
+ {
+ name: 'params[].default',
+ type: 'string',
+ description: 'Default value as a string, if optional with a default.',
+ },
+ {
+ name: 'params[].required',
+ type: 'boolean',
+ description: 'True if required. Omit if optional.',
+ },
+ ],
+ },
+ {
+ name: 'returns',
+ type: 'HookReturnDoc[]',
+ description:
+ 'Return value documentation. For object returns, list each field; for primitive returns, use a single entry.',
+ required: true,
+ fields: [
+ {
+ name: 'returns[].name',
+ type: 'string',
+ description:
+ "Field name on the returned object, or 'value' for primitive returns.",
+ required: true,
+ },
+ {
+ name: 'returns[].type',
+ type: 'string',
+ description: 'TypeScript type.',
+ required: true,
+ },
+ {
+ name: 'returns[].description',
+ type: 'string',
+ description: 'What this return value provides.',
+ required: true,
+ },
+ ],
+ },
+ {
+ name: 'usage',
+ type: 'UsageDoc',
+ description: 'Usage documentation — description and best practices.',
+ required: true,
+ fields: [
+ {
+ name: 'usage.description',
+ type: 'string',
+ description:
+ 'What the hook is and when to use it, in 2-3 short sentences.',
+ required: true,
+ },
+ {
+ name: 'usage.bestPractices',
+ type: 'ComponentBestPractice[]',
+ description:
+ "3-4 do/don't design-guidance items ({guidance: boolean, description: string}).",
+ },
+ {
+ name: 'usage.anatomy',
+ type: 'ComponentAnatomyElement[]',
+ description:
+ 'Structural/visual anatomy elements (rarely used for hooks).',
+ },
+ ],
+ },
+ {
+ name: 'relatedComponents',
+ type: 'string[]',
+ description:
+ 'Component names this hook is commonly used with. Enables cross-referencing (e.g. `astryx hook useToast` links back to Toast).',
+ },
+ {
+ name: 'relatedHooks',
+ type: 'string[]',
+ description: 'Other hook names this hook is commonly used with.',
+ },
+ {
+ name: 'importPath',
+ type: 'string',
+ description:
+ "Import path, e.g. '@astryxdesign/core/hooks' or '@astryxdesign/core/Toast'.",
+ },
+ {
+ name: 'category',
+ type: 'string',
+ description: 'Category for grouping in listings.',
+ },
+ ],
+ examples: [
+ {
+ label: 'A standalone hook doc',
+ code: `/** @type {import('@astryxdesign/cli/authoring').HookDoc} */
+export const docs = {
+ type: 'function',
+ name: 'useMediaQuery',
+ displayName: 'useMediaQuery',
+ importPath: '@astryxdesign/core/hooks',
+ params: [
+ {name: 'query', type: 'string', description: 'A CSS media query, e.g. "(min-width: 768px)".', required: true},
+ ],
+ returns: [
+ {name: 'matches', type: 'boolean', description: 'Whether the query currently matches.'},
+ ],
+ usage: {
+ description:
+ 'Subscribes to a CSS media query and re-renders when it changes. Use for responsive behavior that CSS alone cannot express, such as swapping components by breakpoint.',
+ },
+ relatedHooks: ['useIsMobile'],
+};`,
+ },
+ ],
+ notes: [
+ {
+ type: 'prose',
+ text: "A hook's discriminant is `type: 'function'` — HookDoc and FunctionDoc share the generalized function kind. HookDoc is the hook-flavored view: named `returns` fields and a required `usage` block.",
+ },
+ {
+ type: 'prose',
+ text: "Only standalone hooks get their own file. A hook that is part of a component API is documented as an entry in that component's MultiComponentDoc `components` array (with `params`/`returns`), so it renders under the component.",
+ },
+ ],
+};
diff --git a/packages/cli/authoring/doctypes/parse.d.mts b/packages/cli/authoring/doctypes/parse.d.mts
index 24a760f54f..bcea907a99 100644
--- a/packages/cli/authoring/doctypes/parse.d.mts
+++ b/packages/cli/authoring/doctypes/parse.d.mts
@@ -1,4 +1,21 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-import type {ComponentDoc, HookDoc, ReferenceDoc, TemplateDoc} from './types';
-export function parseDoc(input: unknown, label?: string): ComponentDoc | HookDoc | ReferenceDoc | TemplateDoc;
+import type {
+ ComponentDoc,
+ HookDoc,
+ FunctionDoc,
+ ReferenceDoc,
+ TemplateDoc,
+ SchemaDoc,
+ CommandDoc,
+ EnumDoc,
+} from './types';
+
+// Must stay in step with the @returns of parseDoc in ./parse.mjs — one entry per
+// doc kind it dispatches to. This declaration shadows the implementation for
+// published consumers, so a missing member silently makes that kind unnarrowable.
+// check:cli-structure enforces the coverage.
+export function parseDoc(
+ input: unknown,
+ label?: string,
+): ComponentDoc | HookDoc | FunctionDoc | ReferenceDoc | TemplateDoc | SchemaDoc | CommandDoc | EnumDoc;
diff --git a/packages/cli/authoring/doctypes/parse.mjs b/packages/cli/authoring/doctypes/parse.mjs
index 8e9403edda..a354d7dc37 100644
--- a/packages/cli/authoring/doctypes/parse.mjs
+++ b/packages/cli/authoring/doctypes/parse.mjs
@@ -12,21 +12,29 @@ import {parseComponent} from './component/parse.mjs';
import {parseHook} from './hook/parse.mjs';
import {parseReference} from './reference/parse.mjs';
import {parseTemplate} from './template/parse.mjs';
+import {parseSchema} from './schema/parse.mjs';
+import {parseCommand} from './command/parse.mjs';
+import {parseEnum} from './enum/parse.mjs';
import {parseLegacyDoc} from './legacy.mjs';
/** @typedef {import('./types').ComponentDoc} ComponentDoc */
/** @typedef {import('./types').HookDoc} HookDoc */
+/** @typedef {import('./types').FunctionDoc} FunctionDoc */
/** @typedef {import('./types').ReferenceDoc} ReferenceDoc */
/** @typedef {import('./types').TemplateDoc} TemplateDoc */
+/** @typedef {import('./types').SchemaDoc} SchemaDoc */
+/** @typedef {import('./types').CommandDoc} CommandDoc */
+/** @typedef {import('./types').EnumDoc} EnumDoc */
/**
* Validate an unknown loaded doc value into its typed shape, or throw.
* Dispatches on the stamped `type`; unstamped docs fall back to
- * shape-sniffing. The reference/topic discriminant is `'generic'`.
+ * shape-sniffing. The reference/topic discriminant is `'generic'`; a hook and a
+ * CLI/API function share `'function'`.
*
* @param {unknown} input
* @param {string} [label]
- * @returns {ComponentDoc | HookDoc | ReferenceDoc | TemplateDoc}
+ * @returns {ComponentDoc | HookDoc | FunctionDoc | ReferenceDoc | TemplateDoc | SchemaDoc | CommandDoc | EnumDoc}
*/
export function parseDoc(input, label = 'doc') {
const type =
@@ -44,6 +52,12 @@ export function parseDoc(input, label = 'doc') {
case 'page':
case 'block':
return parseTemplate(input, label);
+ case 'schema':
+ return parseSchema(input, label);
+ case 'command':
+ return parseCommand(input, label);
+ case 'enum':
+ return parseEnum(input, label);
default:
return parseLegacyDoc(input, label);
}
diff --git a/packages/cli/authoring/doctypes/reference/reference.doc.mjs b/packages/cli/authoring/doctypes/reference/reference.doc.mjs
new file mode 100644
index 0000000000..324f3d767e
--- /dev/null
+++ b/packages/cli/authoring/doctypes/reference/reference.doc.mjs
@@ -0,0 +1,146 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file SchemaDoc for the `ReferenceDoc` doc-type — how to author a topic/guide
+ * doc (design tokens, principles, theming, patterns, migration). Colocated with
+ * the type it describes (`type.ts`).
+ * @position packages/cli/authoring/doctypes/reference — doc-type documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').SchemaDoc} */
+export const doc = {
+ type: 'schema',
+ name: 'reference-doc',
+ displayName: 'ReferenceDoc',
+ namespace: 'authoring',
+ description:
+ 'The doc-type for a reference/topic doc — tokens, principles, theming, patterns, ' +
+ 'accessibility, migration guides. Unlike ComponentDoc it is not tied to a component: ' +
+ 'drop a `.doc.mjs` in the docs directory and it shows up in `astryx docs`. Content is ' +
+ 'built from ordered sections of mixed content blocks.',
+ appliesTo: 'assets/docs/<topic>.doc.mjs',
+ fields: [
+ {
+ name: 'type',
+ type: "'generic'",
+ description:
+ "Doc-kind discriminant. Stays 'generic' (the reference/topic discriminant). Legacy `export const docs = {...}` docs omit it.",
+ },
+ {
+ name: 'name',
+ type: 'string',
+ description:
+ "URL-safe identifier, used as the CLI topic name. e.g. 'tokens', 'principles'.",
+ required: true,
+ },
+ {
+ name: 'title',
+ type: 'string',
+ description:
+ "Human-readable title. e.g. 'All Tokens'. (Reference docs use `title`, not `displayName`.)",
+ required: true,
+ },
+ {
+ name: 'description',
+ type: 'string',
+ description: 'One-line summary shown in topic listings.',
+ required: true,
+ },
+ {
+ name: 'category',
+ type: 'string',
+ description: "Navigation category: 'guide' or 'foundations'.",
+ },
+ {
+ name: 'sections',
+ type: 'ReferenceSection[]',
+ description:
+ 'Ordered sections that make up the doc. Each becomes an h2 in full output and can be retrieved via `astryx docs <topic> <section>`.',
+ required: true,
+ fields: [
+ {
+ name: 'sections[].title',
+ type: 'string',
+ description:
+ 'Section title, e.g. "Spacing Tokens", "Light/Dark Mode".',
+ required: true,
+ },
+ {
+ name: 'sections[].category',
+ type: 'string',
+ description:
+ "Navigation category ('guide' | 'foundations'). Mirrors the parent doc's category so sections can be grouped independently.",
+ },
+ {
+ name: 'sections[].content',
+ type: 'ReferenceContentBlock[]',
+ description:
+ 'Ordered content blocks. Mix prose, code, tables, and lists freely.',
+ required: true,
+ },
+ {
+ name: 'sections[].previewType',
+ type: 'ReferenceTokenPreviewType',
+ description:
+ "Preview type for token tables in this section. When set, the docsite renders a visual preview column from the token's computed value. Omit for non-token sections.",
+ },
+ ],
+ },
+ {
+ name: 'tokenCategory',
+ type: 'string',
+ description:
+ "Token category for foundational docs that map to a token section (e.g. 'color'). Lets the tokens overview link to this doc for detailed guidance.",
+ },
+ ],
+ examples: [
+ {
+ label: 'A reference doc with one section',
+ code: `/** @type {import('@astryxdesign/cli/authoring').ReferenceDoc} */
+export const docs = {
+ type: 'generic',
+ name: 'spacing',
+ title: 'Spacing',
+ description: 'Spacing tokens for gap, margin, and padding.',
+ category: 'foundations',
+ tokenCategory: 'spacing',
+ sections: [
+ {
+ title: 'Spacing Tokens',
+ content: [
+ {type: 'prose', text: 'Use spacing tokens instead of raw pixel values so layouts stay on the 4px grid.'},
+ {type: 'table', headers: ['Token', 'Value'], rows: [['--spacing-4', '16px']]},
+ ],
+ previewType: 'spacing-bar',
+ },
+ ],
+};`,
+ },
+ ],
+ notes: [
+ {
+ type: 'prose',
+ text: 'Each `sections[].content` is an ordered array of ReferenceContentBlock — a discriminated union. New block types can be added without breaking existing docs. The same union is reused by the `notes` field on SchemaDoc and CommandDoc.',
+ },
+ {
+ type: 'code',
+ lang: 'ts',
+ label: 'ReferenceContentBlock union',
+ code: `type ReferenceContentBlock =
+ | { type: 'prose'; text: string }
+ | { type: 'heading'; level: 3 | 4 | 5 | 6; text: string }
+ | { type: 'code'; lang: string; code: string; label?: string }
+ | { type: 'table'; headers: string[]; rows: string[][] }
+ | { type: 'list'; style: 'ordered' | 'unordered' | 'do' | 'dont'; items: string[] }
+ | { type: 'token-ref'; topic: string; section: string };`,
+ },
+ {
+ type: 'prose',
+ text: "A `token-ref` block (e.g. {type: 'token-ref', topic: 'tokens', section: 'Color Tokens'}) references a token table in another topic; the CLI resolves and inlines it at read time so the docsite can render live theme values.",
+ },
+ {
+ type: 'prose',
+ text: "A section may set `previewType` to render a visual preview column for token tables — one of 'swatch' | 'shadow-box' | 'radius-box' | 'spacing-bar' | 'size-bar' | 'border-line' | 'duration-bar' | 'easing-curve' | 'font-sample'.",
+ },
+ ],
+};
diff --git a/packages/cli/authoring/doctypes/schema/parse.d.mts b/packages/cli/authoring/doctypes/schema/parse.d.mts
new file mode 100644
index 0000000000..50550ae09f
--- /dev/null
+++ b/packages/cli/authoring/doctypes/schema/parse.d.mts
@@ -0,0 +1,4 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import type {SchemaDoc} from '../types';
+export function parseSchema(input: unknown, label?: string): SchemaDoc;
diff --git a/packages/cli/authoring/doctypes/schema/parse.mjs b/packages/cli/authoring/doctypes/schema/parse.mjs
new file mode 100644
index 0000000000..9aa0df1435
--- /dev/null
+++ b/packages/cli/authoring/doctypes/schema/parse.mjs
@@ -0,0 +1,26 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Schema doc parser (stamped `type: 'schema'`). Zod is sealed in
+ * `../_schema.mjs`; consumers call `parseSchema` or use `parseDoc`.
+ */
+
+import {SchemaDocKindSchema} from '../_schema.mjs';
+import {formatZodError} from '../../_shared/errors.mjs';
+
+/** @typedef {import('../types').SchemaDoc} SchemaDoc */
+
+/**
+ * Validate an unknown value as a stamped schema doc, or throw.
+ *
+ * @param {unknown} input
+ * @param {string} [label]
+ * @returns {SchemaDoc}
+ */
+export function parseSchema(input, label = 'schema doc') {
+ const result = SchemaDocKindSchema.safeParse(input);
+ if (!result.success) {
+ throw new Error(formatZodError(label, result.error));
+ }
+ return /** @type {SchemaDoc} */ (/** @type {unknown} */ (result.data));
+}
diff --git a/packages/cli/authoring/doctypes/schema/schema.doc.mjs b/packages/cli/authoring/doctypes/schema/schema.doc.mjs
new file mode 100644
index 0000000000..6585a9fd05
--- /dev/null
+++ b/packages/cli/authoring/doctypes/schema/schema.doc.mjs
@@ -0,0 +1,197 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file SchemaDoc for the `SchemaDoc` doc-type itself — the self-describing
+ * entry that documents how to author a schema/object `.doc.mjs`. Colocated
+ * with the type it describes (`type.ts`).
+ * @position packages/cli/authoring/doctypes/schema — doc-type documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').SchemaDoc} */
+export const doc = {
+ type: 'schema',
+ name: 'schema-doc',
+ displayName: 'SchemaDoc',
+ namespace: 'authoring',
+ description:
+ 'The doc-type for documenting an authored/received OBJECT shape (astryx.config, ' +
+ 'a codemod payload, the doc-types themselves). Colocated as a `.doc.mjs` next to ' +
+ 'the schema it describes. Fields nest recursively, so a whole shape is one tree.',
+ appliesTo: '<schema>.doc.mjs',
+ fields: [
+ {
+ name: 'type',
+ type: "'schema'",
+ description: 'Doc-kind discriminant. Marks the file as a schema doc.',
+ },
+ {
+ name: 'name',
+ type: 'string',
+ description:
+ 'URL-safe identifier, used as the docs slug within its namespace.',
+ required: true,
+ example: "'config'",
+ },
+ {
+ name: 'displayName',
+ type: 'string',
+ description: 'Human-readable title.',
+ required: true,
+ example: "'Astryx Config'",
+ },
+ {
+ name: 'description',
+ type: 'string',
+ description: 'One-line summary shown in listings.',
+ required: true,
+ },
+ {
+ name: 'namespace',
+ type: 'string',
+ description:
+ "Docs namespace path (e.g. 'cli' | 'authoring'). Defaults are applied by the docs index; set explicitly to place the schema.",
+ },
+ {
+ name: 'aliases',
+ type: 'string[]',
+ description:
+ 'Alternate slugs that also resolve to this doc (back-compat).',
+ },
+ {
+ name: 'appliesTo',
+ type: 'string',
+ description:
+ "What this schema applies to, e.g. 'astryx.config.{ts,mjs,js}' | 'AstryxConfig'.",
+ },
+ {
+ name: 'fields',
+ type: 'SchemaFieldDoc[]',
+ description:
+ "The fields that make up the shape. Object-typed fields nest their members recursively via each field's own `fields`, so the whole shape is one tree.",
+ required: true,
+ fields: [
+ {
+ name: 'fields[].name',
+ type: 'string',
+ description:
+ "Field name, or a dotted path for a nested field (e.g. 'hooks.postCodemod').",
+ required: true,
+ },
+ {
+ name: 'fields[].type',
+ type: 'string',
+ description:
+ "TypeScript type signature as a string, e.g. 'string[]' | \"'a' | 'b'\".",
+ required: true,
+ },
+ {
+ name: 'fields[].description',
+ type: 'string',
+ description: 'What the field is for, in 1-2 sentences.',
+ required: true,
+ },
+ {
+ name: 'fields[].required',
+ type: 'boolean',
+ description:
+ "True if the field must be provided. Omit (don't set false) if optional.",
+ },
+ {
+ name: 'fields[].default',
+ type: 'string',
+ description: 'Default value as a string, if any.',
+ },
+ {
+ name: 'fields[].example',
+ type: 'string',
+ description: 'A short inline example value.',
+ },
+ {
+ name: 'fields[].deprecated',
+ type: 'string',
+ description: 'Deprecation reason, if the field is deprecated.',
+ },
+ {
+ name: 'fields[].fields',
+ type: 'SchemaFieldDoc[]',
+ description:
+ 'Nested object fields, for object-typed fields. Recursive.',
+ },
+ ],
+ },
+ {
+ name: 'examples',
+ type: '{ label?: string; code: string }[]',
+ description: 'Full example objects/snippets.',
+ fields: [
+ {
+ name: 'examples[].label',
+ type: 'string',
+ description: 'Optional heading shown above the snippet.',
+ },
+ {
+ name: 'examples[].code',
+ type: 'string',
+ description: 'The example source.',
+ required: true,
+ },
+ ],
+ },
+ {
+ name: 'notes',
+ type: 'ReferenceContentBlock[]',
+ description:
+ 'Freeform prose/notes rendered after the field table. Same block union as ReferenceDoc (prose, heading, code, table, list, token-ref).',
+ },
+ ],
+ examples: [
+ {
+ label: 'A small schema doc with a nested object field',
+ code: `/** @type {import('@astryxdesign/cli/authoring').SchemaDoc} */
+export const doc = {
+ type: 'schema',
+ name: 'integration',
+ displayName: 'Astryx Integration',
+ namespace: 'cli',
+ description: 'The astryx.integration.* manifest that registers the components a package provides.',
+ appliesTo: 'astryx.integration.{ts,mjs,js}',
+ fields: [
+ {name: 'name', type: 'string', description: 'Package name.', required: true},
+ {
+ name: 'components',
+ type: '{ dir: string }',
+ description: 'Where component sources live.',
+ fields: [
+ {name: 'components.dir', type: 'string', description: 'Glob root for XDS*.tsx files.', required: true},
+ ],
+ },
+ ],
+};`,
+ },
+ ],
+ notes: [
+ {
+ type: 'prose',
+ text: 'SchemaFieldDoc is recursive: an object-typed field lists its members in its own `fields`, so an entire nested shape (including paths like `hooks.postCodemod` or `experimental.xle.components`) is documented as one tree.',
+ },
+ {
+ type: 'prose',
+ text: 'Name nested fields with a dotted path from the root (e.g. `hooks.postCodemod`) so readers can see where each field sits in the shape.',
+ },
+ {
+ type: 'list',
+ style: 'do',
+ items: [
+ 'Set `required: true` only for mandatory fields.',
+ 'Keep `type` close to the real TS type; use single quotes for string-literal unions.',
+ ],
+ },
+ {
+ type: 'list',
+ style: 'dont',
+ items: [
+ 'Set `required: false` for optional fields — omit `required` entirely instead.',
+ ],
+ },
+ ],
+};
diff --git a/packages/cli/authoring/doctypes/schema/type.ts b/packages/cli/authoring/doctypes/schema/type.ts
new file mode 100644
index 0000000000..0d0b0eb1f3
--- /dev/null
+++ b/packages/cli/authoring/doctypes/schema/type.ts
@@ -0,0 +1,62 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Schema doc types — documentation for an authored/received OBJECT shape
+ * (astryx.config, astryx.integration, a codemod, the doc-types themselves, the
+ * response envelope). Colocated as a `.doc.mjs` next to the schema it describes.
+ */
+
+import type {ReferenceContentBlock} from '../reference/type';
+
+/**
+ * One documented field of a schema. Object fields nest via `fields`, so a whole
+ * shape (including `hooks.postCodemod` or `experimental.xle`) is one tree.
+ */
+export interface SchemaFieldDoc {
+ /** Field name, or a dotted path for a nested field (e.g. 'hooks.postCodemod'). */
+ name: string;
+ /** TypeScript type signature as a string, e.g. 'string[]' | "'a' | 'b'". */
+ type: string;
+ /** What the field is for, in 1-2 sentences. */
+ description: string;
+ /** True if the field must be provided. Omit (don't set false) if optional. */
+ required?: boolean;
+ /** Default value as a string, if any. */
+ default?: string;
+ /** A short inline example value. */
+ example?: string;
+ /** Deprecation reason, if the field is deprecated. */
+ deprecated?: string;
+ /** Nested object fields, for object-typed fields. */
+ fields?: SchemaFieldDoc[];
+}
+
+/**
+ * A schema/object documentation file (.doc.mjs), colocated with the schema.
+ *
+ * /\*\* @type {import('@astryxdesign/cli/authoring').SchemaDoc} \*\/
+ * export const doc = { type: 'schema', name: 'config', ... };
+ */
+export interface SchemaDoc {
+ /** Doc-kind discriminant. */
+ type?: 'schema';
+ /** URL-safe identifier, used as the docs slug within its namespace. */
+ name: string;
+ /** Human-readable title, e.g. 'Astryx Config'. */
+ displayName: string;
+ /** One-line summary shown in listings. */
+ description: string;
+ /** Docs namespace path (e.g. 'cli' | 'authoring'). Defaults are applied by
+ * the docs index; set explicitly to place the schema. */
+ namespace?: string;
+ /** Alternate slugs that also resolve to this doc (back-compat). */
+ aliases?: string[];
+ /** What this schema applies to, e.g. 'astryx.config.{ts,mjs,js}' | 'AstryxConfig'. */
+ appliesTo?: string;
+ /** The fields that make up the shape. */
+ fields: SchemaFieldDoc[];
+ /** Full example objects/snippets. */
+ examples?: {label?: string; code: string}[];
+ /** Freeform prose/notes rendered after the field table. */
+ notes?: ReferenceContentBlock[];
+}
diff --git a/packages/cli/authoring/doctypes/template/template.doc.mjs b/packages/cli/authoring/doctypes/template/template.doc.mjs
new file mode 100644
index 0000000000..b6a4eac955
--- /dev/null
+++ b/packages/cli/authoring/doctypes/template/template.doc.mjs
@@ -0,0 +1,162 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file SchemaDoc for the `TemplateDoc` doc-type — how to author metadata for a
+ * page or block template. A union of PageTemplateDoc and BlockTemplateDoc that
+ * share BaseTemplateDoc. Colocated with the type it describes (`type.ts`).
+ * @position packages/cli/authoring/doctypes/template — doc-type documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').SchemaDoc} */
+export const doc = {
+ type: 'schema',
+ name: 'template-doc',
+ displayName: 'TemplateDoc',
+ namespace: 'authoring',
+ description:
+ 'The doc-type for template metadata. A discriminated union of PageTemplateDoc ' +
+ "(type: 'page') for full page templates and BlockTemplateDoc (type: 'block') for " +
+ 'component example blocks. Both share BaseTemplateDoc; block templates add ' +
+ 'example/preview fields.',
+ appliesTo: '<Name>.template.mjs',
+ fields: [
+ {
+ name: 'type',
+ type: "'page' | 'block'",
+ description:
+ "Discriminant selecting the variant: 'page' for a full page template, 'block' for a component example block.",
+ required: true,
+ },
+ {
+ name: 'name',
+ type: 'string',
+ description:
+ 'Identifier. For block templates it matches the React component import name; for page templates it is a human-readable label.',
+ required: true,
+ },
+ {
+ name: 'displayName',
+ type: 'string',
+ description:
+ "Human-readable label for the gallery/CLI. Spaces out block names that mirror a PascalCase component ('ChatMessageMetadata' → 'Chat Message Metadata').",
+ required: true,
+ },
+ {
+ name: 'description',
+ type: 'string',
+ description: 'One-sentence description of what the template provides.',
+ },
+ {
+ name: 'isReady',
+ type: 'boolean',
+ description:
+ "Whether the template is ready for use. false shows as '(WIP)' in the gallery and CLI.",
+ },
+ {
+ name: 'scaffold',
+ type: 'boolean',
+ description:
+ 'Scaffolding-only template (e.g. blank page): available via the CLI but hidden from browsable galleries.',
+ },
+ {
+ name: 'category',
+ type: 'TemplateCategory',
+ description:
+ "Functional gallery category following a 'Group - Variant' convention (e.g. 'Dashboard - Analytics', 'Table - Basic', 'Form - Wizard'). The overview groups by the text before ' - '.",
+ },
+ {
+ name: 'isHiddenFromOverview',
+ type: 'boolean',
+ description:
+ 'Opt out of the Templates overview gallery while staying available via the CLI. Use for duplicate/experimental variants. Scaffold templates are hidden automatically.',
+ },
+ {
+ name: 'exampleFor',
+ type: 'string',
+ description:
+ "Block templates only (required): the component this block is an example of, matching the component's doc name (e.g. 'Button'). Powers examples on component detail pages.",
+ },
+ {
+ name: 'alsoExampleFor',
+ type: 'string[]',
+ description:
+ 'Block templates only: additional component/hook doc pages whose Examples section should include this block.',
+ },
+ {
+ name: 'alsoShowcaseFor',
+ type: 'string[]',
+ description:
+ 'Block templates only: additional doc pages whose hero showcase should reuse this block (secondary placements; does not change the primary showcase).',
+ },
+ {
+ name: 'aspectRatio',
+ type: 'number',
+ description:
+ 'Block templates only (required): width-to-height ratio for preview containers (e.g. 16/9, 1, 3/4).',
+ },
+ {
+ name: 'scale',
+ type: 'number',
+ description: 'Block templates only: scale factor for the block preview.',
+ default: '1',
+ },
+ {
+ name: 'componentsUsed',
+ type: 'string[]',
+ description:
+ "Block templates only: component names this block uses, for 'See also'/'Used in' cross-references (not primary attribution).",
+ },
+ {
+ name: 'isShowcase',
+ type: 'boolean',
+ description:
+ "Block templates only: when true this block is the canonical 'hero' showcase for its `exampleFor` component.",
+ },
+ ],
+ examples: [
+ {
+ label: 'Page template',
+ code: `/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
+export const doc = {
+ type: 'page',
+ name: 'Dashboard',
+ displayName: 'Dashboard',
+ description: 'An analytics dashboard with KPI cards and charts.',
+ category: 'Dashboard - Analytics',
+ isReady: true,
+};`,
+ },
+ {
+ label: 'Block template (component example)',
+ code: `/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
+export const doc = {
+ type: 'block',
+ name: 'ButtonGroupExample',
+ displayName: 'Button Group Example',
+ description: 'A row of related buttons showing primary and secondary actions.',
+ exampleFor: 'Button',
+ aspectRatio: 16 / 9,
+ componentsUsed: ['Button', 'HStack'],
+ isShowcase: true,
+};`,
+ },
+ ],
+ notes: [
+ {
+ type: 'prose',
+ text: "TemplateDoc is a discriminated union keyed by `type`. Set `type: 'page'` for a standalone page template (only the BaseTemplateDoc fields apply) or `type: 'block'` for a component example (the exampleFor/aspectRatio/showcase fields apply).",
+ },
+ {
+ type: 'list',
+ style: 'unordered',
+ items: [
+ "PageTemplateDoc (type: 'page') — a full page template; `name` doubles as its display value.",
+ "BlockTemplateDoc (type: 'block') — an example of a component; requires `exampleFor` and `aspectRatio`.",
+ ],
+ },
+ {
+ type: 'prose',
+ text: "`category` uses the shared TemplateCategory taxonomy: 'Group - Variant' strings (e.g. 'Table - Bulk Actions'). Not every value maps to an existing template — unused values are reserved so authors get autocomplete for the full taxonomy.",
+ },
+ ],
+};
diff --git a/packages/cli/authoring/doctypes/types.ts b/packages/cli/authoring/doctypes/types.ts
index 9c0793ea33..29fa9b0c5f 100644
--- a/packages/cli/authoring/doctypes/types.ts
+++ b/packages/cli/authoring/doctypes/types.ts
@@ -10,5 +10,9 @@
export type * from './base/type';
export type * from './component/type';
export type * from './hook/type';
+export type * from './function/type';
export type * from './reference/type';
export type * from './template/type';
+export type * from './schema/type';
+export type * from './command/type';
+export type * from './enum/type';
diff --git a/packages/cli/authoring/index.d.ts b/packages/cli/authoring/index.d.ts
index 1bcb0ba77c..6f1fba37a5 100644
--- a/packages/cli/authoring/index.d.ts
+++ b/packages/cli/authoring/index.d.ts
@@ -25,8 +25,12 @@
// ═══════════════════════════════════════════════════════════════════════
export type {ComponentDoc} from './doctypes/types'; // Button.doc.{ts,mjs}
export type {HookDoc} from './doctypes/types'; // useToast.doc.{ts,mjs}
+export type {FunctionDoc} from './doctypes/types'; // search.doc.mjs (hook | api)
export type {ReferenceDoc} from './doctypes/types'; // theming.doc.{ts,mjs}
export type {TemplateDoc} from './doctypes/types'; // Foo.template.{ts,mjs}
+export type {SchemaDoc} from './doctypes/types'; // config.doc.mjs (object shape)
+export type {CommandDoc} from './doctypes/types'; // search.doc.mjs (CLI command)
+export type {EnumDoc} from './doctypes/types'; // error-codes.doc.mjs (vocabulary)
export type {AstryxConfig} from './config/type'; // astryx.config.{ts,mjs}
export type {AstryxIntegration} from './integration/type'; // astryx.integration.{ts,mjs}
export type {AstryxCodemod, AstryxConfigCodemod} from './codemod/type'; // codemods/*
@@ -37,8 +41,12 @@ export type {AstryxCodemod, AstryxConfigCodemod} from './codemod/type'; // codem
export {parseDoc} from './doctypes/parse.mjs';
export {parseComponent} from './doctypes/component/parse.mjs';
export {parseHook} from './doctypes/hook/parse.mjs';
+export {parseFunction} from './doctypes/function/parse.mjs';
export {parseReference} from './doctypes/reference/parse.mjs';
export {parseTemplate} from './doctypes/template/parse.mjs';
+export {parseSchema} from './doctypes/schema/parse.mjs';
+export {parseCommand} from './doctypes/command/parse.mjs';
+export {parseEnum} from './doctypes/enum/parse.mjs';
export {parseLegacyDoc} from './doctypes/legacy.mjs';
export {parseConfig} from './config/parse.mjs';
export {parseIntegration} from './integration/parse.mjs';
@@ -70,6 +78,10 @@ export type {
HookParamDoc,
HookReturnDoc,
HookTranslationDoc,
+ // function (hooks + CLI/API functions)
+ FunctionReturnDoc,
+ FunctionThrowsDoc,
+ FunctionExampleDoc,
// reference
ReferenceSection,
ReferenceContentBlock,
@@ -77,6 +89,14 @@ export type {
ReferenceTranslationDoc,
// template
TemplateCategory,
+ // schema
+ SchemaFieldDoc,
+ // command
+ CommandArgDoc,
+ CommandOptionDoc,
+ CommandExampleDoc,
+ // enum
+ EnumMemberDoc,
} from './doctypes/types';
export type {PostCodemodHook} from './config/type';
export type {
diff --git a/packages/cli/authoring/index.mjs b/packages/cli/authoring/index.mjs
index 2d00f345e6..2bed05337a 100644
--- a/packages/cli/authoring/index.mjs
+++ b/packages/cli/authoring/index.mjs
@@ -20,6 +20,10 @@ export {parseCodemod} from './codemod/parse.mjs';
export {parseDoc} from './doctypes/parse.mjs';
export {parseComponent} from './doctypes/component/parse.mjs';
export {parseHook} from './doctypes/hook/parse.mjs';
+export {parseFunction} from './doctypes/function/parse.mjs';
export {parseReference} from './doctypes/reference/parse.mjs';
export {parseTemplate} from './doctypes/template/parse.mjs';
+export {parseSchema} from './doctypes/schema/parse.mjs';
+export {parseCommand} from './doctypes/command/parse.mjs';
+export {parseEnum} from './doctypes/enum/parse.mjs';
export {parseLegacyDoc} from './doctypes/legacy.mjs';
diff --git a/packages/cli/authoring/integration/integration.doc.mjs b/packages/cli/authoring/integration/integration.doc.mjs
new file mode 100644
index 0000000000..0462a85fa4
--- /dev/null
+++ b/packages/cli/authoring/integration/integration.doc.mjs
@@ -0,0 +1,75 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file SchemaDoc for the `astryx.integration.*` manifest (AstryxIntegration).
+ * Colocated with the schema (`type.ts` + `parse.mjs`) it documents.
+ * @position packages/cli/authoring/integration — schema documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').SchemaDoc} */
+export const doc = {
+ type: 'schema',
+ name: 'integration',
+ displayName: 'Astryx Integration',
+ namespace: 'cli',
+ description:
+ 'The astryx.integration.* manifest that sits beside an integration ' +
+ "package's package.json. Points the CLI at the package's components, " +
+ 'templates, and codemods, and where to file issues. Every field is optional.',
+ appliesTo: 'astryx.integration.{ts,mjs,js}',
+ fields: [
+ {
+ name: 'components',
+ type: 'string',
+ description:
+ 'Relative path to the components/docs root (resolved to absolute).',
+ example: "'./src/components'",
+ },
+ {
+ name: 'templates',
+ type: 'string',
+ description:
+ 'Relative path to the templates root (resolved to absolute).',
+ example: "'./src/templates'",
+ },
+ {
+ name: 'codemods',
+ type: 'string',
+ description: 'Relative path to the codemods root (resolved to absolute).',
+ example: "'./codemods'",
+ },
+ {
+ name: 'issuesUrl',
+ type: 'string',
+ description: 'Where to file issues/feedback for this integration.',
+ example: "'https://github.com/acme/widgets/issues'",
+ },
+ ],
+ examples: [
+ {
+ label: 'Typical',
+ code: `export default {
+ components: './src/components',
+ templates: './src/templates',
+ codemods: './codemods',
+ issuesUrl: 'https://github.com/acme/widgets/issues',
+};`,
+ },
+ ],
+ notes: [
+ {
+ type: 'prose',
+ text:
+ "Identity — the integration's name and version — comes from the " +
+ "package's package.json, not from this manifest. The manifest only " +
+ 'declares where the CLI finds each kind of artifact.',
+ },
+ {
+ type: 'prose',
+ text:
+ 'Validate a manifest with `astryx validate-integration`. It is checked ' +
+ 'at the load boundary with a strict schema (parseIntegration): unknown ' +
+ 'keys are errors, and issuesUrl must be a valid URL.',
+ },
+ ],
+};
diff --git a/packages/cli/clients/cli/commands/blog.doc.mjs b/packages/cli/clients/cli/commands/blog.doc.mjs
new file mode 100644
index 0000000000..2edace9db7
--- /dev/null
+++ b/packages/cli/clients/cli/commands/blog.doc.mjs
@@ -0,0 +1,32 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CommandDoc for `astryx blog`. The terminal binding of the `blog()`
+ * 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: 'blog',
+ displayName: 'astryx blog',
+ namespace: 'cli',
+ summary: 'Read the Astryx blog from the published feed',
+ description:
+ 'Reads the design-system blog over its published RSS feed (never the source ' +
+ "files). With no slug it lists every post; with a slug it reads that post's " +
+ 'full plaintext body.',
+ fn: 'blog',
+ args: [{name: 'slug', param: 'slug', required: false}],
+ examples: [
+ {label: 'List posts', cli: 'astryx blog'},
+ {label: 'Read one post', cli: 'astryx blog introducing-astryx --json'},
+ ],
+ exitCodes: [
+ {code: 0, when: 'success'},
+ {code: 1, when: 'unknown slug, or the feed or a post cannot be fetched'},
+ ],
+ related: ['docs', 'search'],
+};
diff --git a/packages/cli/clients/cli/commands/blog.mjs b/packages/cli/clients/cli/commands/blog.mjs
index 062f612e17..310d8699eb 100644
--- a/packages/cli/clients/cli/commands/blog.mjs
+++ b/packages/cli/clients/cli/commands/blog.mjs
@@ -19,15 +19,17 @@ import {jsonOut} from '../../../foundation/response/json.mjs';
import {emit, section, text, record, records, code} from '../formatters/index.mjs';
import {cliError} from '../lib/cli-error.mjs';
import {blog as blogApi} from '../../../api/blog/blog.mjs';
+import {defineCommand} from '../lib/define-command.mjs';
+import {doc as blogCommand} from './blog.doc.mjs';
+import {doc as blogFn} from '../../../api/blog/blog.doc.mjs';
/**
* @param {import('commander').Command} program
*/
export function registerBlog(program) {
- program
- .command('blog [slug]')
- .description('Read the Astryx blog from the published feed')
- .action(async (/** @type {string | undefined} */ slug) => {
+ defineCommand(program, blogCommand, {
+ fn: blogFn,
+ action: async (/** @type {string | undefined} */ slug) => {
const run = getRunPrefix();
/** @type {import('../../../api/blog/blog.type.mjs').BlogListResponse | import('../../../api/blog/blog.type.mjs').BlogDetailResponse} */
let result;
@@ -68,5 +70,6 @@ export function registerBlog(program) {
// (code() so article typography/spacing isn't ASCII-normalized).
emit(record({feed: result.data.feedUrl}), code(result.data.text));
}
- });
+ },
+ });
}
diff --git a/packages/cli/clients/cli/commands/build-theme.mjs b/packages/cli/clients/cli/commands/build-theme.mjs
index eec3ac35e0..bfbb5a2fa1 100644
--- a/packages/cli/clients/cli/commands/build-theme.mjs
+++ b/packages/cli/clients/cli/commands/build-theme.mjs
@@ -10,6 +10,10 @@
* AstryxError → cliError. Watch mode (a human-interactive, long-running loop)
* stays here because it re-invokes `theme build` as a child process.
*
+ * The command surface (group + subcommand descriptions, args, flags) is sourced
+ * from the colocated CommandDocs via `defineCommand`; this file supplies only
+ * the actions (and the group's unknown-subcommand guard).
+ *
* Usage:
* astryx theme build ./src/themes/ocean.ts
* astryx theme build ./src/themes/ocean.ts --out ./dist/ocean.css
@@ -28,6 +32,14 @@ import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
import {themeAdd} from '../../../api/theme/add/add.mjs';
import {themeList} from '../../../api/theme/list/list.mjs';
import {themeBuild, importSpecifier} from '../../../api/theme/build/build.mjs';
+import {defineCommand} from '../lib/define-command.mjs';
+import {doc as themeGroup} from './theme.doc.mjs';
+import {doc as themeBuildCommand} from './theme-build.doc.mjs';
+import {doc as themeListCommand} from './theme-list.doc.mjs';
+import {doc as themeAddCommand} from './theme-add.doc.mjs';
+import {doc as themeBuildFn} from '../../../api/theme/themeBuild.doc.mjs';
+import {doc as themeListFn} from '../../../api/theme/themeList.doc.mjs';
+import {doc as themeAddFn} from '../../../api/theme/themeAdd.doc.mjs';
/**
* Path to this CLI's real entry (clients/cli/bin/astryx.mjs), resolved from
@@ -161,121 +173,106 @@ function printThemeList(themes) {
* @param {import('commander').Command} program
*/
export function registerTheme(program) {
- const theme = program
- .command('theme')
- .description('Theme tools — build, export, and manage themes')
- .action(
- (
- /** @type {unknown} */ options,
- /** @type {import('commander').Command} */ cmd,
- ) => {
- // Parent group has no default behaviour. If the user passed an
- // unknown subcommand (e.g. `astryx theme bogus`), Commander hands it to
- // us as a positional in cmd.args — exit 1 with a clear error.
- const extras = (cmd && cmd.args) || [];
- if (extras.length > 0) {
- const unknown = String(extras[0]);
- const known = (theme.commands || []).map(c => c.name());
- const suggestions = known.map(name => ({
- name,
- reason: 'available subcommand',
- }));
- cliError(`unknown subcommand 'theme ${unknown}'`, {
- suggestions,
- code: ERROR_CODES.ERR_UNKNOWN_SUBCOMMAND,
- });
- return;
- }
- // Bare `astryx theme` — show the subcommand list. Exit 0 (help is success).
- theme.help();
- },
- );
+ const theme = defineCommand(program, themeGroup, {
+ action: (
+ /** @type {unknown} */ options,
+ /** @type {import('commander').Command} */ cmd,
+ ) => {
+ // Parent group has no default behaviour. If the user passed an
+ // unknown subcommand (e.g. `astryx theme bogus`), Commander hands it to
+ // us as a positional in cmd.args — exit 1 with a clear error.
+ const extras = (cmd && cmd.args) || [];
+ if (extras.length > 0) {
+ const unknown = String(extras[0]);
+ const known = (theme.commands || []).map(c => c.name());
+ const suggestions = known.map(name => ({
+ name,
+ reason: 'available subcommand',
+ }));
+ cliError(`unknown subcommand 'theme ${unknown}'`, {
+ suggestions,
+ code: ERROR_CODES.ERR_UNKNOWN_SUBCOMMAND,
+ });
+ return;
+ }
+ // Bare `astryx theme` — show the subcommand list. Exit 0 (help is success).
+ theme.help();
+ },
+ });
- theme
- .command('build <file>')
- .description('Compile a defineTheme file to CSS + JS')
- .option('-o, --out <path>', 'Output CSS file path')
- .option(
- '-w, --watch',
- 'Rebuild automatically when the theme file changes (Ctrl-C to stop)',
- )
- .option(
- '-c, --check',
- 'Verify the committed outputs match the source without writing; exit non-zero if stale',
- )
- .action(
- async (
- /** @type {string} */ file,
- /** @type {{out?: string, watch?: boolean, check?: boolean}} */ options,
- ) => {
- const filePath = path.resolve(process.cwd(), file);
- const json = program.opts().json || false;
+ defineCommand(theme, themeBuildCommand, {
+ fn: themeBuildFn,
+ action: async (
+ /** @type {string} */ file,
+ /** @type {{out?: string, watch?: boolean, check?: boolean}} */ options,
+ ) => {
+ const filePath = path.resolve(process.cwd(), file);
+ const json = program.opts().json || false;
- if (!fs.existsSync(filePath)) {
- cliError(`File not found: ${filePath}`, {
- code: ERROR_CODES.ERR_FILE_NOT_FOUND,
- });
- return;
- }
+ if (!fs.existsSync(filePath)) {
+ cliError(`File not found: ${filePath}`, {
+ code: ERROR_CODES.ERR_FILE_NOT_FOUND,
+ });
+ return;
+ }
- // --check and --watch are mutually exclusive: check is a one-shot,
- // exit-coded verification; watch is a long-running rebuild loop.
- if (options.check && options.watch) {
- cliError('--check cannot be combined with --watch', {
+ // --check and --watch are mutually exclusive: check is a one-shot,
+ // exit-coded verification; watch is a long-running rebuild loop.
+ if (options.check && options.watch) {
+ cliError('--check cannot be combined with --watch', {
+ code: ERROR_CODES.ERR_THEME_INVALID,
+ });
+ return;
+ }
+
+ // Watch mode: run an initial build, then rebuild on every change to the
+ // theme file. Watch is a human-interactive, long-running mode — it is not
+ // supported in --json (machine) mode, which expects a single envelope.
+ if (options.watch) {
+ if (json) {
+ cliError('--watch is not supported with --json', {
code: ERROR_CODES.ERR_THEME_INVALID,
});
return;
}
+ await runThemeBuildWatch(file, filePath, options);
+ return;
+ }
- // Watch mode: run an initial build, then rebuild on every change to the
- // theme file. Watch is a human-interactive, long-running mode — it is not
- // supported in --json (machine) mode, which expects a single envelope.
- if (options.watch) {
- if (json) {
- cliError('--watch is not supported with --json', {
- code: ERROR_CODES.ERR_THEME_INVALID,
- });
- return;
- }
- await runThemeBuildWatch(file, filePath, options);
- return;
- }
-
- // Non-watch: delegate to the API compiler. Enable human output unless in
- // --json mode (log → stdout via humanLog, warn/error → stderr). The
- // "Building theme from" line, the ✓/warning lines, and the install
- // instructions are all emitted from inside themeBuild via the shared logger.
- logger.setSilent(json);
- try {
- const result = await themeBuild(
- file,
- {out: options.out, check: options.check},
- {cwd: process.cwd()},
- );
- if (json && result) jsonOut(result);
- // In --check mode a stale/missing output is a failure: exit non-zero
- // (after emitting the receipt) so CI can gate on it. The receipt is
- // already printed above (shared logger or --json envelope).
- if (
- options.check &&
- result &&
- result.type === 'theme.build.check' &&
- !result.data.upToDate
- ) {
- process.exitCode = 1;
- }
- } catch (e) {
- const err =
- /** @type {import('../../../api/error.mjs').AstryxError} */ (e);
- cliError(err.message, {suggestions: err.suggestions, code: err.code});
+ // Non-watch: delegate to the API compiler. Enable human output unless in
+ // --json mode (log → stdout via humanLog, warn/error → stderr). The
+ // "Building theme from" line, the ✓/warning lines, and the install
+ // instructions are all emitted from inside themeBuild via the shared logger.
+ logger.setSilent(json);
+ try {
+ const result = await themeBuild(
+ file,
+ {out: options.out, check: options.check},
+ {cwd: process.cwd()},
+ );
+ if (json && result) jsonOut(result);
+ // In --check mode a stale/missing output is a failure: exit non-zero
+ // (after emitting the receipt) so CI can gate on it. The receipt is
+ // already printed above (shared logger or --json envelope).
+ if (
+ options.check &&
+ result &&
+ result.type === 'theme.build.check' &&
+ !result.data.upToDate
+ ) {
+ process.exitCode = 1;
}
- },
- );
+ } catch (e) {
+ const err =
+ /** @type {import('../../../api/error.mjs').AstryxError} */ (e);
+ cliError(err.message, {suggestions: err.suggestions, code: err.code});
+ }
+ },
+ });
- theme
- .command('list')
- .description('List themes available to add')
- .action(async () => {
+ defineCommand(theme, themeListCommand, {
+ fn: themeListFn,
+ action: async () => {
const json = program.opts().json || false;
/** @type {import('../../../api/theme/theme.type.mjs').ThemeListResponse} */
let result;
@@ -294,73 +291,70 @@ export function registerTheme(program) {
if (json) return jsonOut(result);
printThemeList(result.data);
- });
+ },
+ });
- theme
- .command('add [slug] [path]')
- .description('Scaffold a theme into your project as editable source')
- .option('-f, --overwrite', 'Overwrite existing files without prompting')
- .option('--list', 'List available themes')
- .action(
- async (
- /** @type {string | undefined} */ slug,
- /** @type {string | undefined} */ targetPath,
- /** @type {{list?: boolean, overwrite?: boolean}} */ options,
- ) => {
- const json = program.opts().json || false;
+ defineCommand(theme, themeAddCommand, {
+ fn: themeAddFn,
+ action: async (
+ /** @type {string | undefined} */ slug,
+ /** @type {string | undefined} */ targetPath,
+ /** @type {{list?: boolean, overwrite?: boolean}} */ options,
+ ) => {
+ const json = program.opts().json || false;
- // The CLI is non-interactive: never prompt to confirm an overwrite.
- // Existing files require an explicit --overwrite; otherwise themeAdd's
- // ERR_FILE_EXISTS guard rejects the write. `--list` (or a bare `theme add`
- // with no slug) is the list affordance — route it to the list leaf.
- /** @type {import('../../../api/theme/theme.type.mjs').ThemeListResponse | import('../../../api/theme/theme.type.mjs').ThemeAddResponse} */
- let result;
- try {
- result =
- options.list || !slug
- ? themeList()
- : await themeAdd(slug, {
- targetPath,
- overwrite: options.overwrite,
- cwd: process.cwd(),
- });
- } catch (e) {
- const err =
- /** @type {import('../../../api/error.mjs').AstryxError} */ (e);
- cliError(err.message, {
- suggestions: err.suggestions || [],
- code: err.code,
- });
- return;
- }
+ // The CLI is non-interactive: never prompt to confirm an overwrite.
+ // Existing files require an explicit --overwrite; otherwise themeAdd's
+ // ERR_FILE_EXISTS guard rejects the write. `--list` (or a bare `theme add`
+ // with no slug) is the list affordance — route it to the list leaf.
+ /** @type {import('../../../api/theme/theme.type.mjs').ThemeListResponse | import('../../../api/theme/theme.type.mjs').ThemeAddResponse} */
+ let result;
+ try {
+ result =
+ options.list || !slug
+ ? themeList()
+ : await themeAdd(slug, {
+ targetPath,
+ overwrite: options.overwrite,
+ cwd: process.cwd(),
+ });
+ } catch (e) {
+ const err =
+ /** @type {import('../../../api/error.mjs').AstryxError} */ (e);
+ cliError(err.message, {
+ suggestions: err.suggestions || [],
+ code: err.code,
+ });
+ return;
+ }
- if (json) return jsonOut(result);
+ if (json) return jsonOut(result);
- if (result.type === 'theme.list') {
- printThemeList(result.data);
- return;
- }
+ if (result.type === 'theme.list') {
+ printThemeList(result.data);
+ return;
+ }
- // theme.add — print where files landed + how to use the theme.
- const {displayName, outputDir, entry, exportName, files} = result.data;
- const entryModule = importSpecifier(
- outputDir,
- entry.replace(/\.tsx?$/, ''),
- );
- emit(
- text(`[ok] Added ${displayName} theme to ${outputDir}/`),
- list(files.map(f => `${outputDir}/${f}`)),
- text(
- 'Use it in your app (import path is relative to a file in src/ — adjust if yours lives elsewhere):',
- ),
- code(
- `import { ${exportName} } from '${entryModule}';\n\n` +
- `<Theme theme={${exportName}}>\n <App />\n</Theme>`,
- ),
- text(
- `This is your copy of the ${displayName} theme — edit ${entry} to make it your own.`,
- ),
- );
- },
- );
+ // theme.add — print where files landed + how to use the theme.
+ const {displayName, outputDir, entry, exportName, files} = result.data;
+ const entryModule = importSpecifier(
+ outputDir,
+ entry.replace(/\.tsx?$/, ''),
+ );
+ emit(
+ text(`[ok] Added ${displayName} theme to ${outputDir}/`),
+ list(files.map(f => `${outputDir}/${f}`)),
+ text(
+ 'Use it in your app (import path is relative to a file in src/ — adjust if yours lives elsewhere):',
+ ),
+ code(
+ `import { ${exportName} } from '${entryModule}';\n\n` +
+ `<Theme theme={${exportName}}>\n <App />\n</Theme>`,
+ ),
+ text(
+ `This is your copy of the ${displayName} theme — edit ${entry} to make it your own.`,
+ ),
+ );
+ },
+ });
}
diff --git a/packages/cli/clients/cli/commands/build.doc.mjs b/packages/cli/clients/cli/commands/build.doc.mjs
new file mode 100644
index 0000000000..7c3a14709f
--- /dev/null
+++ b/packages/cli/clients/cli/commands/build.doc.mjs
@@ -0,0 +1,50 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CommandDoc for `astryx build`. The terminal binding of the `build()`
+ * 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: 'build',
+ displayName: 'astryx build',
+ namespace: 'cli',
+ summary:
+ 'Build a page: composition kit for an idea, or the workflow playbook (no args)',
+ description:
+ 'The assemble-a-page entry point. With no query it returns the how-to-build-a-page ' +
+ 'playbook; with a query it groups the unified search hits into a composition kit — ' +
+ 'the closest templates, drop-in blocks, and idea-specific components and hooks.',
+ fn: 'build',
+ args: [{name: 'query', param: 'query', required: false}],
+ options: [
+ {
+ flag: '--type <domain>',
+ param: 'options.type',
+ choices: ['component', 'hook', 'template'],
+ description: 'Filter the kit to one domain (component|hook|template)',
+ },
+ {
+ flag: '--limit <n>',
+ param: 'options.limit',
+ description: 'Max candidates to draw from (default 60)',
+ },
+ {
+ flag: '--verbose',
+ description: 'Verbose output (include import paths and match reason)',
+ },
+ ],
+ examples: [
+ {label: 'Get the playbook', cli: 'astryx build'},
+ {label: 'Compose a page', cli: 'astryx build "analytics dashboard" --json'},
+ ],
+ exitCodes: [
+ {code: 0, when: 'success (including zero matches)'},
+ {code: 1, when: 'invalid --type or a non-positive --limit'},
+ ],
+ related: ['search', 'template', 'component', 'hook', 'init'],
+};
diff --git a/packages/cli/clients/cli/commands/build.mjs b/packages/cli/clients/cli/commands/build.mjs
index 59aef6ce45..7c010c132b 100644
--- a/packages/cli/clients/cli/commands/build.mjs
+++ b/packages/cli/clients/cli/commands/build.mjs
@@ -16,7 +16,10 @@ import {getCliInvocation, formatCliCommand} from '../../../foundation/env/packag
import {jsonOut} from '../../../foundation/response/json.mjs';
import {emit, section, text, record, records, ARROW} from '../formatters/index.mjs';
import {cliError} from '../lib/cli-error.mjs';
+import {defineCommand} from '../lib/define-command.mjs';
import {build as buildApi} from '../../../api/build/build.mjs';
+import {doc as buildCommand} from './build.doc.mjs';
+import {doc as buildFn} from '../../../api/build/build.doc.mjs';
/**
* Emit the build playbook (shown when `build` is run with no query).
@@ -66,13 +69,9 @@ function printPlaybook(run) {
* @param {import('commander').Command} program
*/
export function registerBuild(program) {
- program
- .command('build [query]')
- .description('Build a page: composition kit for an idea, or the workflow playbook (no args)')
- .option('--type <domain>', 'Filter the kit to one domain (component|hook|template)')
- .option('--limit <n>', 'Max candidates to draw from (default 60)')
- .option('--verbose', 'Verbose output (include import paths and match reason)')
- .action(async (/** @type {string | undefined} */ query, /** @type {{type?: import('../../../api/search/search.type.mjs').SearchDomain, limit?: string, verbose?: boolean}} */ options) => {
+ defineCommand(program, buildCommand, {
+ fn: buildFn,
+ action: async (/** @type {string | undefined} */ query, /** @type {{type?: import('../../../api/search/search.type.mjs').SearchDomain, limit?: string, verbose?: boolean}} */ options) => {
const run = getCliInvocation();
const json = program.opts().json || false;
@@ -195,5 +194,6 @@ export function registerBuild(program) {
);
emit(...out);
- });
+ },
+ });
}
diff --git a/packages/cli/clients/cli/commands/component.doc.mjs b/packages/cli/clients/cli/commands/component.doc.mjs
new file mode 100644
index 0000000000..f1dfd4de19
--- /dev/null
+++ b/packages/cli/clients/cli/commands/component.doc.mjs
@@ -0,0 +1,76 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CommandDoc for `astryx component`. The terminal binding of the
+ * `component()` 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: 'component',
+ displayName: 'astryx component',
+ namespace: 'cli',
+ summary: 'List components or print component docs',
+ description:
+ 'Resolves a component by name across core and integration packages and prints ' +
+ 'its authored doc, or lists the catalog grouped by category. Boolean flags narrow ' +
+ 'a single component to just its props, source, showcase, or example blocks.',
+ fn: 'component',
+ args: [{name: 'name', param: 'name', required: false}],
+ options: [
+ {
+ flag: '--list',
+ param: 'options.list',
+ description: 'List all components grouped by category',
+ },
+ {
+ flag: '--category <category>',
+ param: 'options.category',
+ description: 'List components in a specific category',
+ },
+ {
+ flag: '--props',
+ param: 'options.props',
+ description: 'Print only the props table',
+ },
+ {
+ flag: '--source',
+ param: 'options.source',
+ description: 'Print component source code',
+ },
+ {
+ flag: '--showcase',
+ param: 'options.showcase',
+ description: 'Print showcase source code',
+ },
+ {
+ flag: '--blocks',
+ param: 'options.blocks',
+ description: 'List example blocks: showcase, examples, and related',
+ },
+ {
+ flag: '--package <name>',
+ param: 'options.package',
+ description: 'Scope lookup to an external package (e.g. @acme/xds-widgets)',
+ },
+ ],
+ examples: [
+ {label: 'Browse the catalog', cli: 'astryx component --list'},
+ {
+ label: 'Props table as JSON',
+ cli: 'astryx component XDSButton --props --json',
+ },
+ ],
+ exitCodes: [
+ {code: 0, when: 'success'},
+ {
+ code: 1,
+ when: 'unknown component, category, or package — or @astryxdesign/core cannot be resolved',
+ },
+ ],
+ related: ['search', 'hook', 'docs', 'template', 'swizzle'],
+};
diff --git a/packages/cli/clients/cli/commands/component/index.mjs b/packages/cli/clients/cli/commands/component/index.mjs
index f38f3c4bdd..2bb6af84b6 100644
--- a/packages/cli/clients/cli/commands/component/index.mjs
+++ b/packages/cli/clients/cli/commands/component/index.mjs
@@ -22,11 +22,14 @@ import {getCliInvocation} from '../../../../foundation/env/package-manager.mjs';
import {jsonOut} from '../../../../foundation/response/json.mjs';
import {emit, section, text, list, record, records, code} from '../../formatters/index.mjs';
import {cliError} from '../../lib/cli-error.mjs';
+import {defineCommand} from '../../lib/define-command.mjs';
import {ERROR_CODES} from '../../../../foundation/response/error-codes.mjs';
import {component as componentApi} from '../../../../api/component/component.mjs';
import {findRelatedBlocks} from '../../../../api/template/template.mjs';
import {Project} from '../../../../foundation/config/project.mjs';
import {warnOnIntegrationIssues} from '../../../../foundation/integrations/integration-warnings.mjs';
+import {doc as componentCommand} from '../component.doc.mjs';
+import {doc as componentFn} from '../../../../api/component/component.doc.mjs';
/**
* The api layer's component() widens its return to `{type: string, data: unknown}`,
@@ -47,17 +50,9 @@ import {warnOnIntegrationIssues} from '../../../../foundation/integrations/integ
* @param {import('commander').Command} program
*/
export function registerComponent(program) {
- program
- .command('component [name]')
- .description('List components or print component docs')
- .option('--list', 'List all components grouped by category')
- .option('--category <category>', 'List components in a specific category')
- .option('--props', 'Print only the props table')
- .option('--source', 'Print component source code')
- .option('--showcase', 'Print showcase source code')
- .option('--blocks', 'List example blocks: showcase, examples, and related')
- .option('--package <name>', 'Scope lookup to an external package (e.g. @acme/xds-widgets)')
- .action(async (/** @type {string | undefined} */ name, /** @type {{list?: boolean, category?: string, props?: boolean, source?: boolean, showcase?: boolean, blocks?: boolean, package?: string}} */ options) => {
+ defineCommand(program, componentCommand, {
+ fn: componentFn,
+ action: async (/** @type {string | undefined} */ name, /** @type {{list?: boolean, category?: string, props?: boolean, source?: boolean, showcase?: boolean, blocks?: boolean, package?: string}} */ options) => {
const run = getCliInvocation();
const zh = program.opts().zh || false;
const dense = program.opts().dense || false;
@@ -258,7 +253,8 @@ export function registerComponent(program) {
break;
}
}
- });
+ },
+ });
}
diff --git a/packages/cli/clients/cli/commands/discover.doc.mjs b/packages/cli/clients/cli/commands/discover.doc.mjs
new file mode 100644
index 0000000000..520bd687a5
--- /dev/null
+++ b/packages/cli/clients/cli/commands/discover.doc.mjs
@@ -0,0 +1,43 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CommandDoc for `astryx discover`. The terminal binding of the
+ * `discover()` 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: 'discover',
+ displayName: 'astryx discover',
+ namespace: 'cli',
+ summary: 'Discover external packages and components',
+ description:
+ 'Explores components contributed by configured external packages and integrations. ' +
+ 'With no query it lists those packages; an @scope/name query browses one package; ' +
+ 'an @scope/name/Component path or a free-text term resolves to a component doc.',
+ fn: 'discover',
+ args: [{name: 'query', param: 'query', required: false}],
+ options: [
+ {
+ flag: '--components',
+ param: 'options.components',
+ description: 'List components only',
+ },
+ ],
+ examples: [
+ {label: 'List packages', cli: 'astryx discover --json'},
+ {label: 'Browse a package', cli: 'astryx discover @acme/ui'},
+ ],
+ exitCodes: [
+ {code: 0, when: 'success'},
+ {
+ code: 1,
+ when: 'unknown package or component, a malformed doc, or an empty free-text query',
+ },
+ ],
+ related: ['component', 'search', 'template'],
+};
diff --git a/packages/cli/clients/cli/commands/discover.mjs b/packages/cli/clients/cli/commands/discover.mjs
index 159aa66183..46460f3313 100644
--- a/packages/cli/clients/cli/commands/discover.mjs
+++ b/packages/cli/clients/cli/commands/discover.mjs
@@ -16,6 +16,9 @@ import {emit, section, text, record, records, list, code} from '../formatters/in
import {cliError} from '../lib/cli-error.mjs';
import {discover as discoverApi} from '../../../api/discover/discover.mjs';
import {getCliInvocation} from '../../../foundation/env/package-manager.mjs';
+import {defineCommand} from '../lib/define-command.mjs';
+import {doc as discoverCommand} from './discover.doc.mjs';
+import {doc as discoverFn} from '../../../api/discover/discover.doc.mjs';
// Max components to list inline per package before summarizing with "+N more".
const MAX_COMPONENTS_SHOWN = 10;
@@ -24,11 +27,9 @@ const MAX_COMPONENTS_SHOWN = 10;
* @param {import('commander').Command} program
*/
export function registerDiscover(program) {
- program
- .command('discover [query]')
- .description('Discover external packages and components')
- .option('--components', 'List components only')
- .action(
+ defineCommand(program, discoverCommand, {
+ fn: discoverFn,
+ action:
/**
* @param {string | undefined} query
* @param {{components?: boolean}} options
@@ -133,5 +134,6 @@ export function registerDiscover(program) {
break;
}
}
- });
+ },
+ });
}
diff --git a/packages/cli/clients/cli/commands/docs.doc.mjs b/packages/cli/clients/cli/commands/docs.doc.mjs
new file mode 100644
index 0000000000..380de719c9
--- /dev/null
+++ b/packages/cli/clients/cli/commands/docs.doc.mjs
@@ -0,0 +1,38 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CommandDoc for `astryx docs`. The terminal binding of the `docs()`
+ * 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: 'docs',
+ displayName: 'astryx docs',
+ namespace: 'cli',
+ summary: 'Print reference docs',
+ description:
+ 'Reads the reference docs: with no topic it lists every topic; a topic prints that ' +
+ 'full doc; a topic plus a section returns the first section whose title contains the ' +
+ '(case-insensitive) query.',
+ fn: 'docs',
+ args: [
+ {name: 'topic', param: 'topic', required: false},
+ {name: 'section', param: 'section', required: false},
+ ],
+ examples: [
+ {label: 'List topics', cli: 'astryx docs'},
+ {label: 'One topic as JSON', cli: 'astryx docs spacing --json'},
+ ],
+ exitCodes: [
+ {code: 0, when: 'success'},
+ {
+ code: 1,
+ when: 'unknown topic, or a section that matches no title in the topic',
+ },
+ ],
+ related: ['search', 'component', 'hook', 'template'],
+};
diff --git a/packages/cli/clients/cli/commands/docs.mjs b/packages/cli/clients/cli/commands/docs.mjs
index fc641b0f5b..488ce8b66a 100644
--- a/packages/cli/clients/cli/commands/docs.mjs
+++ b/packages/cli/clients/cli/commands/docs.mjs
@@ -16,7 +16,10 @@ import {getCliInvocation} from '../../../foundation/env/package-manager.mjs';
import {jsonOut} from '../../../foundation/response/json.mjs';
import {emit, section, records, text, code} from '../formatters/index.mjs';
import {cliError} from '../lib/cli-error.mjs';
+import {defineCommand} from '../lib/define-command.mjs';
import {docs as docsApi} from '../../../api/docs/docs.mjs';
+import {doc as docsCommand} from './docs.doc.mjs';
+import {doc as docsFn} from '../../../api/docs/docs.doc.mjs';
// ─── Formatting ──────────────────────────────────────────────────────────────
@@ -133,10 +136,9 @@ function formatReferenceFull(docs, detail) {
* @param {import('commander').Command} program
*/
export function registerDocs(program) {
- program
- .command('docs [topic] [section]')
- .description('Print reference docs')
- .action(async (/** @type {string | undefined} */ topic, /** @type {string | undefined} */ sectionName) => {
+ defineCommand(program, docsCommand, {
+ fn: docsFn,
+ action: async (/** @type {string | undefined} */ topic, /** @type {string | undefined} */ sectionName) => {
const run = getCliInvocation();
const lang = program.opts().lang || null;
const zh = program.opts().zh || false;
@@ -184,5 +186,6 @@ export function registerDocs(program) {
break;
}
}
- });
+ },
+ });
}
diff --git a/packages/cli/clients/cli/commands/doctor.doc.mjs b/packages/cli/clients/cli/commands/doctor.doc.mjs
new file mode 100644
index 0000000000..808fff2918
--- /dev/null
+++ b/packages/cli/clients/cli/commands/doctor.doc.mjs
@@ -0,0 +1,31 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CommandDoc for `astryx doctor`. The terminal binding of the `doctor()`
+ * 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: 'doctor',
+ displayName: 'astryx doctor',
+ namespace: 'cli',
+ summary: 'Diagnose your XDS setup and report problems with fixes',
+ description:
+ 'Runs read-only diagnostics — Node version, @astryxdesign/core install and version ' +
+ 'alignment, installed themes, config validity, agent docs, and the package manager — ' +
+ 'and reports pass/warn/fail with an actionable fix for each problem. Safe as a CI gate.',
+ fn: 'doctor',
+ examples: [
+ {label: 'Run diagnostics', cli: 'astryx doctor'},
+ {label: 'Machine-readable report', cli: 'astryx doctor --json'},
+ ],
+ exitCodes: [
+ {code: 0, when: 'no checks failed (warnings are allowed)'},
+ {code: 1, when: 'one or more checks failed'},
+ ],
+ related: ['init', 'upgrade'],
+};
diff --git a/packages/cli/clients/cli/commands/doctor.mjs b/packages/cli/clients/cli/commands/doctor.mjs
index 4811ac86de..2d444ce61b 100644
--- a/packages/cli/clients/cli/commands/doctor.mjs
+++ b/packages/cli/clients/cli/commands/doctor.mjs
@@ -13,6 +13,9 @@
import {runChecks} from '../../../api/doctor/doctor.mjs';
import {jsonOut} from '../../../foundation/response/json.mjs';
import {emit, section, records, text} from '../formatters/index.mjs';
+import {defineCommand} from '../lib/define-command.mjs';
+import {doc as doctorCommand} from './doctor.doc.mjs';
+import {doc as doctorFn} from '../../../api/doctor/doctor.doc.mjs';
/** Status -> ASCII token (plain, matching the rest of the CLI). */
const STATUS = {
@@ -63,16 +66,9 @@ function printHuman(report) {
* @param {import('commander').Command} program
*/
export function registerDoctor(program) {
- program
- .command('doctor')
- .description('Diagnose your XDS setup and report problems with fixes')
- .addHelpText(
- 'after',
- '\nExit code:\n' +
- ' 0 no failures (warnings are allowed) — safe as a CI gate\n' +
- ' 1 one or more checks failed\n',
- )
- .action(async () => {
+ defineCommand(program, doctorCommand, {
+ fn: doctorFn,
+ action: async () => {
const json = program.opts().json || false;
const report = await runChecks();
const hasFailure = report.summary.fail > 0;
@@ -87,5 +83,11 @@ export function registerDoctor(program) {
if (hasFailure) {
process.exitCode = 1;
}
- });
+ },
+ }).addHelpText(
+ 'after',
+ '\nExit code:\n' +
+ ' 0 no failures (warnings are allowed) — safe as a CI gate\n' +
+ ' 1 one or more checks failed\n',
+ );
}
diff --git a/packages/cli/clients/cli/commands/hook.doc.mjs b/packages/cli/clients/cli/commands/hook.doc.mjs
new file mode 100644
index 0000000000..643e2cc8ec
--- /dev/null
+++ b/packages/cli/clients/cli/commands/hook.doc.mjs
@@ -0,0 +1,51 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CommandDoc for `astryx hook`. The terminal binding of the `hook()`
+ * 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: 'hook',
+ displayName: 'astryx hook',
+ namespace: 'cli',
+ summary: 'List hooks or print hook docs',
+ description:
+ 'Resolves a hook by name and prints its authored doc, or lists the catalog grouped ' +
+ 'by category. The --params flag narrows a single hook to just its parameters table.',
+ fn: 'hook',
+ args: [{name: 'name', param: 'name', required: false}],
+ options: [
+ {
+ flag: '--list',
+ param: 'options.list',
+ description: 'List all hooks grouped by category',
+ },
+ {
+ flag: '--category <category>',
+ param: 'options.category',
+ description: 'List hooks in a specific category',
+ },
+ {
+ flag: '--params',
+ param: 'options.params',
+ description: 'Print only the parameters table',
+ },
+ ],
+ examples: [
+ {label: 'Browse the catalog', cli: 'astryx hook --list'},
+ {label: 'One hook as JSON', cli: 'astryx hook useToggle --json'},
+ ],
+ exitCodes: [
+ {code: 0, when: 'success'},
+ {
+ code: 1,
+ when: 'unknown hook or category, or @astryxdesign/core cannot be resolved',
+ },
+ ],
+ related: ['search', 'component', 'docs', 'template'],
+};
diff --git a/packages/cli/clients/cli/commands/hook/index.mjs b/packages/cli/clients/cli/commands/hook/index.mjs
index 1ee308328d..a9c82ce0f1 100644
--- a/packages/cli/clients/cli/commands/hook/index.mjs
+++ b/packages/cli/clients/cli/commands/hook/index.mjs
@@ -16,9 +16,12 @@ import {getCliInvocation} from '../../../../foundation/env/package-manager.mjs';
import {jsonOut} from '../../../../foundation/response/json.mjs';
import {emit, section, text, list, records, code} from '../../formatters/index.mjs';
import {cliError} from '../../lib/cli-error.mjs';
+import {defineCommand} from '../../lib/define-command.mjs';
import {ERROR_CODES} from '../../../../foundation/response/error-codes.mjs';
import {hook as hookApi} from '../../../../api/hook/hook.mjs';
import {findRelatedBlocks} from '../../../../api/template/template.mjs';
+import {doc as hookCommand} from '../hook.doc.mjs';
+import {doc as hookFn} from '../../../../api/hook/hook.doc.mjs';
/**
* The api layer's hook() widens its return to `{type: string, data: unknown}`,
@@ -34,13 +37,9 @@ import {findRelatedBlocks} from '../../../../api/template/template.mjs';
/** @param {import('commander').Command} program */
export function registerHook(program) {
- program
- .command('hook [name]')
- .description('List hooks or print hook docs')
- .option('--list', 'List all hooks grouped by category')
- .option('--category <category>', 'List hooks in a specific category')
- .option('--params', 'Print only the parameters table')
- .action(
+ defineCommand(program, hookCommand, {
+ fn: hookFn,
+ action:
/**
* @param {string|undefined} name
* @param {{list?: boolean, category?: string, params?: boolean}} options
@@ -176,7 +175,8 @@ export function registerHook(program) {
break;
}
}
- });
+ },
+ });
}
// Re-export lib functions for external consumers
diff --git a/packages/cli/clients/cli/commands/init.doc.mjs b/packages/cli/clients/cli/commands/init.doc.mjs
new file mode 100644
index 0000000000..a4d21964da
--- /dev/null
+++ b/packages/cli/clients/cli/commands/init.doc.mjs
@@ -0,0 +1,65 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CommandDoc for `astryx init`. The terminal binding of the `init()`
+ * 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: 'init',
+ displayName: 'astryx init',
+ namespace: 'cli',
+ summary: 'Initialize the design system in your project',
+ description:
+ 'Non-interactive project setup (no prompts, so it behaves the same for humans, ' +
+ 'agents, and CI). By default it installs the AGENTS.md/CLAUDE.md agent-docs and ' +
+ 'prints getting-started guidance; features/--all add theme and page-building ' +
+ 'guidance and can scaffold a starter template.',
+ fn: 'init',
+ options: [
+ {
+ flag: '--features <list>',
+ param: 'options.features',
+ description:
+ 'Comma-separated features to install (agents, theme, template)',
+ },
+ {
+ flag: '--all',
+ param: 'options.all',
+ description: 'Install all features, no prompts',
+ },
+ {
+ flag: '--remove-agents',
+ param: 'options.removeAgents',
+ description: 'Remove AI agent docs from all agent doc files',
+ },
+ {
+ flag: '--agent <tool>',
+ param: 'options.agent',
+ choices: ['claude', 'cursor', 'codex', 'hermes', 'all'],
+ description:
+ 'Target AI tool for agent docs: claude, cursor, codex, hermes, all',
+ },
+ {
+ flag: '--agent-docs-path <path...>',
+ param: 'options.agentDocsPath',
+ description: 'Explicit file path(s) for agent docs',
+ },
+ ],
+ examples: [
+ {label: 'Default setup', cli: 'astryx init'},
+ {label: 'All features, no prompts', cli: 'astryx init --all'},
+ ],
+ exitCodes: [
+ {code: 0, when: 'success'},
+ {
+ code: 1,
+ when: 'unknown --agent, an unknown feature or template, or a starter template would overwrite an existing page',
+ },
+ ],
+ related: ['doctor', 'upgrade', 'build', 'theme'],
+};
diff --git a/packages/cli/clients/cli/commands/init.mjs b/packages/cli/clients/cli/commands/init.mjs
index e543ce4a18..6aa0ae916d 100644
--- a/packages/cli/clients/cli/commands/init.mjs
+++ b/packages/cli/clients/cli/commands/init.mjs
@@ -17,20 +17,17 @@
import {init} from '../../../api/init/init.mjs';
import {logger} from '../../../api/logger.mjs';
import {cliError} from '../lib/cli-error.mjs';
+import {defineCommand} from '../lib/define-command.mjs';
+import {doc as initCommand} from './init.doc.mjs';
+import {doc as initFn} from '../../../api/init/init.doc.mjs';
/**
* @param {import('commander').Command} program
*/
export function registerInit(program) {
- program
- .command('init')
- .description('Initialize the design system in your project')
- .option('--features <list>', 'Comma-separated features to install (agents, theme, template)')
- .option('--all', 'Install all features, no prompts')
- .option('--remove-agents', 'Remove AI agent docs from all agent doc files')
- .option('--agent <tool>', 'Target AI tool for agent docs: claude, cursor, codex, hermes, all')
- .option('--agent-docs-path <path...>', 'Explicit file path(s) for agent docs')
- .action(async (/** @type {import('../../../api/init/init.mjs').InitOptions} */ options) => {
+ defineCommand(program, initCommand, {
+ fn: initFn,
+ action: async (/** @type {import('../../../api/init/init.mjs').InitOptions} */ options) => {
// init has no --json mode: enable human output (log → stdout via humanLog,
// warn/error → stderr). humanLog still self-suppresses under a global
// --json flag, so a JSON envelope can never be corrupted.
@@ -46,5 +43,6 @@ export function registerInit(program) {
const e = /** @type {import('../../../api/error.mjs').AstryxError} */ (err);
cliError(e.message, {suggestions: e.suggestions, code: e.code});
}
- });
+ },
+ });
}
diff --git a/packages/cli/clients/cli/commands/layout-check.doc.mjs b/packages/cli/clients/cli/commands/layout-check.doc.mjs
new file mode 100644
index 0000000000..3db63db5dd
--- /dev/null
+++ b/packages/cli/clients/cli/commands/layout-check.doc.mjs
@@ -0,0 +1,54 @@
+// 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',
+ 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}],
+ options: [
+ {flag: '--file <file>', description: 'Read the expression from a file'},
+ {
+ 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 or empty, 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.mjs
new file mode 100644
index 0000000000..36f9a326a6
--- /dev/null
+++ b/packages/cli/clients/cli/commands/layout-expand.doc.mjs
@@ -0,0 +1,66 @@
+// 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',
+ 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},
+ {name: 'path', param: 'options.targetPath', required: false},
+ ],
+ options: [
+ {flag: '--file <file>', description: 'Read the expression from a file'},
+ {
+ 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 expression, 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.mjs
new file mode 100644
index 0000000000..5b4ec7a50c
--- /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',
+ 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.mjs
new file mode 100644
index 0000000000..9a2a4d6167
--- /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',
+ 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: 'success (help shown, or a subcommand succeeded)'},
+ {code: 1, when: 'an unknown subcommand'},
+ ],
+ related: ['template', 'build'],
+};
diff --git a/packages/cli/clients/cli/commands/layout.mjs b/packages/cli/clients/cli/commands/layout.mjs
index 2e0b9ff541..83ab6638fd 100644
--- a/packages/cli/clients/cli/commands/layout.mjs
+++ b/packages/cli/clients/cli/commands/layout.mjs
@@ -10,6 +10,10 @@
*
* 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';
@@ -19,6 +23,14 @@ import {emit, section, text, list, record, code, WARN} from '../formatters/index
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';
/**
* The api layer's @returns for these functions widen the `type` discriminator
@@ -99,18 +111,11 @@ async function readExpression(expr, options = {}) {
* @param {import('commander').Command} program
*/
export function registerLayout(program) {
- const layoutCmd = program
- .command('layout')
- .description('Generate XDS layouts from compressed expressions (XLE/XLO)');
+ const layoutCmd = defineCommand(program, layoutGroup);
- layoutCmd
- .command('expand [expression] [path]')
- .description('Expand a layout expression into validated XDS TSX')
- .option('--file <file>', 'Read the expression from a file')
- .option('--form <form>', 'Input surface: compact, outline, or auto', 'auto')
- .option('--name <name>', 'Generated component name (PascalCase)', 'GeneratedLayout')
- .option('--loose', 'Downgrade unknown {block} hints to TODO placeholders')
- .action(async (/** @type {string} */ expression, /** @type {string} */ targetPath, /** @type {LayoutExpandOptions} */ options) => {
+ 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() === '') {
@@ -161,15 +166,12 @@ export function registerLayout(program) {
out.push(code(result.data.code));
}
emit(...out);
- });
+ },
+ });
- layoutCmd
- .command('check [expression]')
- .description('Validate a layout expression and echo canonical compact/outline forms')
- .option('--file <file>', 'Read the expression from a file')
- .option('--form <form>', 'Input surface: compact, outline, or auto', 'auto')
- .option('--loose', 'Downgrade unknown {block} hints to TODO placeholders')
- .action(async (/** @type {string} */ expression, /** @type {LayoutCheckOptions} */ options) => {
+ 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() === '') {
@@ -223,12 +225,12 @@ export function registerLayout(program) {
// The canonical compact/outline surfaces are preformatted — emit verbatim.
out.push(section('compact'), code(compact), section('outline'), code(outline));
emit(...out);
- });
+ },
+ });
- layoutCmd
- .command('grammar')
- .description('Print the XLE/XLO cheatsheet (alias table generated from this branch)')
- .action(async () => {
+ defineCommand(layoutCmd, layoutGrammarCommand, {
+ fn: layoutGrammarFn,
+ action: async () => {
const json = program.opts().json || false;
/** @type {LayoutGrammarResponse} */
let result;
@@ -242,5 +244,6 @@ export function registerLayout(program) {
if (json) return jsonOut(result);
// The cheatsheet is a preformatted document — emit verbatim.
emit(code(result.data.text));
- });
+ },
+ });
}
diff --git a/packages/cli/clients/cli/commands/manifest.doc.mjs b/packages/cli/clients/cli/commands/manifest.doc.mjs
new file mode 100644
index 0000000000..fea7e8f2cf
--- /dev/null
+++ b/packages/cli/clients/cli/commands/manifest.doc.mjs
@@ -0,0 +1,30 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CommandDoc for `astryx manifest`. A CLI-only capability manifest with no
+ * wrapped API function (so no `fn`); it emits the full command surface — args,
+ * flags, subcommands, and JSON response types — as a single typed envelope.
+ * @position packages/cli/clients/cli/commands — command documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').CommandDoc} */
+export const doc = {
+ type: 'command',
+ name: 'manifest',
+ displayName: 'astryx manifest',
+ namespace: 'cli',
+ summary: 'Print the full CLI capability manifest (use with --json).',
+ description:
+ 'Emits the complete CLI surface — every command with its arguments, options, ' +
+ 'subcommands, and JSON response types — as a single typed envelope for agents and ' +
+ 'tooling to introspect. Intended to be run with --json.',
+ examples: [
+ {label: 'Full manifest', cli: 'astryx manifest --json'},
+ {label: 'Shorthand', cli: 'astryx --json'},
+ ],
+ exitCodes: [
+ {code: 0, when: 'success'},
+ {code: 1, when: 'the manifest cannot be generated'},
+ ],
+ related: ['docs', 'discover', 'search'],
+};
diff --git a/packages/cli/clients/cli/commands/search.doc.mjs b/packages/cli/clients/cli/commands/search.doc.mjs
new file mode 100644
index 0000000000..3b174556c9
--- /dev/null
+++ b/packages/cli/clients/cli/commands/search.doc.mjs
@@ -0,0 +1,51 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CommandDoc for `astryx search`. The terminal binding of the `search()`
+ * function (referenced via `fn`); 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: 'search',
+ displayName: 'astryx search',
+ namespace: 'cli',
+ summary: 'Search components, hooks, docs, and templates in one ranked list',
+ description:
+ 'Terminal front-end to search() — prints one ranked, greppable list across ' +
+ 'every content domain, each row carrying a follow-up command to act on it.',
+ fn: 'search',
+ args: [{name: 'query', param: 'query', required: true}],
+ options: [
+ {
+ flag: '--type <domain>',
+ param: 'options.type',
+ choices: ['component', 'hook', 'doc', 'template'],
+ description: 'Filter to one domain (component|hook|doc|template)',
+ },
+ {
+ flag: '--limit <n>',
+ param: 'options.limit',
+ description: 'Max number of results (default 20)',
+ },
+ {
+ flag: '--verbose',
+ description: 'Verbose output (include import paths and match reason)',
+ },
+ ],
+ examples: [
+ {label: 'Ranked results', cli: 'astryx search button'},
+ {
+ label: 'Filter + JSON',
+ cli: 'astryx search "data table" --type template --json',
+ },
+ ],
+ exitCodes: [
+ {code: 0, when: 'success (including zero matches)'},
+ {code: 1, when: 'invalid --type or a non-positive --limit'},
+ ],
+ related: ['component', 'hook', 'docs', 'template', 'build'],
+};
diff --git a/packages/cli/clients/cli/commands/search.mjs b/packages/cli/clients/cli/commands/search.mjs
index b7368b3c76..e45a9927f3 100644
--- a/packages/cli/clients/cli/commands/search.mjs
+++ b/packages/cli/clients/cli/commands/search.mjs
@@ -8,6 +8,10 @@
* with their domain, with a follow-up command so the user knows what to run
* next.
*
+ * The command surface (description, args, flags) is sourced from the colocated
+ * `search.doc.mjs` CommandDoc via `defineCommand`; this file supplies only the
+ * action (parse flags -> call the api function -> render).
+ *
* Usage:
* astryx search button Ranked results across all domains
* astryx search modal --type component Filter to a single domain
@@ -20,26 +24,27 @@ import {getCliInvocation, formatCliCommand} from '../../../foundation/env/packag
import {jsonOut} from '../../../foundation/response/json.mjs';
import {emit, section, text, records} from '../formatters/index.mjs';
import {cliError} from '../lib/cli-error.mjs';
-import {search as searchApi, SEARCH_DOMAINS} from '../../../api/search/search.mjs';
+import {defineCommand} from '../lib/define-command.mjs';
+import {search as searchApi} from '../../../api/search/search.mjs';
+import {doc as searchCommand} from './search.doc.mjs';
+import {doc as searchFn} from '../../../api/search/search.doc.mjs';
/**
* @param {import('commander').Command} program
*/
export function registerSearch(program) {
- program
- .command('search <query>')
- .description('Search components, hooks, docs, and templates in one ranked list')
- .option('--type <domain>', `Filter to one domain (${SEARCH_DOMAINS.join('|')})`)
- .option('--limit <n>', 'Max number of results (default 20)')
- .option('--verbose', 'Verbose output (include import paths and match reason)')
- .action(async (/** @type {string} */ query, /** @type {{type?: import('../../../api/search/search.type.mjs').SearchDomain, limit?: string, verbose?: boolean}} */ options) => {
+ defineCommand(program, searchCommand, {
+ fn: searchFn,
+ action: async (
+ /** @type {string} */ query,
+ /** @type {{type?: import('../../../api/search/search.type.mjs').SearchDomain, limit?: string, verbose?: boolean}} */ options,
+ ) => {
const json = program.opts().json || false;
// Parse --limit to a number; the API validates it (positive integer) and
// throws ERR_INVALID_ARGUMENT, so we pass NaN through rather than
// pre-rejecting with a generic code here.
- const limit =
- options.limit != null ? Number.parseInt(options.limit, 10) : 20;
+ const limit = options.limit != null ? Number.parseInt(options.limit, 10) : 20;
/** @type {import('../../../api/search/search.type.mjs').SearchResponse} */
let result;
@@ -83,7 +88,8 @@ export function registerSearch(program) {
section(`Results for "${q}" (${results.length})`),
records(results, {fields, format: {command: formatCliCommand}}),
);
- });
+ },
+ });
}
// Re-export the API for external consumers.
diff --git a/packages/cli/clients/cli/commands/swizzle.doc.mjs b/packages/cli/clients/cli/commands/swizzle.doc.mjs
new file mode 100644
index 0000000000..8282f1d339
--- /dev/null
+++ b/packages/cli/clients/cli/commands/swizzle.doc.mjs
@@ -0,0 +1,58 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CommandDoc for `astryx swizzle`. The terminal binding of the `swizzle()`
+ * 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: 'swizzle',
+ displayName: 'astryx swizzle',
+ namespace: 'cli',
+ summary: 'Copy component source for customization',
+ description:
+ "Ejects a component's source from the resolved @astryxdesign/core (or its owning " +
+ 'integration) into your project for deep customization, rewriting imports that ' +
+ 'escape the component directory. With no name it lists the swizzlable components.',
+ fn: 'swizzle',
+ args: [{name: 'component', param: 'component', required: false}],
+ options: [
+ {
+ flag: '--output <dir>',
+ param: 'options.output',
+ default: './components/astryx',
+ description: 'Output directory',
+ },
+ {
+ flag: '--package <pkg>',
+ param: 'options.package',
+ description: 'Scope to a specific owning package',
+ },
+ {
+ flag: '--list',
+ param: 'options.list',
+ description: 'List available components',
+ },
+ {
+ flag: '-f, --overwrite',
+ param: 'options.overwrite',
+ description: 'Overwrite existing files without prompting',
+ },
+ ],
+ examples: [
+ {label: 'List swizzlable components', cli: 'astryx swizzle --list'},
+ {label: 'Eject a component', cli: 'astryx swizzle XDSButton'},
+ ],
+ exitCodes: [
+ {code: 0, when: 'success'},
+ {
+ code: 1,
+ when: 'unknown or ambiguous component, no source on disk, a path escape, or existing files without --overwrite',
+ },
+ ],
+ related: ['component', 'discover', 'upgrade'],
+};
diff --git a/packages/cli/clients/cli/commands/swizzle.mjs b/packages/cli/clients/cli/commands/swizzle.mjs
index a48ac2fba6..bfcfa52d9f 100644
--- a/packages/cli/clients/cli/commands/swizzle.mjs
+++ b/packages/cli/clients/cli/commands/swizzle.mjs
@@ -15,19 +15,17 @@ import {emit, section, list, text, WARN} from '../formatters/index.mjs';
import {cliError} from '../lib/cli-error.mjs';
import {getCliInvocation} from '../../../foundation/env/package-manager.mjs';
import {swizzle as swizzleApi} from '../../../api/swizzle/swizzle.mjs';
+import {defineCommand} from '../lib/define-command.mjs';
+import {doc as swizzleCommand} from './swizzle.doc.mjs';
+import {doc as swizzleFn} from '../../../api/swizzle/swizzle.doc.mjs';
/**
* @param {import('commander').Command} program
*/
export function registerSwizzle(program) {
- program
- .command('swizzle [component]')
- .description('Copy component source for customization')
- .option('--output <dir>', 'Output directory', './components/astryx')
- .option('--package <pkg>', 'Scope to a specific owning package')
- .option('--list', 'List available components')
- .option('-f, --overwrite', 'Overwrite existing files without prompting')
- .action(async (/** @type {string | undefined} */ component, /** @type {{output: string, package?: string, list?: boolean, overwrite?: boolean}} */ options) => {
+ defineCommand(program, swizzleCommand, {
+ fn: swizzleFn,
+ action: async (/** @type {string | undefined} */ component, /** @type {{output: string, package?: string, list?: boolean, overwrite?: boolean}} */ options) => {
const json = program.opts().json || false;
const run = getCliInvocation();
@@ -109,5 +107,6 @@ export function registerSwizzle(program) {
}
emit(...out);
- });
+ },
+ });
}
diff --git a/packages/cli/clients/cli/commands/template.doc.mjs b/packages/cli/clients/cli/commands/template.doc.mjs
new file mode 100644
index 0000000000..a6500a6b70
--- /dev/null
+++ b/packages/cli/clients/cli/commands/template.doc.mjs
@@ -0,0 +1,67 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CommandDoc for `astryx template`. The terminal binding of the
+ * `template()` 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: 'template',
+ displayName: 'astryx template',
+ namespace: 'cli',
+ summary: 'Inject a page or block template',
+ description:
+ 'One entry point for the template family: with no name it lists the discovered ' +
+ 'templates; with a name it shows the source or a layout skeleton, or scaffolds it ' +
+ 'into the project at a target path. Narrow an ambiguous name with --type and/or --package.',
+ fn: 'template',
+ args: [
+ {name: 'name', param: 'name', required: false},
+ {name: 'path', param: 'options.targetPath', required: false},
+ ],
+ options: [
+ {flag: '--list', param: 'options.list', description: 'List available templates'},
+ {
+ flag: '--type <type>',
+ param: 'options.type',
+ choices: ['page', 'block'],
+ description: 'Filter by template type: page or block',
+ },
+ {
+ flag: '--package <pkg>',
+ param: 'options.package',
+ description: 'Narrow to templates from a specific package',
+ },
+ {
+ flag: '--skeleton',
+ param: 'options.skeleton',
+ description:
+ 'Show layout skeleton with spatial annotations (padding, gap, nesting)',
+ },
+ {
+ flag: '-f, --overwrite',
+ param: 'options.overwrite',
+ description: 'Overwrite existing files without prompting',
+ },
+ ],
+ examples: [
+ {label: 'List templates', cli: 'astryx template --json'},
+ {
+ label: 'Scaffold into the app',
+ cli: 'astryx template dashboard ./src/app',
+ },
+ ],
+ exitCodes: [
+ {code: 0, when: 'success'},
+ {
+ code: 1,
+ when: 'unknown or ambiguous template, no source, a path escape, or an existing target without --overwrite',
+ },
+ ],
+ related: ['component', 'search', 'discover', 'init'],
+};
diff --git a/packages/cli/clients/cli/commands/template.mjs b/packages/cli/clients/cli/commands/template.mjs
index a36d41a0b4..e064b8e989 100644
--- a/packages/cli/clients/cli/commands/template.mjs
+++ b/packages/cli/clients/cli/commands/template.mjs
@@ -14,6 +14,9 @@ import {template as templateApi} from '../../../api/template/template.mjs';
import {Project} from '../../../foundation/config/project.mjs';
import {warnOnIntegrationIssues} from '../../../foundation/integrations/integration-warnings.mjs';
import {getCliInvocation} from '../../../foundation/env/package-manager.mjs';
+import {defineCommand} from '../lib/define-command.mjs';
+import {doc as templateCommand} from './template.doc.mjs';
+import {doc as templateFn} from '../../../api/template/template.doc.mjs';
export {discoverTemplates, listTemplates} from '../../../api/template/template.mjs';
@@ -46,15 +49,9 @@ export {discoverTemplates, listTemplates} from '../../../api/template/template.m
* @param {import('commander').Command} program
*/
export function registerTemplate(program) {
- program
- .command('template [name] [path]')
- .description('Inject a page or block template')
- .option('--list', 'List available templates')
- .option('--type <type>', 'Filter by template type: page or block')
- .option('--package <pkg>', 'Narrow to templates from a specific package')
- .option('--skeleton', 'Show layout skeleton with spatial annotations (padding, gap, nesting)')
- .option('-f, --overwrite', 'Overwrite existing files without prompting')
- .action(
+ defineCommand(program, templateCommand, {
+ fn: templateFn,
+ action:
/**
* @param {string | undefined} name
* @param {string | undefined} targetPath
@@ -183,7 +180,8 @@ export function registerTemplate(program) {
break;
}
}
- });
+ },
+ });
}
/**
diff --git a/packages/cli/clients/cli/commands/theme-add.doc.mjs b/packages/cli/clients/cli/commands/theme-add.doc.mjs
new file mode 100644
index 0000000000..975eee551b
--- /dev/null
+++ b/packages/cli/clients/cli/commands/theme-add.doc.mjs
@@ -0,0 +1,50 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CommandDoc for `astryx theme add`. The terminal binding of the
+ * `themeAdd()` 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: 'theme add',
+ displayName: 'astryx theme add',
+ namespace: 'cli',
+ summary: 'Scaffold a theme into your project as editable source',
+ description:
+ "Copies a bundled theme's source into your project so you own it — no theme package " +
+ 'needed. Writes are staged then renamed, rolling back on failure. Running it with no ' +
+ 'slug, or with --list, lists the bundled themes instead.',
+ fn: 'themeAdd',
+ args: [
+ {name: 'slug', param: 'slug', required: false},
+ {name: 'path', param: 'options.targetPath', required: false},
+ ],
+ options: [
+ {
+ flag: '-f, --overwrite',
+ param: 'options.overwrite',
+ description: 'Overwrite existing files without prompting',
+ },
+ {flag: '--list', description: 'List available themes'},
+ ],
+ examples: [
+ {label: 'Scaffold a theme', cli: 'astryx theme add matcha'},
+ {
+ label: 'Custom target path',
+ cli: 'astryx theme add matcha ./src/themes/matcha',
+ },
+ ],
+ exitCodes: [
+ {code: 0, when: 'success'},
+ {
+ code: 1,
+ when: 'unknown theme, a path escape, a missing bundled file, or an existing file without --overwrite',
+ },
+ ],
+ related: ['theme list', 'theme build'],
+};
diff --git a/packages/cli/clients/cli/commands/theme-build.doc.mjs b/packages/cli/clients/cli/commands/theme-build.doc.mjs
new file mode 100644
index 0000000000..bff86f067a
--- /dev/null
+++ b/packages/cli/clients/cli/commands/theme-build.doc.mjs
@@ -0,0 +1,58 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CommandDoc for `astryx theme build`. The terminal binding of the
+ * `themeBuild()` 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: 'theme build',
+ displayName: 'astryx theme build',
+ namespace: 'cli',
+ summary: 'Compile a defineTheme file to CSS + JS',
+ description:
+ 'Compiles a file that calls defineTheme() into a scoped CSS file, a JS module, and ' +
+ 'type declarations — the exact CSS the <Theme> runtime emits. With --check it writes ' +
+ 'nothing and instead reports whether the committed outputs have drifted from source.',
+ fn: 'themeBuild',
+ args: [{name: 'file', param: 'file', required: true}],
+ options: [
+ {flag: '-o, --out <path>', param: 'options.out', description: 'Output CSS file path'},
+ {
+ flag: '-w, --watch',
+ description: 'Rebuild automatically when the theme file changes (Ctrl-C to stop)',
+ },
+ {
+ flag: '-c, --check',
+ param: 'options.check',
+ description:
+ 'Verify the committed outputs match the source without writing; exit non-zero if stale',
+ },
+ ],
+ examples: [
+ {
+ label: 'Build to a CSS file',
+ cli: 'astryx theme build ./src/themes/ocean.ts --out ./dist/ocean.css',
+ },
+ {
+ label: 'Check for drift (CI)',
+ cli: 'astryx theme build ./src/themes/ocean.ts --check',
+ },
+ ],
+ exitCodes: [
+ {
+ code: 0,
+ when: 'the theme builds, or --check finds the outputs up to date',
+ },
+ {
+ code: 1,
+ when: 'a build or validation error, or --check finds stale or missing outputs',
+ },
+ ],
+ related: ['theme add', 'theme list'],
+};
diff --git a/packages/cli/clients/cli/commands/theme-list.doc.mjs b/packages/cli/clients/cli/commands/theme-list.doc.mjs
new file mode 100644
index 0000000000..47ecd195aa
--- /dev/null
+++ b/packages/cli/clients/cli/commands/theme-list.doc.mjs
@@ -0,0 +1,28 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CommandDoc for `astryx theme list`. The terminal binding of the
+ * `themeList()` 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: 'theme list',
+ displayName: 'astryx theme list',
+ namespace: 'cli',
+ summary: 'List themes available to add',
+ description:
+ 'Lists the themes bundled with this CLI build — the ones theme add can scaffold — ' +
+ 'each with its slug, display name, description, and maintained flag.',
+ fn: 'themeList',
+ examples: [{label: 'List bundled themes', cli: 'astryx theme list --json'}],
+ exitCodes: [
+ {code: 0, when: 'success'},
+ {code: 1, when: 'the bundled-theme manifest cannot be read'},
+ ],
+ related: ['theme add', 'theme build'],
+};
diff --git a/packages/cli/clients/cli/commands/theme.doc.mjs b/packages/cli/clients/cli/commands/theme.doc.mjs
new file mode 100644
index 0000000000..c3c64f098c
--- /dev/null
+++ b/packages/cli/clients/cli/commands/theme.doc.mjs
@@ -0,0 +1,31 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CommandDoc for the `astryx theme` command group. A parent group with no
+ * behavior of its own; it dispatches to the build/add/list 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: 'theme',
+ displayName: 'astryx theme',
+ namespace: 'cli',
+ summary: 'Theme tools — build, export, and manage themes',
+ description:
+ 'The theme command group. Running astryx theme with no subcommand prints the ' +
+ 'subcommand list; the work happens in the subcommands — compile a theme (build), ' +
+ 'scaffold one into your project (add), or list the bundled themes (list).',
+ subcommands: ['build', 'add', 'list'],
+ examples: [
+ {label: 'List bundled themes', cli: 'astryx theme list'},
+ {label: 'Scaffold a theme', cli: 'astryx theme add matcha'},
+ ],
+ exitCodes: [
+ {code: 0, when: 'success (help shown, or a subcommand succeeded)'},
+ {code: 1, when: 'an unknown subcommand'},
+ ],
+ related: ['init'],
+};
diff --git a/packages/cli/clients/cli/commands/upgrade.doc.mjs b/packages/cli/clients/cli/commands/upgrade.doc.mjs
new file mode 100644
index 0000000000..368d199351
--- /dev/null
+++ b/packages/cli/clients/cli/commands/upgrade.doc.mjs
@@ -0,0 +1,90 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CommandDoc for `astryx upgrade`. The terminal binding of the `upgrade()`
+ * 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: 'upgrade',
+ displayName: 'astryx upgrade',
+ namespace: 'cli',
+ summary: 'Run codemods to migrate between versions',
+ description:
+ 'Migrates project source from a previous Astryx version to the installed one by ' +
+ 'running the registered codemods, and refreshes the managed agent-docs block. ' +
+ 'Dry-run by default (preview only); pass --apply to write changes to disk.',
+ fn: 'upgrade',
+ options: [
+ {
+ flag: '--from <version>',
+ param: 'options.from',
+ description: 'Previous version before the dependency upgrade',
+ },
+ {
+ flag: '--apply',
+ param: 'options.apply',
+ description: 'Write changes to disk (default: dry-run)',
+ default: false,
+ },
+ {
+ flag: '--force',
+ param: 'options.force',
+ description:
+ 'Run codemods even if --from is newer than the installed version',
+ default: false,
+ },
+ {
+ flag: '--codemod <name>',
+ param: 'options.codemod',
+ description: 'Run a specific transform only',
+ },
+ {
+ flag: '--skip-codemod <name...>',
+ param: 'options.skipCodemod',
+ description:
+ 'Exclude named codemods (repeatable). Re-run past a failed codemod by skipping it.',
+ },
+ {
+ flag: '--integration <package-or-file>',
+ param: 'options.integration',
+ description:
+ 'Explicit integration package name or integration file path (repeatable)',
+ default: [],
+ },
+ {
+ flag: '--path <dir>',
+ param: 'options.path',
+ description: 'Source directory to scan',
+ default: './src',
+ },
+ {
+ flag: '--install-deps',
+ param: 'options.installDeps',
+ description: 'Auto-install jscodeshift without prompting',
+ default: false,
+ },
+ {
+ flag: '--list',
+ param: 'options.list',
+ description: 'List available codemods',
+ default: false,
+ },
+ ],
+ examples: [
+ {label: 'List available codemods', cli: 'astryx upgrade --list --json'},
+ {label: 'Apply a migration', cli: 'astryx upgrade --from 0.1.0 --apply'},
+ ],
+ exitCodes: [
+ {code: 0, when: 'success (including dry-run previews)'},
+ {
+ code: 1,
+ when: 'missing or invalid --from, a --path escape, an unknown codemod, or a codemod failure',
+ },
+ ],
+ related: ['init', 'doctor'],
+};
diff --git a/packages/cli/clients/cli/commands/upgrade.mjs b/packages/cli/clients/cli/commands/upgrade.mjs
index 09f63fb46d..63004330e2 100644
--- a/packages/cli/clients/cli/commands/upgrade.mjs
+++ b/packages/cli/clients/cli/commands/upgrade.mjs
@@ -15,27 +15,18 @@
import {jsonOut, jsonError} from '../../../foundation/response/json.mjs';
import {logger} from '../../../api/logger.mjs';
import {AstryxError} from '../../../api/error.mjs';
+import {defineCommand} from '../lib/define-command.mjs';
import {upgrade as upgradeApi} from '../../../api/upgrade/upgrade.mjs';
+import {doc as upgradeCommand} from './upgrade.doc.mjs';
+import {doc as upgradeFn} from '../../../api/upgrade/upgrade.doc.mjs';
/**
* @param {import('commander').Command} program
*/
export function registerUpgrade(program) {
- program
- .command('upgrade')
- .description('Run codemods to migrate between versions')
- .option('--from <version>', 'Previous version before the dependency upgrade')
- .option('--apply', 'Write changes to disk (default: dry-run)', false)
- .option('--force', 'Run codemods even if --from is newer than the installed version', false)
- .option('--codemod <name>', 'Run a specific transform only')
- .option('--skip-codemod <name...>', 'Exclude named codemods (repeatable). Re-run past a failed codemod by skipping it.')
- .option('--integration <package-or-file>', 'Explicit integration package name or integration file path (repeatable)',
- /** @param {string} value @param {string[]} previous */
- (value, previous) => [...(previous ?? []), value], [])
- .option('--path <dir>', 'Source directory to scan', './src')
- .option('--install-deps', 'Auto-install jscodeshift without prompting', false)
- .option('--list', 'List available codemods', false)
- .action(
+ const cmd = defineCommand(program, upgradeCommand, {
+ fn: upgradeFn,
+ action:
/**
* @param {import('../../../api/upgrade/upgrade.mjs').UpgradeOptions} options
*/
@@ -63,5 +54,18 @@ export function registerUpgrade(program) {
if (json) jsonOut(result);
},
+ });
+
+ // `--integration` is a repeatable value flag: multiple flags accumulate into
+ // the string[] the API expects. defineCommand builds a plain value option
+ // (its [] default comes from the doc), so restore the collector coercion that
+ // the previous inline `.option(..., fn, [])` supplied. Help output is
+ // unaffected — only parse-time value assembly.
+ const integration = cmd.options.find(o => o.long === '--integration');
+ if (integration) {
+ integration.argParser(
+ /** @param {string} value @param {string[]} previous */
+ (value, previous) => [...(previous ?? []), value],
);
+ }
}
diff --git a/packages/cli/clients/cli/commands/validate-integration.doc.mjs b/packages/cli/clients/cli/commands/validate-integration.doc.mjs
new file mode 100644
index 0000000000..b3201328cc
--- /dev/null
+++ b/packages/cli/clients/cli/commands/validate-integration.doc.mjs
@@ -0,0 +1,36 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CommandDoc for `astryx validate-integration`. The terminal binding of
+ * the `validateIntegration()` 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: 'validate-integration',
+ displayName: 'astryx validate-integration',
+ namespace: 'cli',
+ summary: 'Validate an Astryx integration package (manifest + contributions)',
+ description:
+ 'Validates ONE integration at a time — the local package rooted at cwd, or an ' +
+ 'installed package resolved by name — schema-checking its manifest, verifying each ' +
+ 'declared contribution root, and reporting every finding. Safe as a CI gate.',
+ fn: 'validateIntegration',
+ args: [{name: 'package', param: 'pkg', required: false}],
+ examples: [
+ {label: 'Validate the local package', cli: 'astryx validate-integration'},
+ {
+ label: 'Validate an installed package',
+ cli: 'astryx validate-integration @acme/widgets --json',
+ },
+ ],
+ exitCodes: [
+ {code: 0, when: 'no error-severity issues (warnings are allowed)'},
+ {code: 1, when: 'one or more error-severity issues'},
+ ],
+ related: ['doctor', 'upgrade'],
+};
diff --git a/packages/cli/clients/cli/commands/validate-integration.mjs b/packages/cli/clients/cli/commands/validate-integration.mjs
index 9014417a08..af2cde7320 100644
--- a/packages/cli/clients/cli/commands/validate-integration.mjs
+++ b/packages/cli/clients/cli/commands/validate-integration.mjs
@@ -16,10 +16,13 @@
import {jsonOut} from '../../../foundation/response/json.mjs';
import {emit, section, text, records} from '../formatters/index.mjs';
+import {defineCommand} from '../lib/define-command.mjs';
import {
validateIntegration,
summarizeIssues,
} from '../../../api/integration/validate-integration.mjs';
+import {doc as validateIntegrationCommand} from './validate-integration.doc.mjs';
+import {doc as validateIntegrationFn} from '../../../api/integration/validateIntegration.doc.mjs';
/**
* Render a validation result for humans.
@@ -58,21 +61,9 @@ const NO_MANIFEST_GUIDANCE =
* @param {import('commander').Command} program
*/
export function registerValidateIntegration(program) {
- program
- .command('validate-integration [package]')
- .description(
- 'Validate an Astryx integration package (manifest + contributions)',
- )
- .addHelpText(
- 'after',
- '\nWith no argument, validates the integration package rooted at the\n' +
- 'current directory. Pass a package name to validate an installed\n' +
- 'integration resolved from ./node_modules.\n\n' +
- 'Exit code:\n' +
- ' 0 no error issues (warnings are allowed) — safe as a CI gate\n' +
- ' 1 one or more error issues\n',
- )
- .action(async pkg => {
+ defineCommand(program, validateIntegrationCommand, {
+ fn: validateIntegrationFn,
+ action: async pkg => {
const json = program.opts().json || false;
const result = await validateIntegration(pkg);
@@ -90,5 +81,14 @@ export function registerValidateIntegration(program) {
if (errors > 0) {
process.exitCode = 1;
}
- });
+ },
+ }).addHelpText(
+ 'after',
+ '\nWith no argument, validates the integration package rooted at the\n' +
+ 'current directory. Pass a package name to validate an installed\n' +
+ 'integration resolved from ./node_modules.\n\n' +
+ 'Exit code:\n' +
+ ' 0 no error issues (warnings are allowed) — safe as a CI gate\n' +
+ ' 1 one or more error issues\n',
+ );
}
diff --git a/packages/cli/clients/cli/lib/define-command.mjs b/packages/cli/clients/cli/lib/define-command.mjs
new file mode 100644
index 0000000000..83f5bb1e79
--- /dev/null
+++ b/packages/cli/clients/cli/lib/define-command.mjs
@@ -0,0 +1,72 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file The CommandDoc -> Commander converter. One place turns a typed
+ * `CommandDoc` (+ the FunctionDoc it wraps, for inherited param descriptions)
+ * into a configured Commander command, so `--help` and the manifest can be
+ * sourced from the same colocated docs that feed `astryx docs` and the docsite.
+ *
+ * The CommandDoc type lives in `@astryxdesign/cli/authoring` with no Commander
+ * dependency; this converter is the CLI-side adapter. Only the metadata is
+ * generic — each command still supplies its own action (the thin wrapper that
+ * calls the api function and renders).
+ *
+ * @input a CommandDoc (+ optional FunctionDoc) + an action
+ * @output a configured commander Command added to the given parent
+ * @position packages/cli/clients/cli/lib — CLI command converter
+ */
+
+/**
+ * Build a Commander command from a CommandDoc and attach it to `parent`.
+ *
+ * @param {import('commander').Command} parent - program or a group command.
+ * @param {import('@astryxdesign/cli/authoring').CommandDoc} doc
+ * @param {{fn?: import('@astryxdesign/cli/authoring').FunctionDoc, action?: (...args: any[]) => unknown}} [impl]
+ * @returns {import('commander').Command} the created command.
+ */
+export function defineCommand(parent, doc, {fn, action} = {}) {
+ // The command token is the last path segment ("theme build" -> "build"),
+ // since subcommands are added to their group command, not the program.
+ const token = doc.name.split(' ').pop() ?? doc.name;
+ const argSpec = (doc.args ?? [])
+ .map(a => {
+ const inner = a.variadic ? `${a.name}...` : a.name;
+ return a.required ? `<${inner}>` : `[${inner}]`;
+ })
+ .join(' ');
+
+ const cmd = parent.command(argSpec ? `${token} ${argSpec}` : token);
+ if (doc.summary) cmd.description(doc.summary);
+
+ const paramDesc = (/** @type {string | undefined} */ name) =>
+ (fn?.params ?? []).find(p => p.name === name)?.description ?? '';
+
+ for (const arg of doc.args ?? []) {
+ // Only set an arg description when the doc gives one explicitly. Commander
+ // renders an "Arguments:" help section only for described args; inheriting
+ // the FunctionDoc param description here would add that section where the
+ // current CLI has none. (Docsite/`astryx docs` read the arg's `param` for
+ // its description instead.)
+ if (arg.description) {
+ const argument = cmd.registeredArguments?.find(a => a.name() === arg.name);
+ if (argument) argument.description = arg.description;
+ }
+ }
+
+ for (const o of doc.options ?? []) {
+ const desc = o.description ?? (o.param ? paramDesc(o.param) : '');
+ const option = cmd.createOption(o.flag, desc);
+ if (o.default != null) option.default(o.default);
+ cmd.addOption(option);
+ }
+
+ // `choices` and `examples` are doc metadata surfaced by `astryx docs` and the
+ // doc site; they are intentionally NOT injected into `--help` here. Choices
+ // stay described in the option text (Commander `.choices()` would also change
+ // validation from the api layer's ERR_INVALID_ARGUMENT), and the current CLI
+ // help carries no per-command examples epilog. Keeping both out preserves the
+ // exact `--help`/manifest surface as registrations migrate to this converter.
+
+ if (action) cmd.action(/** @type {(...args: any[]) => void | Promise<void>} */ (action));
+ return cmd;
+}
diff --git a/packages/cli/clients/cli/lib/define-command.test.mjs b/packages/cli/clients/cli/lib/define-command.test.mjs
new file mode 100644
index 0000000000..37b5b543c2
--- /dev/null
+++ b/packages/cli/clients/cli/lib/define-command.test.mjs
@@ -0,0 +1,49 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Unit tests for the CommandDoc -> Commander converter.
+ */
+
+import {Command} from 'commander';
+import {describe, it, expect} from 'vitest';
+import {defineCommand} from './define-command.mjs';
+import {doc as searchCommand} from '../commands/search.doc.mjs';
+import {doc as searchFn} from '../../../api/search/search.doc.mjs';
+
+describe('defineCommand', () => {
+ it('builds a Commander command from a CommandDoc', () => {
+ const program = new Command();
+ const cmd = defineCommand(program, searchCommand, {
+ fn: searchFn,
+ action: () => {},
+ });
+
+ expect(cmd.name()).toBe('search');
+ expect(cmd.description()).toBe(searchCommand.summary);
+ expect(cmd.registeredArguments.map(a => a.name())).toEqual(['query']);
+ expect(cmd.registeredArguments[0].required).toBe(true);
+ expect(cmd.options.map(o => o.flags)).toEqual([
+ '--type <domain>',
+ '--limit <n>',
+ '--verbose',
+ ]);
+ });
+
+ it('nests a subcommand token under a group parent', () => {
+ const program = new Command();
+ const group = program.command('theme');
+ const cmd = defineCommand(
+ group,
+ {
+ type: 'command',
+ name: 'theme build',
+ displayName: 'astryx theme build',
+ summary: 'Build.',
+ args: [{name: 'file', required: true}],
+ },
+ {action: () => {}},
+ );
+ expect(cmd.name()).toBe('build');
+ expect(cmd.registeredArguments.map(a => a.name())).toEqual(['file']);
+ });
+});
diff --git a/packages/cli/foundation/response/error-codes.doc.mjs b/packages/cli/foundation/response/error-codes.doc.mjs
new file mode 100644
index 0000000000..16d591a018
--- /dev/null
+++ b/packages/cli/foundation/response/error-codes.doc.mjs
@@ -0,0 +1,239 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file EnumDoc for the CLI's stable error-code taxonomy. Colocated with the
+ * source of truth it documents (`error-codes.mjs`); the member set must stay in
+ * lockstep with ERROR_CODES — a drift test enforces that the two match exactly.
+ * @position packages/cli/foundation/response — enum documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').EnumDoc} */
+export const doc = {
+ type: 'enum',
+ name: 'error-codes',
+ displayName: 'Error Codes',
+ namespace: 'cli',
+ description:
+ 'Stable, append-only machine-readable error codes on the --json error envelope (envelope.code). Codes never change or get removed; branch on these, not on prose.',
+ members: [
+ // Generic
+ {
+ value: 'ERR_UNKNOWN',
+ description: 'Fallback for any error without a more specific code.',
+ },
+
+ // CLI parsing / dispatch (Commander + bare invocation)
+ {
+ value: 'ERR_UNKNOWN_COMMAND',
+ description:
+ 'A top-level command name was not recognized (e.g. `astryx bogus`).',
+ },
+ {
+ value: 'ERR_UNKNOWN_SUBCOMMAND',
+ description:
+ 'A subcommand under a command group was not recognized (e.g. `astryx theme bogus`).',
+ },
+ {
+ value: 'ERR_INVALID_OPTION',
+ description:
+ 'An unknown flag/option was passed (Commander `unknownOption`).',
+ },
+ {
+ value: 'ERR_INVALID_ARGUMENT',
+ description:
+ "An option/argument had a value Commander's parser rejected.",
+ },
+ {
+ value: 'ERR_MISSING_ARGUMENT',
+ description:
+ 'A required positional argument was omitted (Commander `missingArgument`).',
+ },
+ {
+ value: 'ERR_INVALID_LANG',
+ description:
+ '`--lang` was given a value outside its choices (en, zh, dense).',
+ },
+ {
+ value: 'ERR_INVALID_DETAIL',
+ description:
+ '`--detail` was given a value outside its choices (full, compact, brief).',
+ },
+
+ // Environment / runtime
+ {
+ value: 'ERR_NODE_VERSION',
+ description:
+ 'The running Node.js version is below the supported minimum.',
+ },
+ {
+ value: 'ERR_CORE_NOT_FOUND',
+ description:
+ '`@astryxdesign/core` could not be located (not installed / not in a monorepo).',
+ },
+
+ // "Unknown <subject>" lookups
+ {
+ value: 'ERR_UNKNOWN_COMPONENT',
+ description: 'No component matched the requested name.',
+ },
+ {
+ value: 'ERR_UNKNOWN_HOOK',
+ description: 'No hook matched the requested name.',
+ },
+ {
+ value: 'ERR_UNKNOWN_TOPIC',
+ description: 'No docs topic matched the requested name.',
+ },
+ {
+ value: 'ERR_UNKNOWN_SECTION',
+ description:
+ 'A docs topic exists but the requested section within it does not.',
+ },
+ {
+ value: 'ERR_UNKNOWN_CATEGORY',
+ description:
+ 'A `--category` filter value did not match any known category.',
+ },
+ {
+ value: 'ERR_UNKNOWN_TEMPLATE',
+ description: 'No template matched the requested name.',
+ },
+ {
+ value: 'ERR_AMBIGUOUS_TEMPLATE',
+ description:
+ 'A template id matched more than one template (narrow with --type/--package).',
+ },
+ {
+ value: 'ERR_AMBIGUOUS_COMPONENT',
+ description:
+ 'A component name is owned by more than one package (narrow with --package).',
+ },
+ {
+ value: 'ERR_UNKNOWN_THEME',
+ description: 'No theme matched the requested slug (theme add).',
+ },
+ {
+ value: 'ERR_UNKNOWN_PACKAGE',
+ description: 'No package matched the requested name (discover).',
+ },
+ {
+ value: 'ERR_UNKNOWN_AGENT',
+ description:
+ 'An unrecognized `--agent` value was passed to agent-docs/init.',
+ },
+ {
+ value: 'ERR_UNKNOWN_FEATURE',
+ description: 'An unrecognized `--features` value was passed to init.',
+ },
+ {
+ value: 'ERR_UNKNOWN_CODEMOD',
+ description:
+ 'A `--codemod` value did not match any registered codemod (upgrade).',
+ },
+ {
+ value: 'ERR_CODEMOD_FAILED',
+ description: 'One or more codemods failed during an upgrade run.',
+ },
+ {
+ value: 'ERR_NOT_FOUND',
+ description:
+ 'A generic discover/lookup query matched nothing in any package.',
+ },
+
+ // Resource shape problems (subject exists, artifact missing)
+ {
+ value: 'ERR_NO_DOC',
+ description: 'A component exists but has no typed `.doc.mjs` file.',
+ },
+ {
+ value: 'ERR_NO_SHOWCASE',
+ description: 'No showcase exists for the requested component.',
+ },
+ {
+ value: 'ERR_NO_SOURCE',
+ description:
+ 'No source file could be located for the requested component/template.',
+ },
+ {
+ value: 'ERR_INVALID_DOC',
+ description:
+ "A component's docs failed validation (malformed `.doc.mjs`).",
+ },
+
+ // Filesystem
+ {
+ value: 'ERR_FILE_NOT_FOUND',
+ description: 'A required input file did not exist.',
+ },
+ {
+ value: 'ERR_FILE_EXISTS',
+ description:
+ 'Refused to overwrite an existing file in non-interactive mode.',
+ },
+ {
+ value: 'ERR_PATH_TRAVERSAL',
+ description:
+ 'A path escaped its allowed root, or a name contained traversal markers.',
+ },
+ {
+ value: 'ERR_WRITE_FAILED',
+ description: 'Writing output files failed (and was rolled back).',
+ },
+
+ // Theme build
+ {
+ value: 'ERR_THEME_INVALID',
+ description:
+ 'A theme definition was missing a required property (e.g. `name`).',
+ },
+ {
+ value: 'ERR_THEME_LOAD',
+ description:
+ 'A theme file could not be loaded / parsed into a defineTheme result.',
+ },
+
+ // Upgrade
+ {
+ value: 'ERR_VERSION_DETECT',
+ description:
+ 'The current `@astryxdesign/core` version could not be detected.',
+ },
+ {
+ value: 'ERR_INVALID_VERSION',
+ description: 'A `--from`/`--to` value was not a valid semver string.',
+ },
+ {
+ value: 'ERR_DEP_MISSING',
+ description:
+ 'A required external dependency (e.g. jscodeshift) is missing.',
+ },
+
+ // GitHub CLI
+ {
+ value: 'ERR_GH_CLI',
+ description: 'GitHub CLI (`gh`) is not installed or not authenticated.',
+ },
+
+ // Blog (read via the published RSS feed)
+ {
+ value: 'ERR_UNKNOWN_POST',
+ description: 'No blog post matched the requested slug in the feed.',
+ },
+ {
+ value: 'ERR_FETCH_FAILED',
+ description: 'A network fetch (RSS feed or post text) failed.',
+ },
+
+ // Layout expressions (XLE/XLO)
+ {
+ value: 'ERR_LAYOUT_PARSE',
+ description:
+ 'A layout expression failed to parse (syntax error, with line/col).',
+ },
+ {
+ value: 'ERR_LAYOUT_INVALID',
+ description:
+ 'A layout expression parsed but failed validation (unknown component/prop/enum/block).',
+ },
+ ],
+};
diff --git a/packages/cli/foundation/response/response-types.doc.mjs b/packages/cli/foundation/response/response-types.doc.mjs
new file mode 100644
index 0000000000..653ca06206
--- /dev/null
+++ b/packages/cli/foundation/response/response-types.doc.mjs
@@ -0,0 +1,242 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file EnumDoc for the `type` discriminant carried on every --json success
+ * envelope. The vocabulary mirrors the RESPONSE_TYPES map (each command's
+ * `jsonOut(...)` call sites) in `clients/cli/lib/manifest.mjs`; a consumer
+ * switches on `type` to narrow the `data` payload.
+ * @position packages/cli/foundation/response — enum documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').EnumDoc} */
+export const doc = {
+ type: 'enum',
+ name: 'response-types',
+ displayName: 'Response Types',
+ namespace: 'cli',
+ description:
+ 'The `type` discriminant present on every --json success envelope. Consumers switch on it to narrow `data`.',
+ members: [
+ // component
+ {
+ value: 'component.list',
+ description:
+ 'The component catalog grouped by category: `detail` (the level — names | compact | full) and `components`, the grouped map of names+package, brief entries, or a full ComponentDoc per entry.',
+ },
+ {
+ value: 'component.detail',
+ description:
+ "One component's authored ComponentDoc plus ownership metadata (owner package, import specifier, and whether source is available).",
+ },
+ {
+ value: 'component.detail.props',
+ description: "Just one component's props table (ComponentPropDoc[]).",
+ },
+ {
+ value: 'component.detail.source',
+ description: "One component's source file, as {component, source}.",
+ },
+ {
+ value: 'component.detail.showcase',
+ description:
+ "One component's showcase example, as {component, aspectRatio, source}.",
+ },
+ {
+ value: 'component.detail.blocks',
+ description:
+ "One component's example blocks, as {component, showcase, examples, related} of BlockEntry.",
+ },
+
+ // docs
+ {
+ value: 'docs.list',
+ description:
+ 'All reference-doc topics as DocsListEntry[] ({topic, description}), in discovery order.',
+ },
+ {
+ value: 'docs.detail',
+ description:
+ "One topic's full ReferenceDoc, with token-ref blocks inlined.",
+ },
+ {
+ value: 'docs.detail.section',
+ description:
+ 'A single ReferenceSection of a topic — the first whose title contains the section query.',
+ },
+
+ // blog (read from the published RSS feed)
+ {
+ value: 'blog.list',
+ description:
+ 'The feed URL plus every post parsed from the RSS feed — each with slug, title, description, date, type, authors, link, and plaintext URL.',
+ },
+ {
+ value: 'blog.detail',
+ description:
+ "One post's metadata plus the feed URL and the post's full plaintext body.",
+ },
+
+ // discover (external / integration packages)
+ {
+ value: 'discover.list',
+ description:
+ 'The configured external packages (name, category, components, version, description); when empty it carries meta.configured to tell "nothing configured" from "nothing discovered".',
+ },
+ {
+ value: 'discover.detail',
+ description: 'A single external package entry, for an @scope/name query.',
+ },
+ {
+ value: 'discover.detail.doc',
+ description:
+ 'The validated ComponentDoc for one external component — an @scope/name/Component query, or a free-text term resolving to exactly one component.',
+ },
+ {
+ value: 'discover.search',
+ description:
+ 'The echoed query plus the matching {package, component} pairs, when a free-text term matches several components.',
+ },
+
+ // search
+ {
+ value: 'search',
+ description:
+ 'The echoed query plus a ranked SearchResultEntry[] (domain, name, score, reason, description, follow-up command, and import path where relevant).',
+ },
+
+ // build
+ {
+ value: 'build.help',
+ description:
+ 'A marker (`playbook: true`) that the renderer expands into the how-to-build-a-page workflow; emitted when no query is given.',
+ },
+ {
+ value: 'build.kit',
+ description:
+ 'The grouped composition kit: echoed query, hasResults/directMatch flags, the closest page templates, drop-in block patterns, idea-specific components/hooks, and the always-on frame + foundation component-name arrays.',
+ },
+
+ // swizzle
+ {
+ value: 'swizzle.list',
+ description:
+ "The names of swizzlable components discoverable from cwd's @astryxdesign/core.",
+ },
+ {
+ value: 'swizzle.copy',
+ description:
+ 'An eject receipt: component name, owning package, output directory, files-copied count, the written file names, whether any file uses StyleX, and an optional maintainer note.',
+ },
+
+ // template
+ {
+ value: 'template.list',
+ description:
+ 'Every discovered template (page + block); each entry carries id, name, description, kind, owning package, optional category and componentsUsed, and readiness flags.',
+ },
+ {
+ value: 'template.show',
+ description:
+ "The resolved template's raw source plus its description, kind, and the component names it composes.",
+ },
+ {
+ value: 'template.skeleton',
+ description:
+ "A layout skeleton (structural tags with spatial annotations) plus the template's description and the components it composes.",
+ },
+ {
+ value: 'template.copy',
+ description:
+ 'A scaffold receipt: template id, output directory, written file name, and file count.',
+ },
+
+ // hook
+ {
+ value: 'hook.list',
+ description:
+ 'The hook catalog grouped by category: `detail` (the level — names | compact | full) and `components`, the grouped map of hook names, brief entries, or a full HookDoc per entry.',
+ },
+ {value: 'hook.detail', description: "One hook's full authored HookDoc."},
+ {
+ value: 'hook.detail.params',
+ description: "Just one hook's parameters table (HookParamDoc[]).",
+ },
+
+ // theme
+ {
+ value: 'theme.build',
+ description:
+ 'A theme build receipt: name, token- and component-override counts, output size, the written outputs {css, js, dts, and variantsDts when applicable}, and any validation warnings.',
+ },
+ {
+ value: 'theme.build.check',
+ description:
+ 'The --check receipt: theme name, an upToDate flag, the stale outputs (each {path, reason: missing | outdated}), and the full list of checked paths. Writes nothing.',
+ },
+ {
+ value: 'theme.list',
+ description:
+ 'Every bundled theme as a ThemeListEntry[] — each with slug, displayName, description, and a maintained flag.',
+ },
+ {
+ value: 'theme.add',
+ description:
+ 'A scaffold receipt: resolved slug, displayName, maintained flag, outputDir (relative to cwd), the theme entry file, its exportName, and the files written.',
+ },
+
+ // upgrade
+ {
+ value: 'upgrade.list',
+ description:
+ 'Every available codemod, oldest→newest, as {name, title, version, optional}; returned for --list without running anything.',
+ },
+ {
+ value: 'upgrade.status',
+ description:
+ 'A short-circuit outcome with no codemods run — up_to_date, no_codemods, or config_fixable — each carrying the agent-docs summary.',
+ },
+ {
+ value: 'upgrade.run',
+ description:
+ 'The run receipt: from/to versions, codemod count, integrations processed, the agent-docs summary, and (apply mode) filesChanged, transformsApplied, and per-codemod errors.',
+ },
+
+ // manifest
+ {
+ value: 'manifest',
+ description:
+ 'The self-describing CLI capability manifest: name, version, apiVersion, global options, the command tree (args, options, json flag, response types, examples), the jsonSupported allowlist, and the flat responseTypes index.',
+ },
+
+ // doctor
+ {
+ value: 'doctor',
+ description:
+ 'The health-check report: `checks` (each with id, label, status: pass | warn | fail | info, a message, and a fix when not passing) plus a `summary` of counts per status.',
+ },
+
+ // validate-integration
+ {
+ value: 'integration.validate',
+ description:
+ 'The validation result: the package name and version (both null when no local manifest is found) plus issues, an AstryxIntegrationIssue[] of {code, severity: warning | error, message}.',
+ },
+
+ // 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/response/response.doc.mjs b/packages/cli/foundation/response/response.doc.mjs
new file mode 100644
index 0000000000..c0ef10977b
--- /dev/null
+++ b/packages/cli/foundation/response/response.doc.mjs
@@ -0,0 +1,161 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file SchemaDoc for the Astryx CLI JSON output envelope (the `astryx --json`
+ * contract). Colocated with the serializer (`json.mjs`) and shared types
+ * (`base.d.ts`) it documents.
+ * @position packages/cli/foundation/response — schema documentation
+ */
+
+/** @type {import('@astryxdesign/cli/authoring').SchemaDoc} */
+export const doc = {
+ type: 'schema',
+ name: 'output',
+ displayName: 'Output Envelope',
+ namespace: 'cli',
+ description:
+ 'The single JSON envelope every command emits under --json. Success is ' +
+ '{ apiVersion, type, data, meta? }; failure is { apiVersion, error, code, ' +
+ 'suggestions? }. Discriminate by checking whether `error` is present.',
+ appliesTo: 'astryx --json',
+ fields: [
+ {
+ name: 'Success envelope',
+ type: '{ apiVersion: number; type: string; data: unknown; meta?: Record<string, unknown> }',
+ description:
+ 'Emitted for every successful command in --json mode: a type ' +
+ 'discriminator, its data payload, and an optional meta sidecar.',
+ fields: [
+ {
+ name: 'apiVersion',
+ type: 'number',
+ description:
+ 'Version of the JSON envelope contract. Bump on breaking shape ' +
+ 'changes so consumers can negotiate. Currently 1.',
+ required: true,
+ example: '1',
+ },
+ {
+ name: 'type',
+ type: 'string',
+ description:
+ 'Discriminator naming the payload shape. Each command guarantees ' +
+ 'its own `type` at its return; there is no central union.',
+ required: true,
+ },
+ {
+ name: 'data',
+ type: 'unknown',
+ description:
+ "The command's payload. Structural by design — narrowed by the " +
+ 'per-command return type, not by a map in the serializer.',
+ required: true,
+ },
+ {
+ name: 'meta',
+ type: 'Record<string, unknown>',
+ description:
+ 'Optional sidecar, emitted as a sibling of data (never merged in).',
+ },
+ ],
+ },
+ {
+ name: 'Error envelope',
+ type: '{ apiVersion: number; error: string; code: ErrorCode; suggestions?: Suggestion[] }',
+ description:
+ 'Emitted for every failure in --json mode — including uncaught throws ' +
+ 'and Commander parse errors, which are converted to this shape.',
+ fields: [
+ {
+ name: 'apiVersion',
+ type: 'number',
+ description:
+ 'The same contract version carried on the success envelope.',
+ required: true,
+ example: '1',
+ },
+ {
+ name: 'error',
+ type: 'string',
+ description:
+ 'Human-readable message. It is for people and changes freely, so ' +
+ 'never branch on it.',
+ required: true,
+ },
+ {
+ name: 'code',
+ type: 'ErrorCode',
+ description:
+ 'Stable, machine-readable identifier — always present, append-only, ' +
+ 'and never changes meaning. Branch on this.',
+ required: true,
+ example: "'ERR_UNKNOWN_COMPONENT'",
+ },
+ {
+ name: 'suggestions',
+ type: 'Suggestion[]',
+ description:
+ 'Optional "did you mean…" hints, present only when candidates exist.',
+ fields: [
+ {
+ name: 'suggestions[].name',
+ type: 'string',
+ description:
+ 'The suggested value (e.g. a candidate component name).',
+ required: true,
+ },
+ {
+ name: 'suggestions[].reason',
+ type: 'string',
+ description:
+ 'Optional per-item explanation; some call sites emit a bare ' +
+ 'name with no reason.',
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ examples: [
+ {
+ label: 'Success',
+ code: `{
+ "apiVersion": 1,
+ "type": "component",
+ "data": { "name": "Button" }
+}`,
+ },
+ {
+ label: 'Error',
+ code: `{
+ "apiVersion": 1,
+ "error": "No component named \\"Buton\\"",
+ "code": "ERR_UNKNOWN_COMPONENT",
+ "suggestions": [{ "name": "Button" }]
+}`,
+ },
+ ],
+ notes: [
+ {
+ type: 'prose',
+ text:
+ 'The human-readable (text) output is a deterministic projection of this ' +
+ 'same JSON: --json exposes the structured source of truth, and the ' +
+ 'default format is rendered from the same data.',
+ },
+ {
+ type: 'prose',
+ text:
+ '`code` is the stable contract — see the error-codes enum (ErrorCode) ' +
+ 'for the full append-only list. Branch on `code`, never on the `error` ' +
+ 'prose, which can be reworded or localized at any time.',
+ },
+ {
+ type: 'prose',
+ text:
+ 'The process exit code is part of the contract too: successful commands ' +
+ 'exit 0, and a JSON error envelope is accompanied by a non-zero exit ' +
+ '(jsonError exits 1).',
+ },
+ ],
+};
diff --git a/packages/cli/package.json b/packages/cli/package.json
index 89e7e50cd3..6e5175199d 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -80,11 +80,15 @@
"scripts": {
"astryx": "node clients/cli/bin/astryx.mjs",
"postinstall": "node scripts/postinstall.mjs",
+ "test": "vitest run --root ../.. packages/cli",
+ "test:watch": "vitest --root ../.. packages/cli",
"typecheck:template-docs": "tsc --project tsconfig.template-docs.json",
"typecheck:json-api": "tsc --project tsconfig.json-api.json",
"typecheck:strict": "tsc --project tsconfig.strict.json",
"typecheck:authoring": "tsc --project tsconfig.authoring-contract.json",
"sync:api-types": "node scripts/sync-api-types.mjs",
+ "readme": "node scripts/generate-cli-readme.mjs",
+ "readme:check": "node scripts/generate-cli-readme.mjs --check",
"prepack": "pnpm sync:api-types"
},
"dependencies": {
diff --git a/packages/cli/scripts/generate-cli-readme.mjs b/packages/cli/scripts/generate-cli-readme.mjs
new file mode 100644
index 0000000000..5522b354a5
--- /dev/null
+++ b/packages/cli/scripts/generate-cli-readme.mjs
@@ -0,0 +1,119 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Generate the drift-prone reference tables in packages/cli/README.md from
+ * the sources of truth, so they can't fall out of sync again:
+ * - the Commands table <- `astryx manifest --json` (the live command set)
+ * - the Error codes table <- the error-codes EnumDoc (== ERROR_CODES, enforced
+ * by the docs drift harness)
+ *
+ * Content is written between `<!-- BEGIN GENERATED: <name> -->` and
+ * `<!-- END GENERATED: <name> -->` markers. `--check` verifies the committed
+ * README matches (CI gate); without it, the README is rewritten in place.
+ *
+ * @input astryx manifest + foundation/response/error-codes.doc.mjs
+ * @output packages/cli/README.md (between generated markers)
+ * @position packages/cli/scripts — README table generator
+ *
+ * Usage:
+ * node packages/cli/scripts/generate-cli-readme.mjs # write
+ * node packages/cli/scripts/generate-cli-readme.mjs --check # CI gate
+ */
+
+import {spawnSync} from 'node:child_process';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {fileURLToPath, pathToFileURL} from 'node:url';
+import prettier from 'prettier';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const CLI_ROOT = path.resolve(HERE, '..');
+const BIN = path.join(CLI_ROOT, 'clients/cli/bin/astryx.mjs');
+const README = path.join(CLI_ROOT, 'README.md');
+
+function getManifest() {
+ const res = spawnSync('node', [BIN, 'manifest', '--json'], {
+ encoding: 'utf8',
+ maxBuffer: 64 * 1024 * 1024,
+ });
+ // Report a CLI that failed to boot as itself. Without this, the parse below
+ // turns it into "Unexpected end of JSON input", which says nothing useful
+ // when this runs as a CI gate.
+ if (res.error) throw res.error;
+ if (res.status !== 0 || !res.stdout.trim()) {
+ throw new Error(
+ `\`astryx manifest --json\` failed (exit ${res.status}).\n${res.stderr}`,
+ );
+ }
+ return JSON.parse(res.stdout).data;
+}
+
+/** @param {string} rel @returns {Promise<any>} */
+async function loadDoc(rel) {
+ const mod = await import(pathToFileURL(path.join(CLI_ROOT, rel)).href);
+ return mod.doc ?? mod.docs;
+}
+
+/** @param {string[]} headers @param {string[][]} rows */
+function table(headers, rows) {
+ const esc = (/** @type {unknown} */ s) => String(s).replace(/\|/g, '\\|');
+ const head = `| ${headers.join(' | ')} |`;
+ const sep = `| ${headers.map(() => '---').join(' | ')} |`;
+ const body = rows.map(r => `| ${r.map(esc).join(' | ')} |`).join('\n');
+ return [head, sep, body].join('\n');
+}
+
+/** @param {string} content @param {string} name @param {string} block */
+function replaceBlock(content, name, block) {
+ const begin = `<!-- BEGIN GENERATED: ${name} -->`;
+ const end = `<!-- END GENERATED: ${name} -->`;
+ const re = new RegExp(
+ `${begin.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}[\\s\\S]*?${end.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}`,
+ );
+ if (!re.test(content)) throw new Error(`README markers for "${name}" not found`);
+ return content.replace(re, `${begin}\n\n${block}\n\n${end}`);
+}
+
+async function build() {
+ const manifest = getManifest();
+ const commandRows = manifest.commands
+ .filter((/** @type {any} */ c) => c.name !== 'manifest')
+ .map((/** @type {any} */ c) => [`\`${c.name}\``, c.description]);
+
+ const errorCodes = await loadDoc('foundation/response/error-codes.doc.mjs');
+ const errorRows = errorCodes.members.map((/** @type {any} */ m) => [`\`${m.value}\``, m.description]);
+
+ const responseTypes = await loadDoc('foundation/response/response-types.doc.mjs');
+ const rtRows = responseTypes.members.map((/** @type {any} */ m) => [`\`${m.value}\``, m.description]);
+
+ let content = fs.readFileSync(README, 'utf8');
+ content = replaceBlock(content, 'commands', table(['Command', 'Description'], commandRows));
+ content = replaceBlock(content, 'error-codes', table(['Code', 'Meaning'], errorRows));
+ content = replaceBlock(content, 'response-types', table(['Type', 'What `data` carries'], rtRows));
+
+ // Format through the repo's prettier config so the generated tables match what
+ // the commit hook (lint-staged prettier over *.md) would produce; otherwise
+ // `--check` would flag the file as drifted right after a commit reformats it.
+ const config = (await prettier.resolveConfig(README)) ?? {};
+ return prettier.format(content, {...config, parser: 'markdown', filepath: README});
+}
+
+async function main() {
+ const check = process.argv.includes('--check');
+ const next = await build();
+ const current = fs.readFileSync(README, 'utf8');
+ if (check) {
+ if (current !== next) {
+ console.error(
+ 'README generated tables are out of date. Run: pnpm -F @astryxdesign/cli readme',
+ );
+ process.exit(1);
+ }
+ console.log('README generated tables are in sync.');
+ } else {
+ fs.writeFileSync(README, next);
+ console.log('README generated tables written.');
+ }
+}
+
+main();
diff --git a/packages/cli/test/drift/docs-drift.mjs b/packages/cli/test/drift/docs-drift.mjs
new file mode 100644
index 0000000000..6777a56040
--- /dev/null
+++ b/packages/cli/test/drift/docs-drift.mjs
@@ -0,0 +1,192 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Drift checks for the colocated CLI docs. Keeps the hand-authored docs
+ * honest against their sources of truth:
+ * - every `*.doc.mjs` under the doc roots parses via `parseDoc`;
+ * - each CommandDoc's `fn` resolves to a FunctionDoc, its arg/option `param`s
+ * exist on that function, and its `name` is a real manifest command;
+ * - the error-codes EnumDoc == ERROR_CODES exactly;
+ * - the response-types EnumDoc == the manifest's response discriminants.
+ *
+ * @position packages/cli/test/drift — colocated-docs drift harness
+ */
+
+import {spawnSync} from 'node:child_process';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {fileURLToPath, pathToFileURL} from 'node:url';
+import {parseDoc} from '../../authoring/index.mjs';
+import {allErrorCodes} from '../../foundation/response/error-codes.mjs';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const CLI_ROOT = path.resolve(HERE, '../..');
+const BIN = path.join(CLI_ROOT, 'clients/cli/bin/astryx.mjs');
+const DOC_ROOTS = [
+ 'authoring',
+ 'api',
+ 'clients/cli/commands',
+ 'foundation/response',
+].map(r => path.join(CLI_ROOT, r));
+
+/** @param {string} dir @returns {string[]} */
+function walk(dir) {
+ if (!fs.existsSync(dir)) return [];
+ return fs.readdirSync(dir, {withFileTypes: true}).flatMap(e => {
+ const p = path.join(dir, e.name);
+ if (e.isDirectory()) return walk(p);
+ return e.name.endsWith('.doc.mjs') ? [p] : [];
+ });
+}
+
+/** @returns {Promise<{file: string, doc: any}[]>} */
+export async function collectDocs() {
+ const files = DOC_ROOTS.flatMap(walk);
+ const out = [];
+ for (const f of files) {
+ const mod = await import(pathToFileURL(f).href);
+ out.push({file: path.relative(CLI_ROOT, f), doc: mod.doc ?? mod.docs});
+ }
+ return out;
+}
+
+/** @returns {any} the manifest `data` object. */
+export function getManifest() {
+ const res = spawnSync('node', [BIN, 'manifest', '--json'], {
+ encoding: 'utf8',
+ maxBuffer: 64 * 1024 * 1024,
+ });
+ return JSON.parse(res.stdout).data;
+}
+
+/** Run all drift checks. @returns {Promise<{count: number, errors: string[]}>} */
+export async function runDrift() {
+ /** @type {string[]} */
+ const errors = [];
+ const docs = await collectDocs();
+
+ for (const {file, doc} of docs) {
+ if (!doc) {
+ errors.push(`${file}: no \`doc\` export`);
+ continue;
+ }
+ try {
+ parseDoc(doc);
+ } catch (e) {
+ errors.push(`${file}: parse failed: ${/** @type {Error} */ (e).message}`);
+ }
+ }
+
+ const of = (/** @type {string} */ t) =>
+ docs.filter(d => d.doc && d.doc.type === t);
+ const fnByName = new Map(of('function').map(d => [d.doc.name, d.doc]));
+
+ // Command drift: fn resolves, params resolve, name is real.
+ const manifest = getManifest();
+ const manifestNames = new Set();
+ /** @type {Map<string, any>} */
+ const manifestByName = new Map();
+ const walkCmd = (/** @type {any} */ c) => {
+ manifestNames.add(c.name);
+ manifestByName.set(c.name, c);
+ (c.subcommands || []).forEach(walkCmd);
+ };
+ manifest.commands.forEach(walkCmd);
+
+ for (const {file, doc} of of('command')) {
+ if (doc.name && !manifestNames.has(doc.name)) {
+ errors.push(`${file}: command "${doc.name}" is not in the manifest`);
+ }
+ if (doc.fn) {
+ const fnDoc = fnByName.get(doc.fn);
+ if (!fnDoc) {
+ errors.push(`${file}: fn "${doc.fn}" has no FunctionDoc`);
+ } else {
+ const params = new Set(
+ (fnDoc.params || []).map((/** @type {any} */ p) => p.name),
+ );
+ for (const a of doc.args || [])
+ if (a.param && !params.has(a.param))
+ errors.push(
+ `${file}: arg param "${a.param}" is not a param of ${doc.fn}()`,
+ );
+ for (const o of doc.options || [])
+ if (o.param && !params.has(o.param))
+ errors.push(
+ `${file}: option param "${o.param}" is not a param of ${doc.fn}()`,
+ );
+ }
+ }
+ }
+
+ // Command structure drift: doc args/options/subcommands mirror the live CLI.
+ const argKey = (/** @type {any} */ a) =>
+ `${a.name}:${a.required ? 'req' : 'opt'}${a.variadic ? ':var' : ''}`;
+ for (const {file, doc} of of('command')) {
+ const mc = manifestByName.get(doc.name);
+ if (!mc) continue;
+ const docArgs = (doc.args || []).map(argKey);
+ const mArgs = (mc.arguments || []).map(argKey);
+ if (JSON.stringify(docArgs) !== JSON.stringify(mArgs))
+ errors.push(
+ `${file}: args ${JSON.stringify(docArgs)} != manifest ${JSON.stringify(mArgs)}`,
+ );
+ const docFlags = new Set(
+ (doc.options || []).map((/** @type {any} */ o) => o.flag),
+ );
+ const mFlags = new Set(
+ (mc.options || []).map((/** @type {any} */ o) => o.flag),
+ );
+ for (const f of mFlags)
+ if (!docFlags.has(f))
+ errors.push(
+ `${file}: option "${f}" is in the CLI but missing from the doc`,
+ );
+ for (const f of docFlags)
+ if (!mFlags.has(f))
+ errors.push(`${file}: option "${f}" is in the doc but not the CLI`);
+ const docSubs = new Set(doc.subcommands || []);
+ const mSubs = new Set(
+ (mc.subcommands || []).map((/** @type {any} */ s) =>
+ s.name.split(' ').pop(),
+ ),
+ );
+ for (const s of mSubs)
+ if (!docSubs.has(s))
+ errors.push(
+ `${file}: subcommand "${s}" is in the CLI but missing from the doc`,
+ );
+ for (const s of docSubs)
+ if (!mSubs.has(s))
+ errors.push(`${file}: subcommand "${s}" is in the doc but not the CLI`);
+ }
+
+ // Enum drift: error-codes == ERROR_CODES; response-types == manifest set.
+ checkEnumSet(errors, docs, 'error-codes', new Set(allErrorCodes()));
+ checkEnumSet(
+ errors,
+ docs,
+ 'response-types',
+ new Set(Object.values(manifest.responseTypes).flat()),
+ );
+
+ return {count: docs.length, errors};
+}
+
+/** @param {string[]} errors @param {{doc:any}[]} docs @param {string} name @param {Set<string>} realSet */
+function checkEnumSet(errors, docs, name, realSet) {
+ const entry = docs.find(
+ d => d.doc && d.doc.type === 'enum' && d.doc.name === name,
+ );
+ if (!entry) {
+ errors.push(`missing ${name} EnumDoc`);
+ return;
+ }
+ const docSet = new Set(
+ entry.doc.members.map((/** @type {any} */ m) => m.value),
+ );
+ for (const v of realSet)
+ if (!docSet.has(v)) errors.push(`${name}: missing member "${v}"`);
+ for (const v of docSet)
+ if (!realSet.has(v)) errors.push(`${name}: extra member "${v}"`);
+}
diff --git a/packages/cli/test/drift/docs-drift.test.mjs b/packages/cli/test/drift/docs-drift.test.mjs
new file mode 100644
index 0000000000..f133bde64e
--- /dev/null
+++ b/packages/cli/test/drift/docs-drift.test.mjs
@@ -0,0 +1,22 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CI gate: the colocated CLI docs must stay in sync with their sources of
+ * truth (parse, command↔function refs, and the two enums vs their real sets).
+ */
+
+import {describe, it, expect} from 'vitest';
+import {runDrift} from './docs-drift.mjs';
+
+describe('colocated CLI docs drift', () => {
+ it('every doc parses and stays in sync with its source of truth', async () => {
+ const {count, errors} = await runDrift();
+ expect(count).toBeGreaterThan(0);
+ if (errors.length) {
+ throw new Error(
+ `docs drift detected (${errors.length}):\n ${errors.join('\n ')}`,
+ );
+ }
+ expect(errors).toEqual([]);
+ }, 60_000);
+});
diff --git a/packages/cli/test/readme-gen.test.mjs b/packages/cli/test/readme-gen.test.mjs
new file mode 100644
index 0000000000..3702f259b6
--- /dev/null
+++ b/packages/cli/test/readme-gen.test.mjs
@@ -0,0 +1,31 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file CI gate: the generated tables in packages/cli/README.md (commands,
+ * error codes, response types) must stay in sync with their sources (the
+ * manifest + the error-codes / response-types EnumDocs). Regenerate with
+ * `pnpm -F @astryxdesign/cli readme` when this fails.
+ */
+
+import {spawnSync} from 'node:child_process';
+import * as path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {describe, it, expect} from 'vitest';
+
+const CLI_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+
+describe('README generated tables', () => {
+ it('are in sync with the manifest + EnumDocs', () => {
+ const res = spawnSync(
+ 'node',
+ [path.join(CLI_ROOT, 'scripts/generate-cli-readme.mjs'), '--check'],
+ {encoding: 'utf8', maxBuffer: 16 * 1024 * 1024},
+ );
+ if (res.status !== 0) {
+ throw new Error(
+ `README tables are out of date. Run \`pnpm -F @astryxdesign/cli readme\`.\n${res.stdout}\n${res.stderr}`,
+ );
+ }
+ expect(res.status).toBe(0);
+ }, 30_000);
+});
diff --git a/scripts/check-cli-structure.mjs b/scripts/check-cli-structure.mjs
new file mode 100644
index 0000000000..0ecd83ab8a
--- /dev/null
+++ b/scripts/check-cli-structure.mjs
@@ -0,0 +1,163 @@
+#!/usr/bin/env node
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * Repo check: the CLI's structural conventions, from CONTRIBUTING >
+ * "Working on the astryx CLI".
+ *
+ * These are invariants about which files exist *next to each other*, which is
+ * precisely what typechecking and unit tests cannot see — every individual file
+ * is valid, the set is incomplete.
+ *
+ * 1. Every doc-type ships a complete quartet:
+ * type.ts the authored shape
+ * parse.mjs the sealed parser (the CLI's load boundary)
+ * parse.d.mts the parser's declaration
+ * <kind>.doc.mjs the doc-type documenting itself
+ * The declaration is not optional: `authoring/index.d.ts` re-exports each
+ * parser, so a missing parse.d.mts makes a strict consumer of the published
+ * package resolve it as `any`. That shipped once and only surfaced at pack
+ * time in CI (TS7016) — long after local typechecks passed clean, because
+ * they run with checkJs and never exercise the packed ./api type surface.
+ *
+ * 2. Every api/<name>/ leaf carries its colocated contract and proof:
+ * *.type.mjs the Options + { type, data } response typedefs, or a
+ * published index.ts for a barrel that re-exports them
+ * *.doc.mjs the FunctionDoc
+ * *.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 (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.
+ *
+ * Usage: node scripts/check-cli-structure.mjs
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {fileURLToPath} from 'node:url';
+
+const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
+const CLI = path.join(REPO_ROOT, 'packages/cli');
+const DOCTYPES = path.join(CLI, 'authoring/doctypes');
+const API = path.join(CLI, 'api');
+
+/** `base/` holds the shared leaf types (SlotDoc, ExampleDoc, ...) that other
+ * doc-types compose. It is not a doc kind: nothing parses a "base doc". */
+const DOCTYPE_EXEMPT = new Set(['base']);
+
+/** @param {string} dir @returns {string[]} */
+const dirsIn = dir =>
+ fs.existsSync(dir)
+ ? fs.readdirSync(dir).filter(f => fs.statSync(path.join(dir, f)).isDirectory())
+ : [];
+
+/** Recursively collect file names under a directory. @param {string} dir @returns {string[]} */
+function walk(dir) {
+ /** @type {string[]} */
+ const out = [];
+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {
+ if (entry.isDirectory()) out.push(...walk(path.join(dir, entry.name)));
+ else out.push(entry.name);
+ }
+ return out;
+}
+
+/** @type {string[]} */
+const errors = [];
+let doctypeCount = 0;
+let apiCount = 0;
+
+// ── 1. doc-type quartets ────────────────────────────────────────────────
+const authoringIndexTypes = fs.readFileSync(path.join(CLI, 'authoring/index.d.ts'), 'utf8');
+const authoringIndexImpl = fs.readFileSync(path.join(CLI, 'authoring/index.mjs'), 'utf8');
+const aggregateParseDecl = fs.readFileSync(
+ path.join(DOCTYPES, 'parse.d.mts'),
+ 'utf8',
+);
+
+for (const kind of dirsIn(DOCTYPES)) {
+ if (DOCTYPE_EXEMPT.has(kind)) continue;
+ doctypeCount++;
+ const dir = path.join(DOCTYPES, kind);
+
+ for (const required of ['type.ts', 'parse.mjs', 'parse.d.mts', `${kind}.doc.mjs`]) {
+ if (!fs.existsSync(path.join(dir, required))) {
+ errors.push(
+ `doc-type "${kind}" is missing authoring/doctypes/${kind}/${required}`,
+ );
+ }
+ }
+
+ // A parser nobody re-exports is unreachable from @astryxdesign/cli/authoring.
+ const spec = `./doctypes/${kind}/parse.mjs`;
+ if (!authoringIndexTypes.includes(spec)) {
+ errors.push(`doc-type "${kind}" parser is not re-exported from authoring/index.d.ts`);
+ }
+ if (!authoringIndexImpl.includes(spec)) {
+ errors.push(`doc-type "${kind}" parser is not re-exported from authoring/index.mjs`);
+ }
+
+ // The aggregate parseDoc declaration shadows its implementation for published
+ // consumers, so a kind missing from that union is silently unnarrowable —
+ // `type === 'schema'` reads as a no-overlap comparison and `fields` is
+ // inaccessible. Existence of parse.d.mts is not enough; it must cover the kind.
+ const docType = `${kind[0].toUpperCase()}${kind.slice(1)}Doc`;
+ if (!aggregateParseDecl.includes(docType)) {
+ errors.push(
+ `doc-type "${kind}" is missing from the parseDoc return union in authoring/doctypes/parse.d.mts (expected ${docType})`,
+ );
+ }
+}
+
+// ── 2. api/<name>/ leaves ───────────────────────────────────────────────
+for (const name of dirsIn(API)) {
+ apiCount++;
+ const dir = path.join(API, name);
+ const files = walk(dir);
+ const topLevel = fs.readdirSync(dir);
+
+ if (!files.some(f => f.endsWith('.doc.mjs'))) {
+ errors.push(`api/${name}/ is missing a FunctionDoc (*.doc.mjs)`);
+ }
+ // Types ship as colocated JSDoc typedefs, or — for a barrel that only
+ // re-exports other leaves' types (api/json) — as the published index.ts that
+ // package.json's "exports" points at.
+ if (!files.some(f => f.endsWith('.type.mjs')) && !topLevel.includes('index.ts')) {
+ errors.push(
+ `api/${name}/ is missing response typedefs (*.type.mjs, or a published index.ts)`,
+ );
+ }
+ if (!files.some(f => f.endsWith('.test.mjs'))) {
+ errors.push(`api/${name}/ is missing a test (*.test.mjs)`);
+ }
+}
+
+// If a directory is moved or renamed, the loops above simply iterate nothing and
+// this would report a cheerful "0 checked". A check that passes when its subject
+// disappears is worse than no check, so require having found something real.
+if (doctypeCount === 0) {
+ errors.push(
+ `found no doc-type folders under ${path.relative(REPO_ROOT, DOCTYPES)} — has the directory moved? Update this check.`,
+ );
+}
+if (apiCount === 0) {
+ errors.push(
+ `found no api/<name>/ folders under ${path.relative(REPO_ROOT, API)} — has the directory moved? Update this check.`,
+ );
+}
+
+if (errors.length > 0) {
+ console.error('❌ CLI structure violations:\n');
+ for (const e of errors) console.error(` ${e}`);
+ console.error(
+ `\n${errors.length} error(s). See CONTRIBUTING > "Working on the astryx CLI".`,
+ );
+ process.exit(1);
+}
+
+console.log(
+ `✅ ${doctypeCount} doc-type(s) + ${apiCount} api folder(s) checked — CLI structure is intact.`,
+);