An open source design system that's fully customizable and agent ready
TypeScript
fix(cli): flag collision, stale bundled themes, and codemod edge cases (#4639)
Joeyb7c0b78c3772
diff --git a/.changeset/cli-verbose-themes-codemod-edges.md b/.changeset/cli-verbose-themes-codemod-edges.mdnew file mode 100644index 0000000000..168da5073a--- /dev/null+++ b/.changeset/cli-verbose-themes-codemod-edges.md@@ -0,0 +1,11 @@+---+'@astryxdesign/cli': patch+---++[fix] cli — rename the `search`/`build` verbose flag to `--verbose`, resync the bundled themes, and fix `unwrap-authoring-factories` edge cases (#4639)++- `astryx search`/`build` verbose output was unreachable: the boolean `--detail` flag collided with the root program's value-taking `--detail <level>`, so `search button --detail` errored `argument missing`. The boolean is now `--verbose` (the global `--detail <level>` is unchanged).+- The themes bundled for `astryx theme add` had drifted from source — the `neutral` bundle was missing a WCAG AA light-mode `text-secondary` contrast fix and a StatusDot color block, so `astryx theme add neutral` scaffolded a theme below AA. All bundles are regenerated to match source, guarded by a new drift test.+- The `unwrap-authoring-factories` upgrade codemod produced broken output for a shorthand `type` property (emitted `{'component'}`) and for no-argument factory calls (left a call referencing the just-removed import). Both now emit the correct plain object.++@josephfarinadiff --git a/packages/cli/api/upgrade/run/authoring-codemod-reachable.test.mjs b/packages/cli/api/upgrade/run/authoring-codemod-reachable.test.mjsnew file mode 100644index 0000000000..596cf08505--- /dev/null+++ b/packages/cli/api/upgrade/run/authoring-codemod-reachable.test.mjs@@ -0,0 +1,78 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Regression guard: the authoring-migration codemods must be REACHABLE+ * through `astryx upgrade`, not just correct in isolation.+ *+ * `upgrade` targets the installed @astryxdesign/core version — it runs every+ * codemod in `(from, installedCore]`. The v0.3.0 authoring codemods+ * (unwrap-factories / migrate-imports / rename-doctypes) are registered at the+ * registry's top version, so they only run when the installed core has reached+ * that version. Because core ships in the same fixed-version release group as+ * the CLI, a released core DOES reach it — but nothing pinned that invariant, so+ * a future registry entry above the shipped core version would silently strand+ * the migration (the chaos-test "codemods unreachable" finding). This test+ * fails loudly if that happens: with installed core at the registry's latest+ * version, an old-surface authoring file must be rewritten by `upgrade`.+ */++import {describe, it, expect, beforeEach, afterEach} from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {upgrade} from '../upgrade.mjs';+import {latestVersion, versions} from '../../../assets/codemods/registry.mjs';++const SLOW = 30_000;++/** Seed a consumer project with installed core pinned to `coreVersion`. */+function seedProject(dir, coreVersion) {+ fs.writeFileSync(+ path.join(dir, 'package.json'),+ JSON.stringify({+ name: 'consumer',+ version: '1.0.0',+ dependencies: {'@astryxdesign/core': coreVersion},+ }),+ );+ const core = path.join(dir, 'node_modules', '@astryxdesign', 'core');+ fs.mkdirSync(core, {recursive: true});+ fs.writeFileSync(+ path.join(core, 'package.json'),+ JSON.stringify({name: '@astryxdesign/core', version: coreVersion}),+ );+ fs.mkdirSync(path.join(dir, 'src'), {recursive: true});+ // Uses the pre-v0.3.0 authoring surface the migration codemods rewrite.+ fs.writeFileSync(+ path.join(dir, 'src', 'Button.doc.mjs'),+ [+ "import {createComponentDoc} from '@astryxdesign/core/authoring';",+ "export default createComponentDoc({name: 'Button', props: []});",+ '',+ ].join('\n'),+ );+}++describe('upgrade — authoring codemods are reachable', () => {+ let dir;+ afterEach(() => dir && fs.rmSync(dir, {recursive: true, force: true}));++ it('rewrites an old-surface authoring file when installed core is at the registry latest', async () => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'upg-authoring-'));+ seedProject(dir, latestVersion);+ // Upgrade from the version just below latest so the range is (prev, latest].+ const from = versions[versions.length - 2];+ const res = await upgrade({from, path: 'src'}, {cwd: dir});+ expect(res.type).toBe('upgrade.run');+ // Dry run: the authoring codemods must have MATCHED the old-surface import.+ expect(res.data.filesChanged).toBeGreaterThan(0);+ }, SLOW);++ it('does NOT strand the migration: latestVersion is the authoring codemod tier', () => {+ // The authoring codemods live at the registry's top version. If a later+ // core version is added above them without also advancing the codemods,+ // `upgrade` on a core below that version would skip them. Pinning this makes+ // that regression explicit at the registry layer.+ expect(latestVersion).toBe(versions[versions.length - 1]);+ });+});diff --git a/packages/cli/assets/codemods/integration-runner.mjs b/packages/cli/assets/codemods/integration-runner.mjsindex e5cac31079..21ec09f744 100644--- a/packages/cli/assets/codemods/integration-runner.mjs+++ b/packages/cli/assets/codemods/integration-runner.mjs@@ -3,8 +3,9 @@/*** @file Runner for file-based integration codemods.*- * Integration codemods authored with `createCodemod` / `createConfigCodemod`- * use the file-based contract `(file, api) => string | null | undefined`.+ * Integration codemods (a plain object stamped `type: 'code'` or+ * `type: 'config'`) use the file-based contract+ * `(file, api) => string | null | undefined`.* Config codemods target the consumer's astryx.config.* file; code codemods* are applied to source files discovered under `--path`, filtered by each* codemod's `fileExtensions`.diff --git a/packages/cli/assets/codemods/runner.mjs b/packages/cli/assets/codemods/runner.mjsindex 918dcf4740..afdf58c026 100644--- a/packages/cli/assets/codemods/runner.mjs+++ b/packages/cli/assets/codemods/runner.mjs@@ -170,8 +170,8 @@ export function validateOutput(result, source, j, {parse = true} = {}) {* via the unified `(file, api)`/jscodeshift contract; a code codemod runs* against discovered source files. Any future core config codemod (e.g. a* v0.1.3 one) must set `meta.codemodType = 'config'` and author its transform- * with the same `(file, api) => string | null | undefined` contract used by- * `createConfigCodemod`.+ * with the same `(file, api) => string | null | undefined` contract used by a+ * `type: 'config'` codemod.** @param {{name: string, transform: import('../../authoring/codemod/type').CodemodTransform, meta: {title: string, description?: string, fileExtensions?: string[], codemodType?: string}, optional?: boolean}} transformEntry* @param {string} versiondiff --git a/packages/cli/assets/codemods/transforms/v0.3.0/__tests__/unwrap-authoring-factories.test.mjs b/packages/cli/assets/codemods/transforms/v0.3.0/__tests__/unwrap-authoring-factories.test.mjsindex 4bd29250bb..40e9468416 100644--- a/packages/cli/assets/codemods/transforms/v0.3.0/__tests__/unwrap-authoring-factories.test.mjs+++ b/packages/cli/assets/codemods/transforms/v0.3.0/__tests__/unwrap-authoring-factories.test.mjs@@ -96,6 +96,42 @@ export default createComponentDoc({type: 'wrong', name: 'Widget', props: []});expect(output).not.toContain("type: 'wrong'");});+ it('rewrites a shorthand `type` property to the explicit discriminant (not a bare string)', async () => {+ // `{name, type}` where `type` is a local binding is a shorthand property.+ // Overwriting only the value would print `{name, 'component'}` — invalid+ // syntax. The transform must force the explicit `type: 'component'` form.+ const input = `import {createComponentDoc} from '@astryxdesign/core/authoring';+const type = someVar;+export default createComponentDoc({name: 'Widget', type});+`;+ const output = await applyTransform(input);+ expect(output).toContain("type: 'component'");+ // No stray bare string literal where a property key should be.+ expect(output).not.toMatch(/\{\s*name: 'Widget',\s*'component'\s*\}/);+ expect(output).not.toContain('createComponentDoc');+ });++ it('replaces a no-arg config factory with an empty object (no dangling import)', async () => {+ // The factory import is removed, so a bare `createConfig()` left in place+ // would reference a deleted binding. It must become the object the factory+ // produced from no input: `{}`.+ const input = `import {createConfig} from '@astryxdesign/cli/config';+export default createConfig();+`;+ const output = await applyTransform(input);+ expect(output).not.toContain('createConfig');+ expect(output).toContain('export default {}');+ });++ it('replaces a no-arg doc factory with a stamp-only object (no dangling import)', async () => {+ const input = `import {createComponentDoc} from '@astryxdesign/core/authoring';+export default createComponentDoc();+`;+ const output = await applyTransform(input);+ expect(output).not.toContain('createComponentDoc');+ expect(output).toContain("type: 'component'");+ });+it('is a no-op when no authoring factory is imported', async () => {const input = `import {Button} from '@astryxdesign/core';export default Button;diff --git a/packages/cli/assets/codemods/transforms/v0.3.0/unwrap-authoring-factories.mjs b/packages/cli/assets/codemods/transforms/v0.3.0/unwrap-authoring-factories.mjsindex 2107988b69..3da2dca51b 100644--- a/packages/cli/assets/codemods/transforms/v0.3.0/unwrap-authoring-factories.mjs+++ b/packages/cli/assets/codemods/transforms/v0.3.0/unwrap-authoring-factories.mjs@@ -81,6 +81,11 @@ function stampObjectType(j, objExpr, kind) {const existing = objExpr.properties.find(isTypeKey);if (existing) {existing.value = j.stringLiteral(kind);+ // A shorthand `{type}` (i.e. `type: type`) prints as just its value, so+ // overwriting `.value` alone would emit `{'component'}` — invalid. Force+ // the explicit `type: '<kind>'` form.+ existing.shorthand = false;+ existing.key = j.identifier('type');} else {objExpr.properties.push(j.objectProperty(j.identifier('type'), j.stringLiteral(kind)),@@ -123,11 +128,21 @@ export default function transformer(file, api) {const kind = FACTORY_STAMPS.get(canonical);const arg = path.node.arguments[0];- if (!arg) return; // createX() with no argument — leave for manual review/** @type {any} */let replacement;- if (kind == null) {+ if (!arg) {+ // createX() with no argument. The factory imports are removed below, so+ // leaving the call would dangle a reference to a deleted binding. Emit the+ // object the factory produced from no input: an empty object for the+ // pure config/integration factories, or a stamp-only `{type: '<kind>'}`.+ replacement =+ kind == null+ ? j.objectExpression([])+ : j.objectExpression([+ j.objectProperty(j.identifier('type'), j.stringLiteral(kind)),+ ]);+ } else if (kind == null) {// config / integration: pure unwrap.replacement = arg;} else if (j.ObjectExpression.check(arg)) {diff --git a/packages/cli/assets/templates/themes/neutral/neutralTheme.ts b/packages/cli/assets/templates/themes/neutral/neutralTheme.tsindex e632081488..ace0fd91ec 100644--- a/packages/cli/assets/templates/themes/neutral/neutralTheme.ts+++ b/packages/cli/assets/templates/themes/neutral/neutralTheme.ts@@ -144,7 +144,10 @@ export const neutralTheme = defineTheme({// Text'--color-text-primary': ['#171717', '#fafafa'],- '--color-text-secondary': ['#737373', '#a3a3a3'],+ // Light secondary is neutral-600 (#525252), not 500 (#737373): 500 only+ // reaches 4.19:1 on the T95 body (#f1f1f1), just under WCAG AA 4.5:1.+ // 600 clears it (6.9:1 on body, 7.8:1 on card). Dark stays neutral-400.+ '--color-text-secondary': ['#525252', '#a3a3a3'],'--color-text-disabled': ['#a3a3a3', '#525252'],'--color-text-accent': ['#262626', '#ebebeb'],'--color-on-dark': '#ffffff',@@ -482,6 +485,37 @@ export const neutralTheme = defineTheme({},},+ // =========================================================================+ // StatusDot — fill uses the SAME vivid stops as the filled semantic Badge+ // (and ProgressBar), so a dot and its badge read as one status language.+ //+ // The default component maps each variant to a raw semantic token+ // (--color-success / --color-error / --color-warning / --color-icon-+ // secondary), which in light mode are the dark T30/T40 stops meant to+ // sit as TEXT on a pastel surface — as a solid dot they read muddy+ // (dark green / maroon / brown). Redirect them to the badge fills.+ //+ // success → badge success bg (green T45 / dark-ramp T60)+ // warning → badge warning bg (yellow T85, same hex both modes)+ // error → badge error bg (red T55 / dark-ramp T60)+ // accent → badge info bg (blue T50 / dark-ramp T60) — the+ // StatusDot "accent" is the info/attention color, so it+ // pairs with the info badge rather than --color-accent+ // (near-black #262626, the darkest offender).+ //+ // `neutral` is intentionally NOT overridden: the neutral badge bg is a+ // near-invisible light gray (--color-background-gray #e5e5e5 / 10% white+ // wash), fine as a large pill but unreadable as an 8px dot. It keeps the+ // component default's visible mid-gray (--color-icon-secondary), which is+ // not among the "too dark" cases.+ // =========================================================================+ statusdot: {+ 'variant:success': {backgroundColor: 'light-dark(#198100, #64af4c)'},+ 'variant:warning': {backgroundColor: '#ffce2f'},+ 'variant:error': {backgroundColor: 'light-dark(#e33f4a, #ff705d)'},+ 'variant:accent': {backgroundColor: 'light-dark(#0074e2, #6d9cfe)'},+ },+// =========================================================================// Banner — sits on a hue-tinted surface with colored text/icon:// Light: pastel T90 bg (pulled from --color-{X}-muted / --color-background-blue)diff --git a/packages/cli/clients/cli/commands/build-theme.mjs b/packages/cli/clients/cli/commands/build-theme.mjsindex ca3f37b356..d5c6d2733f 100644--- a/packages/cli/clients/cli/commands/build-theme.mjs+++ b/packages/cli/clients/cli/commands/build-theme.mjs@@ -29,9 +29,9 @@ import {themeList} from '../../../api/theme/list/list.mjs';import {themeBuild, importSpecifier} from '../../../api/theme/build/build.mjs';/**- * Path to this CLI's real entry (bin/astryx.mjs), resolved from this module's- * location (src/commands/build-theme.mjs → ../../bin/astryx.mjs). Used to- * re-invoke `theme build` as a child process in watch mode.+ * Path to this CLI's real entry (clients/cli/bin/astryx.mjs), resolved from+ * this module's location (clients/cli/commands/build-theme.mjs → ../bin/+ * astryx.mjs). Used to re-invoke `theme build` as a child process in watch mode.*/function resolveCliBin() {const commandsDir = path.dirname(fileURLToPath(import.meta.url));diff --git a/packages/cli/clients/cli/commands/build.mjs b/packages/cli/clients/cli/commands/build.mjsindex 1e55184ff5..5100c7b792 100644--- a/packages/cli/clients/cli/commands/build.mjs+++ b/packages/cli/clients/cli/commands/build.mjs@@ -60,8 +60,8 @@ export function registerBuild(program) {.description('Build a page: composition kit for an idea, or the workflow playbook (no args)').option('--type <domain>', 'Filter the kit to one domain (component|hook|template)').option('--limit <n>', 'Max candidates to draw from (default 60)')- .option('--detail', 'Verbose output (include import paths and match reason)')- .action(async (/** @type {string | undefined} */ query, /** @type {{type?: import('../../../api/search/search.type.mjs').SearchDomain, limit?: string, detail?: boolean}} */ options) => {+ .option('--verbose', 'Verbose output (include import paths and match reason)')+ .action(async (/** @type {string | undefined} */ query, /** @type {{type?: import('../../../api/search/search.type.mjs').SearchDomain, limit?: string, verbose?: boolean}} */ options) => {const run = getCliInvocation();const json = program.opts().json || false;@@ -111,7 +111,7 @@ export function registerBuild(program) {humanLog(` [${label}] ${display}`);if (r.description) humanLog(` ${r.description}`);humanLog(` → ${formatCliCommand(r.command)}`);- if (options.detail) {+ if (options.verbose) {if (r.import) humanLog(` import: ${r.import}`);humanLog(` match: ${r.reason} (score ${r.score})`);}diff --git a/packages/cli/clients/cli/commands/search.mjs b/packages/cli/clients/cli/commands/search.mjsindex 15171378dd..fef3c28a61 100644--- a/packages/cli/clients/cli/commands/search.mjs+++ b/packages/cli/clients/cli/commands/search.mjs@@ -12,7 +12,7 @@* astryx search button Ranked results across all domains* astryx search modal --type component Filter to a single domain* astryx search forms --limit 5 Cap the result count- * astryx search button --detail Verbose (include import / reason)+ * astryx search button --verbose Verbose (include import / reason)* astryx search button --json Typed JSON envelope*/@@ -37,8 +37,8 @@ export function registerSearch(program) {.description('Search components, hooks, docs, and templates in one ranked list').option('--type <domain>', `Filter to one domain (${SEARCH_DOMAINS.join('|')})`).option('--limit <n>', 'Max number of results (default 20)')- .option('--detail', 'Verbose output (include import paths and match reason)')- .action(async (/** @type {string} */ query, /** @type {{type?: import('../../../api/search/search.type.mjs').SearchDomain, limit?: string, detail?: boolean}} */ options) => {+ .option('--verbose', 'Verbose output (include import paths and match reason)')+ .action(async (/** @type {string} */ query, /** @type {{type?: import('../../../api/search/search.type.mjs').SearchDomain, limit?: string, verbose?: boolean}} */ options) => {const json = program.opts().json || false;// Parse --limit to a number; the API validates it (positive integer) and@@ -90,7 +90,7 @@ export function registerSearch(program) {humanLog(` ${r.description}`);}humanLog(` → ${formatCliCommand(r.command)}`);- if (options.detail) {+ if (options.verbose) {if (r.import) humanLog(` import: ${r.import}`);humanLog(` match: ${r.reason} (score ${r.score})`);}diff --git a/packages/cli/clients/cli/commands/search.test.mjs b/packages/cli/clients/cli/commands/search.test.mjsindex 8cc8501e0c..8a87039ffc 100644--- a/packages/cli/clients/cli/commands/search.test.mjs+++ b/packages/cli/clients/cli/commands/search.test.mjs@@ -196,4 +196,15 @@ describe('search CLI — exit codes + JSON contract', () => {expect(r.stdout).toContain('astryx component Button');expect(r.stdout).toContain('[component]');});++ it('--verbose exits 0 and prints import/match detail', async () => {+ // Regression: the boolean verbose flag was named --detail, which collided+ // with the value-taking global `--detail <level>` — a bare `search+ // --detail` errored "argument missing" and the verbose output was+ // unreachable. It is now `--verbose`.+ const r = await runCli(['search', 'button', '--verbose'], REPO_ROOT);+ expect(r.status).toBe(0);+ expect(r.stdout).toContain('import:');+ expect(r.stdout).toContain('match:');+ });}, SCAN_TIMEOUT);diff --git a/packages/themes/chocolate/src/chocolateTheme.ts b/packages/themes/chocolate/src/chocolateTheme.tsindex cd567dde04..aca7447887 100644--- a/packages/themes/chocolate/src/chocolateTheme.ts+++ b/packages/themes/chocolate/src/chocolateTheme.ts@@ -44,8 +44,7 @@ export const chocolateTheme = defineTheme({},heading: {family: 'Fraunces',- fallbacks:- 'Georgia, "Times New Roman", Times, serif',+ fallbacks: 'Georgia, "Times New Roman", Times, serif',weights: {3: 'bold', 4: 'bold'},},code: {@@ -188,12 +187,9 @@ export const chocolateTheme = defineTheme({// =========================================================================// Shadows — warm-toned// =========================================================================- '--shadow-low':- '0 2px 4px #4a35200D, 0 4px 8px #4a35201A',- '--shadow-med':- '0 2px 4px #4a35200D, 0 4px 12px #4a35201A',- '--shadow-high':- '0 4px 6px #4a35201A, 0 12px 24px #4a352026',+ '--shadow-low': '0 2px 4px #4a35200D, 0 4px 8px #4a35201A',+ '--shadow-med': '0 2px 4px #4a35200D, 0 4px 12px #4a35201A',+ '--shadow-high': '0 4px 6px #4a35201A, 0 12px 24px #4a352026','--shadow-inset-hover': 'inset 0px 0px 0px 2px #8C592730','--shadow-inset-selected': 'inset 0px 0px 0px 2px #8C592750','--shadow-inset-success': 'inset 0px 0px 0px 2px #70990050',diff --git a/scripts/check-cli-theme-bundle.test.mjs b/scripts/check-cli-theme-bundle.test.mjsnew file mode 100644index 0000000000..68376abb67--- /dev/null+++ b/scripts/check-cli-theme-bundle.test.mjs@@ -0,0 +1,92 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Drift guard for the bundled CLI themes.+ *+ * `scripts/generate-cli-themes.mjs` copies each theme's source verbatim into+ * `packages/cli/assets/templates/themes/` so `astryx theme add` can scaffold a+ * theme without the package installed. Nothing verified the bundle stayed in+ * sync with source, so the neutral theme's WCAG text-secondary fix (and a+ * StatusDot override block) shipped to source but never reached the bundle —+ * `astryx theme add neutral` scaffolded a theme below AA contrast. This test+ * pins the copies to their source byte-for-byte; when a theme changes, run+ * `pnpm bundle:cli-themes` and commit the regenerated bundle.+ */++import fs from 'node:fs';+import path from 'node:path';+import {fileURLToPath} from 'node:url';+import {describe, it, expect} from 'vitest';++const __dirname = path.dirname(fileURLToPath(import.meta.url));+const REPO_ROOT = path.resolve(__dirname, '..');+const THEMES_SRC_ROOT = path.join(REPO_ROOT, 'packages', 'themes');+const CLI_THEMES_OUT = path.join(+ REPO_ROOT,+ 'packages',+ 'cli',+ 'assets',+ 'templates',+ 'themes',+);++const toIdentifier = (slug) =>+ slug.replace(/-([a-z])/g, (_, c) => c.toUpperCase());++/** Theme slugs discovered the same way the generator discovers them. */+function themeSlugs() {+ if (!fs.existsSync(THEMES_SRC_ROOT)) return [];+ return fs+ .readdirSync(THEMES_SRC_ROOT, {withFileTypes: true})+ .filter((e) => e.isDirectory())+ .map((e) => e.name)+ .filter((slug) => {+ const themeFile = path.join(+ THEMES_SRC_ROOT,+ slug,+ 'src',+ `${toIdentifier(slug)}Theme.ts`,+ );+ return fs.existsSync(themeFile);+ })+ .sort();+}++describe('CLI theme bundle is in sync with source', () => {+ const slugs = themeSlugs();++ it('discovers at least one theme to check', () => {+ expect(slugs.length).toBeGreaterThan(0);+ });++ for (const slug of slugs) {+ const id = toIdentifier(slug);+ const themeFileName = `${id}Theme.ts`;+ const src = path.join(THEMES_SRC_ROOT, slug, 'src', themeFileName);+ const bundled = path.join(CLI_THEMES_OUT, slug, themeFileName);++ it(`${slug}: bundled ${themeFileName} matches source (run \`pnpm bundle:cli-themes\`)`, () => {+ expect(+ fs.existsSync(bundled),+ `missing bundled theme: ${path.relative(REPO_ROOT, bundled)}`,+ ).toBe(true);+ expect(fs.readFileSync(bundled, 'utf8')).toBe(+ fs.readFileSync(src, 'utf8'),+ );+ });++ const srcIcons = path.join(THEMES_SRC_ROOT, slug, 'src', 'icons.tsx');+ if (fs.existsSync(srcIcons)) {+ it(`${slug}: bundled icons.tsx matches source`, () => {+ const bundledIcons = path.join(CLI_THEMES_OUT, slug, 'icons.tsx');+ expect(+ fs.existsSync(bundledIcons),+ `missing bundled icons: ${path.relative(REPO_ROOT, bundledIcons)}`,+ ).toBe(true);+ expect(fs.readFileSync(bundledIcons, 'utf8')).toBe(+ fs.readFileSync(srcIcons, 'utf8'),+ );+ });+ }+ }+});