Skip to content

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

TypeScript

fix(cli): enable ESLint coverage for CLI source + enforce JSON-stdout contract (#2576)

Joeyda5a37f00661
diff --git a/eslint.config.js b/eslint.config.js
index b373526855..e573cb7775 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -36,7 +36,13 @@ export default tseslint.config(
"**/internal/eslint-plugin-xds/**",
".github/scripts/**",
"scripts/**",
+ // .mjs is ignored everywhere EXCEPT the CLI package, whose runtime is
+ // entirely .mjs. The negations below opt packages/cli back into linting
+ // (see the dedicated CLI block lower down). Scoped to packages/cli on
+ // purpose — other packages' .mjs stay unlinted (#2468).
"**/*.mjs",
+ "!packages/cli/src/**/*.mjs",
+ "!packages/cli/bin/**/*.mjs",
"**/*.test-violations.tsx",
"apps/example-nextjs/*.js",
"**/next-env.d.ts",
@@ -275,4 +281,72 @@ export default tseslint.config(
"no-console": "off",
},
},
+ // CLI runtime (.mjs). The CLI ships as ESM Node modules and was never linted
+ // (the global **/*.mjs ignore swallowed it; see #2468). This block gives the
+ // .mjs sources a Node language environment and enforces the JSON-stdout
+ // contract (#2467) at author time via @xds/no-raw-console-cli.
+ {
+ files: ["packages/cli/src/**/*.mjs", "packages/cli/bin/**/*.mjs"],
+ plugins: {
+ '@xds': xdsPlugin,
+ },
+ languageOptions: {
+ sourceType: "module",
+ globals: {
+ // Node globals (no `globals` package dependency in this repo).
+ process: "readonly",
+ console: "readonly",
+ Buffer: "readonly",
+ URL: "readonly",
+ URLSearchParams: "readonly",
+ TextEncoder: "readonly",
+ TextDecoder: "readonly",
+ setTimeout: "readonly",
+ clearTimeout: "readonly",
+ setInterval: "readonly",
+ clearInterval: "readonly",
+ setImmediate: "readonly",
+ clearImmediate: "readonly",
+ queueMicrotask: "readonly",
+ __dirname: "readonly",
+ __filename: "readonly",
+ global: "readonly",
+ globalThis: "readonly",
+ structuredClone: "readonly",
+ fetch: "readonly",
+ AbortController: "readonly",
+ },
+ },
+ rules: {
+ "@typescript-eslint/no-unused-vars": ["error", {
+ argsIgnorePattern: "^_",
+ varsIgnorePattern: "^_",
+ destructuredArrayIgnorePattern: "^_",
+ caughtErrorsIgnorePattern: "^_",
+ }],
+ // Bare console.log corrupts --json stdout. Route human chatter through
+ // humanLog(); console.error/console.warn (stderr) stay allowed.
+ "@xds/no-raw-console-cli": "error",
+ },
+ },
+ // Copyright header for CLI .mjs sources (the main copyright block only
+ // covers .ts/.tsx).
+ {
+ files: ["packages/cli/src/**/*.mjs", "packages/cli/bin/**/*.mjs"],
+ plugins: {
+ '@xds': xdsPlugin,
+ },
+ rules: {
+ '@xds/copyright-header': 'error',
+ },
+ },
+ // CLI tests — relax author-ergonomics rules (test files emit freely and may
+ // keep intentionally-unused fixtures). Must come after the CLI block above.
+ {
+ files: ["packages/cli/**/*.test.mjs"],
+ rules: {
+ "@xds/no-raw-console-cli": "off",
+ "@typescript-eslint/no-unused-vars": "off",
+ },
+ },
);
diff --git a/internal/eslint-plugin-xds/index.js b/internal/eslint-plugin-xds/index.js
index a0718cb426..c3f2d5a24f 100644
--- a/internal/eslint-plugin-xds/index.js
+++ b/internal/eslint-plugin-xds/index.js
@@ -24,6 +24,7 @@ import noHardcodedAnchorRule from './no-hardcoded-anchor.js';
import noBorderShorthandRule from './no-border-shorthand.js';
import noReactNamespaceHooksRule from './no-react-namespace-hooks.js';
import copyrightHeaderRule from './copyright-header.js';
+import noRawConsoleCliRule from './no-raw-console-cli.js';
import requireBasePropsRule from './require-base-props.js';
import requireRefPropRule from './require-ref-prop.js';
@@ -238,6 +239,7 @@ const plugin = {
'require-base-props': requireBasePropsRule,
'require-ref-prop': requireRefPropRule,
'copyright-header': copyrightHeaderRule,
+ 'no-raw-console-cli': noRawConsoleCliRule,
},
configs: {},
};
diff --git a/internal/eslint-plugin-xds/no-raw-console-cli.js b/internal/eslint-plugin-xds/no-raw-console-cli.js
new file mode 100644
index 0000000000..cf052df93c
--- /dev/null
+++ b/internal/eslint-plugin-xds/no-raw-console-cli.js
@@ -0,0 +1,91 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file no-raw-console-cli.js
+ * @description Ban bare `console.log` in CLI runtime files so it can never
+ * corrupt the `--json` stdout contract (#2467).
+ *
+ * The CLI's machine-readable JSON output owns stdout in `--json` mode. A stray
+ * `console.log` writes to that same stream and breaks JSON consumers. The
+ * sanctioned escape hatch is `humanLog()` (lib/json.mjs), which is a no-op in
+ * JSON mode. This rule pushes authors toward it:
+ *
+ * Banned: console.log(...) (writes raw stdout)
+ * Allowed: console.error(...) (stderr — never corrupts JSON)
+ * console.warn(...) (stderr)
+ * humanLog(...) (json-aware stdout)
+ *
+ * Autofix rewrites `console.log(` → `humanLog(`. The author is responsible for
+ * ensuring `humanLog` is imported from `../lib/json.mjs`; the fix only renames
+ * the call so the wrong primitive isn't silently kept.
+ *
+ * A handful of files legitimately write raw stdout — the JSON envelope writers
+ * and the banner — and are exempt:
+ * - packages/cli/src/lib/json.mjs (defines humanLog / jsonOut)
+ * - packages/cli/src/index.mjs (wiring / banner)
+ * - packages/cli/bin/xds.mjs (entrypoint / error boundary)
+ */
+
+const EXEMPT_SUFFIXES = [
+ 'packages/cli/src/lib/json.mjs',
+ 'packages/cli/src/index.mjs',
+ 'packages/cli/bin/xds.mjs',
+];
+
+function isExempt(filename) {
+ // Normalize Windows separators so suffix matching is path-agnostic.
+ const normalized = filename.replace(/\\/g, '/');
+ return EXEMPT_SUFFIXES.some(suffix => normalized.endsWith(suffix));
+}
+
+const rule = {
+ meta: {
+ type: 'problem',
+ docs: {
+ description:
+ 'Ban bare console.log in CLI runtime files; use humanLog so --json stdout stays clean',
+ category: 'XDS Conventions',
+ recommended: true,
+ },
+ fixable: 'code',
+ messages: {
+ noRawConsoleLog:
+ 'Do not use console.log in CLI runtime code — it writes raw stdout and ' +
+ 'can corrupt --json output. Use humanLog() (from lib/json.mjs), or ' +
+ 'console.error/console.warn for stderr.',
+ },
+ schema: [],
+ },
+ create(context) {
+ const filename = context.filename ?? context.getFilename();
+ if (isExempt(filename)) {
+ return {};
+ }
+
+ return {
+ CallExpression(node) {
+ const callee = node.callee;
+ if (
+ callee.type === 'MemberExpression' &&
+ !callee.computed &&
+ callee.object.type === 'Identifier' &&
+ callee.object.name === 'console' &&
+ callee.property.type === 'Identifier' &&
+ callee.property.name === 'log'
+ ) {
+ context.report({
+ node: callee,
+ messageId: 'noRawConsoleLog',
+ fix(fixer) {
+ // console.log -> humanLog (rename the call; import is the
+ // author's responsibility).
+ return fixer.replaceText(callee, 'humanLog');
+ },
+ });
+ }
+ },
+ };
+ },
+};
+
+export default rule;
diff --git a/internal/eslint-plugin-xds/no-raw-console-cli.test.mjs b/internal/eslint-plugin-xds/no-raw-console-cli.test.mjs
new file mode 100644
index 0000000000..975880a502
--- /dev/null
+++ b/internal/eslint-plugin-xds/no-raw-console-cli.test.mjs
@@ -0,0 +1,83 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file no-raw-console-cli.test.mjs
+ */
+
+import {RuleTester} from 'eslint';
+import rule from './no-raw-console-cli.js';
+
+const ruleTester = new RuleTester({
+ languageOptions: {
+ ecmaVersion: 2022,
+ sourceType: 'module',
+ },
+});
+
+ruleTester.run('no-raw-console-cli', rule, {
+ valid: [
+ // console.error is allowed (stderr — never corrupts --json stdout)
+ {
+ code: `console.error('boom');`,
+ filename: '/repo/packages/cli/src/commands/search.mjs',
+ },
+ // console.warn is allowed (stderr)
+ {
+ code: `console.warn('heads up');`,
+ filename: '/repo/packages/cli/src/commands/search.mjs',
+ },
+ // humanLog is the sanctioned json-aware stdout primitive
+ {
+ code: `import {humanLog} from '../lib/json.mjs'; humanLog('hi');`,
+ filename: '/repo/packages/cli/src/commands/search.mjs',
+ },
+ // Exempt: lib/json.mjs defines the raw writers
+ {
+ code: `console.log('raw');`,
+ filename: '/repo/packages/cli/src/lib/json.mjs',
+ },
+ // Exempt: index.mjs (wiring / banner)
+ {
+ code: `console.log('banner');`,
+ filename: '/repo/packages/cli/src/index.mjs',
+ },
+ // Exempt: bin/xds.mjs (entrypoint / error boundary)
+ {
+ code: `console.log('raw');`,
+ filename: '/repo/packages/cli/bin/xds.mjs',
+ },
+ // Exemption is path-suffix based and tolerant of Windows separators
+ {
+ code: `console.log('raw');`,
+ filename: 'C:\\repo\\packages\\cli\\src\\lib\\json.mjs',
+ },
+ ],
+ invalid: [
+ // Bare console.log -> humanLog
+ {
+ code: `console.log('hello');`,
+ filename: '/repo/packages/cli/src/commands/search.mjs',
+ output: `humanLog('hello');`,
+ errors: [{messageId: 'noRawConsoleLog'}],
+ },
+ // Member access preserved, only the callee renamed
+ {
+ code: `console.log(\`a \${b}\`);`,
+ filename: '/repo/packages/cli/src/api/component.mjs',
+ output: `humanLog(\`a \${b}\`);`,
+ errors: [{messageId: 'noRawConsoleLog'}],
+ },
+ // Multiple violations
+ {
+ code: `console.log('a'); console.log('b');`,
+ filename: '/repo/packages/cli/src/commands/init.mjs',
+ output: `humanLog('a'); humanLog('b');`,
+ errors: [
+ {messageId: 'noRawConsoleLog'},
+ {messageId: 'noRawConsoleLog'},
+ ],
+ },
+ ],
+});
+
+console.log('All tests passed!');
diff --git a/packages/cli/src/api/component.mjs b/packages/cli/src/api/component.mjs
index 39026fc676..2c6329f619 100644
--- a/packages/cli/src/api/component.mjs
+++ b/packages/cli/src/api/component.mjs
@@ -12,7 +12,6 @@ import {ERROR_CODES} from '../lib/error-codes.mjs';
import {findCoreDir, discoverExternalPackages} from '../utils/paths.mjs';
import {
discoverComponents,
- discoverExternalComponents,
discoverExternalComponentsGrouped,
findComponentReadme,
findComponentSource,
@@ -275,7 +274,6 @@ export async function component(name, options = {}) {
let readmePath = findComponentReadme(coreDir, dirName);
let resolvedName = dirName;
- let fromExternal = null;
if (!readmePath) {
const externals = discoverExternalPackages(cwd);
@@ -283,7 +281,6 @@ export async function component(name, options = {}) {
const extDocPath = findExternalComponentDoc(ext.docsDir, dirName);
if (extDocPath) {
readmePath = extDocPath;
- fromExternal = ext;
break;
}
}
diff --git a/packages/cli/src/api/doctor.mjs b/packages/cli/src/api/doctor.mjs
index 9d047e4ab1..3561c07169 100644
--- a/packages/cli/src/api/doctor.mjs
+++ b/packages/cli/src/api/doctor.mjs
@@ -421,7 +421,7 @@ export function checkPeerDeps(ctx) {
_require.resolve(name, {paths: [ctx.cwd]});
present = true;
} catch {
- present = false;
+ // Still unresolved — leave present at its initial false.
}
}
if (!present) missing.push(`${name}@${peers[name]}`);
@@ -496,7 +496,7 @@ export async function runChecks(options = {}) {
const loaded = await loadConfig(cwd);
configTheme = loaded?.theme ?? null;
} catch {
- configTheme = null;
+ // Best-effort: a missing/invalid config leaves configTheme null.
}
/** @type {DoctorContext} */
diff --git a/packages/cli/src/api/search.mjs b/packages/cli/src/api/search.mjs
index 4cf85e4fbf..9e9d01846e 100644
--- a/packages/cli/src/api/search.mjs
+++ b/packages/cli/src/api/search.mjs
@@ -234,7 +234,7 @@ async function gatherDocs() {
/** Build template candidates (page + block) from the template discovery API. */
async function gatherTemplates(cwd) {
- let templates = [];
+ let templates;
try {
templates = await discoverTemplates(cwd);
} catch {
diff --git a/packages/cli/src/codemods/transforms/v0.0.2/rename-form-tooltip-startIcon.mjs b/packages/cli/src/codemods/transforms/v0.0.2/rename-form-tooltip-startIcon.mjs
index 59f552ed67..022ec22479 100644
--- a/packages/cli/src/codemods/transforms/v0.0.2/rename-form-tooltip-startIcon.mjs
+++ b/packages/cli/src/codemods/transforms/v0.0.2/rename-form-tooltip-startIcon.mjs
@@ -1,7 +1,5 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
/**
* @file Codemod: Rename form field tooltip → labelTooltip, startIcon → labelIcon
* @see https://github.com/facebookexperimental/xds/pull/375
diff --git a/packages/cli/src/codemods/transforms/v0.0.2/rename-topnav-title-to-heading.mjs b/packages/cli/src/codemods/transforms/v0.0.2/rename-topnav-title-to-heading.mjs
index 2d2b5868e1..4aaa0769a0 100644
--- a/packages/cli/src/codemods/transforms/v0.0.2/rename-topnav-title-to-heading.mjs
+++ b/packages/cli/src/codemods/transforms/v0.0.2/rename-topnav-title-to-heading.mjs
@@ -1,7 +1,5 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
/**
* @file Codemod: Rename XDSTopNavTitle → XDSTopNavHeading, title → heading
* @see https://github.com/facebookexperimental/xds/pull/527
diff --git a/packages/cli/src/codemods/transforms/v0.0.6/__tests__/migrate-skeleton-radius.test.mjs b/packages/cli/src/codemods/transforms/v0.0.6/__tests__/migrate-skeleton-radius.test.mjs
index 2c860549f7..12d99b13b4 100644
--- a/packages/cli/src/codemods/transforms/v0.0.6/__tests__/migrate-skeleton-radius.test.mjs
+++ b/packages/cli/src/codemods/transforms/v0.0.6/__tests__/migrate-skeleton-radius.test.mjs
@@ -1,7 +1,5 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
-// Copyright (c) Meta Platforms, Inc. and affiliates.
-
import {describe, it, expect} from 'vitest';
async function applyTransform(source) {
diff --git a/packages/cli/src/commands/agent-docs.mjs b/packages/cli/src/commands/agent-docs.mjs
index 823f721a35..1203fa2256 100644
--- a/packages/cli/src/commands/agent-docs.mjs
+++ b/packages/cli/src/commands/agent-docs.mjs
@@ -23,7 +23,6 @@ import {findCoreDir, CLI_ROOT} from '../utils/paths.mjs';
import {assertWithin, PathSafetyError} from '../utils/path-safety.mjs';
import {getRunPrefix} from '../utils/package-manager.mjs';
import {discoverComponents} from '../lib/component-discovery.mjs';
-import {discoverHooks} from '../lib/hook-discovery.mjs';
import {humanLog} from '../lib/json.mjs';
import {cliError} from '../lib/cli-error.mjs';
import {ERROR_CODES} from '../lib/error-codes.mjs';
@@ -98,7 +97,7 @@ export function resolveAgentPaths(targetDir, agent) {
* Templates are positioned first in the workflow to teach agents the
* "look at reference code" reflex before writing any UI.
*/
-export function generateCompressedIndex(version, {coreDir, zh = false, lang, runPrefix = getRunPrefix()} = {}) {
+export function generateCompressedIndex(version, {coreDir, runPrefix = getRunPrefix()} = {}) {
const run = `${runPrefix} xds`;
const lines = [XDS_MARKER_START];
@@ -110,7 +109,9 @@ export function generateCompressedIndex(version, {coreDir, zh = false, lang, run
let total = 0;
for (const list of Object.values(comps)) total += list.length;
if (total > 0) componentCount = String(total);
- } catch {}
+ } catch {
+ // Best-effort: component count is cosmetic; fall back to the default.
+ }
}
// Header
@@ -152,7 +153,9 @@ export function generateCompressedIndex(version, {coreDir, zh = false, lang, run
const fileContent = fs.readFileSync(path.join(docsDir, file), 'utf-8');
const descMatch = fileContent.match(/description:\s*['"](.+?)['"]/);
if (descMatch) desc = descMatch[1];
- } catch {}
+ } catch {
+ // Best-effort: fall back to the topic name if the file is unreadable.
+ }
if (desc.length > 50) desc = desc.slice(0, 47) + '...';
lines.push(`${run} docs ${topic.padEnd(20)} ${desc}`);
}
@@ -210,7 +213,7 @@ export function getXdsVersion(coreDir) {
* @returns {boolean} Whether the file was written
*/
export function injectXdsBlock(filePath, compressedIndex, {createIfMissing = false, header = '', onlyReplace = false} = {}) {
- let content = '';
+ let content;
if (fs.existsSync(filePath)) {
content = fs.readFileSync(filePath, 'utf-8');
@@ -243,7 +246,7 @@ export function injectXdsBlock(filePath, compressedIndex, {createIfMissing = fal
* Inject or update XDS section in AGENTS.md.
* Always creates the file if it doesn't exist.
*/
-export function injectAgentsMd(targetDir, version, {zh = false, lang} = {}) {
+export function injectAgentsMd(targetDir, version) {
const agentsPath = path.join(targetDir, AGENTS_MD);
const compressedIndex = generateCompressedIndex(version, {coreDir: findCoreDir(targetDir)});
injectXdsBlock(agentsPath, compressedIndex, {
@@ -258,7 +261,7 @@ export function injectAgentsMd(targetDir, version, {zh = false, lang} = {}) {
*
* @returns {boolean} Whether the file was written
*/
-export function injectClaudeMd(targetDir, version, {zh = false, lang} = {}) {
+export function injectClaudeMd(targetDir, version) {
const claudePath = path.join(targetDir, CLAUDE_MD);
const compressedIndex = generateCompressedIndex(version, {coreDir: findCoreDir(targetDir)});
return injectXdsBlock(claudePath, compressedIndex);
diff --git a/packages/cli/src/commands/build-theme.mjs b/packages/cli/src/commands/build-theme.mjs
index 998e21107f..04234721c5 100644
--- a/packages/cli/src/commands/build-theme.mjs
+++ b/packages/cli/src/commands/build-theme.mjs
@@ -18,7 +18,7 @@ import {pathToFileURL, fileURLToPath} from 'node:url';
import {createJiti} from 'jiti';
import {getRunPrefix} from '../utils/package-manager.mjs';
import {sanitizeName, PathSafetyError} from '../utils/path-safety.mjs';
-import {jsonOut, jsonError, humanLog} from '../lib/json.mjs';
+import {jsonOut, humanLog} from '../lib/json.mjs';
import {cliError} from '../lib/cli-error.mjs';
import {ERROR_CODES} from '../lib/error-codes.mjs';
@@ -164,54 +164,16 @@ async function getKnownValues(componentName) {
/**
- * Generate TypeScript declaration file with module augmentation for custom
- * component prop values found in the theme's `components` keys.
- *
- * Scans component override keys (e.g. `status:neutral`, `variant:primary-muted`)
- * and generates augmentations for values not in the base type.
+ * Generate TypeScript declaration content with module augmentation for custom
+ * component prop values found in the theme's `components` keys. Reads known
+ * values from doc files to filter out base prop values.
*
* Interface naming convention: XDS + PascalCase(component) + PascalCase(prop) + Map
* banner + status → XDSBannerStatusMap
* button + variant → XDSButtonVariantMap
*
* @param {object} themeDef - Theme definition (resolved by defineTheme)
- * @returns {string|null} TypeScript declaration content, or null if no augmentations needed
- */
-function generateVariantDeclarations(themeDef) {
- if (!themeDef.components || Object.keys(themeDef.components).length === 0) {
- return null;
- }
-
- // Collect custom values: { component: { prop: [value, ...] } }
- const customValues = {};
-
- for (const [component, rules] of Object.entries(themeDef.components)) {
- for (const key of Object.keys(rules)) {
- if (key === 'base') continue;
-
- // Parse prop:value pairs from keys like 'status:neutral' or 'variant:primary+size:sm'
- const pairs = key.split('+');
- for (const pair of pairs) {
- const colonIdx = pair.indexOf(':');
- if (colonIdx === -1) continue;
- const prop = pair.slice(0, colonIdx);
- const value = pair.slice(colonIdx + 1);
-
- // It's a custom value — collect it for augmentation
- // (filtering against known values happens async in generateVariantDeclarationsAsync)
- if (!customValues[component]) customValues[component] = {};
- if (!customValues[component][prop]) customValues[component][prop] = new Set();
- customValues[component][prop].add(value);
- }
- }
- }
-
- // Sync stub — returns null, use generateVariantDeclarationsAsync instead
- return null;
-}
-
-/**
- * Async version of generateVariantDeclarations that reads known values from doc files.
+ * @returns {Promise<string|null>} TypeScript declaration content, or null if no augmentations needed
*/
async function generateVariantDeclarationsAsync(themeDef) {
if (!themeDef.components || Object.keys(themeDef.components).length === 0) {
@@ -569,33 +531,6 @@ function generateCSS(themeDef, {prose = true} = {}) {
// Prose CSS generation
// =============================================================================
-/**
- * Prose HTML element → XDS component class mappings.
- *
- * Prose maps raw HTML elements to their XDS component counterparts so that
- * plain markup (e.g. rendered markdown) inherits the component styles from
- * xds.base. The theme doesn't redefine the styles — it just aliases the
- * selectors, scoped under the theme boundary.
- */
-const PROSE_MAPPINGS = [
- // Headings
- {html: 'h1', xds: '.xds-heading.level-1'},
- {html: 'h2', xds: '.xds-heading.level-2'},
- {html: 'h3', xds: '.xds-heading.level-3'},
- {html: 'h4', xds: '.xds-heading.level-4'},
- {html: 'h5', xds: '.xds-heading.level-5'},
- {html: 'h6', xds: '.xds-heading.level-6'},
- // Text
- {html: 'p', xds: '.xds-text.body'},
- {html: 'small', xds: '.xds-text.supporting'},
- {html: 'code', xds: '.xds-text.code'},
- {html: 'pre', xds: '.xds-text.code'},
- // Standalone components
- {html: 'kbd', xds: '.xds-kbd'},
- {html: 'a', xds: '.xds-link'},
- {html: 'hr', xds: '.xds-divider'},
-];
-
/**
* Generate prose CSS — aliases raw HTML elements to XDS component classes.
*
@@ -616,10 +551,6 @@ function generateProseCSS(themeDef) {
// For now, we co-select: the component overrides in generateCSS already
// target .xds-button, .xds-card, etc. Prose adds the HTML element as
// an additional selector for component overrides that have an HTML equivalent.
- const rules = PROSE_MAPPINGS.map(
- ({html, xds}) => ` ${html} { @extend ${xds}; }`,
- );
-
// CSS @extend isn't widely supported yet. Instead, generate rules that
// reference the same token-based custom properties the components use.
// This is a thin layer — just structural resets + token references.
@@ -729,7 +660,7 @@ function extractThemeDefinitionLegacy(filePath) {
`Expected: defineTheme({ name: '...', tokens: {...} })`,
);
}
- // eslint-disable-next-line no-eval
+
return eval(`(${defaultMatch[1]})`);
}
@@ -738,12 +669,13 @@ function extractThemeDefinitionLegacy(filePath) {
objStr = objStr.replace(/icons:\s*[a-zA-Z_][a-zA-Z0-9_]*/g, 'icons: undefined');
try {
- // eslint-disable-next-line no-eval
+
return eval(`(${objStr})`);
} catch (e) {
throw new Error(
`Failed to parse theme definition in ${filePath}: ${e.message}\n` +
`Make sure the defineTheme() argument is a plain object literal.`,
+ {cause: e},
);
}
}
@@ -974,7 +906,7 @@ function validatePrivateVars(themeDef) {
for (const [component, rules] of Object.entries(themeDef.components)) {
for (const [key, styles] of Object.entries(rules)) {
- for (const [prop, value] of Object.entries(styles)) {
+ for (const prop of Object.keys(styles)) {
if (typeof prop === 'string' && prop.startsWith('--_')) {
errors.push(
`Component "${component}" (${key}) sets private var "${prop}". ` +
diff --git a/packages/cli/src/commands/component/index.mjs b/packages/cli/src/commands/component/index.mjs
index fe5ee2655a..20f9ad8263 100644
--- a/packages/cli/src/commands/component/index.mjs
+++ b/packages/cli/src/commands/component/index.mjs
@@ -6,14 +6,10 @@
* Global options: --detail full|compact|brief, --lang en|zh|dense
*/
-import {findCoreDir, discoverExternalPackages} from '../../utils/paths.mjs';
+import {findCoreDir} from '../../utils/paths.mjs';
import {
- discoverComponents,
- discoverExternalComponents,
- findComponentReadme,
resolveImportPath,
} from '../../lib/component-discovery.mjs';
-import {loadDocs} from '../../lib/component-loader.mjs';
import {
formatFull,
formatCompact,
@@ -23,7 +19,7 @@ import {
} from '../../lib/component-format.mjs';
import {resolveTheme} from '../../lib/resolve-theme.mjs';
import {getRunPrefix} from '../../utils/package-manager.mjs';
-import {jsonOut, jsonError, humanLog} from '../../lib/json.mjs';
+import {jsonOut, humanLog} from '../../lib/json.mjs';
import {cliError} from '../../lib/cli-error.mjs';
import {ERROR_CODES} from '../../lib/error-codes.mjs';
import {component as componentApi} from '../../api/component.mjs';
diff --git a/packages/cli/src/commands/discover.mjs b/packages/cli/src/commands/discover.mjs
index 1f96ce2afa..e86ec59894 100644
--- a/packages/cli/src/commands/discover.mjs
+++ b/packages/cli/src/commands/discover.mjs
@@ -11,9 +11,8 @@
*/
import {loadConfig} from '../lib/config.mjs';
-import {scanAllPackages} from '../lib/package-scanner.mjs';
import {formatFull, formatBrief, formatCompact} from '../lib/component-format.mjs';
-import {jsonOut, jsonError, humanLog} from '../lib/json.mjs';
+import {jsonOut, humanLog} from '../lib/json.mjs';
import {cliError} from '../lib/cli-error.mjs';
import {discover as discoverApi} from '../api/discover.mjs';
diff --git a/packages/cli/src/commands/docs.mjs b/packages/cli/src/commands/docs.mjs
index b35522c2ef..0634199c75 100644
--- a/packages/cli/src/commands/docs.mjs
+++ b/packages/cli/src/commands/docs.mjs
@@ -13,7 +13,7 @@
*/
import {getRunPrefix} from '../utils/package-manager.mjs';
-import {jsonOut, jsonError, humanLog} from '../lib/json.mjs';
+import {jsonOut, humanLog} from '../lib/json.mjs';
import {cliError} from '../lib/cli-error.mjs';
import {docs as docsApi} from '../api/docs.mjs';
@@ -42,8 +42,10 @@ function formatBlock(block, detail) {
case 'code':
if (detail === 'compact' || detail === 'brief') return null;
- const label = block.label ? `// ${block.label}\n` : '';
- return `\`\`\`${block.lang}\n${label}${block.code}\n\`\`\``;
+ {
+ const label = block.label ? `// ${block.label}\n` : '';
+ return `\`\`\`${block.lang}\n${label}${block.code}\n\`\`\``;
+ }
case 'table':
if (detail === 'brief') {
diff --git a/packages/cli/src/commands/hook/index.mjs b/packages/cli/src/commands/hook/index.mjs
index 9d9e929618..9cf8e9b7b6 100644
--- a/packages/cli/src/commands/hook/index.mjs
+++ b/packages/cli/src/commands/hook/index.mjs
@@ -6,9 +6,6 @@
* Global options: --detail full|compact|brief, --lang en|zh
*/
-import {findCoreDir} from '../../utils/paths.mjs';
-import {discoverHooks, findHookDoc} from '../../lib/hook-discovery.mjs';
-import {loadDocs} from '../../lib/component-loader.mjs';
import {
formatHookFull,
formatHookCompact,
@@ -16,7 +13,7 @@ import {
formatHookParams,
} from '../../lib/hook-format.mjs';
import {getRunPrefix} from '../../utils/package-manager.mjs';
-import {jsonOut, jsonError, humanLog} from '../../lib/json.mjs';
+import {jsonOut, humanLog} from '../../lib/json.mjs';
import {cliError} from '../../lib/cli-error.mjs';
import {ERROR_CODES} from '../../lib/error-codes.mjs';
import {hook as hookApi} from '../../api/hook.mjs';
@@ -64,8 +61,6 @@ export function registerHook(program) {
if (json) return jsonOut(result.type, result.data);
// ── Text output ────────────────────────────────────────────
- const coreDir = findCoreDir(process.cwd());
-
switch (result.type) {
case 'hook.list': {
// --detail brief (default for list views) — names only.
diff --git a/packages/cli/src/commands/swizzle.mjs b/packages/cli/src/commands/swizzle.mjs
index 2534e0220e..32087ca441 100644
--- a/packages/cli/src/commands/swizzle.mjs
+++ b/packages/cli/src/commands/swizzle.mjs
@@ -17,7 +17,7 @@ import * as p from '@clack/prompts';
import {findCoreDir, listComponents} from '../utils/paths.mjs';
import {assertWithin, PathSafetyError, isNonInteractive} from '../utils/path-safety.mjs';
import {isInteractive} from '../utils/interactive.mjs';
-import {jsonOut, jsonError, humanLog} from '../lib/json.mjs';
+import {jsonOut, humanLog} from '../lib/json.mjs';
import {cliError} from '../lib/cli-error.mjs';
import {ERROR_CODES} from '../lib/error-codes.mjs';
import {
diff --git a/packages/cli/src/commands/template.mjs b/packages/cli/src/commands/template.mjs
index 6830e28048..12e7a794ca 100644
--- a/packages/cli/src/commands/template.mjs
+++ b/packages/cli/src/commands/template.mjs
@@ -7,9 +7,8 @@
import * as path from 'node:path';
import * as fs from 'node:fs';
import * as p from '@clack/prompts';
-import {CLI_ROOT} from '../utils/paths.mjs';
import {isNonInteractive} from '../utils/path-safety.mjs';
-import {jsonOut, jsonError, humanLog} from '../lib/json.mjs';
+import {jsonOut, humanLog} from '../lib/json.mjs';
import {cliError} from '../lib/cli-error.mjs';
import {ERROR_CODES} from '../lib/error-codes.mjs';
import {template as templateApi, getTemplateById} from '../api/template.mjs';
diff --git a/packages/cli/src/commands/upgrade.mjs b/packages/cli/src/commands/upgrade.mjs
index 4af23db54e..aadcddd50a 100644
--- a/packages/cli/src/commands/upgrade.mjs
+++ b/packages/cli/src/commands/upgrade.mjs
@@ -123,20 +123,8 @@ function getInstallCommand(force = false) {
}
/**
- * List all available codemods across all versions.
+ * Register the `upgrade` command (codemod-driven version migration).
*/
-async function listCodemods() {
- // Walk the full registry once. The previous implementation called
- // getTransformsBetween('0.0.0', v) for every v in versions, so a codemod
- // introduced at 0.0.2 was reprinted for every version >= 0.0.2.
- const manifests = await getTransformsBetween('0.0.0', latestVersion);
- for (const {transforms} of manifests) {
- for (const {name, meta} of transforms) {
- p.log.info(` ${name} — ${meta.title} (${meta.pr})`);
- }
- }
-}
-
export function registerUpgrade(program) {
program
.command('upgrade')
diff --git a/packages/cli/src/lib/component-format.mjs b/packages/cli/src/lib/component-format.mjs
index b3d0f931a6..0f4c25fe2f 100644
--- a/packages/cli/src/lib/component-format.mjs
+++ b/packages/cli/src/lib/component-format.mjs
@@ -6,7 +6,6 @@
import {discoverComponents, findComponentReadme, resolveImportPath} from './component-discovery.mjs';
import {loadDocs} from './component-loader.mjs';
-import * as fs from 'node:fs';
/** Derive the theme component key from a theming target (strips 'xds-' prefix). */
function targetKey(target) {
@@ -222,9 +221,7 @@ export function formatFull(docs, options = {}) {
// Component CSS vars — split into public (directly settable) and private (set via derived)
if (docs.theming?.vars?.length) {
- // Private vars (--_*) are internal — set via standard CSS properties through derived expansion
const publicVars = docs.theming.vars.filter(v => !v.private && !v.derived);
- const privateVars = docs.theming.vars.filter(v => v.private || v.derived);
if (publicVars.length > 0) {
sections.push('**Themeable CSS variables** — additional properties that can be overridden in `defineTheme` component overrides.\n');
diff --git a/packages/cli/src/lib/hook-format.mjs b/packages/cli/src/lib/hook-format.mjs
index 92ad6c9c0d..45e37de152 100644
--- a/packages/cli/src/lib/hook-format.mjs
+++ b/packages/cli/src/lib/hook-format.mjs
@@ -89,7 +89,7 @@ export function formatHookFull(docs) {
if (docs.usage?.bestPractices?.length) {
sections.push('## Best Practices\n');
for (const bp of docs.usage.bestPractices) {
- const badge = bp.guidance ? '**Do:**' : "**Don\'t:**";
+ const badge = bp.guidance ? '**Do:**' : "**Don't:**";
sections.push(`- ${badge} ${bp.description}`);
}
sections.push('');
@@ -135,7 +135,7 @@ export function formatHookCompact(docs, importPath) {
if (docs.usage?.bestPractices?.length) {
sections.push('## Best Practices\n');
for (const bp of docs.usage.bestPractices) {
- const badge = bp.guidance ? '**Do:**' : "**Don\'t:**";
+ const badge = bp.guidance ? '**Do:**' : "**Don't:**";
sections.push(`- ${badge} ${bp.description}`);
}
sections.push('');
diff --git a/packages/cli/src/lib/resolve-theme.mjs b/packages/cli/src/lib/resolve-theme.mjs
index 8f996e135a..8e8b662de6 100644
--- a/packages/cli/src/lib/resolve-theme.mjs
+++ b/packages/cli/src/lib/resolve-theme.mjs
@@ -104,7 +104,7 @@ export function resolveTheme(cwd = process.cwd()) {
}
// 2. Resolve the specifier to a module
- let mod = null;
+ let mod;
if (specifier.startsWith('.') || specifier.startsWith('/')) {
// File path
diff --git a/packages/cli/src/utils/package-manager.mjs b/packages/cli/src/utils/package-manager.mjs
index 56ad337bdc..4f7d1440b4 100644
--- a/packages/cli/src/utils/package-manager.mjs
+++ b/packages/cli/src/utils/package-manager.mjs
@@ -38,7 +38,9 @@ export function detectPackageManager(targetDir = process.cwd()) {
const name = pkg.packageManager.split('@')[0];
if (KNOWN_PMS.has(name)) return name;
}
- } catch {}
+ } catch {
+ // Best-effort: unreadable/invalid package.json — keep walking up.
+ }
}
dir = path.dirname(dir);