An open source design system that's fully customizable and agent ready
TypeScript
perf(cli): doctor and family builds load an installed Core's root only when the load requires it (#8644)
Christopher Chedeau9e3d9f51ce10
diff --git a/.changeset/theme-build-lazy-core-root.md b/.changeset/theme-build-lazy-core-root.mdnew file mode 100644index 0000000000..a4316590f1--- /dev/null+++ b/.changeset/theme-build-lazy-core-root.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[perf] `astryx doctor`'s theme checks, family builds and builds against an older Core defer an installed Core's root entry. It loads only when the theme or one of its `.cjs` dependencies imports it. A theme that does not import Core's root no longer loads all of Core and its components for them.++@vjeuxdiff --git a/packages/cli/api/theme/build/build.mjs b/packages/cli/api/theme/build/build.mjsindex 828dd4e98d..da9bb38f9b 100644--- a/packages/cli/api/theme/build/build.mjs+++ b/packages/cli/api/theme/build/build.mjs@@ -1973,7 +1973,6 @@ async function importThemeModule(filePath, interception, /** @type {any} */ load// A frozen require(esm) namespace cannot be patched, so retain that gap and// let the selected lineage decide whether it matters.const commonJsPatch = interception.patchCommonJs(filePath);- degraded.commonJs = !commonJsPatch.covered;try {try {mod = jiti(filePath);@@ -1995,6 +1994,8 @@ async function importThemeModule(filePath, interception, /** @type {any} */ load});}} finally {+ // Read after the load: the root is wrapped when the load requires it.+ degraded.commonJs = !commonJsPatch.covered;commonJsPatch.undo();}} else {diff --git a/packages/cli/api/theme/build/build.project-core.test.mjs b/packages/cli/api/theme/build/build.project-core.test.mjsindex 4a13012383..62255e2e97 100644--- a/packages/cli/api/theme/build/build.project-core.test.mjs+++ b/packages/cli/api/theme/build/build.project-core.test.mjs@@ -17,7 +17,11 @@ 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 {+ coreUnavailableMessage,+ themeBuild,+ validateThemePrivateInputs,+} from './build.mjs';import {fetchCarriedThemeCoreDir} from '../_adapter.mjs';vi.mock('../_adapter.mjs', async importOriginal => {@@ -137,6 +141,50 @@ describe('theme build generates with the Core the project installed', () => {expect(rules(app)).toContain('#0a0a0a');});+ it('loads the app’s installed root only for a theme that imports it', async () => {+ const app = makeDir();+ installCore(app);+ fs.writeFileSync(+ path.join(app, 'harbor.mjs'),+ "import {defineTheme} from '@astryxdesign/core';\nexport default defineTheme({name: 'harbor', tokens: {'--color-bg': '#0b0b0b'}});\n",+ );+ await themeBuild('harbor.mjs', {}, {cwd: app});+ expect(globalThis.__astryxProjectCoreLoads).toEqual(['theme', 'root']);+ expect(fs.readFileSync(path.join(app, 'harbor.css'), 'utf-8')).toContain(+ '#0b0b0b',+ );+ });++ it('checks a theme’s private inputs without loading the app’s installed root when the theme does not import it', async () => {+ // The doctor's check: the CommonJS patch wraps the installed Core for a+ // `.cjs` dependency, and wraps its root only if something requires it.+ const app = makeDir();+ installCore(app);+ expect(await validateThemePrivateInputs('ocean.mjs', {cwd: app})).toEqual(+ [],+ );+ expect(globalThis.__astryxProjectCoreLoads).toEqual(['theme']);+ });++ it('checks the private inputs of every theme beside an installed Core whose theme entry fails to load', async () => {+ // Doctor runs this check for each added theme. A `.cjs` dependency could+ // not load that entry either, so the CommonJS patch skips it.+ const app = makeDir();+ installCore(app, {+ themeModule: "throw new Error('the theme entry failed to load');\n",+ });+ fs.writeFileSync(+ path.join(app, 'harbor.mjs'),+ "export default {name: 'harbor', tokens: {'--_card-radius': '4px'}};\n",+ );+ expect(await validateThemePrivateInputs('ocean.mjs', {cwd: app})).toEqual(+ [],+ );+ const errors = await validateThemePrivateInputs('harbor.mjs', {cwd: app});+ expect(errors).toHaveLength(1);+ expect(errors[0]).toContain('--_card-radius');+ });+it('keeps the CLI’s own Core when the project has none', async () => {const bare = makeDir();await themeBuild('ocean.mjs', {}, {cwd: bare});diff --git a/packages/cli/api/theme/build/core-interception.mjs b/packages/cli/api/theme/build/core-interception.mjsindex 7450c5900e..1bd9ec0aed 100644--- a/packages/cli/api/theme/build/core-interception.mjs+++ b/packages/cli/api/theme/build/core-interception.mjs@@ -67,7 +67,7 @@* SYNC: packages/cli/api/theme/build/build.mjs (importThemeModule)*/-import {createRequire} from 'node:module';+import Module, {createRequire} from 'node:module';import * as path from 'node:path';import {findInstalledPackage} from '../../../foundation/fs/paths.mjs';@@ -293,20 +293,24 @@ export function interceptCore(coreThemeModule, coreRootModule) {};/** @type {any} */let wrappedRoot;+ let rootRead = false;// 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.- wrappedRoot ??= wrapNamespace(root ?? coreThemeModule);+ if (!rootRead) {+ 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.+ wrappedRoot = wrapNamespace(root ?? coreThemeModule);+ rootRead = true;+ }return wrappedRoot;},});@@ -469,28 +473,19 @@ export function interceptCore(coreThemeModule, coreRootModule) {return {covered, undo: () => {}};}- for (const specifier of [- '@astryxdesign/core/theme',- '@astryxdesign/core',- ]) {- /** @type {any} */- let cjs;- try {- cjs = createRequire(fromFile)(specifier);- } catch {- // A specifier that CommonJS cannot resolve cannot be used by a `.cjs`- // source dependency either, so it creates no unobserved path.- continue;- }-+ const requireFromTheme = createRequire(fromFile);+ /**+ * Wraps `defineTheme` on a CommonJS exports object in place, so a call+ * from a `.cjs` dependency is recorded. False when it cannot be wrapped.+ * @param {any} cjs+ */+ const wrap = cjs => {const real = cjs?.defineTheme;- if (typeof real !== 'function') continue;+ if (typeof real !== 'function') return true;const descriptor = Object.getOwnPropertyDescriptor(cjs, 'defineTheme');if (!descriptor || !(descriptor.writable || descriptor.configurable)) {- covered = false;- continue;+ return false;}-try {Object.defineProperty(cjs, 'defineTheme', {...descriptor,@@ -503,16 +498,84 @@ export function interceptCore(coreThemeModule, coreRootModule) {undo.push(() =>Object.defineProperty(cjs, 'defineTheme', descriptor),);+ return true;} catch {// ESM namespace exotic objects may report a writable descriptor but// still reject redefinition. This is a real coverage failure, not an// absent CommonJS entry: a `.cjs` dependency can call the function// while the recorder cannot wrap it.- covered = false;+ return false;+ }+ };++ // An entry that CommonJS cannot resolve or load cannot be used by a+ // `.cjs` source dependency either, so it creates no unobserved path. It+ // is skipped, as are the entries of a package config CommonJS cannot+ // read. Throwing instead would fail every theme beside such an install.+ /** @param {string} specifier @returns {string | null} */+ const resolveEntry = specifier => {+ try {+ return requireFromTheme.resolve(specifier);+ } catch {+ return null;+ }+ };+ const themeFile = resolveEntry('@astryxdesign/core/theme');+ const rootFile = resolveEntry('@astryxdesign/core');++ // The theme subpath is small, so it is wrapped now.+ if (themeFile) {+ /** @type {any} */+ let themeExports = null;+ try {+ themeExports = requireFromTheme(themeFile);+ } catch {+ // A dependency that requires it fails the same way.+ }+ if (themeExports && !wrap(themeExports)) covered = false;+ }++ // The root loads all of Core, so it is wrapped only once this load+ // requires it. Every CommonJS require goes through `Module._load`,+ // which is watched for the load's duration. The watch reads the require+ // cache, where the root's file is keyed by its real path. So any+ // request that loads that file counts, however it is spelled. A load+ // that never requires the root leaves no path through it to observe.+ if (rootFile) {+ /** @type {any} */+ const loader = Module;+ /** Wraps the root once its file has run; false until then. */+ const wrapLoadedRoot = () => {+ const loaded = loader._cache[rootFile];+ // A CommonJS module is cached before its body runs, so a require+ // inside the root's own body sees it partly built.+ if (!loaded?.loaded) return false;+ if (!wrap(loaded.exports)) covered = false;+ return true;+ };+ if (!wrapLoadedRoot()) {+ const load = loader._load;+ /** @this {any} @param {...any} args */+ const watch = function (...args) {+ const exports = load.apply(this, args);+ if (loader._load === watch && wrapLoadedRoot()) {+ loader._load = load;+ }+ return exports;+ };+ loader._load = watch;+ // Theme loads never overlap: each caller awaits one at a time. The+ // watch is still removed only while it is the one installed.+ undo.push(() => {+ if (loader._load === watch) loader._load = load;+ });}}return {- covered,+ /** Read after the load: a root required during it counts. */+ get covered() {+ return covered;+ },undo() {for (const restore of undo.reverse()) {try {diff --git a/packages/cli/api/theme/build/core-interception.test.mjs b/packages/cli/api/theme/build/core-interception.test.mjsnew file mode 100644index 0000000000..9bc2654703--- /dev/null+++ b/packages/cli/api/theme/build/core-interception.test.mjs@@ -0,0 +1,210 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file core-interception.test.mjs+ * @input interceptCore with a stand-in theme namespace and a root loader; jiti+ * evaluating modules through the interception's virtual modules+ * @output The root namespace is read once, only when a theme module requires+ * the root, with its own exports and `defineTheme` wrapped. A Core with no+ * root entry gives the theme namespace. `patchCommonJs` skips a Core entry+ * that is absent or fails to load, and the entries of an unreadable package+ * config. It wraps the root whatever request loads its file. A theme that+ * imports only the theme subpath never loads the root through jiti.+ * @position Unit test of packages/cli/api/theme/build/core-interception.mjs+ */++import * as fs from 'node:fs';+import {createRequire} from 'node:module';+import * as os from 'node:os';+import * as path from 'node:path';+import {createJiti} from 'jiti';+import {afterEach, describe, expect, it, vi} from 'vitest';+import {interceptCore} from './core-interception.mjs';++const themeNamespace = () => ({+ defineTheme: input => ({...input, defined: true}),+ themeOnly: 'theme',+});+const rootNamespace = () => ({+ defineTheme: input => ({...input, defined: true}),+ Button: 'root-only',+});++let dir;+afterEach(() => {+ if (dir) fs.rmSync(dir, {recursive: true, force: true});+ dir = undefined;+});++describe('interceptCore', () => {+ it('reads the root only when it is asked for, once', () => {+ const loadRoot = vi.fn(rootNamespace);+ const {modules, observed} = interceptCore(themeNamespace(), loadRoot);+ expect(modules['@astryxdesign/core/theme'].themeOnly).toBe('theme');+ expect('@astryxdesign/core' in modules).toBe(true);+ expect(loadRoot).not.toHaveBeenCalled();++ const root = modules['@astryxdesign/core'];+ expect(root.Button).toBe('root-only');+ expect(observed(root.defineTheme({name: 'ocean'}))).toBe(true);+ expect(modules['@astryxdesign/core']).toBe(root);+ expect(loadRoot).toHaveBeenCalledTimes(1);+ });++ it('gives the theme namespace for the root of a Core with no root entry', () => {+ const {modules} = interceptCore(themeNamespace(), null);+ expect(modules['@astryxdesign/core'].themeOnly).toBe('theme');+ });++ it('still takes a root namespace itself', () => {+ const {modules} = interceptCore(themeNamespace(), rootNamespace());+ expect(modules['@astryxdesign/core'].Button).toBe('root-only');+ });++ it('loads the root through jiti only for a module that requires it', async () => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-intercept-'));+ fs.writeFileSync(+ path.join(dir, 'theme-only.ts'),+ "import {defineTheme} from '@astryxdesign/core/theme';\nexport default defineTheme({name: 'ocean'});\n",+ );+ fs.writeFileSync(+ path.join(dir, 'root.ts'),+ "import {Button, defineTheme} from '@astryxdesign/core';\nexport default defineTheme({name: String(Button)});\n",+ );+ const loadRoot = vi.fn(rootNamespace);+ const {modules} = interceptCore(themeNamespace(), loadRoot);+ const jiti = createJiti(import.meta.url, {+ moduleCache: false,+ virtualModules: modules,+ });++ const themeOnly = await jiti.import(path.join(dir, 'theme-only.ts'), {+ default: true,+ });+ expect(themeOnly).toMatchObject({name: 'ocean', defined: true});+ expect(loadRoot).not.toHaveBeenCalled();++ const root = await jiti.import(path.join(dir, 'root.ts'), {default: true});+ expect(root).toMatchObject({name: 'root-only', defined: true});+ expect(loadRoot).toHaveBeenCalledTimes(1);+ });+});++/**+ * A project whose installed Core holds `files` (path to content), and a theme+ * file beside it.+ * @param {Record<string, string>} files+ */+function project(files) {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-core-entries-'));+ const core = path.join(dir, 'node_modules', '@astryxdesign', 'core');+ for (const [relative, content] of Object.entries(files)) {+ const file = path.join(core, relative);+ fs.mkdirSync(path.dirname(file), {recursive: true});+ fs.writeFileSync(file, content);+ }+ const theme = path.join(dir, 'theme.ts');+ fs.writeFileSync(theme, 'export {};\n');+ return {core, theme};+}++const CORE_PACKAGE = JSON.stringify({+ name: '@astryxdesign/core',+ exports: {'.': './index.cjs', './theme': './theme.cjs'},+});++describe("Core's entries", () => {+ it('patchCommonJs reads an entry that is not there as absent', () => {+ const {theme} = project({+ 'package.json': JSON.stringify({+ name: '@astryxdesign/core',+ exports: {'./theme': './theme.cjs'},+ }),+ });+ const patch = interceptCore(themeNamespace(), null).patchCommonJs(theme);+ expect(patch.covered).toBe(true);+ patch.undo();+ });++ it('patchCommonJs skips a theme entry that fails to load, and still wraps the root when the load requires it', () => {+ const {theme} = project({+ 'package.json': CORE_PACKAGE,+ 'theme.cjs': "throw new Error('the theme entry failed to load');",+ 'index.cjs':+ 'module.exports = {defineTheme: input => ({...input, defined: true})};',+ });+ const interception = interceptCore(themeNamespace(), null);+ const patch = interception.patchCommonJs(theme);+ try {+ // A `.cjs` dependency beside the theme requires the root during the load.+ const root = createRequire(theme)('@astryxdesign/core');+ expect(interception.observed(root.defineTheme({name: 'reef'}))).toBe(+ true,+ );+ expect(patch.covered).toBe(true);+ } finally {+ patch.undo();+ }+ });++ it('patchCommonJs wraps the root whatever request loads its file', () => {+ // A vendored Core linked into node_modules: a `.cjs` dependency can reach+ // the root's file by a path that never names the package.+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-core-linked-'));+ const vendored = path.join(dir, 'vendor', 'core');+ fs.mkdirSync(vendored, {recursive: true});+ fs.writeFileSync(path.join(vendored, 'package.json'), CORE_PACKAGE);+ fs.writeFileSync(path.join(vendored, 'theme.cjs'), 'module.exports = {};');+ fs.writeFileSync(+ path.join(vendored, 'index.cjs'),+ 'module.exports = {defineTheme: input => ({...input, defined: true})};',+ );+ const scope = path.join(dir, 'node_modules', '@astryxdesign');+ fs.mkdirSync(scope, {recursive: true});+ fs.symlinkSync(vendored, path.join(scope, 'core'), 'dir');+ const theme = path.join(dir, 'theme.ts');+ fs.writeFileSync(theme, 'export {};\n');+ const interception = interceptCore(themeNamespace(), null);+ const patch = interception.patchCommonJs(theme);+ try {+ const root = createRequire(theme)('./vendor/core/index.cjs');+ expect(interception.observed(root.defineTheme({name: 'reef'}))).toBe(+ true,+ );+ expect(patch.covered).toBe(true);+ } finally {+ patch.undo();+ }+ });++ it('patchCommonJs wraps a root whose body requires other files before it defines defineTheme', () => {+ const {theme} = project({+ 'package.json': CORE_PACKAGE,+ 'theme.cjs': 'module.exports = {};',+ 'util.cjs': 'module.exports = {name: input => input.name};',+ 'index.cjs':+ "const util = require('./util.cjs');\nexports.defineTheme = input => ({...input, defined: util.name(input)});\n",+ });+ const interception = interceptCore(themeNamespace(), null);+ const patch = interception.patchCommonJs(theme);+ try {+ const root = createRequire(theme)('@astryxdesign/core');+ expect(interception.observed(root.defineTheme({name: 'reef'}))).toBe(+ true,+ );+ expect(patch.covered).toBe(true);+ } finally {+ patch.undo();+ }+ });++ it('patchCommonJs skips the entries of a package config it cannot read', () => {+ const {theme} = project({+ 'package.json': '{"name": "@astryxdesign/core", "exports": ',+ 'theme.cjs': 'module.exports = {};',+ });+ const patch = interceptCore(themeNamespace(), null).patchCommonJs(theme);+ expect(patch.covered).toBe(true);+ patch.undo();+ });+});diff --git a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs b/packages/cli/foundation/doc-compiler/doc-loads.test.mjsindex d1469e1407..d7a8103a4b 100644--- a/packages/cli/foundation/doc-compiler/doc-loads.test.mjs+++ b/packages/cli/foundation/doc-compiler/doc-loads.test.mjs@@ -71,8 +71,8 @@ const RUNNERS = {],},'api/theme/build/core-interception.mjs': {- runs: "@astryxdesign/core as a theme's CommonJS dependencies require it, to wrap defineTheme",- sites: ['require(<computed>)'],+ runs: "@astryxdesign/core/theme beside a theme whose CommonJS dependencies may require Core, to wrap defineTheme; Module._load is watched during the load so the root is wrapped only as the load requires it; require.resolve for Core's entries",+ sites: ['module', 'require(<computed>)'],},'api/upgrade/_adapter.mjs': {runs: 'the commands a codemod declares as its post-codemod hooks',