Skip to content

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

TypeScript

fix(cli): theme build reports a theme module that fails to load instead of reading its text (#8767)

Christopher Chedeau031a639806e1
diff --git a/.changeset/theme-build-no-text-fallback.md b/.changeset/theme-build-no-text-fallback.md
new file mode 100644
index 0000000000..f88a18f1b2
--- /dev/null
+++ b/.changeset/theme-build-no-text-fallback.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] `astryx theme build` reports a theme module that fails to load (an import it cannot resolve, or an error it throws) instead of building the theme from the text of its `defineTheme()` or default-export object; a theme module whose default export is a plain object builds as before, and a theme outside a project that imports Core builds with the Core the CLI answers with.
+
+@vjeux
diff --git a/packages/cli/api/theme/build/build.mjs b/packages/cli/api/theme/build/build.mjs
index 91b7f7c8c2..7f070dd46c 100644
--- a/packages/cli/api/theme/build/build.mjs
+++ b/packages/cli/api/theme/build/build.mjs
@@ -58,7 +58,7 @@
import * as fs from 'node:fs';
import * as path from 'node:path';
-import {isBuiltin} from 'node:module';
+import {createRequire, isBuiltin} from 'node:module';
import {fileURLToPath, pathToFileURL} from 'node:url';
import {parse} from '@babel/parser';
import {createJiti} from 'jiti';
@@ -1855,19 +1855,43 @@ async function importThemeModule(filePath, interception, /** @type {any} */ load
commonJsPatch.undo();
}
} else {
- mod = await jiti.import(filePath, {default: true});
+ mod = await jiti.import(filePath);
}
- if (isThemeObject(mod)) return {theme: mod, exportName: 'default', degraded};
-
- if (mod && typeof mod === 'object') {
- if (isThemeObject(mod.default)) {
- return {theme: mod.default, exportName: 'default', degraded};
- }
+ // Both loads hand back the module. The theme is read from the module's own
+ // exports, never from the module object itself: jiti's interop answers a
+ // property the module lacks from its default export (and a missing
+ // `default` with the module), so the module can pass for the theme while
+ // its own keys hide the theme's fields.
+ const isModule = mod != null && typeof mod === 'object';
+ const hasDefault = isModule && Object.hasOwn(mod, 'default');
+ const defaultExport = hasDefault ? mod.default : undefined;
+ if (isThemeObject(defaultExport)) {
+ return {theme: defaultExport, exportName: 'default', degraded};
+ }
+ if (isModule) {
for (const [exportName, value] of Object.entries(mod)) {
+ if (exportName === 'default' || exportName === 'module.exports') continue;
if (isThemeObject(value)) return {theme: value, exportName, degraded};
}
}
+ // A plain-object default export is the module's theme even when it has
+ // no tokens of its own (local tokens, typography or component styles may
+ // be all it defines), or no name: the build's validation says what it
+ // lacks.
+ if (isPlainObject(defaultExport)) {
+ return {theme: defaultExport, exportName: 'default', degraded};
+ }
+ // A CommonJS module whose exports are the theme (`module.exports =
+ // theme`) has no default of its own: interop answers `default` with
+ // those exports, and without interop (a family build's loader) the module
+ // is them.
+ if (isModule && !hasDefault) {
+ const exportsObject = mod.default ?? mod;
+ if (isThemeObject(exportsObject)) {
+ return {theme: exportsObject, exportName: 'default', degraded};
+ }
+ }
throw new Error(
`Could not find a defineTheme() result in ${filePath}.\n` +
@@ -1875,6 +1899,45 @@ async function importThemeModule(filePath, interception, /** @type {any} */ load
);
}
+/**
+ * Whether the theme file's own folder resolves Core's theme entry, as the
+ * theme's own `import ... from '@astryxdesign/core/theme'` would. A theme
+ * outside any project (an empty folder, a fresh clone) does not, and is
+ * handed the Core the CLI answers with instead, as a new project with that
+ * Core would build it (`theme build` runs the same outside a project, spec
+ * AST-081 FR3). Only a Core not installed there (MODULE_NOT_FOUND) reads as
+ * no: an installed Core whose entry does not resolve is the theme's own, and
+ * its load reports that.
+ * @param {string} filePath
+ * @returns {boolean}
+ */
+function themeFolderResolvesCore(filePath) {
+ try {
+ createRequire(filePath).resolve('@astryxdesign/core/theme');
+ return true;
+ } catch (error) {
+ const {code} = /** @type {NodeJS.ErrnoException} */ (error);
+ if (code === 'MODULE_NOT_FOUND') return false;
+ if (code === 'ERR_PACKAGE_PATH_NOT_EXPORTED') return true;
+ throw error;
+ }
+}
+
+/**
+ * A plain object, not an array or a module namespace: a theme module's
+ * default export, read as its theme.
+ * @param {any} value
+ * @returns {boolean}
+ */
+function isPlainObject(value) {
+ return (
+ value != null &&
+ typeof value === 'object' &&
+ !Array.isArray(value) &&
+ value[Symbol.toStringTag] !== 'Module'
+ );
+}
+
/**
* @param {any} value
* @returns {boolean}
@@ -1890,12 +1953,9 @@ function isThemeObject(value) {
}
/**
- * Extract the theme definition from a JS/TS file.
- * Tries jiti first (full TS support), falls back to regex+eval.
- *
- * The legacy fallback needs no interception: it evaluates the `defineTheme()`
- * ARGUMENT, so what it returns is raw authored input with `adaptations` still
- * on it — nothing has erased anything yet. It is therefore never degraded.
+ * Extract the theme definition from a JS/TS file, through jiti (full TS
+ * support). A module that does not load fails with its own error: the theme
+ * is never read from the file's text instead.
*
* @param {string} filePath
* @param {import('./core-interception.mjs').CoreInterception} [interception]
@@ -1906,18 +1966,12 @@ async function extractThemeDefinition(filePath, interception, /** @type {any} */
try {
return await importThemeModule(filePath, interception, loader);
} catch (jitiError) {
- try {
- return {
- theme: extractThemeDefinitionLegacy(filePath),
- degraded: {topLevelAwait: false, commonJs: false},
- };
- } catch {
- const je = /** @type {Error} */ (jitiError);
- throw new Error(
- `Failed to load theme from ${filePath}: ${je.message}\n` +
- `Make sure all imports in the theme file are resolvable.`,
- );
- }
+ const je = /** @type {Error} */ (jitiError);
+ throw new Error(
+ `Failed to load theme from ${filePath}: ${je.message}\n` +
+ `Make sure all imports in the theme file are resolvable.`,
+ {cause: jitiError},
+ );
}
}
@@ -1963,45 +2017,6 @@ export async function validateThemePrivateInputs(
}
}
-/**
- * Fallback extraction via regex + eval.
- * Only works for plain object literals — can't follow imports or variables.
- * Never erase icon references: an unresolved registry must preserve the loader
- * error instead of turning an incomplete theme into a successful build.
- * @param {string} filePath
- * @returns {any}
- */
-function extractThemeDefinitionLegacy(filePath) {
- const content = fs.readFileSync(filePath, 'utf8');
-
- const defineMatch = content.match(/defineTheme\s*\(\s*({[\s\S]*?})\s*\)/);
- if (!defineMatch) {
- const defaultMatch = content.match(/export\s+default\s+({[\s\S]*?});/);
- if (!defaultMatch) {
- throw new Error(
- `Could not find defineTheme() call or default export in ${filePath}.\n` +
- `Expected: defineTheme({ name: '...', tokens: {...} })`,
- );
- }
-
- return eval(`(${defaultMatch[1]})`);
- }
-
- let objStr = defineMatch[1];
- objStr = objStr.replace(/\s+as\s+const/g, '');
-
- try {
- return eval(`(${objStr})`);
- } catch (e) {
- const err = /** @type {Error} */ (e);
- throw new Error(
- `Failed to parse theme definition in ${filePath}: ${err.message}\n` +
- `Make sure the defineTheme() argument is a plain object literal.`,
- {cause: e},
- );
- }
-}
-
/**
* Extract a family member's named registry import from its source file.
* Returns { importPath, exportName } or null when the theme names none.
@@ -2617,13 +2632,15 @@ async function themeBuildInternal(
}
await selectCore(cwd, {projectOnly: projectCore});
- // Standalone builds only need interception when an older Core could erase
- // adaptations. Family preparation always supplies the same recorder as its
+ // Standalone builds need interception when an older Core could erase
+ // adaptations, and when the theme's folder has no Core of its own: its
+ // imports of Core are then handed the Core this build selected, as family
+ // builds' are. Family preparation always supplies the same recorder as its
// shared loader so exact authored parent identity stays CLI-private instead
// of becoming a public DefinedTheme field.
const interception =
options.__familyInterception ??
- (_generateAdaptationCSS
+ (_generateAdaptationCSS && themeFolderResolvesCore(filePath)
? undefined
: interceptCore(_coreThemeModule, _coreRootModule));
diff --git a/packages/cli/api/theme/build/build.test.mjs b/packages/cli/api/theme/build/build.test.mjs
index be9534516d..b548855a5f 100644
--- a/packages/cli/api/theme/build/build.test.mjs
+++ b/packages/cli/api/theme/build/build.test.mjs
@@ -27,6 +27,7 @@ import {
import {
themeBuild,
validateComponentOverridesAgainstRegistry,
+ validateThemePrivateInputs,
} from './build.mjs';
// `themeBuild` captures core's generator once at module load. Wrap the two
@@ -212,6 +213,55 @@ describe('themeBuild() — receipt', () => {
});
});
+describe.each(['mjs', 'ts'])('a .%s theme module with no theme export', ext => {
+ beforeEach(() => {
+ fs.writeFileSync(
+ path.join(tmpDir, `none.${ext}`),
+ 'export const notATheme = 42;\n',
+ );
+ });
+
+ it('fails the build as a module that does not load a theme', async () => {
+ const build = themeBuild(`none.${ext}`, {}, {cwd: tmpDir});
+ await expect(build).rejects.toThrow(
+ /Could not find a defineTheme\(\) result/,
+ );
+ await expect(build).rejects.toMatchObject({code: 'ERR_THEME_LOAD'});
+ });
+
+ it("fails doctor's private-input check the same way, rather than read its exports as a theme", async () => {
+ await expect(
+ validateThemePrivateInputs(`none.${ext}`, {cwd: tmpDir}),
+ ).rejects.toThrow(/Could not find a defineTheme\(\) result/);
+ });
+});
+
+describe('themeBuild() — a theme module that does not load', () => {
+ it('fails with the import error, rather than build the theme from the file text', async () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'unresolved.mjs'),
+ "import './missing-helper.mjs';\nexport default {name: 'unresolved', tokens: {'--color-bg': '#000'}};\n",
+ );
+ await expect(
+ themeBuild('unresolved.mjs', {}, {cwd: tmpDir}),
+ ).rejects.toThrow(
+ /Failed to load theme from .*unresolved\.mjs: .*missing-helper\.mjs/s,
+ );
+ expect(fs.existsSync(path.join(tmpDir, 'unresolved.css'))).toBe(false);
+ });
+
+ it('fails with the error the module throws, rather than build the theme from the file text', async () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'throws.mjs'),
+ "throw new Error('the theme module failed');\nexport default {name: 'throws', tokens: {'--color-bg': '#000'}};\n",
+ );
+ await expect(themeBuild('throws.mjs', {}, {cwd: tmpDir})).rejects.toThrow(
+ /the theme module failed/,
+ );
+ expect(fs.existsSync(path.join(tmpDir, 'throws.css'))).toBe(false);
+ });
+});
+
describe('themeBuild() — dropped declarations reach the receipt', () => {
// Core's generator refuses a declaration whose value would end it early
// (an unquoted `;` or brace, an unclosed string/comment/url). The runtime
diff --git a/packages/cli/clients/cli/commands/build-theme.outside-project.test.mjs b/packages/cli/clients/cli/commands/build-theme.outside-project.test.mjs
new file mode 100644
index 0000000000..5e27d02712
--- /dev/null
+++ b/packages/cli/clients/cli/commands/build-theme.outside-project.test.mjs
@@ -0,0 +1,140 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file `astryx theme build` outside any project, as a separate process.
+ *
+ * A theme in a folder with no Core installed (an empty folder, a fresh clone)
+ * imports `defineTheme` from Core all the same: the build hands its imports
+ * the Core the CLI answers with, as a new project with that Core would build
+ * it (spec AST-081 FR3). The CLI runs as its own process, without the
+ * `NODE_PATH` a pnpm script sets (it reaches the repository's packages): in
+ * the test runner, or with that path, the theme's import would find the
+ * repository's Core, which a real run outside a project cannot.
+ */
+
+import {afterEach, beforeAll, 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 {spawnSync} from 'node:child_process';
+import {fileURLToPath} from 'node:url';
+import {ensureCoreBuilt} from './ensure-core-built.mjs';
+
+const CLI_BIN = fileURLToPath(new URL('../bin/astryx.mjs', import.meta.url));
+const CORE_DIR = fileURLToPath(new URL('../../../../core', import.meta.url));
+
+/** @param {string[]} args @param {string} cwd */
+function runCliProcess(args, cwd) {
+ const {NODE_PATH: _repositoryPackages, ...env} = process.env;
+ const result = spawnSync(process.execPath, [CLI_BIN, ...args], {
+ cwd,
+ encoding: 'utf-8',
+ timeout: 60_000,
+ env,
+ });
+ if (result.error) throw result.error;
+ return result;
+}
+
+beforeAll(() => {
+ ensureCoreBuilt();
+}, 200_000);
+
+let tmpDir;
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-theme-outside-'));
+});
+afterEach(() => {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+/**
+ * A project beside the empty folder: its own package.json and Core (this
+ * repository's, linked), so the same theme builds there through the
+ * project's own resolution.
+ * @param {string} dir
+ */
+function makeProject(dir) {
+ fs.mkdirSync(path.join(dir, 'node_modules', '@astryxdesign'), {
+ recursive: true,
+ });
+ fs.writeFileSync(
+ path.join(dir, 'package.json'),
+ '{"name": "theme-project", "private": true, "dependencies": {"@astryxdesign/core": "*"}}\n',
+ );
+ fs.symlinkSync(
+ CORE_DIR,
+ path.join(dir, 'node_modules', '@astryxdesign', 'core'),
+ 'junction',
+ );
+}
+
+describe('theme build outside any project builds a plain-object theme as a project does', () => {
+ const themes = {
+ typography: `export default {
+ name: 'plain-type',
+ tokens: {'--color-background': '#123456'},
+ typography: {body: {family: 'Helvetica', fallbacks: 'Arial, sans-serif'}},
+ };\n`,
+ 'local tokens and media surfaces': `export default {
+ name: 'plain-local',
+ tokens: {'--color-background': '#123456'},
+ localTokens: {'--ac-selection-ink': ['#0077b6', '#48cae4']},
+ components: {badge: {'variant:info': {backgroundColor: 'var(--ac-selection-ink)'}}},
+ onDark: {components: {badge: {'variant:info': {color: 'var(--ac-selection-ink)'}}}},
+ };\n`,
+ };
+ for (const [what, source] of Object.entries(themes)) {
+ for (const ext of ['mjs', 'ts']) {
+ it(`with ${what}, in a .${ext} file`, () => {
+ const name = /name: '([^']+)'/.exec(source)[1];
+ const project = path.join(tmpDir, 'project');
+ makeProject(project);
+ const outside = path.join(tmpDir, 'outside');
+ fs.mkdirSync(outside);
+ for (const dir of [project, outside]) {
+ fs.writeFileSync(path.join(dir, `theme.${ext}`), source);
+ const result = runCliProcess(['theme', 'build', `theme.${ext}`], dir);
+ expect(result.status, result.stderr + result.stdout).toBe(0);
+ }
+ expect(fs.readFileSync(path.join(outside, `${name}.css`), 'utf8')).toBe(
+ fs.readFileSync(path.join(project, `${name}.css`), 'utf8'),
+ );
+ });
+ }
+ }
+});
+
+describe('theme build outside any project', () => {
+ for (const ext of ['mjs', 'ts']) {
+ it(`builds a .${ext} theme that imports defineTheme from Core, with the Core the CLI answers with`, () => {
+ fs.writeFileSync(
+ path.join(tmpDir, `outside.${ext}`),
+ "import {defineTheme} from '@astryxdesign/core/theme';\n" +
+ "export default defineTheme({name: 'outside', tokens: {'--color-background': '#123456'}});\n",
+ );
+ const result = runCliProcess(
+ ['theme', 'build', `outside.${ext}`],
+ tmpDir,
+ );
+ expect(result.status, result.stderr + result.stdout).toBe(0);
+ expect(
+ fs.readFileSync(path.join(tmpDir, 'outside.css'), 'utf8'),
+ ).toContain('#123456');
+ });
+ }
+
+ for (const ext of ['mjs', 'ts']) {
+ it(`still fails a .${ext} module that defines no theme`, () => {
+ fs.writeFileSync(
+ path.join(tmpDir, `none.${ext}`),
+ 'export const notATheme = 42;\n',
+ );
+ const result = runCliProcess(['theme', 'build', `none.${ext}`], tmpDir);
+ expect(result.status).toBe(1);
+ expect(result.stderr + result.stdout).toMatch(
+ /Could not find a defineTheme\(\) result/,
+ );
+ });
+ }
+});
diff --git a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs b/packages/cli/foundation/doc-compiler/doc-loads.test.mjs
index 5775b115c0..614507009e 100644
--- a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs
+++ b/packages/cli/foundation/doc-compiler/doc-loads.test.mjs
@@ -65,12 +65,11 @@ const RUNNERS = {
sites: ['importThemeArtifact'],
},
'api/theme/build/build.mjs': {
- runs: "theme source modules, through jiti; eval for legacy theme object literals; the project's installed Core",
+ runs: "theme source modules, through jiti; the project's installed Core",
sites: [
'.evalModule() ×2',
'.import()',
'createJiti ×5',
- 'eval ×2',
'import(<computed>) ×3',
],
},
@@ -218,10 +217,7 @@ const RUNNERS = {
},
'clients/cli/commands/hook.mjs': {
runs: SELF_DOCS,
- sites: [
- 'import ../../../api/hook/hook.doc.mjs',
- 'import ./hook.doc.mjs',
- ],
+ sites: ['import ../../../api/hook/hook.doc.mjs', 'import ./hook.doc.mjs'],
},
'clients/cli/commands/init.mjs': {
runs: SELF_DOCS,