An open source design system that's fully customizable and agent ready
TypeScript
[CLI] Keep the doctor themes check beside the app-theme checks (#7179)
Joeyd78473fcbc6d
diff --git a/.changeset/doctor-keeps-themes-check.md b/.changeset/doctor-keeps-themes-check.mdnew file mode 100644index 0000000000..dfc5c39865--- /dev/null+++ b/.changeset/doctor-keeps-themes-check.md@@ -0,0 +1,9 @@+---+'@astryxdesign/cli': patch+---++[fix] `astryx doctor` keeps its `themes` check, with the same id, label and fields, beside the new theme checks, so scripts that read it by id keep working. Without a generated theme module it reports what it did before: whether an `@astryxdesign/theme-*` package is installed, and whether the app's package.json names a theme in `astryx.theme`. Its fix now names `theme add --import`. With a generated module it reports the overall result of the theme checks.++In a workspace, `themes` reads the app's own package.json, the file the CLI reads when it resolves the theme, rather than the package.json beside the root `node_modules`. It no longer counts the `ASTRYX_THEME` variable, which the CLI does not read, as a wired theme.++@josephfarinadiff --git a/.changeset/theme-import-names-package.md b/.changeset/theme-import-names-package.mdindex b4589ce432..89858b15c6 100644--- a/.changeset/theme-import-names-package.md+++ b/.changeset/theme-import-names-package.md@@ -6,6 +6,6 @@`astryx theme add --list` keeps its JSON. Its text now names `theme add <slug> --import` to use a theme and `theme eject <slug>` to fork one, instead of the deprecated copy form.-`astryx doctor`'s `themes` check is now `theme-management`, with focused `theme-*` checks beside it once a project has a generated theme module.+`astryx doctor` adds a `theme-management` check, and focused `theme-*` checks once a project has a generated theme module.@josephfarinadiff --git a/packages/cli/api/doctor/_adapter.mjs b/packages/cli/api/doctor/_adapter.mjsindex 07f46b567a..8485273086 100644--- a/packages/cli/api/doctor/_adapter.mjs+++ b/packages/cli/api/doctor/_adapter.mjs@@ -132,6 +132,54 @@ export function findDoctorInstalledPackage(projectDir, packageName) {return findInstalledPackage(projectDir, packageName);}+/**+ * Names of the `@astryxdesign/theme-*` packages installed in the nearest+ * `node_modules` at or above `cwd`, looking up to six levels.+ * @param {string} cwd+ * @returns {string[]}+ */+export function listDoctorThemePackages(cwd) {+ let dir = path.resolve(cwd);+ let nodeModules = null;+ for (let level = 0; level < 6; level++) {+ const candidate = path.join(dir, 'node_modules');+ if (fs.existsSync(candidate)) {+ nodeModules = candidate;+ break;+ }+ const parent = path.dirname(dir);+ if (parent === dir) break;+ dir = parent;+ }+ if (!nodeModules) return [];+ const scopeDir = path.join(nodeModules, '@astryxdesign');+ let entries;+ try {+ entries = fs.readdirSync(scopeDir, {withFileTypes: true});+ } catch {+ return [];+ }+ /** @type {string[]} */+ const names = [];+ for (const entry of entries) {+ if (!entry.name.startsWith('theme-')) continue;+ // pnpm links packages into node_modules/.pnpm, and a symlink entry does+ // not report itself as a directory, so check what it points to.+ let isDirectory = entry.isDirectory();+ if (!isDirectory && entry.isSymbolicLink()) {+ try {+ isDirectory = fs+ .statSync(path.join(scopeDir, entry.name))+ .isDirectory();+ } catch {+ isDirectory = false;+ }+ }+ if (isDirectory) names.push(`@astryxdesign/${entry.name}`);+ }+ return names;+}+/** @param {string} file */export function readPackageJson(file) {try {diff --git a/packages/cli/api/doctor/doctor.mjs b/packages/cli/api/doctor/doctor.mjsindex 1b598a3db3..d023cd3e95 100644--- a/packages/cli/api/doctor/doctor.mjs+++ b/packages/cli/api/doctor/doctor.mjs@@ -50,7 +50,7 @@ import {import {typedEdges} from '../docs/node/node.mjs';import {detailView, indexView} from '../../foundation/doc-compiler/lenses.mjs';import {semverCompare, isValidSemver, satisfiesRange} from '../../foundation/env/semver.mjs';-import {checkAppThemes} from './theme-checks.mjs';+import {checkAppThemes, checkThemes} from './theme-checks.mjs';/*** @typedef {'pass'|'warn'|'fail'|'info'} DoctorStatus@@ -1197,11 +1197,13 @@ export async function runChecks(options = {}) {/** @type {DoctorCheck[]} */const checks = [];- // Run the app-theme checks and config check after the environment checks.+ // Run the theme checks and config check after the environment checks. The+ // released `themes` check keeps its place, ahead of the app-theme checks.for (const fn of SYNC_CHECKS) {checks.push(fn(ctx));if (fn === checkVersionAlignment) {- checks.push(...(await checkAppThemes(cwd)));+ const appThemeChecks = await checkAppThemes(cwd);+ checks.push(checkThemes(cwd, appThemeChecks), ...appThemeChecks);checks.push(await checkConfig(ctx));}}diff --git a/packages/cli/api/doctor/theme-checks.mjs b/packages/cli/api/doctor/theme-checks.mjsindex 2b71c0fc32..da307d37df 100644--- a/packages/cli/api/doctor/theme-checks.mjs+++ b/packages/cli/api/doctor/theme-checks.mjs@@ -17,6 +17,7 @@ import {findDoctorCoreDir,findDoctorInstalledPackage,isLocalThemeOwner,+ listDoctorThemePackages,listProjectSourceFiles,planThemeAppWrite,readPackageJson,@@ -52,6 +53,8 @@ const CHECKS = [['theme-global-rules', 'Cross-theme global CSS rules'],];+const APP_THEME_CHECK_IDS = new Set(CHECKS.map(([id]) => id));+/*** @param {string} message* @param {Error|null} [moduleError]@@ -385,6 +388,117 @@ function unmigratedCopyCheck(projectDir) {};}+/**+ * Whether the app's package.json names a theme in `astryx.theme`.+ * @param {string} cwd+ */+function appPackageNamesTheme(cwd) {+ let state;+ try {+ state = readThemeState(cwd);+ } catch {+ return false;+ }+ const pkg = readPackageJson(state.packageFile);+ return Boolean(pkg?.astryx?.theme);+}++/**+ * The `themes` check that every released doctor report carries. Its id is+ * stable, so it stays beside the app-theme checks. Without a generated theme+ * module it reports what it always has: whether an `@astryxdesign/theme-*`+ * package is installed, and whether the app's package.json names a theme in+ * `astryx.theme`. With a generated module it reports the overall result of the+ * app-theme checks.+ * @param {string} cwd+ * @param {DoctorCheck[]} appChecks - the checks {@link checkAppThemes} returned+ * @returns {DoctorCheck}+ */+export function checkThemes(cwd, appChecks) {+ const label = 'Theme packages';+ const managed = appChecks.some(+ check => APP_THEME_CHECK_IDS.has(check.id) && check.status !== 'info',+ );+ if (managed) {+ // A check passes only on its own evidence, so the rollup passes only when+ // every check it summarizes passed. An `info` result here means a check+ // could not prove its evidence.+ const needsWork = appChecks.filter(+ check => check.status === 'fail' || check.status === 'warn',+ );+ const unproven = appChecks.filter(check => check.status === 'info');+ if (needsWork.length > 0) {+ const ids = needsWork.map(check => check.id).join(', ');+ return {+ id: 'themes',+ label,+ status: needsWork.some(check => check.status === 'fail')+ ? 'fail'+ : 'warn',+ message:+ needsWork.length === 1+ ? `One theme check needs attention: ${ids}.`+ : `${needsWork.length} theme checks need attention: ${ids}.`,+ fix:+ needsWork.length === 1+ ? `Follow the fix on the ${ids} check.`+ : `Follow the fix on each of these checks: ${ids}.`,+ };+ }+ if (unproven.length > 0) {+ const ids = unproven.map(check => check.id).join(', ');+ return {+ id: 'themes',+ label,+ status: 'info',+ message:+ unproven.length === 1+ ? `One theme check could not prove its result: ${ids}.`+ : `${unproven.length} theme checks could not prove their results: ${ids}.`,+ fix:+ unproven.length === 1+ ? `See the ${ids} check.`+ : `See each of these checks: ${ids}.`,+ };+ }+ return {+ id: 'themes',+ label,+ status: 'pass',+ message:+ 'App themes come from the generated theme module, and every theme check passes.',+ };+ }++ const run = getCliInvocation(cwd);+ const packages = listDoctorThemePackages(cwd);+ if (packages.length === 0) {+ return {+ id: 'themes',+ label,+ status: 'warn',+ message: 'No @astryxdesign/theme-* packages are installed.',+ fix: `Install a theme, e.g. \`npm install @astryxdesign/theme-neutral\`, then add it to the app with \`${run} theme add neutral --import\`.`,+ };+ }+ const names = packages.join(', ');+ if (!appPackageNamesTheme(cwd)) {+ return {+ id: 'themes',+ label,+ status: 'warn',+ message: `Theme package(s) installed (${names}) but no theme appears wired.`,+ fix: `Add one to the app with \`${run} theme add <slug> --import\`.`,+ };+ }+ return {+ id: 'themes',+ label,+ status: 'pass',+ message: `Theme package(s) installed (${names}); wired via package.json astryx.theme.`,+ };+}+/*** Run all ten app-theme checks.* @param {string} cwddiff --git a/packages/cli/api/doctor/theme-checks.test.mjs b/packages/cli/api/doctor/theme-checks.test.mjsindex a03dc7e4b8..4034f3ae4d 100644--- a/packages/cli/api/doctor/theme-checks.test.mjs+++ b/packages/cli/api/doctor/theme-checks.test.mjs@@ -6,7 +6,8 @@ import {afterEach, describe, expect, it} from 'vitest';import * as fs from 'node:fs';import * as path from 'node:path';import {spawnSync} from 'node:child_process';-import {checkAppThemes} from './theme-checks.mjs';+import {checkAppThemes, checkThemes} from './theme-checks.mjs';+import {runChecks} from './doctor.mjs';import {themeAdd} from '../theme/add/add.mjs';import {themeEject} from '../theme/eject/eject.mjs';import {themeBuild} from '../theme/build/build.mjs';@@ -140,6 +141,146 @@ afterEach(() => {}});+describe('the released themes check', () => {+ /** @param {string} name */+ function emptyApp(name) {+ const dir = fs.mkdtempSync(+ path.join(process.cwd(), `.astryx-doctor-${name}-`),+ );+ dirs.push(dir);+ write(path.join(dir, 'package.json'), '{"name":"app","private":true}\n');+ return dir;+ }++ /** @param {string} dir @param {string} slug */+ function installThemePackage(dir, slug) {+ write(+ path.join(+ dir,+ 'node_modules/@astryxdesign',+ `theme-${slug}`,+ 'package.json',+ ),+ JSON.stringify({name: `@astryxdesign/theme-${slug}`, version: '1.0.0'}),+ );+ }++ it('keeps its released id, label, fields, and statuses without a generated theme module', async () => {+ const dir = emptyApp('themes-none');+ expect(checkThemes(dir, await checkAppThemes(dir))).toEqual({+ id: 'themes',+ label: 'Theme packages',+ status: 'warn',+ message: 'No @astryxdesign/theme-* packages are installed.',+ fix: expect.stringContaining('theme add neutral --import'),+ });++ installThemePackage(dir, 'neutral');+ const unwired = checkThemes(dir, await checkAppThemes(dir));+ expect(unwired).toEqual({+ id: 'themes',+ label: 'Theme packages',+ status: 'warn',+ message:+ 'Theme package(s) installed (@astryxdesign/theme-neutral) but no theme appears wired.',+ fix: expect.stringContaining('theme add <slug> --import'),+ });+ expect(unwired.fix).not.toContain('ASTRYX_THEME');++ write(+ path.join(dir, 'package.json'),+ JSON.stringify({+ name: 'app',+ private: true,+ astryx: {theme: '@astryxdesign/theme-neutral'},+ }),+ );+ expect(checkThemes(dir, await checkAppThemes(dir))).toEqual({+ id: 'themes',+ label: 'Theme packages',+ status: 'pass',+ message:+ 'Theme package(s) installed (@astryxdesign/theme-neutral); wired via package.json astryx.theme.',+ });+ });++ it('reports the overall result of the app-theme checks with a generated module', async () => {+ const healthy = await fixture();+ expect(checkThemes(healthy.dir, await checkAppThemes(healthy.dir))).toEqual(+ {+ id: 'themes',+ label: 'Theme packages',+ status: 'pass',+ message:+ 'App themes come from the generated theme module, and every theme check passes.',+ },+ );++ // A module is loaded once per process, so the broken one is a new fixture.+ const {dir, packageDir} = await fixture();+ write(+ path.join(packageDir, 'dist/ocean.js'),+ `import '@acme/definitely-missing-dep';\nexport const oceanTheme = {name: 'ocean', tokens: {}};\n`,+ );+ expect(checkThemes(dir, await checkAppThemes(dir))).toEqual({+ id: 'themes',+ label: 'Theme packages',+ status: 'fail',+ message: 'One theme check needs attention: theme-owners.',+ fix: 'Follow the fix on the theme-owners check.',+ });+ }, 30_000);++ it('passes the module rollup only when every summarized check passed', () => {+ /** @param {string} id @param {'pass'|'warn'|'fail'|'info'} status */+ const result = (id, status) => ({id, label: id, status, message: id});+ const passing = [+ result('theme-owners', 'pass'),+ result('theme-module', 'pass'),+ ];++ expect(+ checkThemes(process.cwd(), [+ ...passing,+ result('theme-stylesheet-imports', 'info'),+ ]),+ ).toEqual({+ id: 'themes',+ label: 'Theme packages',+ status: 'info',+ message:+ 'One theme check could not prove its result: theme-stylesheet-imports.',+ fix: 'See the theme-stylesheet-imports check.',+ });+ expect(+ checkThemes(process.cwd(), [+ result('theme-owners', 'fail'),+ result('theme-module', 'pass'),+ result('theme-fonts', 'warn'),+ result('theme-global-rules', 'info'),+ ]),+ ).toMatchObject({+ status: 'fail',+ message: '2 theme checks need attention: theme-owners, theme-fonts.',+ });+ expect(checkThemes(process.cwd(), passing)).toMatchObject({+ status: 'pass',+ });+ });++ it('appears once in the doctor report, right after version alignment, with and without a module', async () => {+ const {dir} = await fixture();+ for (const cwd of [emptyApp('themes-report'), dir]) {+ const ids = (await runChecks({cwd})).checks.map(item => item.id);+ expect(ids.filter(id => id === 'themes')).toHaveLength(1);+ expect(ids.indexOf('themes')).toBe(ids.indexOf('version-alignment') + 1);+ expect(ids.indexOf('themes')).toBeLessThan(+ ids.findIndex(id => id === 'theme-management' || id === 'theme-owners'),+ );+ }+ }, 30_000);+});+describe('app-theme doctor checks', () => {it('returns ten positive passes for a healthy package theme', async () => {const {dir} = await fixture();diff --git a/packages/cli/clients/cli/commands/doctor.doc.mjs b/packages/cli/clients/cli/commands/doctor.doc.mjsindex 00611df301..6d75f0caa4 100644--- a/packages/cli/clients/cli/commands/doctor.doc.mjs+++ b/packages/cli/clients/cli/commands/doctor.doc.mjs@@ -16,7 +16,7 @@ export const doc = {summary: 'Diagnose Astryx projects and integration packages',description:'Runs read-only project health diagnostics by default: Node version, @astryxdesign/core ' +- 'install and version alignment, generated app themes when present, earlier copied-theme migration, config, integrations (linked without a config entry, ' ++ 'install and version alignment, theme packages, generated app themes when present, earlier copied-theme migration, config, integrations (linked without a config entry, ' +'provider identity, contribution issues), agent docs, core peer dependencies, package manager, ' +"and the docs the CLI reads. It writes nothing, but loading astryx.config runs that file's code. " +'The `integration` subcommands provide authoring checks for one integration package.',