Skip to content

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

TypeScript

perf(cli): a standalone theme build loads Core's root only on import (#9941)

Christopher Chedeau9a4627b50930
diff --git a/.changeset/cli-theme-build-core-root-on-use.md b/.changeset/cli-theme-build-core-root-on-use.md
new file mode 100644
index 0000000000..e77dc75f6c
--- /dev/null
+++ b/.changeset/cli-theme-build-core-root-on-use.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[perf] A standalone `astryx theme build` against the current Core loads Core's root entry only when the theme imports it. A theme that imports only `@astryxdesign/core/theme` no longer loads all of Core and its components. Family builds and builds against an older Core still load the root. Some builds hand the theme its Core: family builds, builds against an older Core, and themes whose folder has no Core. There, a theme that imports a Core root `require()` cannot load, such as one that awaits at its top level, fails with `ERR_THEME_LOAD`. The error names that root.
+
+@vjeux
diff --git a/packages/cli/api/theme/build/build.core-on-demand.test.mjs b/packages/cli/api/theme/build/build.core-on-demand.test.mjs
index 68bfc2210f..d24bd44d39 100644
--- a/packages/cli/api/theme/build/build.core-on-demand.test.mjs
+++ b/packages/cli/api/theme/build/build.core-on-demand.test.mjs
@@ -8,7 +8,8 @@
* not ask for either, or `astryx --version` pays for them whenever a Core is
* installed. A resolve hook in a real subprocess records every request for
* Core or React and the module that made it, whether or not the request
- * resolves.
+ * resolves. It also records whether Core's root entry ran: a build loads the
+ * root only for a theme that imports it.
*/
import {afterAll, beforeAll, describe, expect, it} from 'vitest';
@@ -22,6 +23,9 @@ const BIN = fileURLToPath(
new URL('../../../clients/cli/bin/astryx.mjs', import.meta.url),
);
+/** The key the hook records when Core's root entry runs. */
+const ROOT_RAN = '(root entry ran)';
+
/** @type {string} */
let dir;
/** @type {string} */
@@ -38,14 +42,20 @@ beforeAll(() => {
[
"import {appendFileSync} from 'node:fs';",
`const LOG = ${JSON.stringify(log)};`,
+ `const ROOT = ${JSON.stringify(import.meta.resolve('@astryxdesign/core'))};`,
'const WATCHED = /^(?:@astryxdesign\\/core|react|react-dom)(?:\\/|$)/;',
'export async function resolve(specifier, context, nextResolve) {',
' if (WATCHED.test(specifier)) {',
' const parent = context.parentURL ?? null;',
" appendFileSync(LOG, JSON.stringify({specifier, parent}) + '\\n');",
' }',
+ " // An import that Core's root entry makes means the root ran.",
+ ' if (context.parentURL === ROOT) {',
+ " appendFileSync(LOG, JSON.stringify({specifier: ROOT_RAN, parent: ROOT}) + '\\n');",
+ ' }',
' return nextResolve(specifier, context);',
'}',
+ `const ROOT_RAN = ${JSON.stringify(ROOT_RAN)};`,
'',
].join('\n'),
);
@@ -60,6 +70,20 @@ beforeAll(() => {
path.join(dir, 'ocean.mjs'),
"export default {name: 'ocean', tokens: {'--color-bg': '#0a0a0a'}};\n",
);
+ // A theme that imports a component from the root, which only the root
+ // exports.
+ fs.writeFileSync(
+ path.join(dir, 'reef.ts'),
+ [
+ "import {defineTheme} from '@astryxdesign/core/theme';",
+ "import {Button} from '@astryxdesign/core';",
+ 'export const reefTheme = defineTheme({',
+ " name: 'reef',",
+ " tokens: {'--color-bg': typeof Button === 'function' ? '#0a0a0a' : 'MISSING'},",
+ '});',
+ '',
+ ].join('\n'),
+ );
});
afterAll(() => {
@@ -110,4 +134,26 @@ describe('theme build imports Core on demand', () => {
/\/api\/theme\/build\/build\.mjs$/,
);
});
+
+ it('a theme that imports only the theme entry never runs the root', () => {
+ const {requested} = run([
+ 'theme',
+ 'build',
+ 'ocean.mjs',
+ '--check',
+ '--json',
+ ]);
+ expect(requested['@astryxdesign/core/theme']).toBeDefined();
+ expect(requested).not.toHaveProperty('@astryxdesign/core');
+ expect(requested).not.toHaveProperty(ROOT_RAN);
+ });
+
+ it("a theme that imports the root gets the root's own exports", () => {
+ const {status, requested} = run(['theme', 'build', 'reef.ts']);
+ expect(status).toBe(0);
+ expect(requested).toHaveProperty(ROOT_RAN);
+ expect(fs.readFileSync(path.join(dir, 'reef.css'), 'utf-8')).toContain(
+ '--color-bg: #0a0a0a',
+ );
+ });
});
diff --git a/packages/cli/api/theme/build/build.lazy-root.test.mjs b/packages/cli/api/theme/build/build.lazy-root.test.mjs
new file mode 100644
index 0000000000..f8cd9a27af
--- /dev/null
+++ b/packages/cli/api/theme/build/build.lazy-root.test.mjs
@@ -0,0 +1,89 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Verifies that the theme build loads a Core's root entry only on first
+ * use, once, and that a root it cannot load gives null. A root that only
+ * `import()` can load is named in an error instead.
+ */
+
+import {afterAll, 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, pathToFileURL} from 'node:url';
+import {lazyRootModule} from './build.mjs';
+
+const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-lazy-root-'));
+
+afterAll(() => {
+ fs.rmSync(dir, {recursive: true, force: true});
+});
+
+/**
+ * Write an ES module into the test folder.
+ * @param {string} name
+ * @param {string} source
+ * @returns {string} its path
+ */
+function writeModule(name, source) {
+ const file = path.join(dir, name);
+ fs.writeFileSync(file, source);
+ return file;
+}
+
+describe('lazyRootModule', () => {
+ it('loads the root once, on first use', () => {
+ const file = writeModule(
+ 'root.mjs',
+ 'globalThis.__astryxLazyRootLoads = (globalThis.__astryxLazyRootLoads ?? 0) + 1;\nexport const Button = () => null;\n',
+ );
+ const load = lazyRootModule(() => file);
+ expect(globalThis.__astryxLazyRootLoads).toBeUndefined();
+ expect(typeof load().Button).toBe('function');
+ load();
+ expect(globalThis.__astryxLazyRootLoads).toBe(1);
+ });
+
+ it('gives null for a root that does not load or resolve', () => {
+ expect(lazyRootModule(() => path.join(dir, 'missing.mjs'))()).toBeNull();
+ expect(lazyRootModule(() => null)()).toBeNull();
+ expect(
+ lazyRootModule(() => {
+ throw new Error('no root entry');
+ })(),
+ ).toBeNull();
+ });
+
+ it('names a root that awaits at its top level', () => {
+ const file = writeModule(
+ 'waits.mjs',
+ 'await Promise.resolve();\nexport const Button = () => null;\n',
+ );
+ expect(() => lazyRootModule(() => file)()).toThrow(
+ /cannot be loaded with require\(\) \(ERR_REQUIRE_ASYNC_MODULE\)/,
+ );
+ });
+
+ it('names a root that require() refuses when Node runs without require(esm)', () => {
+ const file = writeModule(
+ 'plain.mjs',
+ 'export const Button = () => null;\n',
+ );
+ const build = pathToFileURL(
+ path.join(path.dirname(fileURLToPath(import.meta.url)), 'build.mjs'),
+ ).href;
+ const script =
+ `import {lazyRootModule} from ${JSON.stringify(build)};\n` +
+ `try { lazyRootModule(() => ${JSON.stringify(file)})(); console.log('loaded'); }\n` +
+ 'catch (error) { console.log(error.message); }\n';
+ const run = spawnSync(
+ process.execPath,
+ ['--no-experimental-require-module', '--input-type=module', '-e', script],
+ {encoding: 'utf8'},
+ );
+ expect(run.stdout, `status ${run.status}: ${run.stderr}`).toMatch(
+ /cannot be loaded with require\(\) \(ERR_REQUIRE_ESM\)/,
+ );
+ });
+});
diff --git a/packages/cli/api/theme/build/build.mjs b/packages/cli/api/theme/build/build.mjs
index 7d4b9ac46d..70afeeb19c 100644
--- a/packages/cli/api/theme/build/build.mjs
+++ b/packages/cli/api/theme/build/build.mjs
@@ -132,12 +132,13 @@ import {resolveIconImports} from './icon-imports.mjs';
*/
/** @type {any} */ let _coreThemeModule = null;
/**
- * The `@astryxdesign/core` ROOT namespace, imported separately because it
+ * The `@astryxdesign/core` ROOT namespace, loaded separately because it
* exports far more than the theme subpath. Interception must hand a theme file
* that imports a component from the root the root's own exports, not the theme
- * namespace wearing its name.
+ * namespace wearing its name. It loads on first use: see lazyRootModule.
+ * @type {(() => any) | null}
*/
-/** @type {any} */ let _coreRootModule = null;
+let _coreRootModule = null;
/** @type {any} */ let _coreImportError = null;
/**
@@ -145,7 +146,7 @@ import {resolveIconImports} from './icon-imports.mjs';
* functions the build calls, and why the import failed, if it did.
* @typedef {{
* themeModule: any,
- * rootModule: any,
+ * rootModule: (() => any) | null,
* importError: any,
* defineTheme: any,
* generateThemeRulesSplit: any,
@@ -154,6 +155,47 @@ import {resolveIconImports} from './icon-imports.mjs';
* }} CoreBindings
*/
+/**
+ * A Core's root namespace, loaded on first use. The root entry loads all of
+ * Core and React, and only a theme that imports the root specifier needs it.
+ * Requiring the file an import resolves to returns the namespace `import()`
+ * gives. A root that cannot be loaded gives null, and interception then hands
+ * the theme namespace in its place. A root that only `import()` can load
+ * throws instead: one that awaits at its top level, or any root when Node runs
+ * without require(esm).
+ * @param {() => string | null} resolveFile
+ * @returns {() => any}
+ */
+export function lazyRootModule(resolveFile) {
+ /** @type {{namespace: any} | null} */
+ let loaded = null;
+ return () => {
+ if (loaded) return loaded.namespace;
+ let namespace = null;
+ let file = null;
+ try {
+ file = resolveFile();
+ } catch {
+ // A Core whose root entry does not resolve falls back below.
+ }
+ try {
+ if (file) namespace = createRequire(import.meta.url)(file);
+ } catch (error) {
+ const code = /** @type {any} */ (error)?.code;
+ // The theme namespace would stand in for the root's own exports here.
+ if (code === 'ERR_REQUIRE_ASYNC_MODULE' || code === 'ERR_REQUIRE_ESM') {
+ throw new Error(
+ `The @astryxdesign/core root entry at ${file} cannot be loaded with require() (${code}), so a theme that imports it cannot be built.`,
+ {cause: error},
+ );
+ }
+ // A Core without a usable root entry still builds themes.
+ }
+ loaded = {namespace};
+ return namespace;
+ };
+}
+
/**
* Import the CLI's own Core: the `@astryxdesign/core` this module resolves.
* Never throws. A failed import is kept as `importError`, so the build can
@@ -178,12 +220,9 @@ async function importCliCore() {
core.generateThemeRulesSplit = coreTheme.generateThemeRulesSplit;
core.generateOnMediaCSS = coreTheme.generateOnMediaCSS;
core.generateAdaptationCSS = coreTheme.generateAdaptationCSS;
- try {
- core.rootModule = await import('@astryxdesign/core');
- } catch {
- // A core without a usable root entry still builds themes; interception
- // falls back to the theme namespace for the root specifier.
- }
+ core.rootModule = lazyRootModule(() =>
+ fileURLToPath(import.meta.resolve('@astryxdesign/core')),
+ );
} catch (e) {
// Capture the reason so the theme action can surface a precise, actionable
// error. The hard failure happens when `theme build` runs.
@@ -350,18 +389,10 @@ async function loadProjectCore(cwd, cliCore, {projectOnly = false} = {}) {
ERROR_CODES.ERR_CORE_INCOMPATIBLE,
);
}
- 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,
+ rootModule: lazyRootModule(() => rootFile),
importError: null,
defineTheme: themeModule.defineTheme,
generateThemeRulesSplit: themeModule.generateThemeRulesSplit,
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 8c2a2fdbad..4a13012383 100644
--- a/packages/cli/api/theme/build/build.project-core.test.mjs
+++ b/packages/cli/api/theme/build/build.project-core.test.mjs
@@ -122,7 +122,8 @@ describe('theme build generates with the Core the project installed', () => {
const app = makeDir();
installCore(app);
await themeBuild('ocean.mjs', {}, {cwd: app});
- expect(globalThis.__astryxProjectCoreLoads).toEqual(['theme', 'root']);
+ // The theme imports nothing from the root entry, so the root never loads.
+ expect(globalThis.__astryxProjectCoreLoads).toEqual(['theme']);
// 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();
diff --git a/packages/cli/api/theme/build/core-interception.mjs b/packages/cli/api/theme/build/core-interception.mjs
index 2649e4d27f..7450c5900e 100644
--- a/packages/cli/api/theme/build/core-interception.mjs
+++ b/packages/cli/api/theme/build/core-interception.mjs
@@ -236,7 +236,8 @@ function mergeGenerativeAxes(inherited, own) {
* standalone builds with current Core do not.
*
* @param {any} coreThemeModule - The installed `@astryxdesign/core/theme` namespace.
- * @param {any} [coreRootModule] - The installed `@astryxdesign/core` namespace.
+ * @param {any} [coreRootModule] - The installed `@astryxdesign/core` namespace,
+ * or a function that loads it. A function is called once, on first use.
* @returns {CoreInterception}
*/
export function interceptCore(coreThemeModule, coreRootModule) {
@@ -287,14 +288,31 @@ export function interceptCore(coreThemeModule, coreRootModule) {
};
};
- return {
- modules: {
- '@astryxdesign/core/theme': wrapNamespace(coreThemeModule),
+ const modules = {
+ '@astryxdesign/core/theme': wrapNamespace(coreThemeModule),
+ };
+ /** @type {any} */
+ let wrappedRoot;
+ // jiti reads a virtual module only when a theme imports its specifier. So
+ // the root, which loads all of Core, loads only for a theme that asks.
+ Object.defineProperty(modules, '@astryxdesign/core', {
+ enumerable: true,
+ configurable: true,
+ get() {
+ const root =
+ typeof coreRootModule === 'function'
+ ? coreRootModule()
+ : coreRootModule;
// Falls back to the theme namespace only when the root could not be
// imported at all; a partial root is better than none, and a core
// missing its own root entry is already broken.
- '@astryxdesign/core': wrapNamespace(coreRootModule ?? coreThemeModule),
+ wrappedRoot ??= wrapNamespace(root ?? coreThemeModule);
+ return wrappedRoot;
},
+ });
+
+ return {
+ modules,
// prettier-ignore
observed(theme) { return wasObserved(theme, byReference); },
diff --git a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs b/packages/cli/foundation/doc-compiler/doc-loads.test.mjs
index 3f2f06d361..b420d04f5f 100644
--- a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs
+++ b/packages/cli/foundation/doc-compiler/doc-loads.test.mjs
@@ -65,12 +65,13 @@ const RUNNERS = {
sites: ['importThemeArtifact'],
},
'api/theme/build/build.mjs': {
- runs: "theme source modules, through jiti; the project's installed Core",
+ runs: "theme source modules, through jiti; the project's installed Core, and a Core's root entry once a theme imports it",
sites: [
'.evalModule() ×2',
'.import()',
'createJiti ×5',
- 'import(<computed>) ×3',
+ 'import(<computed>) ×2',
+ 'require(<computed>)',
],
},
'api/theme/build/core-interception.mjs': {