Skip to content

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

TypeScript

fix(cli): `theme build` in an app uses the app's installed Core (#6962)

Joey5d9940d147e6
diff --git a/.changeset/theme-build-uses-the-app-core.md b/.changeset/theme-build-uses-the-app-core.md
new file mode 100644
index 0000000000..dc8eb1ec64
--- /dev/null
+++ b/.changeset/theme-build-uses-the-app-core.md
@@ -0,0 +1,9 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] `astryx theme build` in an app uses the app's installed `@astryxdesign/core`, and says to install Core when there is none.
+
+Run one-off with `npx @astryxdesign/cli`, it failed with "Build @astryxdesign/core first (e.g. `pnpm -F @astryxdesign/core build`)" even when the app had Core installed, because it looked for Core only next to the CLI. It now generates with the Core the project installed, the same Core the app's `<Theme>` runs on. In an app without Core, the error now says to install it (`npm install @astryxdesign/core`). The build command stays only for the Astryx repository itself. The error code (`ERR_CORE_NOT_FOUND`) is unchanged.
+
+@josephfarina
diff --git a/packages/cli/api/theme/build/build.mjs b/packages/cli/api/theme/build/build.mjs
index a060bf3d2b..8d09263a69 100644
--- a/packages/cli/api/theme/build/build.mjs
+++ b/packages/cli/api/theme/build/build.mjs
@@ -45,7 +45,11 @@ import {fileURLToPath, pathToFileURL} from 'node:url';
import {parse} from '@babel/parser';
import {createJiti} from 'jiti';
import {getCliInvocation} from '../../../foundation/env/package-manager.mjs';
-import {CLI_ROOT, findCoreDir} from '../../../foundation/fs/paths.mjs';
+import {
+ CLI_ROOT,
+ findCoreDir,
+ findInstalledPackage,
+} from '../../../foundation/fs/paths.mjs';
import {
assertWithin,
sanitizeName,
@@ -125,6 +129,232 @@ try {
_coreImportError = e;
}
+/**
+ * The bindings one Core provides: the namespaces interception spreads, the
+ * functions the build calls, and why the import failed, if it did.
+ * @typedef {{
+ * themeModule: any,
+ * rootModule: any,
+ * importError: any,
+ * defineTheme: any,
+ * generateThemeRulesSplit: any,
+ * generateOnMediaCSS: any,
+ * generateAdaptationCSS: any,
+ * dataTokenDefaults: any,
+ * }} CoreBindings
+ */
+
+/**
+ * The bindings exactly as the CLI's own import left them, kept so each build
+ * can choose between them and the project's installed Core.
+ * @type {CoreBindings}
+ */
+const _cliCore = {
+ themeModule: _coreThemeModule,
+ rootModule: _coreRootModule,
+ importError: _coreImportError,
+ defineTheme: _defineTheme,
+ generateThemeRulesSplit: _generateThemeRulesSplit,
+ generateOnMediaCSS: _generateOnMediaCSS,
+ generateAdaptationCSS: _generateAdaptationCSS,
+ dataTokenDefaults: _dataTokenDefaults,
+};
+
+/**
+ * Point the build at one Core: the module-level bindings every step reads.
+ * @param {CoreBindings} core
+ */
+function setCore(core) {
+ _coreThemeModule = core.themeModule;
+ _coreRootModule = core.rootModule;
+ _coreImportError = core.importError;
+ _defineTheme = core.defineTheme;
+ _generateThemeRulesSplit = core.generateThemeRulesSplit;
+ _generateOnMediaCSS = core.generateOnMediaCSS;
+ _generateAdaptationCSS = core.generateAdaptationCSS;
+ _dataTokenDefaults = core.dataTokenDefaults;
+}
+
+/**
+ * The file an `import` of `subpath` reaches through a package's `exports` map,
+ * or null when the map has no entry for it. Conditions are taken in the map's
+ * own order, as Node does, accepting the ones an import matches here: `node`,
+ * `import`, and `default` (so `source` and `types` are skipped).
+ *
+ * @param {string} dir - The package directory.
+ * @param {string} subpath - `'.'` or a subpath such as `'./theme'`.
+ * @returns {string|null}
+ */
+function importTarget(dir, subpath) {
+ let pkg;
+ try {
+ pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf-8'));
+ } catch {
+ return null;
+ }
+ const map = pkg?.exports;
+ const bySubpath =
+ map &&
+ typeof map === 'object' &&
+ !Array.isArray(map) &&
+ Object.keys(map).some(key => key.startsWith('.'));
+ const entry = bySubpath ? map[subpath] : subpath === '.' ? map : undefined;
+ /** @param {any} value @returns {string|null} */
+ const pick = value => {
+ if (typeof value === 'string') return value;
+ if (!value || typeof value !== 'object' || Array.isArray(value))
+ return null;
+ for (const [condition, target] of Object.entries(value)) {
+ if (
+ condition !== 'node' &&
+ condition !== 'import' &&
+ condition !== 'default'
+ )
+ continue;
+ const picked = pick(target);
+ if (picked) return picked;
+ }
+ return null;
+ };
+ const target = pick(entry);
+ return target ? path.resolve(dir, target) : null;
+}
+
+/** @param {string} file @returns {string} its real path, or itself */
+function realOrSelf(file) {
+ try {
+ return fs.realpathSync(file);
+ } catch {
+ return file;
+ }
+}
+
+/**
+ * The Core the project at `cwd` installed, when it differs from the one the
+ * CLI's own import found and loads. The app's `<Theme>` runs on the app's
+ * Core, so building with it keeps the CSS identical; and a CLI run one-off
+ * (`npx @astryxdesign/cli`) has no Core beside it at all. Null when there is
+ * nothing better than the CLI's own import: no installed Core (the Astryx
+ * repository, a bare directory), the same Core, or one that does not load.
+ *
+ * @param {string} cwd
+ * @returns {Promise<CoreBindings | null>}
+ */
+async function loadProjectCore(cwd) {
+ const dir = findInstalledPackage(cwd, '@astryxdesign/core');
+ const themeFile = dir ? importTarget(dir, './theme') : null;
+ if (!dir || !themeFile) return null;
+ if (_cliCore.themeModule) {
+ try {
+ const own = fileURLToPath(
+ import.meta.resolve('@astryxdesign/core/theme'),
+ );
+ if (realOrSelf(own) === realOrSelf(themeFile)) return null;
+ } catch {
+ // The CLI's own Core cannot be located; load the project's.
+ }
+ }
+ let themeModule;
+ try {
+ themeModule = await import(pathToFileURL(themeFile).href);
+ } catch {
+ return null;
+ }
+ if (!themeModule.defineTheme || !themeModule.generateThemeRulesSplit)
+ return null;
+ let rootModule = null;
+ const rootFile = importTarget(dir, '.');
+ if (rootFile) {
+ try {
+ rootModule = await import(pathToFileURL(rootFile).href);
+ } catch {
+ // As with the CLI's own import, the theme namespace stands in for it.
+ }
+ }
+ return {
+ themeModule,
+ rootModule,
+ importError: null,
+ defineTheme: themeModule.defineTheme,
+ generateThemeRulesSplit: themeModule.generateThemeRulesSplit,
+ generateOnMediaCSS: themeModule.generateOnMediaCSS,
+ generateAdaptationCSS: themeModule.generateAdaptationCSS,
+ dataTokenDefaults: themeModule.dataTokenDefaults,
+ };
+}
+
+/** @type {Map<string, Awaited<ReturnType<typeof loadProjectCore>>>} */
+const _projectCores = new Map();
+
+/**
+ * Choose the Core this build generates with: the project's installed one when
+ * {@link loadProjectCore} finds it, else the CLI's own.
+ * @param {string} cwd
+ */
+async function selectCore(cwd) {
+ if (!_projectCores.has(cwd))
+ _projectCores.set(cwd, await loadProjectCore(cwd));
+ setCore(_projectCores.get(cwd) ?? _cliCore);
+}
+
+/**
+ * Whether `cwd` sits in the Astryx repository, where Core is built from
+ * source rather than installed.
+ * @param {string} cwd
+ */
+function inAstryxRepository(cwd) {
+ let dir = cwd;
+ for (let i = 0; i < 6; i++) {
+ try {
+ const pkg = JSON.parse(
+ fs.readFileSync(
+ path.join(dir, 'packages', 'core', 'package.json'),
+ 'utf-8',
+ ),
+ );
+ if (pkg?.name === '@astryxdesign/core') return true;
+ } catch {
+ // Not here; keep walking up.
+ }
+ const parent = path.dirname(dir);
+ if (parent === dir) break;
+ dir = parent;
+ }
+ return false;
+}
+
+/**
+ * Why `theme build` has no Core to generate with, and the fix for where it
+ * ran: the Astryx repository builds Core, an app installs it, and an installed
+ * Core that will not load is named.
+ *
+ * @param {string} cwd
+ * @param {any} importError - Why the import failed, when it threw.
+ * @returns {string}
+ */
+export function coreUnavailableMessage(cwd, importError) {
+ const why =
+ '`astryx theme build` generates CSS with @astryxdesign/core, the same code the runtime <Theme> uses';
+ const detail = importError ? `\n Import error: ${importError.message}` : '';
+ if (inAstryxRepository(cwd)) {
+ return (
+ `Could not load @astryxdesign/core/theme: ${why}. Build @astryxdesign/core ` +
+ `first (e.g. \`pnpm -F @astryxdesign/core build\`).${detail}`
+ );
+ }
+ const installed = findInstalledPackage(cwd, '@astryxdesign/core');
+ if (installed) {
+ return (
+ `Could not load the @astryxdesign/core installed at ` +
+ `${path.relative(cwd, installed) || '.'}: ${why}. Reinstall it.${detail}`
+ );
+ }
+ return (
+ `This project does not have @astryxdesign/core installed: ${why}. Install ` +
+ `it: \`npm install @astryxdesign/core\` (or yarn/pnpm/bun).${detail}`
+ );
+}
+
/**
* Read a package's `version` from a resolved directory. Returns `'unknown'`
* when it can't be read so the header always has a value.
@@ -2107,6 +2337,8 @@ async function themeBuildInternal(
logger.log(`\nBuilding theme from ${path.relative(cwd, filePath)}...`);
+ await selectCore(cwd);
+
// Standalone builds only need interception when an older Core could erase
// adaptations. Family preparation always supplies the same recorder as its
// shared loader so exact authored parent identity stays CLI-private instead
@@ -2233,13 +2465,7 @@ async function themeBuildInternal(
// capability exports are checked against what the theme actually asks for.
if (!_defineTheme || !_generateThemeRulesSplit) {
throw new AstryxError(
- 'Could not load @astryxdesign/core/theme: `astryx theme build` requires a ' +
- 'built, resolvable @astryxdesign/core so it emits the same CSS as the ' +
- 'runtime <Theme>. Build @astryxdesign/core first (e.g. `pnpm -F @astryxdesign/core ' +
- 'build`)' +
- (_coreImportError
- ? `.\n Import error: ${_coreImportError.message}`
- : '.'),
+ coreUnavailableMessage(cwd, _coreImportError),
undefined,
ERROR_CODES.ERR_CORE_NOT_FOUND,
);
@@ -2807,6 +3033,7 @@ export async function themeBuildFamily(
error instanceof Error ? error.message : 'Invalid family key.';
throw new AstryxError(message, undefined, ERROR_CODES.ERR_THEME_INVALID);
}
+ await selectCore(cwd);
const familyInterception = interceptCore(_coreThemeModule, _coreRootModule);
// prettier-ignore
const familyLoader = createJiti(import.meta.url, {moduleCache: true, interopDefault: false, jsx: true, extensions: THEME_MODULE_EXTENSIONS, virtualModules: familyInterception.modules});
diff --git a/packages/cli/api/theme/build/build.project-core.test.mjs b/packages/cli/api/theme/build/build.project-core.test.mjs
new file mode 100644
index 0000000000..8decf1167b
--- /dev/null
+++ b/packages/cli/api/theme/build/build.project-core.test.mjs
@@ -0,0 +1,165 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file `theme build` in an app generates with the Core the app installed.
+ *
+ * A CLI run one-off (`npx @astryxdesign/cli`) has no Core beside it, and the
+ * app's `<Theme>` runs on the app's Core either way, so the build loads the
+ * project's installed `@astryxdesign/core` when it differs from the CLI's own.
+ * When there is no Core to use, the error names the fix for where it ran:
+ * install it in an app, build it in the Astryx repository.
+ */
+
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import {fileURLToPath, pathToFileURL} from 'node:url';
+import {coreUnavailableMessage, themeBuild} from './build.mjs';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const REPO_ROOT = path.resolve(HERE, '../../../../..');
+const CORE_DIST = path.join(REPO_ROOT, 'packages/core/dist');
+
+/** @type {string[]} */
+const tmpDirs = [];
+const makeDir = () => {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-project-core-'));
+ tmpDirs.push(dir);
+ fs.writeFileSync(
+ path.join(dir, 'package.json'),
+ '{"name":"app","type":"module"}',
+ );
+ // A plain theme object: the file itself never imports Core, so only the
+ // build's own Core loading can set the marker below.
+ fs.writeFileSync(
+ path.join(dir, 'ocean.mjs'),
+ "export default {name: 'ocean', tokens: {'--color-bg': '#0a0a0a'}};\n",
+ );
+ return dir;
+};
+
+beforeEach(() => {
+ delete globalThis.__astryxProjectCoreLoads;
+});
+afterEach(() => {
+ delete globalThis.__astryxProjectCoreLoads;
+ for (const dir of tmpDirs.splice(0))
+ fs.rmSync(dir, {recursive: true, force: true});
+});
+
+/**
+ * Install a Core in `dir` that is the built one, re-exported, and records each
+ * entry as it is imported. Its `exports` map lists `source` first, as Core's
+ * own does, so the build must skip that condition to find the runtime file.
+ * @param {string} dir
+ * @param {{broken?: boolean}} [options]
+ */
+function installCore(dir, {broken = false} = {}) {
+ 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: '0.6.5',
+ type: 'module',
+ exports: {
+ '.': {types: './root.d.ts', default: './root.mjs'},
+ './theme': {
+ source: './src/theme/index.ts',
+ types: './theme.d.ts',
+ default: './theme.mjs',
+ },
+ },
+ }),
+ );
+ /** @param {string} entry @param {string} target */
+ const module = (entry, target) =>
+ broken
+ ? "throw new Error('this Core is broken');\n"
+ : `export * from ${JSON.stringify(pathToFileURL(path.join(CORE_DIST, target)).href)};\n` +
+ `globalThis.__astryxProjectCoreLoads = [...(globalThis.__astryxProjectCoreLoads ?? []), '${entry}'];\n`;
+ fs.writeFileSync(
+ path.join(core, 'theme.mjs'),
+ module('theme', 'theme/index.js'),
+ );
+ fs.writeFileSync(path.join(core, 'root.mjs'), module('root', 'index.js'));
+ return core;
+}
+
+describe('theme build generates with the Core the project installed', () => {
+ it('loads the app’s installed Core when it differs from the CLI’s own', async () => {
+ const app = makeDir();
+ installCore(app);
+ await themeBuild('ocean.mjs', {}, {cwd: app});
+ expect(globalThis.__astryxProjectCoreLoads).toEqual(['theme', 'root']);
+ // The same Core, re-exported, emits the same CSS as the CLI's own. The
+ // generated header differs only in the Core version it records.
+ const bare = makeDir();
+ await themeBuild('ocean.mjs', {}, {cwd: bare});
+ /** @param {string} dir */
+ const rules = dir =>
+ fs
+ .readFileSync(path.join(dir, 'ocean.css'), 'utf-8')
+ .replace(/^\/\*[\s\S]*?\*\/\n/, '');
+ expect(rules(app)).toBe(rules(bare));
+ expect(rules(app)).toContain('#0a0a0a');
+ });
+
+ it('keeps the CLI’s own Core when the project has none', async () => {
+ const bare = makeDir();
+ await themeBuild('ocean.mjs', {}, {cwd: bare});
+ expect(globalThis.__astryxProjectCoreLoads).toBeUndefined();
+ expect(fs.existsSync(path.join(bare, 'ocean.css'))).toBe(true);
+ });
+
+ it('keeps the CLI’s own Core when the installed one does not load', async () => {
+ const app = makeDir();
+ installCore(app, {broken: true});
+ await themeBuild('ocean.mjs', {}, {cwd: app});
+ expect(fs.existsSync(path.join(app, 'ocean.css'))).toBe(true);
+ });
+});
+
+describe('the error when there is no Core to generate with', () => {
+ it('tells an app to install Core, not to build it', () => {
+ const app = makeDir();
+ const message = coreUnavailableMessage(
+ app,
+ new Error("Cannot find package '@astryxdesign/core'"),
+ );
+ expect(message).toContain(
+ 'This project does not have @astryxdesign/core installed',
+ );
+ expect(message).toContain('`npm install @astryxdesign/core`');
+ expect(message).not.toContain('pnpm -F');
+ expect(message).toContain(
+ "Import error: Cannot find package '@astryxdesign/core'",
+ );
+ });
+
+ it('names an installed Core that does not load', () => {
+ const app = makeDir();
+ installCore(app, {broken: true});
+ const message = coreUnavailableMessage(
+ app,
+ new Error('this Core is broken'),
+ );
+ expect(message).toContain(
+ `Could not load the @astryxdesign/core installed at ${path.join('node_modules', '@astryxdesign', 'core')}`,
+ );
+ expect(message).toContain('Reinstall it.');
+ expect(message).not.toContain('pnpm -F');
+ });
+
+ it('keeps the build instruction in the Astryx repository', () => {
+ const message = coreUnavailableMessage(
+ path.join(REPO_ROOT, 'packages', 'cli'),
+ undefined,
+ );
+ expect(message).toContain('Build @astryxdesign/core first');
+ expect(message).toContain('`pnpm -F @astryxdesign/core build`');
+ expect(message).not.toContain('Import error');
+ });
+});
diff --git a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs b/packages/cli/foundation/doc-compiler/doc-loads.test.mjs
index 928c107a0e..15aae25e26 100644
--- a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs
+++ b/packages/cli/foundation/doc-compiler/doc-loads.test.mjs
@@ -61,13 +61,13 @@ const RUNNERS = {
sites: ['child_process.execFileSync'],
},
'api/theme/build/build.mjs': {
- runs: 'theme source modules, through jiti; eval for legacy theme object literals',
+ runs: "theme source modules, through jiti; eval for legacy theme object literals; the project's installed Core",
sites: [
'.evalModule() ×2',
'.import()',
'createJiti ×4',
'eval ×2',
- 'import(<computed>)',
+ 'import(<computed>) ×3',
],
},
'api/theme/build/core-interception.mjs': {