Skip to content

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

TypeScript

fix(cli): theme build names the Core that failed to load instead of building with the CLI's own (#8786)

Christopher Chedeauf01c61d53909
diff --git a/.changeset/theme-build-project-core-load-error.md b/.changeset/theme-build-project-core-load-error.md
new file mode 100644
index 0000000000..563f202f9a
--- /dev/null
+++ b/.changeset/theme-build-project-core-load-error.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] `astryx theme build` fails, naming it and its import error, when the project's installed `@astryxdesign/core` (or, outside a project, the Core the CLI release carries) does not load or lacks `defineTheme` or `generateThemeRulesSplit`, instead of building with the CLI's own Core. A project with no Core installed still builds with the CLI's.
+
+@vjeux
diff --git a/packages/cli/api/theme/build/build.mjs b/packages/cli/api/theme/build/build.mjs
index 7f070dd46c..abdde9e57d 100644
--- a/packages/cli/api/theme/build/build.mjs
+++ b/packages/cli/api/theme/build/build.mjs
@@ -306,7 +306,9 @@ function realLocation(target) {
* 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.
+ * repository, a bare directory) or the same Core. A Core that is there but
+ * does not load, or lacks the functions the build calls, throws, naming it:
+ * building with another Core would not match the app's `<Theme>`.
*
* @param {string} cwd
* @param {CoreBindings} cliCore - The CLI's own Core, from {@link loadCliCore}.
@@ -316,29 +318,36 @@ function realLocation(target) {
*/
async function loadProjectCore(cwd, cliCore, {projectOnly = false} = {}) {
// Outside a project, the Core the answering copy carries (spec AST-081 FR3).
- const dir =
- findInstalledPackage(cwd, '@astryxdesign/core') ??
- (projectOnly ? null : fetchCarriedThemeCoreDir(cwd));
+ const installed = findInstalledPackage(cwd, '@astryxdesign/core');
+ const dir = installed ?? (projectOnly ? null : fetchCarriedThemeCoreDir(cwd));
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.
- }
+ const own = cliCoreThemeFile();
+ if (own != null && realOrSelf(own) === realOrSelf(themeFile)) return null;
}
let themeModule;
try {
themeModule = await import(pathToFileURL(themeFile).href);
- } catch {
- return null;
+ } catch (error) {
+ throw new AstryxError(
+ installed == null
+ ? carriedCoreMessage(dir, /** @type {Error} */ (error))
+ : coreUnavailableMessage(cwd, /** @type {Error} */ (error)),
+ undefined,
+ ERROR_CODES.ERR_CORE_NOT_FOUND,
+ );
+ }
+ const missing = ['defineTheme', 'generateThemeRulesSplit'].filter(
+ name => typeof themeModule[name] !== 'function',
+ );
+ if (missing.length > 0) {
+ throw new AstryxError(
+ `The @astryxdesign/core at ${path.relative(cwd, dir) || '.'} does not export ${missing.join(' or ')} from its \`./theme\` entry, which \`${formatCliCommand('theme build')}\` calls. Update it.`,
+ undefined,
+ ERROR_CODES.ERR_CORE_INCOMPATIBLE,
+ );
}
- if (!themeModule.defineTheme || !themeModule.generateThemeRulesSplit)
- return null;
let rootModule = null;
const rootFile = importTarget(dir, '.');
if (rootFile) {
@@ -359,6 +368,40 @@ async function loadProjectCore(cwd, cliCore, {projectOnly = false} = {}) {
};
}
+/**
+ * The file the CLI's own `@astryxdesign/core/theme` resolves to, or null when
+ * the CLI has no Core of its own (a one-off `npx` run).
+ * @returns {string | null}
+ */
+function cliCoreThemeFile() {
+ try {
+ return fileURLToPath(import.meta.resolve('@astryxdesign/core/theme'));
+ } catch (error) {
+ const {code} = /** @type {NodeJS.ErrnoException} */ (error);
+ if (
+ code === 'ERR_MODULE_NOT_FOUND' ||
+ code === 'ERR_PACKAGE_PATH_NOT_EXPORTED'
+ ) {
+ return null;
+ }
+ throw error;
+ }
+}
+
+/**
+ * The error for a Core the answering copy carries (outside a project) that
+ * does not load.
+ * @param {string} dir
+ * @param {Error} importError
+ * @returns {string}
+ */
+function carriedCoreMessage(dir, importError) {
+ return (
+ `Could not load the @astryxdesign/core this CLI release carries, at ${dir}.` +
+ `\n Import error: ${importError.message}`
+ );
+}
+
/** @type {Map<string, Awaited<ReturnType<typeof loadProjectCore>>>} */
const _projectCores = new Map();
@@ -379,7 +422,7 @@ async function selectCore(cwd, {projectOnly = false} = {}) {
// A global or cached copy's own Core is the carried one.
if (projectOnly && !projectCore && carriesCore() && !cliCoreIsProjects(cwd)) {
throw new AstryxError(
- "The project's Core isn't installed or does not load.",
+ "The project's Core isn't installed.",
undefined,
ERROR_CODES.ERR_CORE_NOT_FOUND,
);
@@ -405,13 +448,11 @@ function carriesCore() {
function cliCoreIsProjects(cwd) {
const dir = findProjectCoreDir(cwd);
if (!dir) return false;
- try {
- const own = fileURLToPath(import.meta.resolve('@astryxdesign/core/theme'));
- const theirs = importTarget(dir, './theme');
- return theirs != null && realOrSelf(own) === realOrSelf(theirs);
- } catch {
- return false;
- }
+ const own = cliCoreThemeFile();
+ const theirs = importTarget(dir, './theme');
+ return (
+ own != null && theirs != null && realOrSelf(own) === realOrSelf(theirs)
+ );
}
/**
diff --git a/packages/cli/api/theme/build/build.project-core.test.mjs b/packages/cli/api/theme/build/build.project-core.test.mjs
index 8decf1167b..8c2a2fdbad 100644
--- a/packages/cli/api/theme/build/build.project-core.test.mjs
+++ b/packages/cli/api/theme/build/build.project-core.test.mjs
@@ -7,15 +7,26 @@
* 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.
+ * install it in an app, build it in the Astryx repository. An installed Core
+ * that does not load, or lacks the functions the build calls, fails the build,
+ * naming it, rather than leave the build to the CLI's own Core.
*/
-import {afterEach, beforeEach, describe, expect, it} from 'vitest';
+import {afterEach, beforeEach, describe, expect, it, vi} 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';
+import {fetchCarriedThemeCoreDir} from '../_adapter.mjs';
+
+vi.mock('../_adapter.mjs', async importOriginal => {
+ const actual = /** @type {Record<string, any>} */ (await importOriginal());
+ return {
+ ...actual,
+ fetchCarriedThemeCoreDir: vi.fn(actual.fetchCarriedThemeCoreDir),
+ };
+});
const HERE = path.dirname(fileURLToPath(import.meta.url));
const REPO_ROOT = path.resolve(HERE, '../../../../..');
@@ -53,9 +64,10 @@ afterEach(() => {
* 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]
+ * @param {{broken?: boolean, themeModule?: string}} [options] `themeModule`
+ * replaces the theme entry's source
*/
-function installCore(dir, {broken = false} = {}) {
+function installCore(dir, {broken = false, themeModule} = {}) {
const core = path.join(dir, 'node_modules', '@astryxdesign', 'core');
fs.mkdirSync(core, {recursive: true});
fs.writeFileSync(
@@ -82,12 +94,29 @@ function installCore(dir, {broken = false} = {}) {
`globalThis.__astryxProjectCoreLoads = [...(globalThis.__astryxProjectCoreLoads ?? []), '${entry}'];\n`;
fs.writeFileSync(
path.join(core, 'theme.mjs'),
- module('theme', 'theme/index.js'),
+ themeModule ?? module('theme', 'theme/index.js'),
);
fs.writeFileSync(path.join(core, 'root.mjs'), module('root', 'index.js'));
return core;
}
+describe('theme build outside a project, with the Core this CLI release carries', () => {
+ it('fails naming a carried Core that does not load, rather than build with the CLI’s own', async () => {
+ const carried = installCore(makeDir(), {broken: true});
+ vi.mocked(fetchCarriedThemeCoreDir).mockReturnValueOnce(carried);
+ const bare = makeDir();
+ const build = themeBuild('ocean.mjs', {}, {cwd: bare});
+ await expect(build).rejects.toMatchObject({
+ code: 'ERR_CORE_NOT_FOUND',
+ message: expect.stringContaining(
+ `Could not load the @astryxdesign/core this CLI release carries, at ${carried}`,
+ ),
+ });
+ await expect(build).rejects.toThrow(/Import error: this Core is broken/);
+ expect(fs.existsSync(path.join(bare, 'ocean.css'))).toBe(false);
+ });
+});
+
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();
@@ -114,11 +143,37 @@ describe('theme build generates with the Core the project installed', () => {
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 () => {
+ it('fails naming an installed Core that does not load, rather than build with the CLI’s own', async () => {
const app = makeDir();
installCore(app, {broken: true});
- await themeBuild('ocean.mjs', {}, {cwd: app});
- expect(fs.existsSync(path.join(app, 'ocean.css'))).toBe(true);
+ await expect(themeBuild('ocean.mjs', {}, {cwd: app})).rejects.toMatchObject(
+ {
+ code: 'ERR_CORE_NOT_FOUND',
+ message: expect.stringContaining(
+ `Could not load the @astryxdesign/core installed at ${path.join('node_modules', '@astryxdesign', 'core')}`,
+ ),
+ },
+ );
+ await expect(themeBuild('ocean.mjs', {}, {cwd: app})).rejects.toThrow(
+ /Import error: this Core is broken/,
+ );
+ expect(fs.existsSync(path.join(app, 'ocean.css'))).toBe(false);
+ });
+
+ it('fails naming an installed Core without the functions the build calls, rather than build with the CLI’s own', async () => {
+ const app = makeDir();
+ installCore(app, {
+ themeModule: 'export const defineTheme = theme => theme;\n',
+ });
+ await expect(themeBuild('ocean.mjs', {}, {cwd: app})).rejects.toMatchObject(
+ {
+ code: 'ERR_CORE_INCOMPATIBLE',
+ message: expect.stringContaining(
+ 'does not export generateThemeRulesSplit',
+ ),
+ },
+ );
+ expect(fs.existsSync(path.join(app, 'ocean.css'))).toBe(false);
});
});