An open source design system that's fully customizable and agent ready
TypeScript
feat(cli): let an integration contribute doc topics, and replace or extend one (#5311)
Joey660c7c089617
diff --git a/.changeset/cli-integration-docs-root.md b/.changeset/cli-integration-docs-root.mdnew file mode 100644index 0000000000..177704aaf3--- /dev/null+++ b/.changeset/cli-integration-docs-root.md@@ -0,0 +1,9 @@+---+'@astryxdesign/cli': patch+---++[feat] An integration can contribute reference-doc topics: point `docs` at a root in `astryx.integration.*` and every `{topic}.doc.{ts,mjs,js}` under it is served by `astryx docs`, indexed by `astryx search`, and named in the agent-docs block, beside the built-in topics. A topic may also declare `replaces: '<topic>'` to take over an existing one (renaming it leaves the old name resolving as an alias) or `extends: '<topic>'` to merge onto one section by section. A name that collides without declaring either is an `invalid_doc` issue rather than a silent override, and `validate-integration` reports it. (#5311)++Also fixes the agent-docs block's topic list, which scanned for `\w+` and so silently dropped every hyphenated topic — `getting-started`, `cli-integrations`, `browser-support`, `styling-libraries` and `working-with-ai` were missing from every block ever written, and an agent cannot ask for a topic it was never told about.++@josephfarinadiff --git a/packages/cli/api/docs/_adapter.mjs b/packages/cli/api/docs/_adapter.mjsindex d2e3540888..26d0810a41 100644--- a/packages/cli/api/docs/_adapter.mjs+++ b/packages/cli/api/docs/_adapter.mjs@@ -3,35 +3,50 @@/*** @file Shared doc-loading and topic-resolution helpers for the docs leaves.*- * @input packages/cli/assets/docs/{topic}.doc.mjs and, when a --dense/--zh overlay is- * requested, the sibling {topic}.doc.dense.mjs / {topic}.doc.zh.mjs.- * @output Topic discovery map, overlay-merged reference-doc data, and a combined- * resolve step ({topics, docsData}) that the detail and section leaves share.+ * @input The project's doc catalog — the CLI's own+ * packages/cli/assets/docs/{topic}.doc.mjs plus every topic the configured+ * integrations contribute — and, when a --dense/--zh overlay is requested,+ * the sibling {topic}.doc.dense.mjs / {topic}.doc.zh.mjs.+ * @output Catalog access, overlay- and extension-merged reference-doc data,+ * and a combined resolve step ({catalog, docsData}) that the detail and+ * section leaves share.* @position Sits beside docs.mjs (api/docs/). Owns everything ≥2 leaves need so- * no leaf re-implements discovery, overlay merging, or unknown-topic handling.+ * no leaf re-implements resolution, overlay merging, or unknown-topic+ * handling. Discovery itself lives in foundation/discovery/docs-discovery,+ * which api/search and the agent-docs block read through the same catalog.*/import * as fs from 'node:fs';import * as path from 'node:path';import {pathToFileURL} from 'node:url';-import {CLI_ROOT} from '../../foundation/fs/paths.mjs';+import {Project} from '../../foundation/config/project.mjs';+import {+ DocsCatalog,+ mergeTopic,+} from '../../foundation/discovery/docs-discovery.mjs';import {AstryxError} from '../error.mjs';import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';-const DOCS_DIR = path.join(CLI_ROOT, 'assets', 'docs');-/**- * @returns {Record<string, string>}+ * The project's topics: the built-in ones plus whatever the configured+ * integrations contribute.+ *+ * A docs read must not depend on a healthy project config. `astryx docs+ * tokens` answered without loading anything before integrations could+ * contribute topics, and it still answers when the config is unreadable — the+ * built-in topics are the floor, and the integration issues surface on the+ * commands that own them.+ *+ * @param {string} [cwd]+ * @returns {Promise<DocsCatalog>}*/-export function discoverTopics() {- /** @type {Record<string, string>} */- const topics = Object.create(null);- if (!fs.existsSync(DOCS_DIR)) return topics;- for (const file of fs.readdirSync(DOCS_DIR)) {- const match = file.match(/^([\w-]+)\.doc\.mjs$/);- if (match) topics[match[1]] = path.join(DOCS_DIR, file);+export async function loadDocsCatalog(cwd = process.cwd()) {+ try {+ const project = await Project.load(cwd);+ return await project.docs();+ } catch {+ return DocsCatalog.fromBuiltins();}- return topics;}/**@@ -41,7 +56,7 @@ export function discoverTopics() {*/export async function loadReferenceDocs(docPath, {lang} = {}) {const mod = await import(pathToFileURL(docPath).href);- const docs = mod.docs;+ const docs = mod.docs ?? mod.default;if (!lang || lang === 'en') return docs;const dir = path.dirname(docPath);@@ -96,46 +111,60 @@ export async function loadReferenceDocs(docPath, {lang} = {}) {}/**- * Discover topics, resolve `topic` to its doc file (throwing `ERR_UNKNOWN_TOPIC`- * when unmatched), and load that topic's reference doc with any --dense/--zh- * overlay applied. Shared by the detail and section leaves so topic normalization- * and unknown-topic handling live in exactly one place.+ * Load one catalog entry: its own doc, plus any extension an integration+ * merged onto it, in configuration order.+ *+ * A localization overlay applies to each file before the extensions are+ * merged, so an extension written in the base language stays readable under+ * `--dense`/`--zh` (it replaces its own sections and leaves the rest+ * translated) rather than being dropped.+ *+ * @param {import('../../foundation/discovery/docs-discovery.mjs').DocsTopicEntry} entry+ * @param {{lang?: string|null}} [opts]+ * @returns {Promise<import('./docs.type.mjs').DocsDetailResponse['data']>}+ */+export async function loadTopicDoc(entry, {lang} = {}) {+ let doc = await loadReferenceDocs(entry.path, {lang});+ for (const extension of entry.extensions) {+ doc = mergeTopic(doc, await loadReferenceDocs(extension.path, {lang}));+ }+ return doc;+}++/**+ * Resolve `topic` against the project's catalog (throwing `ERR_UNKNOWN_TOPIC`+ * when unmatched), and load it with any --dense/--zh overlay and any+ * integration extension applied. Shared by the detail and section leaves so+ * topic normalization and unknown-topic handling live in exactly one place.** @param {string} topic* @param {object} [options]* @param {string} [options.lang]* @param {boolean} [options.zh]* @param {boolean} [options.dense]+ * @param {string} [options.cwd]* @returns {Promise<{- * topics: Record<string, string>,+ * catalog: DocsCatalog,* docsData: import('./docs.type.mjs').DocsDetailResponse['data'],* }>}*/export async function resolveTopicDocs(topic, options = {}) {- const {lang = null, zh = false, dense = false} = options;+ const {lang = null, zh = false, dense = false, cwd} = options;const effectiveLang = lang || (dense ? 'dense' : zh ? 'zh' : null);- const topics = discoverTopics();+ const catalog = await loadDocsCatalog(cwd);- // A public API caller could pass a non-string topic; `.toLowerCase()` below- // would throw a raw TypeError (no ERR_* code → downgrades to ERR_UNKNOWN).- // Surface the same stable code the unknown-topic path uses.- if (typeof topic !== 'string') {+ // A public API caller could pass a non-string topic; `resolve` answers+ // undefined for one, which lands on the same stable code as an unknown name+ // rather than a raw TypeError (which downgrades to ERR_UNKNOWN).+ const entry = catalog.resolve(topic);+ if (!entry) {throw new AstryxError(`Unknown topic "${String(topic)}"`,- Object.keys(topics).map(t => ({name: t, reason: 'available topic'})),- ERROR_CODES.ERR_UNKNOWN_TOPIC,- );- }-- const normalized = topic.toLowerCase();- if (!topics[normalized]) {- throw new AstryxError(- `Unknown topic "${topic}"`,- Object.keys(topics).map(t => ({name: t, reason: 'available topic'})),+ catalog.names().map(t => ({name: t, reason: 'available topic'})),ERROR_CODES.ERR_UNKNOWN_TOPIC,);}- const docsData = await loadReferenceDocs(topics[normalized], {lang: effectiveLang});- return {topics, docsData};+ const docsData = await loadTopicDoc(entry, {lang: effectiveLang});+ return {catalog, docsData};}diff --git a/packages/cli/api/docs/detail/detail.mjs b/packages/cli/api/docs/detail/detail.mjsindex 8bccb5b354..1a1c327139 100644--- a/packages/cli/api/docs/detail/detail.mjs+++ b/packages/cli/api/docs/detail/detail.mjs@@ -11,17 +11,19 @@* discovery/loading/topic-resolution with the section leaf via _adapter.mjs.*/-import {pathToFileURL} from 'node:url';-import {resolveTopicDocs} from '../_adapter.mjs';+import {loadTopicDoc, resolveTopicDocs} from '../_adapter.mjs';/*** Resolve token-ref blocks by inlining the referenced section's table.* This allows section docs to reference token tables without duplicating data.+ *+ * The reference is resolved through the catalog, so a topic may point at one+ * an integration contributed (or replaced) rather than only at a built-in.* @param {import('../docs.type.mjs').DocsDetailResponse['data']} docsData- * @param {Record<string, string>} topics+ * @param {import('../../../foundation/discovery/docs-discovery.mjs').DocsCatalog} catalog* @returns {Promise<import('../docs.type.mjs').DocsDetailResponse['data']>}*/-async function resolveTokenRefs(docsData, topics) {+async function resolveTokenRefs(docsData, catalog) {const resolved = {...docsData, sections: [...docsData.sections]};for (let si = 0; si < resolved.sections.length; si++) {const section = resolved.sections[si];@@ -29,13 +31,12 @@ async function resolveTokenRefs(docsData, topics) {const newContent = [];for (const block of section.content) {if (block.type === 'token-ref') {- const refPath = topics[block.topic];- if (!refPath) {+ const refEntry = catalog.resolve(block.topic);+ if (!refEntry) {newContent.push({type: 'prose', text: `[token-ref: unknown topic "${block.topic}"]`});continue;}- const refMod = await import(pathToFileURL(refPath).href);- const refDocs = refMod.docs;+ const refDocs = await loadTopicDoc(refEntry);const refSection = refDocs.sections.find((/** @type {import('@astryxdesign/cli/authoring').ReferenceSection} */ s) =>s.title.toLowerCase() === block.section.toLowerCase(),@@ -72,10 +73,11 @@ async function resolveTokenRefs(docsData, topics) {* @param {string} [options.lang]* @param {boolean} [options.zh]* @param {boolean} [options.dense]+ * @param {string} [options.cwd]* @returns {Promise<import('../docs.type.mjs').DocsDetailResponse>}*/export async function detail(topic, options = {}) {- const {topics, docsData} = await resolveTopicDocs(topic, options);- const resolved = await resolveTokenRefs(docsData, topics);+ const {catalog, docsData} = await resolveTopicDocs(topic, options);+ const resolved = await resolveTokenRefs(docsData, catalog);return {type: 'docs.detail', data: resolved};}diff --git a/packages/cli/api/docs/detail/section/section.mjs b/packages/cli/api/docs/detail/section/section.mjsindex 73681007b3..cf3346a684 100644--- a/packages/cli/api/docs/detail/section/section.mjs+++ b/packages/cli/api/docs/detail/section/section.mjs@@ -24,6 +24,7 @@ import {resolveTopicDocs} from '../../_adapter.mjs';* @param {string} [options.lang]* @param {boolean} [options.zh]* @param {boolean} [options.dense]+ * @param {string} [options.cwd]* @returns {Promise<import('../../docs.type.mjs').DocsDetailSectionResponse>}*/export async function section(topic, sectionName, options = {}) {diff --git a/packages/cli/api/docs/docs.doc.mjs b/packages/cli/api/docs/docs.doc.mjsindex e7fbcd7219..efe95815f5 100644--- a/packages/cli/api/docs/docs.doc.mjs+++ b/packages/cli/api/docs/docs.doc.mjs@@ -18,7 +18,10 @@ export const doc = {'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.',+ '(case-insensitive) query. The topic set is the CLI\'s own docs plus the ' ++ 'ones the project\'s configured integrations contribute — including any ' ++ 'topic an integration replaces or extends — so it depends on the cwd. ' ++ 'Overlay options select localized or dense variants.',importPath: '@astryxdesign/cli/api',signature:'docs(topic?: string, section?: string, options?: DocsOptions): Promise<DocsListResponse | DocsDetailResponse | DocsDetailSectionResponse>',@@ -60,12 +63,18 @@ export const doc = {type: 'boolean',description: 'Return the token-efficient dense doc variant.',},+ {+ name: 'options.cwd',+ type: 'string',+ description:+ "Project directory whose configured integrations contribute topics. Defaults to process.cwd(); an unreadable config falls back to the CLI's own topics.",+ },],returns: [{type: 'docs.list',description:- 'All available reference-doc topics as DocsListEntry[] ({topic, description}), in discovery order.',+ 'All available reference-doc topics as DocsListEntry[] ({topic, description, package, replaces?}), in read order.',},{type: 'docs.detail',diff --git a/packages/cli/api/docs/docs.mjs b/packages/cli/api/docs/docs.mjsindex 20606385b6..c9fc5239ad 100644--- a/packages/cli/api/docs/docs.mjs+++ b/packages/cli/api/docs/docs.mjs@@ -29,6 +29,7 @@ export {list, detail, sectionLeaf as section};* @param {string} [options.lang]* @param {boolean} [options.zh]* @param {boolean} [options.dense]+ * @param {string} [options.cwd]* @returns {Promise<* import('./docs.type.mjs').DocsListResponse |* import('./docs.type.mjs').DocsDetailResponse |@@ -36,7 +37,7 @@ export {list, detail, sectionLeaf as section};* >}*/export async function docs(topic, section, options = {}) {- if (!topic) return list();+ if (!topic) return list(options);if (section) return sectionLeaf(topic, section, options);return detail(topic, options);}diff --git a/packages/cli/api/docs/docs.type.mjs b/packages/cli/api/docs/docs.type.mjsindex 996f11b347..8033743307 100644--- a/packages/cli/api/docs/docs.type.mjs+++ b/packages/cli/api/docs/docs.type.mjs@@ -23,6 +23,10 @@* @typedef {object} DocsListEntry* @property {string} topic* @property {string} description+ * @property {string} package the package that owns this topic —+ * '@astryxdesign/cli' for a built-in one, else the contributing integration+ * @property {string} [replaces] the topic this one took the place of, when it+ * was contributed as a replacement*//**@@ -45,6 +49,8 @@* @property {string} [lang]* @property {boolean} [zh]* @property {boolean} [dense]+ * @property {string} [cwd] project directory whose configured integrations+ * contribute topics; defaults to process.cwd()*/export {};diff --git a/packages/cli/api/docs/integrationDocs.test.mjs b/packages/cli/api/docs/integrationDocs.test.mjsnew file mode 100644index 0000000000..2ae8c3ec59--- /dev/null+++ b/packages/cli/api/docs/integrationDocs.test.mjs@@ -0,0 +1,208 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file End-to-end tests for integration-contributed doc topics: a scaffolded+ * consumer project whose configured integration ships a `docs` root, read back+ * through the public surfaces — `docs()`, `search()`, and the agent-docs block.+ *+ * The unit-level rules (what a docs root contributes, what the catalog does+ * with `replaces`/`extends`) are covered in+ * foundation/discovery/docs-discovery.test.mjs. What is pinned here is that a+ * contributed topic is indistinguishable from a built-in one at the surfaces+ * an agent actually reads.+ *+ * Fixtures live under a repo-local temp dir, not /tmp, because Vite refuses to+ * dynamically import a module from outside the project root.+ */++import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {docs} from './docs.mjs';+import {search} from '../search/search.mjs';+import {loadDocsCatalog} from './_adapter.mjs';+import {AstryxError} from '../error.mjs';++const SLOW = 30_000;++let tmpDir;++/** A minimal, valid topic. */+function topic(fields) {+ return {+ type: 'generic',+ name: 'deploying',+ title: 'Deploying',+ description: 'How to ship an app built with Acme widgets.',+ category: 'guide',+ sections: [+ {title: 'Overview', content: [{type: 'prose', text: 'Push the button.'}]},+ ],+ ...fields,+ };+}++/**+ * A consumer project that configures one integration, optionally with a docs+ * root holding the given topics.+ * @param {Record<string, object|string>} [topics] file name → doc+ * @param {{config?: string}} [options]+ */+function scaffold(topics, {config} = {}) {+ fs.writeFileSync(path.join(tmpDir, 'package.json'), JSON.stringify({name: 'consumer'}));+ fs.writeFileSync(+ path.join(tmpDir, 'astryx.config.mjs'),+ config ?? "export default {integrations: ['@acme/widgets']};\n",+ );++ const pkgDir = path.join(tmpDir, 'node_modules', '@acme', 'widgets');+ fs.mkdirSync(pkgDir, {recursive: true});+ fs.writeFileSync(+ path.join(pkgDir, 'package.json'),+ JSON.stringify({name: '@acme/widgets', version: '1.0.0'}),+ );+ fs.writeFileSync(+ path.join(pkgDir, 'astryx.integration.mjs'),+ `export default ${JSON.stringify(topics ? {docs: './docs'} : {})};\n`,+ );++ if (topics) {+ const docsDir = path.join(pkgDir, 'docs');+ fs.mkdirSync(docsDir, {recursive: true});+ for (const [file, doc] of Object.entries(topics)) {+ fs.writeFileSync(+ path.join(docsDir, file),+ typeof doc === 'string'+ ? doc+ : `export const docs = ${JSON.stringify(doc, null, 2)};\n`,+ );+ }+ }+}++beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-integration-docs-test-'));+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++describe('integration-contributed topics', () => {+ it('lists and reads like a built-in topic, naming its owner', async () => {+ scaffold({'deploying.doc.mjs': topic()});++ const listed = await docs(undefined, undefined, {cwd: tmpDir});+ const entry = listed.data.find(t => t.topic === 'deploying');+ expect(entry).toMatchObject({+ topic: 'deploying',+ description: 'How to ship an app built with Acme widgets.',+ package: '@acme/widgets',+ });+ // The built-in topics keep their own owner.+ expect(listed.data.find(t => t.topic === 'tokens').package).toBe('@astryxdesign/cli');++ const detail = await docs('deploying', undefined, {cwd: tmpDir});+ expect(detail.type).toBe('docs.detail');+ expect(detail.data.sections[0].content[0].text).toBe('Push the button.');++ const section = await docs('deploying', 'overview', {cwd: tmpDir});+ expect(section.data.title).toBe('Overview');+ }, SLOW);++ it('is invisible to a project that does not configure the integration', async () => {+ scaffold({'deploying.doc.mjs': topic()}, {config: 'export default {};\n'});+ const listed = await docs(undefined, undefined, {cwd: tmpDir});+ expect(listed.data.some(t => t.topic === 'deploying')).toBe(false);+ }, SLOW);++ it('serves the replacement of a built-in topic, and says what it replaced', async () => {+ scaffold({+ 'getting-started.doc.mjs': topic({+ name: 'getting-started',+ replaces: 'getting-started',+ title: 'Getting started',+ description: 'Install Acme widgets.',+ sections: [+ {title: 'Install', content: [{type: 'prose', text: 'yarn add @acme/widgets'}]},+ ],+ }),+ });++ const detail = await docs('getting-started', undefined, {cwd: tmpDir});+ expect(detail.data.sections.map(s => s.title)).toEqual(['Install']);+ expect(detail.data.sections[0].content[0].text).toBe('yarn add @acme/widgets');++ const listed = await docs(undefined, undefined, {cwd: tmpDir});+ const entries = listed.data.filter(t => t.topic === 'getting-started');+ expect(entries).toHaveLength(1);+ expect(entries[0]).toMatchObject({+ package: '@acme/widgets',+ replaces: 'getting-started',+ });+ }, SLOW);++ it('keeps the replaced name resolving when the replacement renames it', async () => {+ scaffold({+ 'setup.doc.mjs': topic({name: 'setup', replaces: 'getting-started'}),+ });+ const byOldName = await docs('getting-started', undefined, {cwd: tmpDir});+ const byNewName = await docs('setup', undefined, {cwd: tmpDir});+ expect(byOldName.data.name).toBe('setup');+ expect(byNewName.data.name).toBe('setup');+ }, SLOW);++ it('merges an extension into the topic it extends', async () => {+ const builtin = await docs('theme');+ const baseSectionTitle = builtin.data.sections[0].title;+ scaffold({+ 'theme-internal.doc.mjs': topic({+ name: 'theme-internal',+ extends: 'theme',+ sections: [+ {title: baseSectionTitle, content: [{type: 'prose', text: 'Use the Acme theme.'}]},+ {title: 'Acme themes', content: [{type: 'prose', text: 'Three of them.'}]},+ ],+ }),+ });++ const extended = await docs('theme', undefined, {cwd: tmpDir});+ // The extension is not a topic of its own.+ expect((await docs(undefined, undefined, {cwd: tmpDir})).data.some(+ t => t.topic === 'theme-internal',+ )).toBe(false);+ expect(extended.data.sections[0].content[0].text).toBe('Use the Acme theme.');+ expect(extended.data.sections.at(-1).title).toBe('Acme themes');+ // Everything the extension did not name is still the base doc's.+ expect(extended.data.sections.length).toBe(builtin.data.sections.length + 1);+ }, SLOW);++ it('offers the contributed topics as suggestions on an unknown one', async () => {+ scaffold({'deploying.doc.mjs': topic()});+ await expect(docs('nope-not-a-topic', undefined, {cwd: tmpDir})).rejects.toBeInstanceOf(+ AstryxError,+ );+ try {+ await docs('nope-not-a-topic', undefined, {cwd: tmpDir});+ } catch (err) {+ expect(err.suggestions.map(s => s.name)).toContain('deploying');+ }+ }, SLOW);++ it('indexes a contributed topic in search', async () => {+ scaffold({'deploying.doc.mjs': topic()});+ const {data} = await search('deploying', {cwd: tmpDir, type: 'doc'});+ expect(data.results[0]).toMatchObject({+ domain: 'doc',+ name: 'deploying',+ command: 'astryx docs deploying',+ });+ }, SLOW);++ it("falls back to the CLI's own topics when the project config is unreadable", async () => {+ scaffold({'deploying.doc.mjs': topic()}, {config: 'export default {integrations: 42};\n'});+ const catalog = await loadDocsCatalog(tmpDir);+ expect(catalog.resolve('tokens')).toBeTruthy();+ expect(catalog.resolve('deploying')).toBeUndefined();+ }, SLOW);+});diff --git a/packages/cli/api/docs/list/list.mjs b/packages/cli/api/docs/list/list.mjsindex 1d50fbf2a0..4882b64b87 100644--- a/packages/cli/api/docs/list/list.mjs+++ b/packages/cli/api/docs/list/list.mjs@@ -3,31 +3,47 @@/*** @file docs.list leaf — enumerate the available reference-doc topics.*- * @input Reads packages/cli/assets/docs/{topic}.doc.mjs via the shared adapter's- * topic discovery. Each topic's English `description` is read directly; the- * listing never applies --dense/--zh overlays.- * @output { type: 'docs.list', data: DocsListEntry[] } — one entry per topic,- * in filesystem-discovery order, matching `xds --json docs`.+ * @input The project's doc catalog (built-in topics plus the ones configured+ * integrations contribute), via the shared adapter. A built-in topic's+ * English `description` is read from its file; a contributed topic already+ * carries the one discovery read. The listing never applies --dense/--zh+ * overlays.+ * @output { type: 'docs.list', data: DocsListEntry[] } — one entry per topic in+ * read order, each naming the package that owns it, matching+ * `astryx --json docs`.* @position Leaf under api/docs. Sibling of detail; both share _adapter.mjs.*/import {pathToFileURL} from 'node:url';-import {discoverTopics} from '../_adapter.mjs';+import {loadDocsCatalog} from '../_adapter.mjs';/**+ * @param {object} [options]+ * @param {string} [options.cwd]* @returns {Promise<import('../docs.type.mjs').DocsListResponse>}*/-export async function list() {- const topics = discoverTopics();+export async function list({cwd} = {}) {+ const catalog = await loadDocsCatalog(cwd);/** @type {Array<import('../docs.type.mjs').DocsListEntry>} */const entries = [];- for (const [name, docPath] of Object.entries(topics)) {- try {- const mod = await import(pathToFileURL(docPath).href);- entries.push({topic: name, description: mod.docs.description});- } catch {- entries.push({topic: name, description: ''});+ for (const entry of catalog.entries()) {+ let description = entry.description ?? '';+ if (entry.description == null) {+ try {+ const mod = await import(pathToFileURL(entry.path).href);+ description = (mod.docs ?? mod.default)?.description ?? '';+ } catch {+ description = '';+ }}+ /** @type {import('../docs.type.mjs').DocsListEntry} */+ const listed = {+ topic: entry.name,+ description,+ package: entry.package,+ };+ if (entry.replaces != null) listed.replaces = entry.replaces;+ entries.push(listed);}return {type: 'docs.list', data: entries};}diff --git a/packages/cli/api/init/run/run.mjs b/packages/cli/api/init/run/run.mjsindex d3a7824f6d..8e858928e6 100644--- a/packages/cli/api/init/run/run.mjs+++ b/packages/cli/api/init/run/run.mjs@@ -20,6 +20,7 @@ import {CLI_ROOT} from '../../../foundation/fs/paths.mjs';import {PathSafetyError} from '../../../foundation/fs/path-safety.mjs';import {getCliInvocation} from '../../../foundation/env/package-manager.mjs';import {installAgentDocs} from '../../../foundation/agent-docs/agent-docs.mjs';+import {loadDocsCatalog} from '../../docs/_adapter.mjs';import {themeTemplate} from '../../theme/template/template.mjs';import {listTemplates} from '../../template/template.mjs';import {AstryxError} from '../../error.mjs';@@ -71,7 +72,7 @@ export function getNextSteps(invocation) {* @param {string} invocation* @param {import('../init.type.mjs').InitRunData} data*/-function applyAgents(cwd, options, invocation, data) {+async function applyAgents(cwd, options, invocation, data) {// Validate --agent up front (a hard error, not a swallowed install failure).// ERR_UNKNOWN_AGENT was defined but never wired — a typo like `--agent claud`// otherwise silently fell back to writing AGENTS.md. Mirrors --features.@@ -88,7 +89,11 @@ function applyAgents(cwd, options, invocation, data) {? options.agentDocsPath: [options.agentDocsPath]: undefined;- const written = installAgentDocs(cwd, {agent: options.agent, paths});+ // The block names the topics the agent can read, and an integration's+ // topics are part of that set — resolved here rather than inside+ // installAgentDocs, which is sync and cannot load a project.+ const topics = (await loadDocsCatalog(cwd)).names();+ const written = installAgentDocs(cwd, {agent: options.agent, paths, topics});data.docsWritten = written;logger.log(`✓ AI agent docs installed → ${written.join(', ')}`);} catch (err) {@@ -248,7 +253,7 @@ export async function run(options = {}, {cwd = process.cwd()} = {}) {nextSteps: false,};for (const feature of features) {- if (feature === 'agents') applyAgents(cwd, options, invocation, data);+ if (feature === 'agents') await applyAgents(cwd, options, invocation, data);if (feature === 'theme') applyTheme(cwd, invocation, data);if (feature === 'template') {applyTemplate(cwd, {templateName: options.templateName}, invocation, data);@@ -272,7 +277,7 @@ export async function run(options = {}, {cwd = process.cwd()} = {}) {templatePath: null,nextSteps: true,};- applyAgents(cwd, options, invocation, data);+ await applyAgents(cwd, options, invocation, data);logger.log('');logger.log(` Tip: \`${invocation} init --all\` also points you to the theme and page-building workflows.`,diff --git a/packages/cli/api/integration/validate-integration.mjs b/packages/cli/api/integration/validate-integration.mjsindex fce44436c2..b16bf9c028 100644--- a/packages/cli/api/integration/validate-integration.mjs+++ b/packages/cli/api/integration/validate-integration.mjs@@ -18,7 +18,7 @@* error) so `validate-integration` can stay exit-0 in a non-integration dir.** The on-disk contribution validators themselves (roots + codemods/templates/- * components, behind `validateLoadedIntegration`) live in+ * components/docs, behind `validateLoadedIntegration`) live in* `foundation/integrations/validate-contributions.mjs`, because foundation also* runs them: `Project` collects integration issues and `integration-warnings`* nudges about them on ordinary commands. This file re-exports@@ -158,6 +158,7 @@ async function validateAtPackageDir(packageDir, identity) {components: resolveRoot(manifest.components),templates: resolveRoot(manifest.templates),codemods: resolveRoot(manifest.codemods),+ docs: resolveRoot(manifest.docs),issuesUrl: manifest.issuesUrl,__spec: identity.name,__packageDir: packageDir,diff --git a/packages/cli/api/integration/validate-integration.type.mjs b/packages/cli/api/integration/validate-integration.type.mjsindex 415366b7d7..f21b27ce11 100644--- a/packages/cli/api/integration/validate-integration.type.mjs+++ b/packages/cli/api/integration/validate-integration.type.mjs@@ -17,6 +17,7 @@* @property {string} [components]* @property {string} [templates]* @property {string} [codemods]+ * @property {string} [docs]* @property {string} [issuesUrl]* @property {string} __spec* @property {string} __packageDirdiff --git a/packages/cli/api/search/search.mjs b/packages/cli/api/search/search.mjsindex 19f1726fd7..da12a7d607 100644--- a/packages/cli/api/search/search.mjs+++ b/packages/cli/api/search/search.mjs@@ -30,10 +30,8 @@* sorts above an incidental mention.*/-import * as fs from 'node:fs';-import * as path from 'node:path';import {pathToFileURL} from 'node:url';-import {findCoreDir, CLI_ROOT} from '../../foundation/fs/paths.mjs';+import {findCoreDir} from '../../foundation/fs/paths.mjs';import {discoverComponents,findComponentReadme,@@ -42,11 +40,10 @@ import {import {discoverHooks, findHookDoc} from '../../foundation/discovery/hook-discovery.mjs';import {levenshteinDistance} from '../../foundation/text/string-utils.mjs';import {discoverTemplates, extractComponents} from '../template/template.mjs';+import {loadDocsCatalog, loadTopicDoc} from '../docs/_adapter.mjs';import {AstryxError} from '../error.mjs';import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';-const DOCS_DIR = path.join(CLI_ROOT, 'assets', 'docs');-/*** A search candidate gathered from one content domain. Extra underscore-* prefixed fields carry domain-specific payload used only by {@link toResult}.@@ -424,17 +421,31 @@ async function gatherHooks(coreDir) {/*** Build doc-topic candidates: topic name + description + section prose.+ *+ * Reads the project's catalog rather than the CLI's own docs directory, so a+ * topic an integration contributed (or replaced) is searchable exactly like a+ * built-in one — otherwise the replacement is served by `astryx docs` but+ * invisible to the command whose job is finding it.+ * @param {string} cwd* @returns {Promise<Candidate[]>}*/-async function gatherDocs() {- if (!fs.existsSync(DOCS_DIR)) return [];+async function gatherDocs(cwd) {/** @type {Candidate[]} */const candidates = [];- for (const file of fs.readdirSync(DOCS_DIR)) {- const match = file.match(/^([\w-]+)\.doc\.mjs$/);- if (!match) continue;- const topic = match[1];- const doc = await loadModuleDoc(path.join(DOCS_DIR, file));+ let entries;+ try {+ entries = (await loadDocsCatalog(cwd)).entries();+ } catch {+ return candidates;+ }+ for (const entry of entries) {+ let doc = null;+ try {+ doc = await loadTopicDoc(entry);+ } catch {+ // A topic that cannot be loaded is reported by the commands that own+ // integration issues; search just cannot index it.+ }let description = '';/** @type {string[]} */const prose = [];@@ -449,11 +460,11 @@ async function gatherDocs() {}candidates.push({domain: 'doc',- name: topic,+ name: entry.name,keywords: [],description,prose,- _title: doc?.title || topic,+ _title: doc?.title || entry.title || entry.name,});}return candidates;@@ -602,7 +613,7 @@ export async function search(query, options = {}) {const [components, hooks, docTopics, templates] = await Promise.all([wants('component') ? gatherComponents(coreDir) : [],wants('hook') ? gatherHooks(coreDir) : [],- wants('doc') ? gatherDocs() : [],+ wants('doc') ? gatherDocs(cwd) : [],wants('template') ? gatherTemplates(cwd) : [],]);diff --git a/packages/cli/api/upgrade/_adapter.mjs b/packages/cli/api/upgrade/_adapter.mjsindex 47603210eb..7fb81927d5 100644--- a/packages/cli/api/upgrade/_adapter.mjs+++ b/packages/cli/api/upgrade/_adapter.mjs@@ -27,6 +27,7 @@ import {} from '../../assets/codemods/integration-discovery.mjs';import {runIntegrationCodemods} from '../../assets/codemods/integration-runner.mjs';import {installAgentDocs, inspectAgentDocs} from '../../foundation/agent-docs/agent-docs.mjs';+import {loadDocsCatalog} from '../docs/_adapter.mjs';import {formatCliCommand} from '../../foundation/env/package-manager.mjs';import {Project} from '../../foundation/config/project.mjs';import {loadIntegrations} from '../../foundation/integrations/integrations.mjs';@@ -145,9 +146,9 @@ export async function runPostCodemodHooks(hooks, context) {* EVERY upgrade path, including the no-codemods short-circuits (#4168).** @param {{cwd: string, installedVersion: string, apply: boolean}} ctx- * @returns {import('./upgrade.type.mjs').AgentDocsSummary}+ * @returns {Promise<import('./upgrade.type.mjs').AgentDocsSummary>}*/-export function refreshAgentDocs({cwd, installedVersion, apply}) {+export async function refreshAgentDocs({cwd, installedVersion, apply}) {const inspection = inspectAgentDocs(cwd, installedVersion);/** @type {import('./upgrade.type.mjs').AgentDocsSummary} */const summary = {@@ -186,7 +187,10 @@ export function refreshAgentDocs({cwd, installedVersion, apply}) {// Apply: rewrite only files that already carry a marker (onlyReplace).try {- const written = installAgentDocs(cwd, {onlyReplace: true});+ const written = installAgentDocs(cwd, {+ onlyReplace: true,+ topics: (await loadDocsCatalog(cwd)).names(),+ });summary.refreshed = written.length > 0;summary.files = written;if (summary.refreshed) {diff --git a/packages/cli/api/upgrade/run/run.mjs b/packages/cli/api/upgrade/run/run.mjsindex 968b6e5390..921b54c948 100644--- a/packages/cli/api/upgrade/run/run.mjs+++ b/packages/cli/api/upgrade/run/run.mjs@@ -90,7 +90,7 @@ export async function run(options = {}, {cwd = process.cwd()} = {}) {// Sync the managed agent-docs block FIRST — it documents the installed library// independent of codemods, so refresh on every path (issue #4168).- const agentDocs = refreshAgentDocs({cwd, installedVersion: targetVersion, apply: apply || false});+ const agentDocs = await refreshAgentDocs({cwd, installedVersion: targetVersion, apply: apply || false});if (!options.force && semverGte(currentVersion, targetVersion)) {return statusUpToDate({from: currentVersion, to: targetVersion, agentDocs});diff --git a/packages/cli/assets/docs/cli-integrations.doc.mjs b/packages/cli/assets/docs/cli-integrations.doc.mjsindex 7a4aa86ee0..c7e201acd7 100644--- a/packages/cli/assets/docs/cli-integrations.doc.mjs+++ b/packages/cli/assets/docs/cli-integrations.doc.mjs@@ -16,7 +16,7 @@ export const docs = {content: [{type: 'prose',- text: 'An integration is an npm package that contributes components, templates, and/or upgrade codemods to a consumer\'s design-system workflow. Consumers install the package and add it to their `astryx.config`; from then on the integration\'s contributions show up alongside core\'s in the same CLI commands.',+ text: 'An integration is an npm package that contributes components, templates, doc topics, and/or upgrade codemods to a consumer\'s design-system workflow. Consumers install the package and add it to their `astryx.config`; from then on the integration\'s contributions show up alongside core\'s in the same CLI commands.',},{type: 'prose',@@ -48,12 +48,12 @@ export const docs = {content: [{type: 'prose',- text: 'To register your package as an integration, add an `astryx.integration.{ts,mjs,js}` file as a sibling of your `package.json`. It tells the CLI where to find your components, templates, and codemods. Identity (name, version) comes from your `package.json`, not this file.',+ text: 'To register your package as an integration, add an `astryx.integration.{ts,mjs,js}` file as a sibling of your `package.json`. It tells the CLI where to find your components, templates, doc topics, and codemods. Identity (name, version) comes from your `package.json`, not this file.',},{type: 'code',lang: 'typescript',- code: "// astryx.integration.ts\nexport default {\n components: './components',\n templates: './templates',\n codemods: './codemods',\n issuesUrl: 'https://github.com/acme/widgets/issues',\n};",+ code: "// astryx.integration.ts\nexport default {\n components: './components',\n templates: './templates',\n codemods: './codemods',\n docs: './docs',\n issuesUrl: 'https://github.com/acme/widgets/issues',\n};",},{type: 'prose',@@ -109,6 +109,44 @@ export const docs = {},],},+ {+ title: 'Docs',+ category: 'guide',+ content: [+ {+ type: 'prose',+ text: "Point the integration file's `docs` field at a directory of reference docs and every `{topic}.doc.{ts,mjs,js}` under it becomes a topic the CLI serves — `astryx docs` lists it, `astryx docs <topic>` prints it, `astryx search` indexes it, and `astryx init` names it in the agent block. A topic is a plain object stamped `type: 'generic'`, the same shape core's own topics use.",+ },+ {+ type: 'code',+ lang: 'typescript',+ code: "// docs/deploying.doc.ts\nexport default {\n type: 'generic',\n name: 'deploying',\n title: 'Deploying',\n description: 'Ship an app built with Acme widgets.',\n category: 'guide',\n sections: [\n {title: 'Overview', content: [{type: 'prose', text: '...'}]},\n ],\n};",+ },+ {+ type: 'prose',+ text: "A topic can also speak about one that already exists. `replaces: 'x'` takes over topic x — core's, or another integration's — so a package whose consumers install it differently can serve its own Getting Started instead of the built-in one. Give the replacement a different `name` and the old name keeps resolving to it, so a link or an agent that learned the old topic still lands in the right place.",+ },+ {+ type: 'code',+ lang: 'typescript',+ code: "export default {\n type: 'generic',\n name: 'getting-started',\n replaces: 'getting-started',\n title: 'Getting started',\n description: 'Install Acme widgets and use your first component.',\n sections: [/* ... */],\n};",+ },+ {+ type: 'prose',+ text: "`extends: 'x'` merges onto a topic instead of owning it: a section whose title matches one in the base replaces that section, and a section the base does not have is appended. Reach for it to correct or add to a topic you do not want to fork — a fork of someone else's guide stops receiving their fixes the day you write it.",+ },+ {+ type: 'list',+ style: 'unordered',+ items: [+ 'A topic name is a CLI argument and a docsite path, so it may hold only letters, digits, `_` and `-`.',+ "A name that collides with an existing topic and declares neither `replaces` nor `extends` is an error, not a silent override — the CLI will not guess which one you meant.",+ '`replaces` and `extends` are exclusive: a topic either takes another\'s place or merges onto it.',+ 'Two integrations replacing one topic is a warning, and the one configured later in `astryx.config` wins.',+ ],+ },+ ],+ },{title: 'Codemods',category: 'guide',diff --git a/packages/cli/authoring/doctypes/_schema.mjs b/packages/cli/authoring/doctypes/_schema.mjsindex 10b979143b..59da06d234 100644--- a/packages/cli/authoring/doctypes/_schema.mjs+++ b/packages/cli/authoring/doctypes/_schema.mjs@@ -94,6 +94,11 @@ export const GenericDocKindSchema = z.object({...BaseDocFields,type: z.literal('generic'),+ // Declared rather than left to the passthrough: these two are read by+ // docs discovery to resolve one topic against another, so a non-string+ // should fail at the load boundary, not halfway through resolution.+ replaces: z.string().optional(),+ extends: z.string().optional(),}).passthrough();diff --git a/packages/cli/authoring/doctypes/reference/reference.doc.mjs b/packages/cli/authoring/doctypes/reference/reference.doc.mjsindex 9771242db9..cfdd3a377d 100644--- a/packages/cli/authoring/doctypes/reference/reference.doc.mjs+++ b/packages/cli/authoring/doctypes/reference/reference.doc.mjs@@ -51,6 +51,20 @@ export const doc = {type: 'string',description: "Navigation category: 'guide' or 'foundations'.",},+ {+ name: 'replaces',+ type: 'string',+ description:+ "Name of an existing topic this doc takes the place of. Authored by an integration that serves its own guide instead of the built-in one: on a doc of the same name it swaps the content, and on a doc of another name it also leaves the old name as an alias so `astryx docs <old>` still resolves. Exclusive with `extends`.",+ example: "'getting-started'",+ },+ {+ name: 'extends',+ type: 'string',+ description:+ 'Name of an existing topic this doc merges onto, section by section: a section whose title matches one in the base replaces it, a section the base does not have is appended. For correcting or adding to a topic rather than owning it. Exclusive with `replaces`.',+ example: "'theme'",+ },{name: 'sections',type: 'ReferenceSection[]',diff --git a/packages/cli/authoring/doctypes/reference/type.ts b/packages/cli/authoring/doctypes/reference/type.tsindex 512571d938..400421ba5e 100644--- a/packages/cli/authoring/doctypes/reference/type.ts+++ b/packages/cli/authoring/doctypes/reference/type.ts@@ -68,6 +68,18 @@ export interface ReferenceDoc {description: string;/** Navigation category: 'guide' or 'foundations'. */category?: string;+ /** Name of an existing topic this doc takes the place of. Authored by an+ * integration whose guide should be served instead of the built-in one —+ * `replaces: 'getting-started'` on a doc named `getting-started` swaps the+ * content, and on a doc named something else swaps it and leaves the old+ * name as an alias, so `astryx docs getting-started` still resolves.+ * Ignored on a built-in topic (there is nothing above it to replace). */+ replaces?: string;+ /** Name of an existing topic this doc merges onto, section by section: a+ * section whose title matches one in the base replaces it, and a section+ * the base does not have is appended. For correcting or adding to a topic+ * rather than owning it — `replaces` and `extends` are exclusive. */+ extends?: string;/** Ordered sections that make up the doc. */sections: ReferenceSection[];/** Token category for foundational docs that map to a token section.diff --git a/packages/cli/authoring/integration/integration.doc.mjs b/packages/cli/authoring/integration/integration.doc.mjsindex 1d39285810..92646dced9 100644--- a/packages/cli/authoring/integration/integration.doc.mjs+++ b/packages/cli/authoring/integration/integration.doc.mjs@@ -15,7 +15,8 @@ export const doc = {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.',+ 'templates, codemods, and doc topics, and where to file issues. Every ' ++ 'field is optional.',appliesTo: 'astryx.integration.{ts,mjs,js}',fields: [{@@ -38,6 +39,13 @@ export const doc = {description: 'Relative path to the codemods root (resolved to absolute).',example: "'./codemods'",},+ {+ name: 'docs',+ type: 'string',+ description:+ 'Relative path to the reference-docs (topics) root (resolved to absolute). Every {topic}.doc.{ts,mjs,js} under it is served by `astryx docs` beside the built-in topics; a topic may also declare `replaces` or `extends` to take the place of a built-in one or merge onto it.',+ example: "'./docs'",+ },{name: 'issuesUrl',type: 'string',@@ -52,6 +60,7 @@ export const doc = {components: './src/components',templates: './src/templates',codemods: './codemods',+ docs: './docs',issuesUrl: 'https://github.com/acme/widgets/issues',};`,},diff --git a/packages/cli/authoring/integration/parse.mjs b/packages/cli/authoring/integration/parse.mjsindex 7e199910df..abbcfb5231 100644--- a/packages/cli/authoring/integration/parse.mjs+++ b/packages/cli/authoring/integration/parse.mjs@@ -16,6 +16,7 @@ const integrationSchema = zcomponents: z.string().optional(),templates: z.string().optional(),codemods: z.string().optional(),+ docs: z.string().optional(),issuesUrl: z.string().url().optional(),}).strict();diff --git a/packages/cli/authoring/integration/parse.test.mjs b/packages/cli/authoring/integration/parse.test.mjsindex c68837d93b..c42d0f7fc4 100644--- a/packages/cli/authoring/integration/parse.test.mjs+++ b/packages/cli/authoring/integration/parse.test.mjs@@ -26,6 +26,7 @@ describe('parseIntegration (load boundary)', () => {expect(parseIntegration({components: './src'})).toEqual({components: './src',});+ expect(parseIntegration({docs: './docs'})).toEqual({docs: './docs'});expect(() =>parseIntegration({components: './c', issuesUrl: 'https://example.com/i'}),).not.toThrow();diff --git a/packages/cli/authoring/integration/type.ts b/packages/cli/authoring/integration/type.tsindex 0897588578..79fc7cec85 100644--- a/packages/cli/authoring/integration/type.ts+++ b/packages/cli/authoring/integration/type.ts@@ -14,6 +14,11 @@ export interface AstryxIntegration {templates?: string;/** Relative path to the codemods root (resolved to absolute). */codemods?: string;+ /** Relative path to the reference-docs (topics) root (resolved to+ * absolute). Every `{topic}.doc.{ts,mjs,js}` under it is a topic the CLI+ * serves from `astryx docs`, alongside the built-in ones. A topic may also+ * `replace` or `extend` a built-in topic; see the ReferenceDoc type. */+ docs?: string;/** Where to file issues/feedback for this integration. */issuesUrl?: string;}diff --git a/packages/cli/foundation/agent-docs/agent-docs.mjs b/packages/cli/foundation/agent-docs/agent-docs.mjsindex 562da5688d..dcf394269f 100644--- a/packages/cli/foundation/agent-docs/agent-docs.mjs+++ b/packages/cli/foundation/agent-docs/agent-docs.mjs@@ -299,11 +299,22 @@ export function detectStylingSystem(targetDir) {* configured (see {@link detectStylingSystem}) so the agent never reaches for a* styling path that isn't compiled here.*+ * `topics` is the project's doc-topic list. Passing it is what puts an+ * integration's topics — including one it contributed in place of a built-in —+ * in front of the agent by name; without it the block falls back to the CLI's+ * own topics, because resolving a project's catalog is async and this is not.+ *+ * Either way the list now includes the hyphenated topics. The fallback scan+ * matched `\w+`, which does not match `-`, so five real topics were missing+ * from every block ever written — `getting-started` and `cli-integrations`+ * among them. An agent cannot ask for a topic it was never told about, and+ * `getting-started` is the one it should reach for first.+ ** @param {string} version- * @param {{coreDir?: string|null, invocation?: string, stylingSystem?: 'stylex'|'tailwind'|'css', zh?: boolean, lang?: string}} [options]+ * @param {{coreDir?: string|null, invocation?: string, stylingSystem?: 'stylex'|'tailwind'|'css', zh?: boolean, lang?: string, topics?: string[]}} [options]* @returns {string}*/-export function generateCompressedIndex(version, {coreDir, invocation = getCliInvocation(), stylingSystem = 'css'} = {}) {+export function generateCompressedIndex(version, {coreDir, invocation = getCliInvocation(), stylingSystem = 'css', topics} = {}) {const run = invocation;const lines = [MARKER_START];@@ -377,13 +388,18 @@ export function generateCompressedIndex(version, {coreDir, invocation = getCliInlines.push(` component --list ${componentCount} components by category`);lines.push(' template --list page + block recipes');const docsDir = path.join(CLI_ROOT, 'assets', 'docs');- if (fs.existsSync(docsDir)) {- const topics = fs.readdirSync(docsDir)- .map(f => f.match(/^(\w+)\.doc\.mjs$/))- .filter(/** @returns {m is RegExpMatchArray} */ (m) => m != null)- .map(m => m[1])- .sort();- if (topics.length > 0) lines.push(` docs <topic> ${topics.join(', ')}`);+ const resolvedTopics =+ topics ??+ (fs.existsSync(docsDir)+ ? fs+ .readdirSync(docsDir)+ .map(f => f.match(/^([\w-]+)\.doc\.mjs$/))+ .filter(/** @returns {m is RegExpMatchArray} */ (m) => m != null)+ .map(m => m[1])+ .sort()+ : []);+ if (resolvedTopics.length > 0) {+ lines.push(` docs <topic> ${resolvedTopics.join(', ')}`);}lines.push(' swizzle <Name> eject component source for deep customization');lines.push(' upgrade --apply run after any @astryxdesign/core bump');@@ -566,14 +582,17 @@ export function removeAgentDocs(targetDir) {* @param {string} [options.agent] - Tool preset: 'claude', 'cursor', 'codex', 'hermes', 'all'* @param {string[]} [options.paths] - Explicit paths (overrides agent/auto-detect)* @param {boolean} [options.onlyReplace] - Only update files that already have Astryx markers (for upgrades)+ * @param {string[]} [options.topics] - Doc topics to list in the block; defaults+ * to the CLI's own. Pass the project's catalog (`(await project.docs()).names()`)+ * so an integration's topics reach the agent.* @returns {string[]} List of files written*/-export function installAgentDocs(targetDir, {zh = false, lang, agent, paths, onlyReplace = false} = {}) {+export function installAgentDocs(targetDir, {zh = false, lang, agent, paths, onlyReplace = false, topics} = {}) {const coreDir = findCoreDir(targetDir);const version = getXdsVersion(coreDir);const invocation = getCliInvocation(targetDir);const stylingSystem = detectStylingSystem(targetDir);- const compressedIndex = generateCompressedIndex(version, {coreDir, zh, lang, invocation, stylingSystem});+ const compressedIndex = generateCompressedIndex(version, {coreDir, zh, lang, invocation, stylingSystem, topics});/** @type {string[]} */const written = [];diff --git a/packages/cli/foundation/agent-docs/agent-docs.test.mjs b/packages/cli/foundation/agent-docs/agent-docs.test.mjsindex 466968a6d4..91c691558f 100644--- a/packages/cli/foundation/agent-docs/agent-docs.test.mjs+++ b/packages/cli/foundation/agent-docs/agent-docs.test.mjs@@ -117,6 +117,44 @@ describe('generateCompressedIndex', () => {// The header defines the mapping; the bare "run every command as `npx astryx`" footgun must be absent.expect(result).not.toContain('npx astryx <cmd>');});++ /** The `docs <topic> a, b, c` line of the block. */+ function topicLine(block) {+ return (+ block.split('\n').find(line => line.trimStart().startsWith('docs <topic>')) ?? ''+ );+ }++ it('names the hyphenated topics, which the scan used to drop', () => {+ // The fallback scan matched `\w+`, which does not match `-`, so five real+ // topics were missing from every block ever written. An agent cannot ask+ // for a topic it was never told about, and `getting-started` — the one it+ // should reach for first — was one of them.+ const line = topicLine(generateCompressedIndex('1.0.0'));+ for (const topic of [+ 'getting-started',+ 'cli-integrations',+ 'browser-support',+ 'styling-libraries',+ 'working-with-ai',+ ]) {+ expect(line).toContain(topic);+ }+ });++ it('lists the topics it is given, so an integration’s reach the agent', () => {+ const line = topicLine(+ generateCompressedIndex('1.0.0', {topics: ['tokens', 'deploying']}),+ );+ expect(line).toContain('tokens, deploying');+ // The project's catalog replaces the built-in scan rather than adding to it:+ // a topic an integration replaced must not also be listed under its old name.+ expect(line).not.toContain('typography');+ });++ it('omits the line entirely when the project has no topics', () => {+ expect(topicLine(generateCompressedIndex('1.0.0', {topics: []}))).toBe('');+ });});describe('detectStylingSystem', () => {diff --git a/packages/cli/foundation/config/project.mjs b/packages/cli/foundation/config/project.mjsindex 348eea374e..a260ca5f7f 100644--- a/packages/cli/foundation/config/project.mjs+++ b/packages/cli/foundation/config/project.mjs@@ -6,16 +6,16 @@* `Project` is the one entry point a command uses to read everything it needs* about a consumer's project: the validated config surface, the configured* integrations, and the resolved discovery sets (components, templates,- * codemods) — plus issue routing (issuesUrl) and the accumulated integration- * issues. It replaces the old `loadConfig(cwd)` plain-object loader and the- * per-command fan-out into the various discovery helpers.+ * codemods, docs) — plus issue routing (issuesUrl) and the accumulated+ * integration issues. It replaces the old `loadConfig(cwd)` plain-object loader+ * and the per-command fan-out into the various discovery helpers.** Design:* - `Project.load(cwd, {cache})` is the async factory (constructors can't be* async). It does what loadConfig did — find the config sibling-of* package.json, import + validate it, load the configured integrations —* and nothing more. Discovery is LAZY.- * - Discovery methods (components/templates/codemods) are MEMOIZED per+ * - Discovery methods (components/templates/codemods/docs) are MEMOIZED per* instance (via the pluggable cache) and orchestrate the EXISTING discovery* functions — Project never reimplements discovery.* - SKIP + WARN policy: as a discovery method runs, per-integration work is@@ -45,6 +45,10 @@ import {discoverAll as discoverTemplates,discoverIntegrationTemplatesForOne,} from '../discovery/template-adapter.mjs';+import {+ DocsCatalog,+ discoverIntegrationDocs,+} from '../discovery/docs-discovery.mjs';import {getTransformsBetween} from '../../assets/codemods/registry.mjs';import {discoverIntegrationCodemods,@@ -454,6 +458,63 @@ export class Project {});}+ /**+ * The CLI's own doc topics plus the ones the configured integrations+ * contribute, resolved into one catalog: additions, replacements (with the+ * replaced name left as an alias), and extensions merged in configuration+ * order. Same skip+warn policy as its siblings — a broken integration+ * contributes no topics and its issues are collected. Memoized per instance.+ *+ * Two problems can only be seen with every integration in hand, so they are+ * raised here rather than in the per-integration validators: a topic that+ * collides with one another package already provides, and a `replaces` /+ * `extends` that names a topic nothing provides.+ *+ * @returns {Promise<DocsCatalog>}+ */+ async docs() {+ return this.#memo('docs', async () => {+ const catalog = DocsCatalog.fromBuiltins();++ for (const integration of this.#loadedIntegrations) {+ await this.#collectIssues(integration);+ const pkg = this.#pkgLabel(integration);+ const hadError = this.#issues.some(+ i => i.package === pkg && i.severity === 'error',+ );+ if (hadError) continue;+ if (!integration?.docs) continue;+ try {+ const {records, errors} = await discoverIntegrationDocs(integration);+ for (const e of errors) {+ this.#pushIssue(pkg, {+ code: 'invalid_doc',+ severity: 'error',+ message: e.message,+ });+ }+ // Any unusable doc withdraws the whole package's topics, matching+ // how a bad template withdraws its package's templates: a partial+ // docs contribution is the state where a `replaces` silently does+ // nothing and a reader gets the topic it was meant to replace.+ if (errors.length > 0) continue;+ for (const record of records) {+ const issue = catalog.add(record);+ if (issue) this.#pushIssue(pkg, issue);+ }+ } catch (err) {+ this.#pushIssue(pkg, {+ code: 'invalid_doc',+ severity: 'error',+ message: errorMessage(err),+ });+ }+ }++ return catalog;+ });+ }+/*** Core registry transforms + integration codemods for an upgrade range.* Wraps getTransformsBetween (core) and discoverIntegrationCodemods /diff --git a/packages/cli/foundation/config/project.test.mjs b/packages/cli/foundation/config/project.test.mjsindex 4d27408f0d..418591c02a 100644--- a/packages/cli/foundation/config/project.test.mjs+++ b/packages/cli/foundation/config/project.test.mjs@@ -24,6 +24,7 @@ function scaffold({withCodemods = true,brokenComponent = false,brokenCodemod = false,+ docs = null,integrationIssuesUrl = 'https://example.com/widgets/issues',} = {}) {fs.writeFileSync(@@ -48,6 +49,7 @@ function scaffold({if (withComponents) manifest.components = './components';if (withTemplates) manifest.templates = './templates';if (withCodemods) manifest.codemods = './codemods';+ if (docs) manifest.docs = './docs';if (integrationIssuesUrl) manifest.issuesUrl = integrationIssuesUrl;fs.writeFileSync(path.join(pkgDir, 'astryx.integration.mjs'),@@ -99,9 +101,34 @@ function scaffold({}}+ if (docs) {+ const docsDir = path.join(pkgDir, 'docs');+ fs.mkdirSync(docsDir, {recursive: true});+ for (const [file, doc] of Object.entries(docs)) {+ fs.writeFileSync(+ path.join(docsDir, file),+ typeof doc === 'string'+ ? doc+ : `export const docs = ${JSON.stringify(doc, null, 2)};\n`,+ );+ }+ }+return pkgDir;}+/** A minimal, valid topic for the docs-root fixtures. */+function topicDoc(fields) {+ return {+ type: 'generic',+ name: 'deploying',+ title: 'Deploying',+ description: 'How to ship it.',+ sections: [{title: 'Overview', content: [{type: 'prose', text: 'Ship it.'}]}],+ ...fields,+ };+}+beforeEach(() => {originalCwd = process.cwd();tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-project-test-'));@@ -198,6 +225,45 @@ describe('Project discovery', () => {expect(integration[0].codemods[0].id).toBe('drop-foo');});+ it('docs() adds an integration topic beside the built-in ones', async () => {+ scaffold({docs: {'deploying.doc.mjs': topicDoc()}});+ const project = await Project.load(tmpDir);+ const catalog = await project.docs();+ expect(catalog.resolve('deploying')).toMatchObject({+ name: 'deploying',+ package: '@acme/widgets',+ });+ // The CLI's own topics are still there.+ expect(catalog.resolve('tokens').package).toBe('@astryxdesign/cli');+ expect(await project.issues()).toEqual([]);+ });++ it('docs() lets an integration replace a built-in topic, aliasing the old name', async () => {+ scaffold({+ docs: {+ 'setup.doc.mjs': topicDoc({name: 'setup', replaces: 'getting-started'}),+ },+ });+ const project = await Project.load(tmpDir);+ const catalog = await project.docs();+ expect(catalog.resolve('setup').package).toBe('@acme/widgets');+ expect(catalog.resolve('getting-started').name).toBe('setup');+ });++ it('docs() records an unusable topic as an issue and contributes none', async () => {+ scaffold({+ docs: {+ 'ok.doc.mjs': topicDoc(),+ 'broken.doc.mjs': topicDoc({name: 'broken', sections: []}),+ },+ });+ const project = await Project.load(tmpDir);+ const catalog = await project.docs();+ expect(catalog.resolve('deploying')).toBeUndefined();+ const issues = await project.issues();+ expect(issues.some(i => i.code === 'invalid_doc' && i.severity === 'error')).toBe(true);+ });+it('memoizes components() — the second call does not re-walk', async () => {scaffold();const project = await Project.load(tmpDir);diff --git a/packages/cli/foundation/discovery/docs-discovery.mjs b/packages/cli/foundation/discovery/docs-discovery.mjsnew file mode 100644index 0000000000..27efee64f7--- /dev/null+++ b/packages/cli/foundation/discovery/docs-discovery.mjs@@ -0,0 +1,544 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Reference-doc (topic) discovery — the CLI's own topics plus the ones+ * configured integrations contribute, resolved into one catalog.+ *+ * @input packages/cli/assets/docs/{topic}.doc.mjs (built in), and each loaded+ * integration's resolved `docs` root ({topic}.doc.{ts,mjs,js}).+ * @output A {@link DocsCatalog}: every topic the project can read, keyed by+ * name, carrying its owner package, its file, and any extension overlays —+ * plus the alias a renamed replacement leaves behind.+ * @position foundation/discovery — the single seam every docs surface reads+ * (api/docs, api/search, and the agent-docs block), so a topic contributed+ * once shows up in all of them.+ *+ * An integration contributes a topic the way it contributes a component: a+ * root in its manifest, a file per artifact. What a doc says about its+ * relationship to an existing topic is authored on the doc itself, not in a+ * second registry that has to be kept in step with it:+ *+ * (neither) add a topic under its own name+ * replaces: 'x' take over topic x — core's, or another integration's+ * extends: 'x' merge onto topic x, section by section+ *+ * A topic whose name collides with an existing one and declares neither is an+ * `invalid_doc` issue rather than silent shadowing. Shadowing by name would+ * make a core rename swallow an integration's guide (or the reverse) with no+ * diagnostic anywhere, which is the failure mode integration discovery already+ * refuses for components provided by two packages.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {CLI_ROOT} from '../fs/paths.mjs';+import {importUserModule} from '../fs/module-loader.mjs';+import {parseDoc} from '../../authoring/doctypes/parse.mjs';++/** Where the CLI's own topics live. */+const BUILTIN_DOCS_DIR = path.join(CLI_ROOT, 'assets', 'docs');++/**+ * Owner package recorded for the built-in topics. They ship inside the CLI+ * (assets/docs), not in @astryxdesign/core, so this is the CLI's own name —+ * unlike component discovery, whose built-ins belong to core.+ */+export const BUILTIN_DOCS_PACKAGE = '@astryxdesign/cli';++/**+ * A built-in topic file: `{topic}.doc.mjs`. Anchored at both ends so a+ * localization overlay (`{topic}.doc.zh.mjs`) is not read as a topic of its+ * own — it is loaded by the topic it overlays.+ */+const BUILTIN_TOPIC_FILE_RE = /^([\w-]+)\.doc\.mjs$/;++/** Conventional doc-file suffixes for an integration's topics. */+const INTEGRATION_DOC_SUFFIXES = ['.doc.ts', '.doc.mjs', '.doc.js'];++/** A topic name is a CLI argument and a URL segment; keep it to both. */+const TOPIC_NAME_RE = /^[\w-]+$/;++/**+ * @typedef {object} DocsTopicRecord A doc file discovered under a docs root.+ * @property {string} name+ * @property {string} package owner package+ * @property {string} path absolute path to the doc file+ * @property {string} [title]+ * @property {string} [description]+ * @property {string|null} [category]+ * @property {string} [replaces] topic this doc takes the place of+ * @property {string} [extendsTopic] topic this doc merges onto (`extends`)+ */++/**+ * @typedef {object} DocsTopicEntry A resolved topic in the catalog.+ * @property {string} name+ * @property {string} package owner package+ * @property {string} path absolute path to the doc file+ * @property {string} [title]+ * @property {string} [description]+ * @property {string|null} [category]+ * @property {string} [replaces] the topic this one took the place of+ * @property {Array<{package: string, path: string}>} extensions overlays to+ * merge onto the base doc, in the order their integrations were configured+ */++/**+ * Discover the CLI's own topics.+ * @returns {Record<string, string>} topic name → absolute doc path+ */+export function discoverBuiltinTopics() {+ /** @type {Record<string, string>} */+ const topics = Object.create(null);+ if (!fs.existsSync(BUILTIN_DOCS_DIR)) return topics;+ for (const file of fs.readdirSync(BUILTIN_DOCS_DIR)) {+ const match = file.match(BUILTIN_TOPIC_FILE_RE);+ if (match) topics[match[1]] = path.join(BUILTIN_DOCS_DIR, file);+ }+ return topics;+}++/**+ * Load a topic doc from disk. A `.ts` doc is loaded through jiti, the rest+ * natively; both the historical `export const docs` and the stamped+ * `export default` forms are accepted, because core authors the first and the+ * integration guide documents the second.+ *+ * @param {string} file absolute path to a doc file+ * @returns {Promise<unknown>} the authored doc value+ */+export async function loadTopicModule(file) {+ const mod = await importUserModule(file);+ const doc = mod?.docs ?? mod?.default;+ if (doc == null) {+ throw new Error(+ `${path.basename(file)} exports no doc. A topic exports \`docs\` (or a default export).`,+ );+ }+ return doc;+}++/** Every block kind a section may hold, with the fields each one requires. */+const BLOCK_FIELDS = {+ prose: ['text'],+ heading: ['level', 'text'],+ code: ['lang', 'code'],+ table: ['headers', 'rows'],+ list: ['style', 'items'],+ 'token-ref': ['topic', 'section'],+};++/**+ * Fields a block kind may carry but does not need. Kept per kind rather than+ * globally: only a code block renders a `label`, so allowing it everywhere+ * would wave through the misspellings this check exists to catch.+ */+const OPTIONAL_BLOCK_FIELDS = {code: ['label']};++/**+ * Fields whose value has to be one of a set, because the renderer indexes on+ * it. An unlisted heading level renders at the wrong depth and an unlisted+ * list style resolves to undefined, so the value is checked, not just its+ * presence.+ */+const BLOCK_FIELD_VALUES = {+ heading: {level: [3, 4, 5, 6]},+ list: {style: ['ordered', 'unordered', 'do', 'dont']},+};++/** Keys a section may carry. */+const SECTION_FIELDS = ['title', 'category', 'content', 'previewType'];++/**+ * Check the fields the docs surfaces actually read. `parseDoc` is the outer+ * gate, but the reference-doc schema is a passthrough over `{name, type}` —+ * a doc with no `sections`, or a prose block whose `text` is misspelled,+ * passes it and reaches a reader as a missing section or a blank gap. Those+ * are hard to trace back from the rendered output, so they are caught here,+ * where the file that needs fixing can be named.+ *+ * @param {any} doc a parsed doc+ * @returns {string[]} problems, each already pointed at a place in the doc+ */+export function problemsInTopic(doc) {+ /** @type {string[]} */+ const problems = [];+ for (const field of ['name', 'title', 'description']) {+ if (typeof doc?.[field] !== 'string' || doc[field] === '') {+ problems.push(`${field}: expected a non-empty string`);+ }+ }+ if (typeof doc?.name === 'string' && !TOPIC_NAME_RE.test(doc.name)) {+ problems.push(+ `name: "${doc.name}" is not URL-safe. A topic name is its CLI argument and its docsite path, so it may hold only letters, digits, "_" and "-".`,+ );+ }+ if (!Array.isArray(doc?.sections) || doc.sections.length === 0) {+ problems.push('sections: expected at least one section');+ return problems;+ }++ doc.sections.forEach((/** @type {any} */ section, /** @type {number} */ s) => {+ const at = `sections[${s}]`;+ if (typeof section?.title !== 'string' || section.title === '') {+ problems.push(`${at}.title: expected a non-empty string`);+ }+ for (const key of Object.keys(section ?? {})) {+ if (!SECTION_FIELDS.includes(key)) {+ problems.push(`${at}.${key}: not a field of a section`);+ }+ }+ if (!Array.isArray(section?.content)) {+ problems.push(`${at}.content: expected an array of blocks`);+ return;+ }+ section.content.forEach((/** @type {any} */ block, /** @type {number} */ b) => {+ const blockAt = `${at}.content[${b}]`;+ const fields = /** @type {Record<string, string[]>} */ (BLOCK_FIELDS)[block?.type];+ if (fields == null) {+ problems.push(+ `${blockAt}.type: ${JSON.stringify(block?.type)} is not one of ${Object.keys(BLOCK_FIELDS).join(', ')}`,+ );+ return;+ }+ for (const field of fields) {+ const value = block[field];+ // Empty counts as missing, the way it does for the doc's own title: a+ // block whose text is '' passes every other check and renders as a gap.+ if (value == null) {+ problems.push(`${blockAt}.${field}: required for a ${block.type} block`);+ } else if (typeof value === 'string' && value.trim() === '') {+ problems.push(`${blockAt}.${field}: expected a non-empty string`);+ } else if (Array.isArray(value) && value.length === 0) {+ problems.push(`${blockAt}.${field}: expected a non-empty array`);+ }+ }+ const allowedValues =+ /** @type {Record<string, Record<string, unknown[]>>} */ (BLOCK_FIELD_VALUES)[block.type] ?? {};+ for (const [field, values] of Object.entries(allowedValues)) {+ const value = block[field];+ if (value != null && !values.includes(value)) {+ problems.push(+ `${blockAt}.${field}: ${JSON.stringify(value)} is not one of ${values.join(', ')}`,+ );+ }+ }+ // A table's cells are read by column index, so a short row renders blank+ // cells and a long one drops its tail — both silently.+ if (block.type === 'table' && Array.isArray(block.headers) && Array.isArray(block.rows)) {+ block.rows.forEach((/** @type {any} */ row, /** @type {number} */ r) => {+ if (!Array.isArray(row)) {+ problems.push(`${blockAt}.rows[${r}]: expected an array of cells`);+ } else if (row.length !== block.headers.length) {+ problems.push(+ `${blockAt}.rows[${r}]: has ${row.length} cells but the table has ${block.headers.length} headers`,+ );+ }+ });+ }+ // An unknown key is almost always a misspelled required one, and it+ // would otherwise reach a reader as a block that renders nothing.+ const allowed = [+ 'type',+ ...fields,+ ...(/** @type {Record<string, string[]>} */ (OPTIONAL_BLOCK_FIELDS)[block.type] ?? []),+ ];+ for (const key of Object.keys(block)) {+ if (!allowed.includes(key)) {+ problems.push(`${blockAt}.${key}: not a field of a ${block.type} block`);+ }+ }+ });+ });+ return problems;+}++/**+ * Discover the topics contributed by a single loaded integration. Mirrors+ * `discoverIntegrationComponents`: walk the resolved root, take every+ * conventional doc file, and record what it declares. Unlike component+ * discovery this loads each doc, because a topic's name and its relationship+ * to an existing topic are fields inside the file.+ *+ * Errors are returned, not thrown: one unusable doc is reported as an issue+ * against its package while the rest of the CLI keeps working.+ *+ * @param {{name: string, docs?: string}} integration a loaded integration+ * @returns {Promise<{records: DocsTopicRecord[], errors: Error[]}>}+ */+export async function discoverIntegrationDocs(integration) {+ const docsDir = integration?.docs;+ /** @type {DocsTopicRecord[]} */+ const records = [];+ /** @type {Error[]} */+ const errors = [];+ if (!docsDir || !fs.existsSync(docsDir)) return {records, errors};++ /** @type {string[]} */+ const files = [];+ /** @param {string} dirPath */+ function scanDir(dirPath) {+ for (const entry of fs.readdirSync(dirPath, {withFileTypes: true})) {+ if (entry.name === 'node_modules' || entry.name === '__tests__') continue;+ const full = path.join(dirPath, entry.name);+ if (entry.isDirectory()) {+ scanDir(full);+ } else if (INTEGRATION_DOC_SUFFIXES.some(suffix => entry.name.endsWith(suffix))) {+ files.push(full);+ }+ }+ }+ scanDir(docsDir);+ files.sort();++ /** @type {Map<string, string>} */+ const seen = new Map();+ for (const file of files) {+ let doc;+ try {+ doc = parseDoc(await loadTopicModule(file), path.basename(file));+ } catch (err) {+ errors.push(new Error(`${path.relative(docsDir, file)}: ${/** @type {any} */ (err).message}`));+ continue;+ }+ const problems = problemsInTopic(doc);+ if (problems.length > 0) {+ errors.push(+ new Error(+ `${path.relative(docsDir, file)} is not a usable topic:\n${problems+ .map(problem => ` ${problem}`)+ .join('\n')}`,+ ),+ );+ continue;+ }+ const parsed = /** @type {any} */ (doc);+ // Two files claiming one name would collapse into a single entry, and the+ // one that lost would never be reachable. Named here, where both files are.+ const previous = seen.get(parsed.name);+ if (previous) {+ errors.push(+ new Error(+ `${path.relative(docsDir, file)} and ${previous} both define the topic "${parsed.name}". Each topic name is a URL and a CLI argument, so they have to be unique.`,+ ),+ );+ continue;+ }+ seen.set(parsed.name, path.relative(docsDir, file));+ if (parsed.replaces != null && parsed.extends != null) {+ errors.push(+ new Error(+ `${path.relative(docsDir, file)} declares both \`replaces\` and \`extends\`. A topic either takes another's place or merges onto it.`,+ ),+ );+ continue;+ }+ records.push({+ name: parsed.name,+ package: integration.name,+ path: file,+ title: parsed.title,+ description: parsed.description,+ category: parsed.category ?? null,+ replaces: parsed.replaces,+ extendsTopic: parsed.extends,+ });+ }++ return {records, errors};+}++/**+ * Merge an extension onto a base topic: a section whose title matches one in+ * the base replaces it, a section the base does not have is appended, and the+ * title/description are taken from the extension when it states them.+ *+ * Keyed by section TITLE rather than by position, the way the localization+ * overlays are — position keying grafts an overlay onto whichever section+ * happens to share its index, so a partial or reordered overlay corrupts+ * everything after it (#2182).+ *+ * @param {any} base+ * @param {any} overlay+ * @returns {any} a new doc; neither input is mutated+ */+export function mergeTopic(base, overlay) {+ const sections = [...(base.sections ?? [])];+ for (const section of overlay.sections ?? []) {+ const at = sections.findIndex((/** @type {any} */ s) => s.title === section.title);+ if (at === -1) sections.push(section);+ else sections[at] = section;+ }+ return {+ ...base,+ title: overlay.title || base.title,+ description: overlay.description || base.description,+ sections,+ };+}++/**+ * Every topic a project can read, and the relationships between them.+ *+ * Insertion order is the read order: the built-in topics in discovery order,+ * then whatever the configured integrations add, in the order they are+ * configured. A replacement keeps the position of the topic it replaced, so+ * "the first topic" stays stable for a reader that opens it by default.+ */+export class DocsCatalog {+ /** @type {Map<string, DocsTopicEntry>} */+ #topics = new Map();+ /** @type {Map<string, string>} old topic name → the name that replaced it */+ #aliases = new Map();++ /**+ * Seed a catalog with the CLI's own topics.+ * @param {Record<string, string>} [builtins] topic name → absolute path+ * @returns {DocsCatalog}+ */+ static fromBuiltins(builtins = discoverBuiltinTopics()) {+ const catalog = new DocsCatalog();+ for (const [name, file] of Object.entries(builtins)) {+ catalog.#topics.set(name, {+ name,+ package: BUILTIN_DOCS_PACKAGE,+ path: file,+ extensions: [],+ });+ }+ return catalog;+ }++ /**+ * Add one integration-contributed doc, honoring what it declares. Returns+ * the issue it caused, or null when it applied cleanly — the caller owns+ * routing (an `error` skips the contribution, a `warning` keeps it).+ *+ * @param {DocsTopicRecord} record+ * @returns {import('../integrations/issue').AstryxIntegrationIssue | null}+ */+ add(record) {+ if (record.extendsTopic != null) {+ const target = this.resolve(record.extendsTopic);+ if (!target) {+ return {+ code: 'invalid_doc',+ severity: 'error',+ message: `"${record.name}" extends "${record.extendsTopic}", which is not a topic in this project.`,+ };+ }+ target.extensions.push({package: record.package, path: record.path});+ return null;+ }++ if (record.replaces != null) {+ const target = this.resolve(record.replaces);+ if (!target) {+ return {+ code: 'invalid_doc',+ severity: 'error',+ message: `"${record.name}" replaces "${record.replaces}", which is not a topic in this project.`,+ };+ }+ /** @type {import('../integrations/issue').AstryxIntegrationIssue | null} */+ let warning = null;+ if (target.package !== BUILTIN_DOCS_PACKAGE) {+ // Two integrations replacing one topic is a real configuration, not a+ // broken one: the later-configured package wins, the way the last+ // writer does everywhere else. Both are named so the loser is visible.+ warning = {+ code: 'duplicate_doc',+ severity: 'warning',+ message: `Topic "${record.replaces}" is replaced by both ${target.package} and ${record.package}. ${record.package} is configured later, so it wins.`,+ };+ }+ // The replacement takes the base topic's slot, so a reader that opens+ // the first topic (or the nth) sees the same one it did before.+ const replaced = target.name;+ this.#replaceAt(replaced, {+ name: record.name,+ package: record.package,+ path: record.path,+ title: record.title,+ description: record.description,+ category: record.category,+ replaces: replaced,+ // Extensions were authored against the content that just went away.+ extensions: [],+ });+ if (record.name !== replaced) {+ this.#aliases.set(replaced, record.name);+ // A topic renamed twice keeps every name it has ever answered to.+ for (const [from, to] of this.#aliases) {+ if (to === replaced) this.#aliases.set(from, record.name);+ }+ }+ return warning;+ }++ const existing = this.#topics.get(record.name);+ if (existing) {+ return {+ code: 'invalid_doc',+ severity: 'error',+ message: `Topic "${record.name}" is already provided by ${existing.package}. Give it another name, or declare \`replaces: '${record.name}'\` to take its place.`,+ };+ }+ this.#topics.set(record.name, {+ name: record.name,+ package: record.package,+ path: record.path,+ title: record.title,+ description: record.description,+ category: record.category,+ extensions: [],+ });+ return null;+ }++ /**+ * Look a topic up by name, case-insensitively, following the alias a renamed+ * replacement left behind.+ * @param {unknown} name+ * @returns {DocsTopicEntry | undefined}+ */+ resolve(name) {+ if (typeof name !== 'string') return undefined;+ let key = name.toLowerCase();+ // An alias chain is at most as long as the number of replacements, and a+ // cycle can only come from a bug here; bound the walk either way.+ for (let hops = 0; hops <= this.#aliases.size; hops++) {+ const entry = this.#topics.get(key);+ if (entry) return entry;+ const next = this.#aliases.get(key);+ if (next == null) return undefined;+ key = next;+ }+ return undefined;+ }++ /** @returns {string[]} every topic name, in read order */+ names() {+ return [...this.#topics.keys()];+ }++ /** @returns {DocsTopicEntry[]} every topic, in read order */+ entries() {+ return [...this.#topics.values()];+ }++ /**+ * Swap an entry in place, preserving its position in the read order.+ * @param {string} name+ * @param {DocsTopicEntry} entry+ */+ #replaceAt(name, entry) {+ /** @type {Map<string, DocsTopicEntry>} */+ const next = new Map();+ for (const [key, value] of this.#topics) {+ if (key === name) next.set(entry.name, entry);+ else next.set(key, value);+ }+ this.#topics = next;+ }+}diff --git a/packages/cli/foundation/discovery/docs-discovery.test.mjs b/packages/cli/foundation/discovery/docs-discovery.test.mjsnew file mode 100644index 0000000000..99098a3ae2--- /dev/null+++ b/packages/cli/foundation/discovery/docs-discovery.test.mjs@@ -0,0 +1,341 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Colocated tests for reference-doc discovery: what an integration's+ * docs root contributes, what the catalog does with `replaces` / `extends`,+ * and which authored mistakes are caught at the load boundary rather than+ * reaching a reader as a blank section.+ *+ * Fixtures are scaffolded under a repo-local temp dir, not /tmp, because Vite+ * refuses to dynamically import a module from outside the project root.+ */++import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {+ BUILTIN_DOCS_PACKAGE,+ DocsCatalog,+ discoverBuiltinTopics,+ discoverIntegrationDocs,+ mergeTopic,+ problemsInTopic,+} from './docs-discovery.mjs';++let tmpDir;++/** A minimal, valid topic. */+function topic(fields) {+ return {+ type: 'generic',+ name: 'deploying',+ title: 'Deploying',+ description: 'How to ship it.',+ sections: [{title: 'Overview', content: [{type: 'prose', text: 'Ship it.'}]}],+ ...fields,+ };+}++/** Write a docs root holding one file per topic; returns the integration. */+function integration(name, topics, {docsDir = 'docs'} = {}) {+ const root = path.join(tmpDir, name.replace(/[^\w]/g, '_'), docsDir);+ fs.mkdirSync(root, {recursive: true});+ for (const [file, value] of Object.entries(topics)) {+ fs.writeFileSync(+ path.join(root, file),+ typeof value === 'string'+ ? value+ : `export const docs = ${JSON.stringify(value, null, 2)};\n`,+ );+ }+ return {name, docs: root};+}++beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-docs-test-'));+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++describe('discoverBuiltinTopics', () => {+ it("finds the CLI's own topics and not their localization overlays", () => {+ const topics = discoverBuiltinTopics();+ expect(Object.keys(topics).length).toBeGreaterThan(0);+ expect(topics.tokens).toMatch(/assets[/\\]docs[/\\]tokens\.doc\.mjs$/);+ for (const name of Object.keys(topics)) {+ expect(name).not.toMatch(/\.(zh|dense)$/);+ }+ });+});++describe('discoverIntegrationDocs', () => {+ it('contributes nothing when no docs root is declared or the root is gone', async () => {+ expect(await discoverIntegrationDocs({name: '@acme/widgets'})).toEqual({+ records: [],+ errors: [],+ });+ expect(+ await discoverIntegrationDocs({+ name: '@acme/widgets',+ docs: path.join(tmpDir, 'nope'),+ }),+ ).toEqual({records: [], errors: []});+ });++ it('reads every topic under the root, with what it declares', async () => {+ const {records, errors} = await discoverIntegrationDocs(+ integration('@acme/widgets', {+ 'deploying.doc.mjs': topic(),+ 'getting-started.doc.mjs': topic({+ name: 'getting-started',+ title: 'Getting started',+ replaces: 'getting-started',+ }),+ 'theme-extra.doc.mjs': topic({name: 'theme-extra', extends: 'theme'}),+ }),+ );+ expect(errors).toEqual([]);+ expect(records.map(r => [r.name, r.package, r.replaces, r.extendsTopic])).toEqual([+ ['deploying', '@acme/widgets', undefined, undefined],+ ['getting-started', '@acme/widgets', 'getting-started', undefined],+ ['theme-extra', '@acme/widgets', undefined, 'theme'],+ ]);+ });++ it('accepts a stamped default export as well as `export const docs`', async () => {+ const {records, errors} = await discoverIntegrationDocs(+ integration('@acme/default-export', {+ 'deploying.doc.mjs': `export default ${JSON.stringify(topic())};\n`,+ }),+ );+ expect(errors).toEqual([]);+ expect(records.map(r => r.name)).toEqual(['deploying']);+ });++ it('ignores a localization overlay beside a topic', async () => {+ const {records} = await discoverIntegrationDocs(+ integration('@acme/localized', {+ 'deploying.doc.mjs': topic(),+ 'deploying.doc.zh.mjs': `export const docsZh = {description: '部署', sections: []};\n`,+ }),+ );+ expect(records.map(r => r.name)).toEqual(['deploying']);+ });++ it('reports a doc that exports nothing, rather than skipping it silently', async () => {+ const {records, errors} = await discoverIntegrationDocs(+ integration('@acme/empty', {'deploying.doc.mjs': 'export const nope = 1;\n'}),+ );+ expect(records).toEqual([]);+ expect(errors).toHaveLength(1);+ expect(errors[0].message).toContain('exports no doc');+ });++ it('reports two files claiming one topic name', async () => {+ const {records, errors} = await discoverIntegrationDocs(+ integration('@acme/dupes', {+ 'a-deploying.doc.mjs': topic(),+ 'b-deploying.doc.mjs': topic({title: 'Deploying, again'}),+ }),+ );+ expect(records).toHaveLength(1);+ expect(errors[0].message).toContain('both define the topic "deploying"');+ });++ it('reports a doc that both replaces and extends', async () => {+ const {records, errors} = await discoverIntegrationDocs(+ integration('@acme/both', {+ 'deploying.doc.mjs': topic({replaces: 'theme', extends: 'theme'}),+ }),+ );+ expect(records).toEqual([]);+ expect(errors[0].message).toContain('declares both');+ });+});++describe('problemsInTopic', () => {+ it('passes a well-formed topic', () => {+ expect(problemsInTopic(topic())).toEqual([]);+ });++ it('catches the mistakes that would render as a blank section', () => {+ expect(problemsInTopic(topic({title: ''}))).toContain(+ 'title: expected a non-empty string',+ );+ expect(problemsInTopic(topic({sections: []}))).toContain(+ 'sections: expected at least one section',+ );+ // A misspelled required field: the block renders nothing at all.+ expect(+ problemsInTopic(+ topic({sections: [{title: 'Overview', content: [{type: 'prose', txt: 'oops'}]}]}),+ ),+ ).toEqual([+ 'sections[0].content[0].text: required for a prose block',+ 'sections[0].content[0].txt: not a field of a prose block',+ ]);+ // A heading level the renderer does not index.+ expect(+ problemsInTopic(+ topic({+ sections: [{title: 'Overview', content: [{type: 'heading', level: 2, text: 'x'}]}],+ }),+ ),+ ).toContain('sections[0].content[0].level: 2 is not one of 3, 4, 5, 6');+ // A short row renders blank cells; a long one drops its tail.+ expect(+ problemsInTopic(+ topic({+ sections: [+ {+ title: 'Overview',+ content: [{type: 'table', headers: ['A', 'B'], rows: [['1']]}],+ },+ ],+ }),+ ),+ ).toContain('sections[0].content[0].rows[0]: has 1 cells but the table has 2 headers');+ });++ it('rejects a name that is not URL-safe', () => {+ expect(problemsInTopic(topic({name: 'not a topic'})).join('\n')).toContain('URL-safe');+ });+});++describe('DocsCatalog', () => {+ const record = fields => ({+ name: 'deploying',+ package: '@acme/widgets',+ path: '/pkg/docs/deploying.doc.mjs',+ ...fields,+ });++ it('starts from the built-in topics, owned by the CLI', () => {+ const catalog = DocsCatalog.fromBuiltins({tokens: '/cli/tokens.doc.mjs'});+ expect(catalog.names()).toEqual(['tokens']);+ expect(catalog.resolve('tokens').package).toBe(BUILTIN_DOCS_PACKAGE);+ expect(catalog.resolve('TOKENS').name).toBe('tokens');+ expect(catalog.resolve('nope')).toBeUndefined();+ expect(catalog.resolve(42)).toBeUndefined();+ });++ it('adds a new topic', () => {+ const catalog = DocsCatalog.fromBuiltins({tokens: '/cli/tokens.doc.mjs'});+ expect(catalog.add(record())).toBeNull();+ expect(catalog.names()).toEqual(['tokens', 'deploying']);+ expect(catalog.resolve('deploying').package).toBe('@acme/widgets');+ });++ it('refuses to shadow an existing topic by name alone', () => {+ const catalog = DocsCatalog.fromBuiltins({tokens: '/cli/tokens.doc.mjs'});+ const issue = catalog.add(record({name: 'tokens'}));+ expect(issue).toMatchObject({code: 'invalid_doc', severity: 'error'});+ expect(issue.message).toContain("already provided by @astryxdesign/cli");+ expect(issue.message).toContain("replaces: 'tokens'");+ // The built-in topic is untouched.+ expect(catalog.resolve('tokens').package).toBe(BUILTIN_DOCS_PACKAGE);+ });++ it('replaces a topic in place, keeping its position', () => {+ const catalog = DocsCatalog.fromBuiltins({+ 'getting-started': '/cli/getting-started.doc.mjs',+ tokens: '/cli/tokens.doc.mjs',+ });+ expect(+ catalog.add(record({name: 'getting-started', replaces: 'getting-started'})),+ ).toBeNull();+ expect(catalog.names()).toEqual(['getting-started', 'tokens']);+ const entry = catalog.resolve('getting-started');+ expect(entry.package).toBe('@acme/widgets');+ expect(entry.replaces).toBe('getting-started');+ });++ it('leaves the old name as an alias when the replacement renames it', () => {+ const catalog = DocsCatalog.fromBuiltins({+ 'getting-started': '/cli/getting-started.doc.mjs',+ });+ catalog.add(record({name: 'setup', replaces: 'getting-started'}));+ expect(catalog.names()).toEqual(['setup']);+ expect(catalog.resolve('getting-started').name).toBe('setup');+ expect(catalog.resolve('setup').name).toBe('setup');+ });++ it('keeps every name a twice-renamed topic has answered to', () => {+ const catalog = DocsCatalog.fromBuiltins({+ 'getting-started': '/cli/getting-started.doc.mjs',+ });+ catalog.add(record({name: 'setup', replaces: 'getting-started'}));+ catalog.add(+ record({name: 'install', package: '@acme/later', replaces: 'setup'}),+ );+ expect(catalog.resolve('getting-started').name).toBe('install');+ expect(catalog.resolve('setup').name).toBe('install');+ });++ it('warns, and lets the later package win, when two replace one topic', () => {+ const catalog = DocsCatalog.fromBuiltins({tokens: '/cli/tokens.doc.mjs'});+ expect(catalog.add(record({name: 'tokens', replaces: 'tokens'}))).toBeNull();+ const issue = catalog.add(+ record({name: 'tokens', package: '@acme/later', replaces: 'tokens'}),+ );+ expect(issue).toMatchObject({code: 'duplicate_doc', severity: 'warning'});+ expect(issue.message).toContain('@acme/later is configured later, so it wins');+ expect(catalog.resolve('tokens').package).toBe('@acme/later');+ });++ it('records an extension against its target rather than adding a topic', () => {+ const catalog = DocsCatalog.fromBuiltins({theme: '/cli/theme.doc.mjs'});+ expect(+ catalog.add(record({name: 'theme-extra', extendsTopic: 'theme'})),+ ).toBeNull();+ expect(catalog.names()).toEqual(['theme']);+ expect(catalog.resolve('theme').extensions).toEqual([+ {package: '@acme/widgets', path: '/pkg/docs/deploying.doc.mjs'},+ ]);+ });++ it('reports a replace/extend target that no package provides', () => {+ const catalog = DocsCatalog.fromBuiltins({tokens: '/cli/tokens.doc.mjs'});+ expect(catalog.add(record({replaces: 'nope'}))).toMatchObject({+ code: 'invalid_doc',+ severity: 'error',+ });+ expect(catalog.add(record({extendsTopic: 'nope'}))).toMatchObject({+ code: 'invalid_doc',+ severity: 'error',+ });+ expect(catalog.names()).toEqual(['tokens']);+ });+});++describe('mergeTopic', () => {+ const base = {+ title: 'Theme',+ description: 'Theming.',+ sections: [+ {title: 'Install', content: [{type: 'prose', text: 'npm i'}]},+ {title: 'Tokens', content: [{type: 'prose', text: 'use tokens'}]},+ ],+ };++ it('replaces a section by title, appends a new one, and leaves the rest', () => {+ const merged = mergeTopic(base, {+ sections: [+ {title: 'Install', content: [{type: 'prose', text: 'yarn add'}]},+ {title: 'Internal', content: [{type: 'prose', text: 'the meta way'}]},+ ],+ });+ expect(merged.sections.map(s => s.title)).toEqual(['Install', 'Tokens', 'Internal']);+ expect(merged.sections[0].content[0].text).toBe('yarn add');+ expect(merged.sections[1].content[0].text).toBe('use tokens');+ // The base is untouched.+ expect(base.sections[0].content[0].text).toBe('npm i');+ });++ it('takes the title and description only when the overlay states them', () => {+ expect(mergeTopic(base, {sections: []}).title).toBe('Theme');+ expect(mergeTopic(base, {title: 'Theming', sections: []}).title).toBe('Theming');+ });+});diff --git a/packages/cli/foundation/integrations/integrations.mjs b/packages/cli/foundation/integrations/integrations.mjsindex 2c897e4ce8..4a44a01aa8 100644--- a/packages/cli/foundation/integrations/integrations.mjs+++ b/packages/cli/foundation/integrations/integrations.mjs@@ -6,7 +6,7 @@* Integrations are PACKAGE NAMES listed in astryx.config.{ts,mjs,js}. Each* package declares a single conventional root manifest sibling to its* package.json — astryx.integration.{ts,mjs,js} — which contributes- * components/templates/codemods roots and an optional issuesUrl. Identity+ * components/templates/codemods/docs roots and an optional issuesUrl. Identity* (name, version) comes from the package's package.json, not the manifest.*/@@ -18,15 +18,16 @@ import {loadModuleWithParser, findPresentFiles} from '../fs/module-loader.mjs';/*** A fully-resolved, loaded integration. Identity (`name`, `version`) comes from- * the package's package.json; the `components`/`templates`/`codemods` roots are- * absolute paths resolved from the manifest. The `__`-prefixed fields are- * internal bookkeeping used by validate-integration and Project.+ * the package's package.json; the `components`/`templates`/`codemods`/`docs`+ * roots are absolute paths resolved from the manifest. The `__`-prefixed fields+ * are internal bookkeeping used by validate-integration and Project.* @typedef {object} LoadedIntegration* @property {string} name* @property {string} [version]* @property {string} [components]* @property {string} [templates]* @property {string} [codemods]+ * @property {string} [docs]* @property {string} [issuesUrl]* @property {string} __spec* @property {string} __packageDir@@ -187,6 +188,7 @@ export async function loadIntegrations(specs = [], {cwd = process.cwd()} = {}) {components: resolveRoot(manifest.components),templates: resolveRoot(manifest.templates),codemods: resolveRoot(manifest.codemods),+ docs: resolveRoot(manifest.docs),issuesUrl: manifest.issuesUrl,__spec: spec,__packageDir: packageDir,diff --git a/packages/cli/foundation/integrations/validate-contributions.mjs b/packages/cli/foundation/integrations/validate-contributions.mjsindex 20762efdac..76dcfc44ce 100644--- a/packages/cli/foundation/integrations/validate-contributions.mjs+++ b/packages/cli/foundation/integrations/validate-contributions.mjs@@ -23,6 +23,7 @@ import * as fs from 'node:fs';import {discoverIntegrationCodemods} from '../../assets/codemods/integration-discovery.mjs';import {discoverIntegrationTemplatesForOne} from '../discovery/template-adapter.mjs';import * as componentDiscovery from '../discovery/component-discovery.mjs';+import {discoverIntegrationDocs} from '../discovery/docs-discovery.mjs';/*** @typedef {import('./issue').AstryxIntegrationIssue} Issue@@ -37,12 +38,12 @@ export function issueError(code, message) {/*** Verify each declared contribution root exists on disk. A declared-but-missing* root is a `missing_root` error.- * @param {{components?: string, templates?: string, codemods?: string}} resolved+ * @param {{components?: string, templates?: string, codemods?: string, docs?: string}} resolved* absolute resolved roots (undefined when not declared)* @param {Issue[]} issues*/function checkRoots(resolved, issues) {- const kinds = /** @type {const} */ (['components', 'templates', 'codemods']);+ const kinds = /** @type {const} */ (['components', 'templates', 'codemods', 'docs']);for (const kind of kinds) {const root = resolved[kind];if (root == null) continue;@@ -124,6 +125,31 @@ async function checkComponents(integration, issues) {}}+/**+ * Validate the integration's doc topics via the landed discovery. A doc that+ * cannot be loaded, is not a usable topic, or collides with a sibling is+ * reported as an `invalid_doc` error.+ *+ * Only per-file problems are visible here: a topic that collides with another+ * PACKAGE's, or names a `replaces`/`extends` target that does not exist, can+ * only be judged once every integration is resolved together, so those are+ * raised by `Project.docs()` instead.+ *+ * @param {LoadedIntegration} integration loaded-integration-shaped object+ * @param {Issue[]} issues+ */+async function checkDocs(integration, issues) {+ if (!integration.docs || !fs.existsSync(integration.docs)) return;+ try {+ const {errors} = await discoverIntegrationDocs(integration);+ for (const e of errors) {+ issues.push(issueError('invalid_doc', e.message));+ }+ } catch (err) {+ issues.push(issueError('invalid_doc', /** @type {any} */ (err).message));+ }+}+/*** Run every contribution validator against a loaded-integration-shaped object.* @param {LoadedIntegration} integration@@ -133,6 +159,7 @@ async function runContributionChecks(integration, issues) {await checkCodemods(integration, issues);await checkTemplates(integration, issues);await checkComponents(integration, issues);+ await checkDocs(integration, issues);}/**@@ -161,6 +188,7 @@ export async function validateLoadedIntegration(loaded) {components: loaded.components,templates: loaded.templates,codemods: loaded.codemods,+ docs: loaded.docs,},issues,);