Skip to content

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

TypeScript

feat(cli): load docs and hooks from integrations config (#3168)

EJ Hammond7e591d069fe0
diff --git a/.changeset/fuzzy-integrations-config.md b/.changeset/fuzzy-integrations-config.md
new file mode 100644
index 0000000000..f13b175e94
--- /dev/null
+++ b/.changeset/fuzzy-integrations-config.md
@@ -0,0 +1,6 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[feat] Let `astryx.config.mjs` integrations contribute package docs, gap-report hooks, template fetching hooks, upgrade codemods, and post-codemod hooks.
+@ejhammond
diff --git a/packages/cli/package.json b/packages/cli/package.json
index b4d69d82d1..14d7ffe745 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -38,6 +38,10 @@
"./api": {
"types": "./src/types/api.d.ts",
"import": "./src/api/index.mjs"
+ },
+ "./config": {
+ "types": "./src/types/config.d.ts",
+ "import": "./src/config.mjs"
}
},
"files": [
@@ -56,7 +60,8 @@
"@clack/prompts": "^1.5.1",
"commander": "^12.1.0",
"jiti": "^2.7.0",
- "jscodeshift": "^17.3.0"
+ "jscodeshift": "^17.3.0",
+ "zod": "^4.4.3"
},
"peerDependencies": {
"@astryxdesign/core": "*",
diff --git a/packages/cli/src/api/discover.mjs b/packages/cli/src/api/discover.mjs
index 5230c07564..65ccbace15 100644
--- a/packages/cli/src/api/discover.mjs
+++ b/packages/cli/src/api/discover.mjs
@@ -5,19 +5,28 @@
*/
import {loadConfig} from '../lib/config.mjs';
-import {scanAllPackages, findComponentInPackages} from '../lib/package-scanner.mjs';
+import {
+ scanAllPackages,
+ findComponentInPackages,
+} from '../lib/package-scanner.mjs';
import {loadDocs} from '../lib/component-loader.mjs';
import {levenshteinDistance} from '../lib/string-utils.mjs';
import {AstryxError} from './error.mjs';
import {ERROR_CODES} from '../lib/error-codes.mjs';
function validateDocs(docs) {
- if (!docs || typeof docs !== 'object') return 'docs export is missing or not an object';
- if (typeof docs.name !== 'string' || !docs.name) return 'docs.name is missing or not a string';
- if (!docs.usage || typeof docs.usage.description !== 'string') return 'docs.usage.description is missing or not a string';
- if (docs.props && !Array.isArray(docs.props)) return 'docs.props must be an array';
- if (docs.components && !Array.isArray(docs.components)) return 'docs.components must be an array';
- if (docs.usage?.bestPractices && !Array.isArray(docs.usage.bestPractices)) return 'docs.usage.bestPractices must be an array';
+ if (!docs || typeof docs !== 'object')
+ return 'docs export is missing or not an object';
+ if (typeof docs.name !== 'string' || !docs.name)
+ return 'docs.name is missing or not a string';
+ if (!docs.usage || typeof docs.usage.description !== 'string')
+ return 'docs.usage.description is missing or not a string';
+ if (docs.props && !Array.isArray(docs.props))
+ return 'docs.props must be an array';
+ if (docs.components && !Array.isArray(docs.components))
+ return 'docs.components must be an array';
+ if (docs.usage?.bestPractices && !Array.isArray(docs.usage.bestPractices))
+ return 'docs.usage.bestPractices must be an array';
return null;
}
@@ -32,7 +41,7 @@ function validateDocs(docs) {
export async function discover(query, options = {}) {
const {lang = null, zh = false} = options;
const config = await loadConfig();
- const toEntry = (pkg) => ({
+ const toEntry = pkg => ({
name: pkg.name,
category: pkg.category,
components: pkg.components,
@@ -41,11 +50,14 @@ export async function discover(query, options = {}) {
displayName: pkg.displayName,
});
- if (config.packages.length === 0) {
+ const explicitPackages = (config.loadedIntegrations ?? [])
+ .map(integration => integration.package)
+ .filter(Boolean);
+ if (config.packages.length === 0 && explicitPackages.length === 0) {
return {type: 'discover.list', data: [], meta: {configured: false}};
}
- const packages = scanAllPackages(config.packages);
+ const packages = scanAllPackages(config.packages, explicitPackages);
if (packages.length === 0) {
return {type: 'discover.list', data: [], meta: {configured: true}};
@@ -61,7 +73,10 @@ export async function discover(query, options = {}) {
if (slashIdx > 0) {
const pkgName = query.slice(0, slashIdx);
const compName = query.slice(slashIdx + 1);
- return await resolveComponentDocs(packages, compName, pkgName, {lang, zh});
+ return await resolveComponentDocs(packages, compName, pkgName, {
+ lang,
+ zh,
+ });
}
const pkg = packages.find(p => p.name === query);
@@ -99,7 +114,16 @@ export async function discover(query, options = {}) {
}
if (substringMatches.length > 1) {
- return {type: 'discover.search', data: {query, matches: substringMatches.map(m => ({package: m.pkg.name, component: m.comp}))}};
+ return {
+ type: 'discover.search',
+ data: {
+ query,
+ matches: substringMatches.map(m => ({
+ package: m.pkg.name,
+ component: m.comp,
+ })),
+ },
+ };
}
// Fuzzy fallback
@@ -110,7 +134,10 @@ export async function discover(query, options = {}) {
}
}
const fuzzyMatches = allComponents
- .map(item => ({...item, distance: levenshteinDistance(lower, item.comp.toLowerCase())}))
+ .map(item => ({
+ ...item,
+ distance: levenshteinDistance(lower, item.comp.toLowerCase()),
+ }))
.filter(m => m.distance <= 3)
.sort((a, b) => a.distance - b.distance)
.slice(0, 5);
@@ -118,30 +145,46 @@ export async function discover(query, options = {}) {
if (fuzzyMatches.length > 0) {
throw new AstryxError(
`"${query}" not found`,
- fuzzyMatches.map(m => ({name: m.pkg.name + '/' + m.comp, reason: 'similar name'})),
+ fuzzyMatches.map(m => ({
+ name: m.pkg.name + '/' + m.comp,
+ reason: 'similar name',
+ })),
ERROR_CODES.ERR_NOT_FOUND,
);
}
- throw new AstryxError(`"${query}" not found in any package`, undefined, ERROR_CODES.ERR_NOT_FOUND);
+ throw new AstryxError(
+ `"${query}" not found in any package`,
+ undefined,
+ ERROR_CODES.ERR_NOT_FOUND,
+ );
}
async function resolveComponentDocs(packages, compName, pkgName, {lang, zh}) {
const pkg = packages.find(p => p.name === pkgName);
- if (!pkg) throw new AstryxError(`Package "${pkgName}" not found`, undefined, ERROR_CODES.ERR_UNKNOWN_PACKAGE);
+ if (!pkg)
+ throw new AstryxError(
+ `Package "${pkgName}" not found`,
+ undefined,
+ ERROR_CODES.ERR_UNKNOWN_PACKAGE,
+ );
const result = findComponentInPackages([pkg], compName);
if (!result) {
const lower = compName.toLowerCase();
const hits = pkg.components.filter(c => c.toLowerCase().includes(lower));
- const suggestions = hits.length > 0
- ? hits
- : pkg.components
- .map(c => ({name: c, distance: levenshteinDistance(lower, c.toLowerCase())}))
- .filter(m => m.distance <= 3)
- .sort((a, b) => a.distance - b.distance)
- .slice(0, 5)
- .map(m => m.name);
+ const suggestions =
+ hits.length > 0
+ ? hits
+ : pkg.components
+ .map(c => ({
+ name: c,
+ distance: levenshteinDistance(lower, c.toLowerCase()),
+ }))
+ .filter(m => m.distance <= 3)
+ .sort((a, b) => a.distance - b.distance)
+ .slice(0, 5)
+ .map(m => m.name);
throw new AstryxError(
`Component "${compName}" not found in ${pkgName}`,
suggestions.map(s => ({name: s, reason: 'similar name'})),
@@ -157,9 +200,18 @@ async function loadAndValidate(result, {lang, zh}) {
try {
docs = await loadDocs(result.docPath, {zh, lang});
} catch (e) {
- throw new AstryxError(`Failed to load docs for ${result.componentName}: ${e.message}`, undefined, ERROR_CODES.ERR_INVALID_DOC);
+ throw new AstryxError(
+ `Failed to load docs for ${result.componentName}: ${e.message}`,
+ undefined,
+ ERROR_CODES.ERR_INVALID_DOC,
+ );
}
const err = validateDocs(docs);
- if (err) throw new AstryxError(`Invalid docs for ${result.componentName}: ${err}`, undefined, ERROR_CODES.ERR_INVALID_DOC);
+ if (err)
+ throw new AstryxError(
+ `Invalid docs for ${result.componentName}: ${err}`,
+ undefined,
+ ERROR_CODES.ERR_INVALID_DOC,
+ );
return {type: 'discover.detail.doc', data: docs};
}
diff --git a/packages/cli/src/api/template.mjs b/packages/cli/src/api/template.mjs
index bfbecf2d52..69bbc48a5c 100644
--- a/packages/cli/src/api/template.mjs
+++ b/packages/cli/src/api/template.mjs
@@ -7,7 +7,11 @@
import * as fs from 'node:fs';
import * as path from 'node:path';
import {CLI_ROOT, discoverExternalPackages} from '../utils/paths.mjs';
-import {assertWithin, isFilePathArg, PathSafetyError} from '../utils/path-safety.mjs';
+import {
+ assertWithin,
+ isFilePathArg,
+ PathSafetyError,
+} from '../utils/path-safety.mjs';
import {AstryxError} from './error.mjs';
import {ERROR_CODES} from '../lib/error-codes.mjs';
import {loadConfig} from '../lib/config.mjs';
@@ -23,7 +27,7 @@ const BLOCKS_DIR = path.join(TEMPLATES_DIR, 'blocks');
* or not. Mirrors apps/docsite/public/template-assets/placeholder.svg.
*/
const PLACEHOLDER_IMAGE =
- "data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20400%20300%22%20preserveAspectRatio%3D%22xMidYMid%20slice%22%3E%3Crect%20width%3D%22400%22%20height%3D%22300%22%20fill%3D%22%23f5f6f8%22%2F%3E%3Cg%20transform%3D%22translate%28200%20150%29%22%20fill%3D%22none%22%20stroke%3D%22%23c2cad6%22%20stroke-width%3D%225%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Crect%20x%3D%22-44%22%20y%3D%22-44%22%20width%3D%2288%22%20height%3D%2288%22%20rx%3D%2216%22%2F%3E%3Ccircle%20cx%3D%2218%22%20cy%3D%22-18%22%20r%3D%222.5%22%20fill%3D%22%23c2cad6%22%20stroke%3D%22none%22%2F%3E%3Cpath%20d%3D%22M-34%2030%20L-8%200%20L10%2018%20L20%208%20L34%2024%22%2F%3E%3C%2Fg%3E%3C%2Fsvg%3E";
+ 'data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20viewBox%3D%220%200%20400%20300%22%20preserveAspectRatio%3D%22xMidYMid%20slice%22%3E%3Crect%20width%3D%22400%22%20height%3D%22300%22%20fill%3D%22%23f5f6f8%22%2F%3E%3Cg%20transform%3D%22translate%28200%20150%29%22%20fill%3D%22none%22%20stroke%3D%22%23c2cad6%22%20stroke-width%3D%225%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%3E%3Crect%20x%3D%22-44%22%20y%3D%22-44%22%20width%3D%2288%22%20height%3D%2288%22%20rx%3D%2216%22%2F%3E%3Ccircle%20cx%3D%2218%22%20cy%3D%22-18%22%20r%3D%222.5%22%20fill%3D%22%23c2cad6%22%20stroke%3D%22none%22%2F%3E%3Cpath%20d%3D%22M-34%2030%20L-8%200%20L10%2018%20L20%208%20L34%2024%22%2F%3E%3C%2Fg%3E%3C%2Fsvg%3E';
/**
* Demo-image sources to strip from scaffolded projects — Meta's lookaside CDN
@@ -60,9 +64,12 @@ export {discoverAll as discoverTemplates};
export function listTemplates() {
const all = [];
if (fs.existsSync(PAGES_DIR)) {
- all.push(...fs.readdirSync(PAGES_DIR, {withFileTypes: true})
- .filter(e => e.isDirectory())
- .map(e => e.name));
+ all.push(
+ ...fs
+ .readdirSync(PAGES_DIR, {withFileTypes: true})
+ .filter(e => e.isDirectory())
+ .map(e => e.name),
+ );
}
return all.sort();
}
@@ -83,7 +90,8 @@ function findDocFiles(dir, pattern) {
async function discoverPages() {
if (!fs.existsSync(PAGES_DIR)) return [];
- const dirs = fs.readdirSync(PAGES_DIR, {withFileTypes: true})
+ const dirs = fs
+ .readdirSync(PAGES_DIR, {withFileTypes: true})
.filter(e => e.isDirectory());
const templates = [];
@@ -138,7 +146,11 @@ async function discoverBlocks() {
* @param {string} [cwd]
*/
async function discoverExternalBlocks(cwd = process.cwd()) {
- const externals = discoverExternalPackages(cwd);
+ const config = await loadConfig(cwd);
+ const integrationPackages = (config.loadedIntegrations ?? [])
+ .map(integration => integration.package)
+ .filter(Boolean);
+ const externals = [...discoverExternalPackages(cwd), ...integrationPackages];
const blocks = [];
for (const ext of externals) {
@@ -193,9 +205,7 @@ async function discoverAll() {
export async function findRelatedBlocks(componentName, cwd) {
const blocks = await discoverAllBlocks(cwd);
return blocks.filter(b =>
- b.componentsUsed.some(c =>
- c.toLowerCase() === componentName.toLowerCase(),
- ),
+ b.componentsUsed.some(c => c.toLowerCase() === componentName.toLowerCase()),
);
}
@@ -218,7 +228,7 @@ export async function findShowcase(componentName, cwd, options) {
return true;
});
- const toResult = (b) => ({
+ const toResult = b => ({
name: b.name,
aspectRatio: b.aspectRatio,
filePath: b.filePath,
@@ -242,8 +252,14 @@ export async function findShowcase(componentName, cwd, options) {
}
const UBIQUITOUS = new Set([
- 'Text', 'Heading', 'Button', 'HStack', 'VStack', 'Link',
- 'StackItem', 'Icon',
+ 'Text',
+ 'Heading',
+ 'Button',
+ 'HStack',
+ 'VStack',
+ 'Link',
+ 'StackItem',
+ 'Icon',
]);
export function extractComponents(pagePath) {
@@ -259,26 +275,60 @@ export function extractComponents(pagePath) {
while ((m = tagRegex.exec(src)) !== null) {
matches.push(m[2]);
}
- return [...new Set(
- matches
- .filter(n => !['Theme', 'ThemeProvider'].includes(n))
- .filter(n => !UBIQUITOUS.has(n))
- .map(n => n.replace(/(Item|Section|Header|Content|Footer|Panel|Heading|CollapseButton|Column|Sortable|Selection|Group|Source)$/, ''))
- .filter(Boolean),
- )].sort();
+ return [
+ ...new Set(
+ matches
+ .filter(n => !['Theme', 'ThemeProvider'].includes(n))
+ .filter(n => !UBIQUITOUS.has(n))
+ .map(n =>
+ n.replace(
+ /(Item|Section|Header|Content|Footer|Panel|Heading|CollapseButton|Column|Sortable|Selection|Group|Source)$/,
+ '',
+ ),
+ )
+ .filter(Boolean),
+ ),
+ ].sort();
}
const STRUCTURAL = new Set([
- 'AppShell', 'Layout', 'LayoutHeader', 'LayoutContent', 'LayoutPanel',
- 'LayoutFooter', 'Card', 'Section', 'Grid', 'GridSpan', 'List',
- 'Table', 'TabList', 'Toolbar', 'SideNav', 'TopNav', 'Dialog',
- 'FormLayout', 'Center',
+ 'AppShell',
+ 'Layout',
+ 'LayoutHeader',
+ 'LayoutContent',
+ 'LayoutPanel',
+ 'LayoutFooter',
+ 'Card',
+ 'Section',
+ 'Grid',
+ 'GridSpan',
+ 'List',
+ 'Table',
+ 'TabList',
+ 'Toolbar',
+ 'SideNav',
+ 'TopNav',
+ 'Dialog',
+ 'FormLayout',
+ 'Center',
]);
const SPATIAL_PROPS = [
- 'padding', 'contentPadding', 'gap', 'rowGap', 'columnGap',
- 'columns', 'minChildWidth', 'hasDivider', 'defaultHasDividers',
- 'variant', 'density', 'role', 'height', 'width', 'maxWidth',
+ 'padding',
+ 'contentPadding',
+ 'gap',
+ 'rowGap',
+ 'columnGap',
+ 'columns',
+ 'minChildWidth',
+ 'hasDivider',
+ 'defaultHasDividers',
+ 'variant',
+ 'density',
+ 'role',
+ 'height',
+ 'width',
+ 'maxWidth',
];
/**
@@ -346,11 +396,18 @@ function extractSkeleton(source) {
for (let i = 0; i < lines.length; i++) {
const t = lines[i].trim();
- if (t.match(/^export\s+default\s+function/)) { inDefaultExport = true; continue; }
- if (inDefaultExport && t.match(/^return\s*\(/)) { capturing = true; continue; }
+ if (t.match(/^export\s+default\s+function/)) {
+ inDefaultExport = true;
+ continue;
+ }
+ if (inDefaultExport && t.match(/^return\s*\(/)) {
+ capturing = true;
+ continue;
+ }
if (!capturing) continue;
if (out.length >= MAX_LINES) {
- if (!out[out.length - 1]?.includes('...')) out.push(' '.repeat(depth) + '...');
+ if (!out[out.length - 1]?.includes('...'))
+ out.push(' '.repeat(depth) + '...');
continue;
}
@@ -372,7 +429,9 @@ function extractSkeleton(source) {
const hasSpatialProps = props.length > 0;
const propStr = hasSpatialProps ? ' ' + props.join(' ') : '';
const isVStack = comp === 'VStack' || comp === 'HStack';
- const isSelfClosing = tagText.match(new RegExp('<' + tagName + '[^>]*/>', 's'));
+ const isSelfClosing = tagText.match(
+ new RegExp('<' + tagName + '[^>]*/>', 's'),
+ );
if (isVStack && !hasSpatialProps) continue;
@@ -399,13 +458,18 @@ function extractSkeleton(source) {
continue;
}
- const slotMatch = t.match(/^(header|content|footer|start|end|sideNav|topNav)\s*=\s*\{/);
+ const slotMatch = t.match(
+ /^(header|content|footer|start|end|sideNav|topNav)\s*=\s*\{/,
+ );
if (slotMatch) {
out.push(' '.repeat(depth) + `/* ${slotMatch[1]}: */`);
continue;
}
- if (t.startsWith('<div') && (t.includes('padding') || t.includes('maxWidth') || t.includes('gap:'))) {
+ if (
+ t.startsWith('<div') &&
+ (t.includes('padding') || t.includes('maxWidth') || t.includes('gap:'))
+ ) {
const styleProps = [];
const divText = lines.slice(i, Math.min(i + 5, lines.length)).join(' ');
const pp = divText.match(/padding[^:]*:\s*['"]?([^'"},)]+)/);
@@ -445,7 +509,7 @@ export async function getTemplateById(id, options = {}) {
'Add a template.get function to astryx.config.mjs:\n\n' +
' export default {\n' +
' template: {\n' +
- " get: async (id) => { /* return template source string */ },\n" +
+ ' get: async (id) => { /* return template source string */ },\n' +
' },\n' +
' };',
undefined,
@@ -458,7 +522,11 @@ export async function getTemplateById(id, options = {}) {
source = await getter(id);
} catch (err) {
const detail = err instanceof Error ? err.message : String(err);
- throw new AstryxError(`template.get("${id}") threw an error: ${detail}`, undefined, ERROR_CODES.ERR_TEMPLATE_GET);
+ throw new AstryxError(
+ `template.get("${id}") threw an error: ${detail}`,
+ undefined,
+ ERROR_CODES.ERR_TEMPLATE_GET,
+ );
}
if (source == null) {
@@ -500,7 +568,14 @@ export async function getTemplateById(id, options = {}) {
* @returns {Promise<{type: string, data: unknown}>}
*/
export async function template(name, options = {}) {
- const {list = false, skeleton = false, show = false, targetPath, type, cwd = process.cwd()} = options;
+ const {
+ list = false,
+ skeleton = false,
+ show = false,
+ targetPath,
+ type,
+ cwd = process.cwd(),
+ } = options;
const templates = await discoverAll();
if (list || (!name && !skeleton)) {
@@ -537,7 +612,11 @@ export async function template(name, options = {}) {
);
}
if (!fs.existsSync(match.filePath)) {
- throw new AstryxError(`No source file found for template "${name}"`, undefined, ERROR_CODES.ERR_NO_SOURCE);
+ throw new AstryxError(
+ `No source file found for template "${name}"`,
+ undefined,
+ ERROR_CODES.ERR_NO_SOURCE,
+ );
}
const src = fs.readFileSync(match.filePath, 'utf-8');
return {
@@ -552,7 +631,11 @@ export async function template(name, options = {}) {
}
if (!fs.existsSync(match.filePath)) {
- throw new AstryxError(`No source file found for template "${name}"`, undefined, ERROR_CODES.ERR_NO_SOURCE);
+ throw new AstryxError(
+ `No source file found for template "${name}"`,
+ undefined,
+ ERROR_CODES.ERR_NO_SOURCE,
+ );
}
if (show || !targetPath) {
@@ -579,7 +662,11 @@ export async function template(name, options = {}) {
});
} catch (err) {
if (err instanceof PathSafetyError) {
- throw new AstryxError(err.message, undefined, ERROR_CODES.ERR_PATH_TRAVERSAL);
+ throw new AstryxError(
+ err.message,
+ undefined,
+ ERROR_CODES.ERR_PATH_TRAVERSAL,
+ );
}
throw err;
}
@@ -596,9 +683,8 @@ export async function template(name, options = {}) {
outputFilePath = resolvedTarget;
} else {
outputDir = resolvedTarget;
- outputFileName = match.type === 'block'
- ? path.basename(match.filePath)
- : 'page.tsx';
+ outputFileName =
+ match.type === 'block' ? path.basename(match.filePath) : 'page.tsx';
outputFilePath = path.join(outputDir, outputFileName);
}
@@ -613,6 +699,11 @@ export async function template(name, options = {}) {
const relOutput = path.relative(cwd, outputDir) || '.';
return {
type: 'template.copy',
- data: {template: name, outputDir: relOutput, fileName: outputFileName, filesCopied: 1},
+ data: {
+ template: name,
+ outputDir: relOutput,
+ fileName: outputFileName,
+ filesCopied: 1,
+ },
};
}
diff --git a/packages/cli/src/commands/gap-report.mjs b/packages/cli/src/commands/gap-report.mjs
index 041d72e2a0..f054cad9b1 100644
--- a/packages/cli/src/commands/gap-report.mjs
+++ b/packages/cli/src/commands/gap-report.mjs
@@ -132,7 +132,7 @@ export function registerGapReport(program) {
.action(async () => {
p.intro('Gap report setup');
- const config = loadGapReportConfig();
+ const config = await loadGapReportConfig();
const currentMode = !config.enabled
? 'disabled'
: config.command
@@ -252,9 +252,14 @@ export function registerGapReport(program) {
return;
}
- const config = loadGapReportConfig();
+ const config = await loadGapReportConfig();
if (!config.enabled) {
- if (json) return jsonError('Gap reporting is disabled', undefined, ERROR_CODES.ERR_GAP_REPORT_FAILED);
+ if (json)
+ return jsonError(
+ 'Gap reporting is disabled',
+ undefined,
+ ERROR_CODES.ERR_GAP_REPORT_FAILED,
+ );
humanLog(
`Gap reporting is disabled (ASTRYX_GAP_REPORT=off or astryx.config.mjs).\n` +
`Run \`${getRunPrefix()} astryx gap-report setup\` to configure.`,
@@ -295,7 +300,7 @@ export function registerGapReport(program) {
return;
}
- const preview = buildGapReportPreview({
+ const preview = await buildGapReportPreview({
component: options.component,
category: options.category,
intention: options.reason,
@@ -326,7 +331,7 @@ export function registerGapReport(program) {
}
try {
- const url = createGapReport({
+ const url = await createGapReport({
component: options.component,
category: options.category,
intention: options.reason,
@@ -343,7 +348,9 @@ export function registerGapReport(program) {
humanLog('\nGap reporting is disabled via configuration.\n');
}
} catch (err) {
- cliError(`Filing gap report failed: ${err.message}`, {code: ERROR_CODES.ERR_GAP_REPORT_FAILED});
+ cliError(`Filing gap report failed: ${err.message}`, {
+ code: ERROR_CODES.ERR_GAP_REPORT_FAILED,
+ });
return;
}
return;
@@ -386,7 +393,8 @@ export function registerGapReport(program) {
placeholder:
'e.g. "Need a compact variant for use in dense data tables"',
validate: val => {
- if (!val.trim()) return 'Please describe what you were trying to do';
+ if (!val.trim())
+ return 'Please describe what you were trying to do';
},
}),
);
@@ -406,7 +414,7 @@ export function registerGapReport(program) {
source: 'interactive',
};
- const preview = buildGapReportPreview(previewArgs);
+ const preview = await buildGapReportPreview(previewArgs);
// Always show the user exactly what would be filed before sending.
p.note(
@@ -440,7 +448,7 @@ export function registerGapReport(program) {
s.start('Filing gap report');
try {
- const url = createGapReport(previewArgs);
+ const url = await createGapReport(previewArgs);
s.stop(url ? 'Gap report filed' : 'Gap reporting is disabled');
if (url) {
p.log.success(url);
diff --git a/packages/cli/src/commands/gap-report.test.mjs b/packages/cli/src/commands/gap-report.test.mjs
index e671018af9..46200d4f16 100644
--- a/packages/cli/src/commands/gap-report.test.mjs
+++ b/packages/cli/src/commands/gap-report.test.mjs
@@ -40,9 +40,9 @@ describe('shouldActuallyFile', () => {
});
it('--dry-run wins over --commit (safety)', () => {
- expect(
- shouldActuallyFile({isTTY: true, commit: true, dryRun: true}),
- ).toBe(false);
+ expect(shouldActuallyFile({isTTY: true, commit: true, dryRun: true})).toBe(
+ false,
+ );
});
});
@@ -54,7 +54,9 @@ describe('formatPreview', () => {
title: '[gap] Button: missing compact variant',
body: '## User Intention\n\nNeed a compact variant',
});
- expect(out).toContain('Would file GitHub issue on facebookexperimental/xds');
+ expect(out).toContain(
+ 'Would file GitHub issue on facebookexperimental/xds',
+ );
expect(out).toContain('[gap] Button');
expect(out).toContain('Need a compact variant');
expect(out).toContain('Labels: gap-report');
@@ -91,13 +93,14 @@ describe('ASTRYX_GAP_REPORT=off env var', () => {
it('disables gap reporting when set to "off"', async () => {
process.env.ASTRYX_GAP_REPORT = 'off';
vi.resetModules();
- const {loadGapReportConfig, createGapReport} = await import(
- '../utils/github.mjs'
- );
- expect(loadGapReportConfig().enabled).toBe(false);
+ const {loadGapReportConfig, createGapReport} =
+ await import('../utils/github.mjs');
+ await expect(loadGapReportConfig()).resolves.toMatchObject({
+ enabled: false,
+ });
// createGapReport must return null and never invoke gh.
- const result = createGapReport({
+ const result = await createGapReport({
component: 'Button',
category: 'other',
intention: 'test',
@@ -109,12 +112,16 @@ describe('ASTRYX_GAP_REPORT=off env var', () => {
process.env.ASTRYX_GAP_REPORT = 'false';
vi.resetModules();
let mod = await import('../utils/github.mjs');
- expect(mod.loadGapReportConfig().enabled).toBe(false);
+ await expect(mod.loadGapReportConfig()).resolves.toMatchObject({
+ enabled: false,
+ });
process.env.ASTRYX_GAP_REPORT = '0';
vi.resetModules();
mod = await import('../utils/github.mjs');
- expect(mod.loadGapReportConfig().enabled).toBe(false);
+ await expect(mod.loadGapReportConfig()).resolves.toMatchObject({
+ enabled: false,
+ });
});
});
@@ -133,16 +140,14 @@ describe('buildGapReportPreview', () => {
it('renders title and body without invoking gh', async () => {
vi.resetModules();
const {buildGapReportPreview} = await import('../utils/github.mjs');
- const preview = buildGapReportPreview({
+ const preview = await buildGapReportPreview({
component: 'Button',
category: 'missing_variant',
intention: 'Need compact variant for tables',
});
expect(preview.mode).toBe('github');
expect(preview.enabled).toBe(true);
- expect(preview.title).toBe(
- '[gap] Button: Need compact variant for tables',
- );
+ expect(preview.title).toBe('[gap] Button: Need compact variant for tables');
expect(preview.body).toContain('| **Component** | Button |');
expect(preview.body).toContain('Need compact variant for tables');
expect(preview.repo).toBe('facebookexperimental/xds');
@@ -152,7 +157,7 @@ describe('buildGapReportPreview', () => {
process.env.ASTRYX_GAP_REPORT = 'off';
vi.resetModules();
const {buildGapReportPreview} = await import('../utils/github.mjs');
- const preview = buildGapReportPreview({
+ const preview = await buildGapReportPreview({
component: 'Button',
category: 'other',
intention: 'x',
diff --git a/packages/cli/src/commands/swizzle.mjs b/packages/cli/src/commands/swizzle.mjs
index f7b8983746..1552875e2d 100644
--- a/packages/cli/src/commands/swizzle.mjs
+++ b/packages/cli/src/commands/swizzle.mjs
@@ -15,7 +15,11 @@ import * as fs from 'node:fs';
import * as path from 'node:path';
import * as p from '@clack/prompts';
import {findCoreDir, listComponents} from '../utils/paths.mjs';
-import {assertWithin, PathSafetyError, isNonInteractive} from '../utils/path-safety.mjs';
+import {
+ assertWithin,
+ PathSafetyError,
+ isNonInteractive,
+} from '../utils/path-safety.mjs';
import {isInteractive} from '../utils/interactive.mjs';
import {jsonOut, humanLog} from '../lib/json.mjs';
import {cliError} from '../lib/cli-error.mjs';
@@ -104,7 +108,9 @@ export function registerSwizzle(program) {
}
humanLog(`\nUsage: astryx swizzle <component>\n`);
humanLog('Example: astryx swizzle Button');
- humanLog(' astryx swizzle XDSButton (XDS prefix also works)\n');
+ humanLog(
+ ' astryx swizzle XDSButton (XDS prefix also works)\n',
+ );
return;
}
@@ -112,10 +118,10 @@ export function registerSwizzle(program) {
const componentDir = path.join(coreDir, 'src', dirName);
if (!fs.existsSync(componentDir)) {
- cliError(
- `Component "${component}" not found.`,
- {suggestions: components.slice(0, 10).map((n) => ({name: n})), code: ERROR_CODES.ERR_UNKNOWN_COMPONENT},
- );
+ cliError(`Component "${component}" not found.`, {
+ suggestions: components.slice(0, 10).map(n => ({name: n})),
+ code: ERROR_CODES.ERR_UNKNOWN_COMPONENT,
+ });
return;
}
@@ -196,11 +202,16 @@ export function registerSwizzle(program) {
}
const relOutput = path.relative(process.cwd(), outputDir);
- const copiedFiles = files.filter(f => !f.includes('.test.') && f !== 'README.md' && fs.statSync(path.join(componentDir, f)).isFile());
+ const copiedFiles = files.filter(
+ f =>
+ !f.includes('.test.') &&
+ f !== 'README.md' &&
+ fs.statSync(path.join(componentDir, f)).isFile(),
+ );
// --- Gap reporting ---
- const gapConfig = loadGapReportConfig();
+ const gapConfig = await loadGapReportConfig();
let gapReportUrl = null;
let gapDryRunPreview = null;
@@ -224,7 +235,7 @@ export function registerSwizzle(program) {
json,
});
- const preview = buildGapReportPreview(previewArgs);
+ const preview = await buildGapReportPreview(previewArgs);
if (!willFile) {
// Dry-run: do NOT call gh. Surface what would have been filed.
@@ -239,10 +250,12 @@ export function registerSwizzle(program) {
};
} else if (gapConfig.command || checkGhCli()) {
try {
- gapReportUrl = createGapReport(previewArgs);
+ gapReportUrl = await createGapReport(previewArgs);
} catch (err) {
if (!json)
- console.error(`Warning: Could not file gap report: ${err.message}`);
+ console.error(
+ `Warning: Could not file gap report: ${err.message}`,
+ );
}
}
}
@@ -259,17 +272,23 @@ export function registerSwizzle(program) {
gapReportSuppressed: reportingSuppressed || !gapConfig.enabled,
});
humanLog(`\n✓ Copied ${copied} files to ${relOutput}/\n`);
- humanLog('Relative imports have been rewritten to use @astryxdesign/core.');
+ humanLog(
+ 'Relative imports have been rewritten to use @astryxdesign/core.',
+ );
humanLog('You can now customize the component source freely.\n');
if (gapReportUrl) {
humanLog(`✓ Gap report filed: ${gapReportUrl}\n`);
} else if (gapDryRunPreview) {
- humanLog(formatPreview(buildGapReportPreview({
- component: dirName,
- category: options.gapCategory || 'other',
- intention: options.gap,
- source: 'llm-auto',
- })));
+ humanLog(
+ formatPreview(
+ await buildGapReportPreview({
+ component: dirName,
+ category: options.gapCategory || 'other',
+ intention: options.gap,
+ source: 'llm-auto',
+ }),
+ ),
+ );
humanLog(
'\n[dry-run] No gap report was filed. Re-run with --commit to file.',
);
@@ -283,10 +302,18 @@ export function registerSwizzle(program) {
return;
}
- if (json) return jsonOut('swizzle.copy', {component: dirName, outputDir: relOutput, filesCopied: copied, files: copiedFiles.map(f => f)});
+ if (json)
+ return jsonOut('swizzle.copy', {
+ component: dirName,
+ outputDir: relOutput,
+ filesCopied: copied,
+ files: copiedFiles.map(f => f),
+ });
humanLog(`\n✓ Copied ${copied} files to ${relOutput}/\n`);
- humanLog('Relative imports have been rewritten to use @astryxdesign/core.');
+ humanLog(
+ 'Relative imports have been rewritten to use @astryxdesign/core.',
+ );
humanLog('You can now customize the component source freely.\n');
if (reportingSuppressed || !gapConfig.enabled) {
@@ -330,7 +357,8 @@ export function registerSwizzle(program) {
placeholder:
'e.g. "Need a compact variant for use in dense data tables"',
validate: val => {
- if (!val.trim()) return 'Please describe what you were trying to do';
+ if (!val.trim())
+ return 'Please describe what you were trying to do';
},
}),
);
@@ -350,7 +378,7 @@ export function registerSwizzle(program) {
source: 'interactive',
};
- const preview = buildGapReportPreview(previewArgs);
+ const preview = await buildGapReportPreview(previewArgs);
p.note(
`${preview.mode === 'github' ? `Repo: ${preview.repo}` : `Custom command: ${preview.command}`}\n\n` +
@@ -378,7 +406,7 @@ export function registerSwizzle(program) {
s.start('Filing gap report');
try {
- const url = createGapReport(previewArgs);
+ const url = await createGapReport(previewArgs);
s.stop('Gap report filed');
humanLog(`✓ ${url}\n`);
} catch (err) {
diff --git a/packages/cli/src/commands/upgrade.mjs b/packages/cli/src/commands/upgrade.mjs
index 94190fa0da..586d626527 100644
--- a/packages/cli/src/commands/upgrade.mjs
+++ b/packages/cli/src/commands/upgrade.mjs
@@ -26,7 +26,6 @@
import * as fs from 'node:fs';
import * as path from 'node:path';
-import {pathToFileURL} from 'node:url';
import {execFile} from 'node:child_process';
import {promisify} from 'node:util';
import * as p from '@clack/prompts';
@@ -38,6 +37,7 @@ import {getRunPrefix} from '../utils/package-manager.mjs';
import {isValidSemver, semverGte, semverGt} from '../utils/semver.mjs';
import {jsonOut, jsonError} from '../lib/json.mjs';
import {loadConfig} from '../lib/config.mjs';
+import {loadIntegrations} from '../lib/integrations.mjs';
import {ERROR_CODES} from '../lib/error-codes.mjs';
const execFileAsync = promisify(execFile);
@@ -64,75 +64,6 @@ function detectInstalledTargetVersion() {
return null;
}
-function isPathSpec(spec) {
- return (
- spec.startsWith('.') ||
- spec.startsWith('/') ||
- spec.endsWith('.mjs') ||
- spec.endsWith('.js')
- );
-}
-
-function resolvePackageDir(packageName) {
- const parts = packageName.split('/');
- return path.resolve(process.cwd(), 'node_modules', ...parts);
-}
-
-function resolveIntegrationFile(spec) {
- if (isPathSpec(spec)) {
- return path.resolve(process.cwd(), spec);
- }
-
- const packageDir = resolvePackageDir(spec);
- const pkgPath = path.join(packageDir, 'package.json');
- let pkg;
- try {
- pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
- } catch {
- throw new Error(
- `Could not find installed integration package "${spec}" at ${pkgPath}. Install it first or pass a direct integration file path.`,
- );
- }
-
- const manifestPath = pkg.astryx?.integration ?? pkg.xds?.integration;
- if (!manifestPath) {
- throw new Error(
- `Package "${spec}" does not declare astryx.integration (or legacy xds.integration) in package.json.`,
- );
- }
- return path.resolve(packageDir, manifestPath);
-}
-
-async function loadIntegrations(specs) {
- const integrations = [];
- for (const spec of specs) {
- const file = resolveIntegrationFile(spec);
- const mod = await import(pathToFileURL(file).href);
- const integration = mod.default ?? mod.integration ?? mod;
- if (!integration || typeof integration !== 'object') {
- throw new Error(`Integration ${spec} did not export an object.`);
- }
- const integrationDir = path.dirname(file);
- if (Array.isArray(integration.codemods)) {
- for (const codemod of integration.codemods) {
- if (typeof codemod.transform === 'string') {
- const transformPath = path.resolve(integrationDir, codemod.transform);
- const transformMod = await import(pathToFileURL(transformPath).href);
- codemod.transform =
- transformMod.default ?? transformMod.transform ?? transformMod;
- }
- }
- }
- integrations.push({
- ...integration,
- __file: file,
- __dir: integrationDir,
- __spec: spec,
- });
- }
- return integrations;
-}
-
function normalizeIntegrationTransforms(integration, from, to) {
const transforms = [];
for (const entry of integration.codemods ?? []) {
diff --git a/packages/cli/src/config.mjs b/packages/cli/src/config.mjs
new file mode 100644
index 0000000000..2e661aead4
--- /dev/null
+++ b/packages/cli/src/config.mjs
@@ -0,0 +1,31 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {validateConfig, validateIntegration} from './lib/config-schema.mjs';
+
+/**
+ * Type-preserving helpers for Astryx config and integration manifests.
+ *
+ * These are intentionally tiny runtime identity functions. Their value is the
+ * exported TypeScript surface from `@astryxdesign/cli/config`, so config files
+ * can get editor/type feedback without coupling to CLI internals.
+ */
+
+/**
+ * @template {import('./types/config').AstryxConfig} T
+ * @param {T} config
+ * @returns {T}
+ */
+export function createConfig(config) {
+ validateConfig(config);
+ return config;
+}
+
+/**
+ * @template {import('./types/config').AstryxIntegration} T
+ * @param {T} integration
+ * @returns {T}
+ */
+export function createIntegration(integration) {
+ validateIntegration(integration);
+ return integration;
+}
diff --git a/packages/cli/src/config.test.mjs b/packages/cli/src/config.test.mjs
new file mode 100644
index 0000000000..a40fdc1f4d
--- /dev/null
+++ b/packages/cli/src/config.test.mjs
@@ -0,0 +1,24 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {describe, expect, it} from 'vitest';
+import {createConfig, createIntegration} from './config.mjs';
+
+describe('config helpers', () => {
+ it('return config and integration objects unchanged', () => {
+ const config = {integrations: ['@acme/widgets']};
+ const integration = {name: '@acme/widgets', docs: './docs'};
+ expect(createConfig(config)).toBe(config);
+ expect(createIntegration(integration)).toBe(integration);
+ });
+
+ it('validates config and integration shapes', () => {
+ expect(() => createConfig({integrations: [42]})).toThrow(/integrations/);
+ expect(() => createIntegration({docs: './docs'})).toThrow(/name/);
+ expect(() =>
+ createIntegration({
+ name: '@acme/widgets',
+ postCodemod: [{name: 'empty'}],
+ }),
+ ).toThrow(/postCodemod/);
+ });
+});
diff --git a/packages/cli/src/lib/config-schema.mjs b/packages/cli/src/lib/config-schema.mjs
new file mode 100644
index 0000000000..f1b302725b
--- /dev/null
+++ b/packages/cli/src/lib/config-schema.mjs
@@ -0,0 +1,119 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** Runtime schemas for Astryx config and integration manifests. */
+
+import {z} from 'zod';
+
+const Fn = z.custom(value => typeof value === 'function', {
+ message: 'Expected function',
+});
+
+const StringOrStringArray = z.union([z.string(), z.array(z.string())]);
+const GapReportSchema = z.union([
+ z.literal(false),
+ z.object({command: z.string()}).passthrough(),
+]);
+
+export const AstryxConfigSchema = z
+ .object({
+ packages: StringOrStringArray.optional(),
+ integrations: StringOrStringArray.optional(),
+ gapReport: GapReportSchema.optional(),
+ template: z
+ .object({
+ get: Fn.optional(),
+ })
+ .passthrough()
+ .optional(),
+ })
+ .passthrough();
+
+export const AstryxIntegrationCodemodSchema = z
+ .object({
+ name: z.string(),
+ from: z.string().optional(),
+ to: z.string().optional(),
+ title: z.string().optional(),
+ description: z.string().optional(),
+ pr: z.string().optional(),
+ optional: z.boolean().optional(),
+ fileExtensions: z.array(z.string()).optional(),
+ transform: z.union([z.string(), Fn]),
+ })
+ .passthrough();
+
+export const AstryxPostCodemodHookSchema = z
+ .object({
+ name: z.string().optional(),
+ run: Fn.optional(),
+ command: Fn.optional(),
+ })
+ .passthrough()
+ .refine(value => value.run || value.command, {
+ message: 'postCodemod hook must define run() or command()',
+ });
+
+export const AstryxIntegrationSchema = z
+ .object({
+ name: z.string(),
+ version: z.string().optional(),
+ displayName: z.string().optional(),
+ description: z.string().optional(),
+ docs: z.string().optional(),
+ category: z.string().optional(),
+ blocks: z.string().optional(),
+ gapReport: GapReportSchema.optional(),
+ template: z
+ .object({
+ get: z.union([z.string(), Fn]).optional(),
+ })
+ .passthrough()
+ .optional(),
+ codemods: z.array(AstryxIntegrationCodemodSchema).optional(),
+ postCodemod: z.array(AstryxPostCodemodHookSchema).optional(),
+ })
+ .passthrough();
+
+/**
+ * @param {string} label
+ * @param {import('zod').ZodError} error
+ */
+function formatZodError(label, error) {
+ const issues = error.issues
+ .map(issue => {
+ const path = issue.path.length ? issue.path.join('.') : '(root)';
+ return `${path}: ${issue.message}`;
+ })
+ .join('; ');
+ return `${label} is invalid: ${issues}`;
+}
+
+/**
+ * @param {unknown} config
+ * @returns {import('../types/config').AstryxConfig}
+ */
+export function validateConfig(config) {
+ const result = AstryxConfigSchema.safeParse(config);
+ if (!result.success) {
+ throw new Error(
+ formatZodError('astryx.config.mjs default export', result.error),
+ );
+ }
+ return result.data;
+}
+
+/**
+ * @param {unknown} integration
+ * @param {string} [label]
+ * @returns {import('../types/config').AstryxIntegration}
+ */
+export function validateIntegration(
+ integration,
+ label = 'integration manifest',
+) {
+ const result = AstryxIntegrationSchema.safeParse(integration);
+ if (!result.success) {
+ throw new Error(formatZodError(label, result.error));
+ }
+ return result.data;
+}
diff --git a/packages/cli/src/lib/config.mjs b/packages/cli/src/lib/config.mjs
index 51dedb8c0d..0b531ce24d 100644
--- a/packages/cli/src/lib/config.mjs
+++ b/packages/cli/src/lib/config.mjs
@@ -10,6 +10,8 @@
import * as fs from 'node:fs';
import * as path from 'node:path';
import {pathToFileURL} from 'node:url';
+import {loadIntegrations} from './integrations.mjs';
+import {validateConfig} from './config-schema.mjs';
const DEFAULTS = {
packages: [],
@@ -40,18 +42,30 @@ export async function loadConfig(startDir = process.cwd()) {
const configPath = findConfigPath(startDir);
if (!configPath) return {...DEFAULTS};
+ let rawConfig;
try {
const mod = await import(pathToFileURL(configPath).href);
- const config = mod.default || {};
- return {
- ...DEFAULTS,
- ...config,
- packages: normalizePackages(config.packages, path.dirname(configPath)),
- integrations: normalizeIntegrations(config.integrations),
- };
+ rawConfig = mod.default || {};
} catch {
return {...DEFAULTS};
}
+
+ const config = validateConfig(rawConfig);
+ const configDir = path.dirname(configPath);
+ const integrationSpecs = normalizeIntegrations(config.integrations);
+ const loadedIntegrations = await loadIntegrations(integrationSpecs, {
+ cwd: configDir,
+ });
+ return {
+ ...DEFAULTS,
+ ...config,
+ packages: normalizePackages(config.packages, configDir),
+ integrations: integrationSpecs,
+ loadedIntegrations,
+ gapReport:
+ config.gapReport ?? firstDefined(loadedIntegrations, 'gapReport'),
+ template: mergeTemplateConfig(config.template, loadedIntegrations),
+ };
}
/**
@@ -84,3 +98,16 @@ function normalizeIntegrations(integrations) {
const arr = Array.isArray(integrations) ? integrations : [integrations];
return arr.filter(value => typeof value === 'string' && value !== '');
}
+
+function firstDefined(integrations, key) {
+ for (const integration of integrations) {
+ if (integration[key] !== undefined) return integration[key];
+ }
+ return undefined;
+}
+
+function mergeTemplateConfig(template, integrations) {
+ if (template?.get) return template;
+ const integrationTemplate = firstDefined(integrations, 'template');
+ return integrationTemplate ?? template;
+}
diff --git a/packages/cli/src/lib/config.test.mjs b/packages/cli/src/lib/config.test.mjs
index 93ec503c46..566764f62b 100644
--- a/packages/cli/src/lib/config.test.mjs
+++ b/packages/cli/src/lib/config.test.mjs
@@ -15,10 +15,25 @@ afterEach(() => {
fs.rmSync(tmpDir, {recursive: true, force: true});
});
+function installIntegrationPackage(dir, name = '@nest/xds-meta') {
+ const packageDir = path.join(dir, 'node_modules', ...name.split('/'));
+ fs.mkdirSync(packageDir, {recursive: true});
+ fs.writeFileSync(
+ path.join(packageDir, 'package.json'),
+ JSON.stringify({name, astryx: {integration: './astryx.integration.mjs'}}),
+ );
+ fs.writeFileSync(
+ path.join(packageDir, 'astryx.integration.mjs'),
+ `export default { name: '${name}' };
+`,
+ );
+}
+
describe('loadConfig', () => {
it('normalizes integrations from astryx.config.mjs', async () => {
const dir = path.join(tmpDir, 'one');
fs.mkdirSync(dir);
+ installIntegrationPackage(dir);
fs.writeFileSync(
path.join(dir, 'astryx.config.mjs'),
`export default { integrations: '@nest/xds-meta' };\n`,
@@ -28,15 +43,49 @@ describe('loadConfig', () => {
});
});
- it('normalizes integration arrays and filters non-strings', async () => {
+ it('rejects invalid integration package manifests', async () => {
+ const dir = path.join(tmpDir, 'bad');
+ fs.mkdirSync(dir);
+ const packageDir = path.join(dir, 'node_modules', '@bad', 'widgets');
+ fs.mkdirSync(packageDir, {recursive: true});
+ fs.writeFileSync(
+ path.join(dir, 'astryx.config.mjs'),
+ `export default { integrations: '@bad/widgets' };\n`,
+ );
+ fs.writeFileSync(
+ path.join(packageDir, 'package.json'),
+ JSON.stringify({
+ name: '@bad/widgets',
+ astryx: {integration: './astryx.integration.mjs'},
+ }),
+ );
+ fs.writeFileSync(
+ path.join(packageDir, 'astryx.integration.mjs'),
+ `export default { docs: './docs' };\n`,
+ );
+ await expect(loadConfig(dir)).rejects.toThrow(/name/);
+ });
+
+ it('normalizes integration arrays', async () => {
const dir = path.join(tmpDir, 'two');
fs.mkdirSync(dir);
+ installIntegrationPackage(dir);
fs.writeFileSync(
path.join(dir, 'astryx.config.mjs'),
- `export default { integrations: ['@nest/xds-meta', '', 42] };\n`,
+ `export default { integrations: ['@nest/xds-meta', ''] };\n`,
);
await expect(loadConfig(dir)).resolves.toMatchObject({
integrations: ['@nest/xds-meta'],
});
});
+
+ it('rejects invalid config shapes', async () => {
+ const dir = path.join(tmpDir, 'invalid');
+ fs.mkdirSync(dir);
+ fs.writeFileSync(
+ path.join(dir, 'astryx.config.mjs'),
+ `export default { integrations: [42] };\n`,
+ );
+ await expect(loadConfig(dir)).rejects.toThrow(/integrations/);
+ });
});
diff --git a/packages/cli/src/lib/integrations.mjs b/packages/cli/src/lib/integrations.mjs
new file mode 100644
index 0000000000..5da50d02b7
--- /dev/null
+++ b/packages/cli/src/lib/integrations.mjs
@@ -0,0 +1,155 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Integration manifest loading for Astryx config.
+ *
+ * Integrations are package names or direct manifest paths listed in
+ * astryx.config.mjs. A manifest can contribute docs/discovery metadata,
+ * gap-report/template hooks, upgrade codemods, and post-codemod hooks.
+ */
+
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {pathToFileURL} from 'node:url';
+import {validateIntegration} from './config-schema.mjs';
+
+export function isPathSpec(spec) {
+ return (
+ spec.startsWith('.') ||
+ spec.startsWith('/') ||
+ spec.endsWith('.mjs') ||
+ spec.endsWith('.js')
+ );
+}
+
+export function resolvePackageDir(packageName, cwd = process.cwd()) {
+ return path.resolve(cwd, 'node_modules', ...packageName.split('/'));
+}
+
+export function resolveIntegrationFile(spec, cwd = process.cwd()) {
+ if (isPathSpec(spec)) {
+ return path.resolve(cwd, spec);
+ }
+
+ const packageDir = resolvePackageDir(spec, cwd);
+ const pkgPath = path.join(packageDir, 'package.json');
+ let pkg;
+ try {
+ pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
+ } catch {
+ throw new Error(
+ `Could not find installed integration package "${spec}" at ${pkgPath}. Install it first or pass a direct integration file path.`,
+ );
+ }
+
+ const manifestPath = pkg.astryx?.integration ?? pkg.xds?.integration;
+ if (!manifestPath) {
+ throw new Error(
+ `Package "${spec}" does not declare astryx.integration (or legacy xds.integration) in package.json.`,
+ );
+ }
+ return path.resolve(packageDir, manifestPath);
+}
+
+function normalizePackageContribution(integration) {
+ const docs = integration.docs;
+ if (!docs) return null;
+ const packageDir = integration.__packageDir ?? integration.__dir;
+ const docsDir = path.resolve(packageDir, docs);
+ return {
+ name: integration.name ?? integration.__spec,
+ version: integration.version,
+ description: integration.description,
+ displayName: integration.displayName,
+ dir: packageDir,
+ astryx: {
+ docs,
+ category: integration.category,
+ blocks: integration.blocks,
+ },
+ category: integration.category ?? integration.name ?? integration.__spec,
+ docsDir,
+ };
+}
+
+function resolveHookFunction(hook, integration) {
+ if (typeof hook === 'function') return hook;
+ if (typeof hook !== 'string') return hook;
+ const [moduleSpec, exportName = 'default'] = hook.split('#');
+ return async (...args) => {
+ const mod = isPathSpec(moduleSpec)
+ ? await import(
+ pathToFileURL(path.resolve(integration.__dir, moduleSpec)).href
+ )
+ : await import(moduleSpec);
+ const fn = exportName === 'default' ? mod.default : mod[exportName];
+ if (typeof fn !== 'function') {
+ throw new Error(
+ `Integration hook ${hook} did not resolve to a function.`,
+ );
+ }
+ return fn(...args);
+ };
+}
+
+export async function loadIntegrations(specs = [], {cwd = process.cwd()} = {}) {
+ const integrations = [];
+ const seen = new Set();
+
+ for (const spec of specs) {
+ if (!spec || seen.has(spec)) continue;
+ seen.add(spec);
+
+ const file = resolveIntegrationFile(spec, cwd);
+ const mod = await import(pathToFileURL(file).href);
+ const exported = mod.default ?? mod.integration ?? mod;
+ if (!exported || typeof exported !== 'object') {
+ throw new Error(`Integration ${spec} did not export an object.`);
+ }
+ const integration = validateIntegration(exported, `Integration ${spec}`);
+
+ const integrationDir = path.dirname(file);
+ const packageDir = isPathSpec(spec)
+ ? integrationDir
+ : resolvePackageDir(spec, cwd);
+ const normalized = {
+ ...integration,
+ __file: file,
+ __dir: integrationDir,
+ __packageDir: packageDir,
+ __spec: spec,
+ };
+
+ if (Array.isArray(normalized.codemods)) {
+ for (const codemod of normalized.codemods) {
+ if (typeof codemod.transform === 'string') {
+ const transformPath = path.resolve(integrationDir, codemod.transform);
+ const transformMod = await import(pathToFileURL(transformPath).href);
+ codemod.transform =
+ transformMod.default ?? transformMod.transform ?? transformMod;
+ }
+ }
+ }
+
+ normalized.package = normalizePackageContribution(normalized);
+ if (
+ normalized.gapReport?.command &&
+ isPathSpec(normalized.gapReport.command)
+ ) {
+ normalized.gapReport = {
+ ...normalized.gapReport,
+ command: path.resolve(packageDir, normalized.gapReport.command),
+ };
+ }
+ if (normalized.template?.get) {
+ normalized.template = {
+ ...normalized.template,
+ get: resolveHookFunction(normalized.template.get, normalized),
+ };
+ }
+
+ integrations.push(normalized);
+ }
+
+ return integrations;
+}
diff --git a/packages/cli/src/lib/integrations.test.mjs b/packages/cli/src/lib/integrations.test.mjs
new file mode 100644
index 0000000000..28d9b3171d
--- /dev/null
+++ b/packages/cli/src/lib/integrations.test.mjs
@@ -0,0 +1,154 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import {loadConfig} from './config.mjs';
+import {discover} from '../api/discover.mjs';
+import {loadGapReportConfig} from '../utils/github.mjs';
+import {getTemplateById} from '../api/template.mjs';
+
+let tmpDir;
+let originalCwd;
+
+beforeEach(() => {
+ originalCwd = process.cwd();
+ tmpDir = fs.mkdtempSync(
+ path.join(process.cwd(), '.astryx-integration-test-'),
+ );
+ fs.mkdirSync(path.join(tmpDir, 'node_modules', '@acme', 'widgets'), {
+ recursive: true,
+ });
+ fs.writeFileSync(
+ path.join(tmpDir, 'astryx.config.mjs'),
+ `export default { integrations: '@acme/widgets' };\n`,
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'node_modules', '@acme', 'widgets', 'package.json'),
+ JSON.stringify({
+ name: '@acme/widgets',
+ version: '1.2.3',
+ displayName: 'Acme Widgets',
+ astryx: {integration: './astryx.integration.mjs'},
+ }),
+ );
+ fs.writeFileSync(
+ path.join(
+ tmpDir,
+ 'node_modules',
+ '@acme',
+ 'widgets',
+ 'astryx.integration.mjs',
+ ),
+ `export default {
+ name: '@acme/widgets',
+ version: '1.2.3',
+ displayName: 'Acme Widgets',
+ docs: './docs',
+ category: 'Acme',
+ gapReport: {command: './scripts/report-gap.sh'},
+ template: {get: './template.mjs#getTemplate'},
+ codemods: [{name: 'noop', from: '0.0.0', to: '9.0.0', transform: './codemod.mjs'}],
+ };\n`,
+ );
+ fs.mkdirSync(path.join(tmpDir, 'node_modules', '@acme', 'widgets', 'docs'));
+ fs.writeFileSync(
+ path.join(
+ tmpDir,
+ 'node_modules',
+ '@acme',
+ 'widgets',
+ 'docs',
+ 'Widget.doc.mjs',
+ ),
+ `export const doc = {
+ name: 'Widget',
+ usage: {description: 'Acme widget'},
+ props: [],
+ };\n`,
+ );
+ fs.mkdirSync(
+ path.join(tmpDir, 'node_modules', '@acme', 'widgets', 'scripts'),
+ );
+ fs.writeFileSync(
+ path.join(
+ tmpDir,
+ 'node_modules',
+ '@acme',
+ 'widgets',
+ 'scripts',
+ 'report-gap.sh',
+ ),
+ '#!/bin/sh\ncat >/dev/null\necho ok\n',
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'node_modules', '@acme', 'widgets', 'template.mjs'),
+ `export async function getTemplate(id) { return 'template:' + id; }\n`,
+ );
+ fs.writeFileSync(
+ path.join(tmpDir, 'node_modules', '@acme', 'widgets', 'codemod.mjs'),
+ `export default function transform() { return undefined; }\n`,
+ );
+ process.chdir(tmpDir);
+});
+
+afterEach(() => {
+ process.chdir(originalCwd);
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+describe('configured integrations', () => {
+ it('load docs/gap/template/codemod metadata from integration manifests', async () => {
+ const config = await loadConfig(tmpDir);
+ expect(config.integrations).toEqual(['@acme/widgets']);
+ expect(config.loadedIntegrations[0].name).toBe('@acme/widgets');
+ expect(config.loadedIntegrations[0].package).toMatchObject({
+ name: '@acme/widgets',
+ category: 'Acme',
+ });
+ expect(config.loadedIntegrations[0].codemods[0].transform).toEqual(
+ expect.any(Function),
+ );
+ expect(config.gapReport.command).toBe(
+ path.join(
+ tmpDir,
+ 'node_modules',
+ '@acme',
+ 'widgets',
+ 'scripts',
+ 'report-gap.sh',
+ ),
+ );
+ await expect(config.template.get('P123')).resolves.toBe('template:P123');
+ });
+
+ it('makes integration docs discoverable without packages config', async () => {
+ const result = await discover(undefined, {});
+ expect(result.type).toBe('discover.list');
+ expect(result.data).toEqual([
+ expect.objectContaining({
+ name: '@acme/widgets',
+ category: 'Acme',
+ components: ['Widget'],
+ }),
+ ]);
+ });
+
+ it('uses integration gap-report and template hooks', async () => {
+ await expect(loadGapReportConfig()).resolves.toMatchObject({
+ enabled: true,
+ command: path.join(
+ tmpDir,
+ 'node_modules',
+ '@acme',
+ 'widgets',
+ 'scripts',
+ 'report-gap.sh',
+ ),
+ });
+ await expect(getTemplateById('P123', {cwd: tmpDir})).resolves.toEqual({
+ type: 'template.get',
+ data: {id: 'P123', source: 'template:P123'},
+ });
+ });
+});
diff --git a/packages/cli/src/lib/package-scanner.mjs b/packages/cli/src/lib/package-scanner.mjs
index 26edf1d604..bf9bd299d8 100644
--- a/packages/cli/src/lib/package-scanner.mjs
+++ b/packages/cli/src/lib/package-scanner.mjs
@@ -15,7 +15,11 @@ export function scanDirectory(scanDir) {
const pkgPath = path.join(scanDir, entry.name, 'package.json');
if (!fs.existsSync(pkgPath)) continue;
let pkg;
- try { pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8')); } catch { continue; }
+ try {
+ pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
+ } catch {
+ continue;
+ }
if (!pkg.astryx || !pkg.astryx.docs) continue;
const pkgDir = path.join(scanDir, entry.name);
const docsDir = path.resolve(pkgDir, pkg.astryx.docs);
@@ -36,9 +40,18 @@ export function scanDirectory(scanDir) {
return packages;
}
-export function scanAllPackages(packageDirs) {
+export function scanAllPackages(packageDirs, explicitPackages = []) {
const all = [];
const seen = new Set();
+
+ for (const pkg of explicitPackages) {
+ if (!pkg || seen.has(pkg.name)) continue;
+ const components = discoverDocComponents(pkg.docsDir);
+ if (components.length === 0) continue;
+ seen.add(pkg.name);
+ all.push({...pkg, components});
+ }
+
for (const dir of packageDirs) {
for (const pkg of scanDirectory(dir)) {
if (seen.has(pkg.name)) continue;
@@ -54,12 +67,17 @@ function discoverDocComponents(docsDir) {
const components = [];
function walk(dir) {
let entries;
- try { entries = fs.readdirSync(dir, {withFileTypes: true}); } catch { return; }
+ try {
+ entries = fs.readdirSync(dir, {withFileTypes: true});
+ } catch {
+ return;
+ }
for (const entry of entries) {
if (entry.name === 'node_modules' || entry.name === '__tests__') continue;
const full = path.join(dir, entry.name);
if (entry.isDirectory()) walk(full);
- else if (entry.name.endsWith('.doc.mjs')) components.push(entry.name.replace('.doc.mjs', ''));
+ else if (entry.name.endsWith('.doc.mjs'))
+ components.push(entry.name.replace('.doc.mjs', ''));
}
}
walk(docsDir);
@@ -81,12 +99,18 @@ function findDocFile(docsDir, name) {
const target = name + '.doc.mjs';
function walk(dir) {
let entries;
- try { entries = fs.readdirSync(dir, {withFileTypes: true}); } catch { return null; }
+ try {
+ entries = fs.readdirSync(dir, {withFileTypes: true});
+ } catch {
+ return null;
+ }
for (const entry of entries) {
if (entry.name === 'node_modules' || entry.name === '__tests__') continue;
const full = path.join(dir, entry.name);
- if (entry.isDirectory()) { const f = walk(full); if (f) return f; }
- else if (entry.name === target) return full;
+ if (entry.isDirectory()) {
+ const f = walk(full);
+ if (f) return f;
+ } else if (entry.name === target) return full;
}
return null;
}
diff --git a/packages/cli/src/types/config.d.ts b/packages/cli/src/types/config.d.ts
new file mode 100644
index 0000000000..175f7fb732
--- /dev/null
+++ b/packages/cli/src/types/config.d.ts
@@ -0,0 +1,99 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/** User config exported from astryx.config.mjs. */
+export interface AstryxConfig {
+ /** External package directories to scan for package.json astryx.docs metadata. */
+ packages?: string | string[];
+ /** Integration package names or manifest paths. */
+ integrations?: string | string[];
+ /** Gap report delivery override. Omit for default GitHub issue filing. */
+ gapReport?: false | {command: string};
+ /** Template hooks. */
+ template?: {
+ get?: (id: string) => string | Promise<string>;
+ };
+ [key: string]: unknown;
+}
+
+export interface AstryxIntegrationCodemod {
+ name: string;
+ from?: string;
+ to?: string;
+ title?: string;
+ description?: string;
+ pr?: string;
+ optional?: boolean;
+ fileExtensions?: string[];
+ transform:
+ | string
+ | ((file: unknown, api: unknown) => string | undefined | null);
+}
+
+export interface AstryxPostCodemodContext {
+ packageDir: string;
+ codemodDir: string;
+ changedFiles: string[];
+ absoluteChangedFiles: string[];
+ packageChangedFiles: string[];
+ apply: boolean;
+ run: (
+ command: string,
+ args?: string[],
+ options?: {
+ cwd?: string;
+ timeoutMs?: number;
+ env?: Record<string, string>;
+ },
+ ) => Promise<void>;
+}
+
+export interface AstryxPostCodemodHook {
+ name?: string;
+ run?: (context: AstryxPostCodemodContext) => void | Promise<void>;
+ command?: (context: AstryxPostCodemodContext) =>
+ | {
+ command: string;
+ args?: string[];
+ cwd?: string;
+ timeoutMs?: number;
+ env?: Record<string, string>;
+ }
+ | null
+ | undefined
+ | Promise<
+ | {
+ command: string;
+ args?: string[];
+ cwd?: string;
+ timeoutMs?: number;
+ env?: Record<string, string>;
+ }
+ | null
+ | undefined
+ >;
+}
+
+/** Integration manifest exported from an astryx.integration.mjs file. */
+export interface AstryxIntegration {
+ name: string;
+ version?: string;
+ displayName?: string;
+ description?: string;
+ /** Relative docs root containing *.doc.mjs files. */
+ docs?: string;
+ category?: string;
+ /** Relative block-template root. */
+ blocks?: string;
+ gapReport?: false | {command: string};
+ template?: {
+ get?: string | ((id: string) => string | Promise<string>);
+ };
+ codemods?: AstryxIntegrationCodemod[];
+ postCodemod?: AstryxPostCodemodHook[];
+ [key: string]: unknown;
+}
+
+export declare function createConfig<T extends AstryxConfig>(config: T): T;
+export declare function createIntegration<T extends AstryxIntegration>(
+ integration: T,
+): T;
diff --git a/packages/cli/src/utils/github.mjs b/packages/cli/src/utils/github.mjs
index 6e99cd4ab2..f49965511a 100644
--- a/packages/cli/src/utils/github.mjs
+++ b/packages/cli/src/utils/github.mjs
@@ -16,8 +16,8 @@
*/
import {execFileSync} from 'node:child_process';
-import * as fs from 'node:fs';
import * as path from 'node:path';
+import {loadConfig} from '../lib/config.mjs';
/** Default target repository for gap report issues. */
const DEFAULT_REPO = 'facebookexperimental/xds';
@@ -44,7 +44,7 @@ export const GAP_CATEGORIES = [
* - command: string → run this script instead of creating a GitHub issue
* - neither → default behavior (GitHub issue to facebookexperimental/xds)
*/
-export function loadGapReportConfig() {
+export async function loadGapReportConfig() {
// 1. Check environment variable
const envVar = process.env.ASTRYX_GAP_REPORT;
if (envVar) {
@@ -55,27 +55,12 @@ export function loadGapReportConfig() {
return {enabled: true, command: envVar};
}
- // 2. Check astryx.config.mjs
- const configPath = path.join(process.cwd(), 'astryx.config.mjs');
- if (fs.existsSync(configPath)) {
- try {
- const content = fs.readFileSync(configPath, 'utf-8');
- const match = content.match(/gapReport\s*:\s*(.+?)[\s,}]/s);
- if (match) {
- const value = match[1].trim();
- if (value === 'false') {
- return {enabled: false};
- }
- // Look for command property in object literal
- const cmdMatch = content.match(
- /gapReport\s*:\s*\{[^}]*command\s*:\s*['"](.+?)['"]/s,
- );
- if (cmdMatch) {
- return {enabled: true, command: cmdMatch[1]};
- }
- }
- } catch {
- // Config parse error — fall through to defaults
+ // 2. Check astryx.config.mjs + integration manifests
+ const config = await loadConfig(process.cwd());
+ if (config.gapReport !== undefined) {
+ if (config.gapReport === false) return {enabled: false};
+ if (config.gapReport?.command) {
+ return {enabled: true, command: config.gapReport.command};
}
}
@@ -172,14 +157,14 @@ function runCustomCommand(command, report) {
* repo: string,
* }}
*/
-export function buildGapReportPreview({
+export async function buildGapReportPreview({
component,
category,
intention,
detail,
source = 'cli',
}) {
- const config = loadGapReportConfig();
+ const config = await loadGapReportConfig();
const categoryLabel =
GAP_CATEGORIES.find(c => c.value === category)?.label ?? category;
@@ -238,8 +223,8 @@ export function buildGapReportPreview({
* @param {string} [opts.source] Who filed it: "interactive", "llm-auto", "cli"
* @returns {string|null} URL of the created issue (or custom command output), null if disabled
*/
-export function createGapReport(opts) {
- const preview = buildGapReportPreview(opts);
+export async function createGapReport(opts) {
+ const preview = await buildGapReportPreview(opts);
if (!preview.enabled) {
return null;
diff --git a/packages/cli/tsconfig.json-api.json b/packages/cli/tsconfig.json-api.json
index dc3bf0f0de..dad96e200a 100644
--- a/packages/cli/tsconfig.json-api.json
+++ b/packages/cli/tsconfig.json-api.json
@@ -12,6 +12,7 @@
"src/lib/json.mjs",
"src/lib/manifest.mjs",
"src/lib/parse.mjs",
+ "src/config.mjs",
"../core/src/docs-types.ts"
]
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 63fc756cdf..46ef0fc842 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -718,6 +718,9 @@ importers:
jscodeshift:
specifier: ^17.3.0
version: 17.3.0
+ zod:
+ specifier: ^4.4.3
+ version: 4.4.3
devDependencies:
'@astryxdesign/core':
specifier: '*'