An open source design system that's fully customizable and agent ready
TypeScript
fix(cli): theme modules that load their own stylesheet pass verify, doctor, and component (#7490)
Joeyb40ba52f32f4
diff --git a/.changeset/doctor-theme-stylesheet-imports.md b/.changeset/doctor-theme-stylesheet-imports.mdnew file mode 100644index 0000000000..56b431cd1c--- /dev/null+++ b/.changeset/doctor-theme-stylesheet-imports.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[fix] `astryx doctor` no longer fails "Theme owners and built imports", and `astryx component` no longer stops with "Could not load the recorded theme", when an added theme's built module imports a stylesheet, as in `import './ocean.css'`. Node cannot load a stylesheet, so the CLI checks that each imported `.css` file exists, then treats it as empty. It looks for each stylesheet from the theme module's folder, also when a module that the theme imports from another folder names it. Doctor still fails when an imported stylesheet is missing, and when the module has any other problem, such as a missing dependency, a syntax error, or an error thrown while it loads.++@josephfarinadiff --git a/.changeset/verify-theme-module-own-styles.md b/.changeset/verify-theme-module-own-styles.mdnew file mode 100644index 0000000000..6945d09abc--- /dev/null+++ b/.changeset/verify-theme-module-own-styles.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[fix] `astryx integration verify` accepts a theme module that loads the theme's own styles. Such a module imports the theme's exported stylesheet and font stylesheet for their side effects, and re-exports from the module `astryx theme build` writes either everything or only its theme, under the theme's export name. Verify also finds that built module by the name `theme build` gives it, the theme's own name, so a theme whose name differs from its slug no longer fails to rebuild. Any other difference from the built module still fails with `theme_module_stale`, and for a module that re-exports the theme, the message now says what is wrong.++@josephfarinadiff --git a/packages/cli/api/doctor/theme-checks.test.mjs b/packages/cli/api/doctor/theme-checks.test.mjsindex f15305fb5c..d1dabfa07f 100644--- a/packages/cli/api/doctor/theme-checks.test.mjs+++ b/packages/cli/api/doctor/theme-checks.test.mjs@@ -340,6 +340,142 @@ describe('app-theme doctor checks', () => {expect(result.message).not.toMatch(/\n\s+at /u);});+ it('passes theme-owners when a built module imports its stylesheet', async () => {+ const {dir, packageDir} = await fixture();+ write(+ path.join(packageDir, 'dist/ocean.js'),+ "import './ocean.css';\nimport '@acme/themes/themes/ocean.css';\nexport const oceanTheme = {name: 'ocean', tokens: {}};\n",+ );++ const checks = await checkAppThemes(dir);++ expect(checks.map(item => item.status)).toEqual(Array(10).fill('pass'));+ expect(check(checks, 'theme-owners').message).toContain(+ 'every built module loads',+ );+ const cli = runDoctor(dir);+ expect(cli.status).toBe(0);+ expect(cli.stdout).not.toContain('could not load its built module');+ }, 30_000);++ it('passes every check for an entry that loads its fonts and stylesheet and re-exports the built module', async () => {+ const {dir, packageDir} = await fixture([+ {+ slug: 'ocean',+ fontFamily: 'Ocean Sans',+ fontCss:+ "@font-face { font-family: 'Ocean Sans'; src: local('Ocean Sans'); }\n",+ },+ ]);+ write(+ path.join(packageDir, 'dist/ocean.built.js'),+ "export const oceanTheme = {name: 'ocean', tokens: {}, fontFamily: 'Ocean Sans'};\n",+ );+ write(+ path.join(packageDir, 'dist/ocean.js'),+ "import './ocean.fonts.css';\nimport '@acme/themes/themes/ocean.css';\nexport {oceanTheme} from './ocean.built.js';\n",+ );++ const checks = await checkAppThemes(dir);++ expect(checks.map(item => [item.id, item.status])).toEqual(+ checks.map(item => [item.id, 'pass']),+ );+ expect(checks).toHaveLength(10);+ const cli = runDoctor(dir);+ expect(cli.status).toBe(0);+ expect(cli.stdout).not.toContain('could not load its built module');+ }, 30_000);++ it('passes every check for an entry that re-exports a theme whose own name differs from its slug', async () => {+ const {dir, packageDir} = await fixture([+ {+ slug: 'ocean',+ css: '[data-astryx-theme="deep-sea"] { --color-text: black; }\n',+ fontFamily: 'Ocean Sans',+ fontCss:+ "@font-face { font-family: 'Ocean Sans'; src: local('Ocean Sans'); }\n",+ },+ ]);+ write(+ path.join(packageDir, 'dist/deep-sea.js'),+ "export const deepSeaTheme = {name: 'deep-sea', tokens: {}, fontFamily: 'Ocean Sans'};\n",+ );+ write(+ path.join(packageDir, 'dist/ocean.js'),+ "import './ocean.fonts.css';\nimport './ocean.css';\nexport {deepSeaTheme as oceanTheme} from './deep-sea.js';\n",+ );++ const checks = await checkAppThemes(dir);++ expect(checks.map(item => [item.id, item.status])).toEqual(+ checks.map(item => [item.id, 'pass']),+ );+ expect(checks).toHaveLength(10);+ }, 30_000);++ it.each([+ [+ 'a missing dependency',+ "import '@acme/definitely-missing-dep';\nexport const oceanTheme = {name: 'ocean', tokens: {}};\n",+ '@acme/definitely-missing-dep',+ ],+ [+ 'a throwing module',+ "throw new Error('broken theme module');\nexport const oceanTheme = {name: 'ocean', tokens: {}};\n",+ 'broken theme module',+ ],+ ])(+ 'still fails theme-owners when a built module imports its stylesheet and has %s',+ async (_label, rest, detail) => {+ const {dir, packageDir} = await fixture();+ write(+ path.join(packageDir, 'dist/ocean.js'),+ `import './ocean.css';\n${rest}`,+ );++ const result = check(await checkAppThemes(dir), 'theme-owners');++ expect(result).toMatchObject({id: 'theme-owners', status: 'fail'});+ expect(result.message).toContain(+ 'Theme "ocean" from @acme/themes could not load its built module',+ );+ expect(result.message).toContain(detail);+ },+ );++ it("still fails theme-owners when the theme's stylesheet export is missing", async () => {+ const {dir, packageDir} = await fixture();+ write(+ path.join(packageDir, 'dist/ocean.js'),+ "import './ocean.css';\nexport const oceanTheme = {name: 'ocean', tokens: {}};\n",+ );+ fs.rmSync(path.join(packageDir, 'dist/ocean.css'));++ const result = check(await checkAppThemes(dir), 'theme-owners');++ expect(result).toMatchObject({id: 'theme-owners', status: 'fail'});+ expect(result.message).toContain(+ 'Missing stylesheet export @acme/themes/themes/ocean.css',+ );+ });++ it('still fails theme-owners when another stylesheet the built module imports is missing', async () => {+ const {dir, packageDir} = await fixture();+ write(+ path.join(packageDir, 'dist/ocean.js'),+ "import './ocean.css';\nimport './fonts.css';\nexport const oceanTheme = {name: 'ocean', tokens: {}};\n",+ );++ const result = check(await checkAppThemes(dir), 'theme-owners');++ expect(result).toMatchObject({id: 'theme-owners', status: 'fail'});+ expect(result.message).toContain(+ 'Theme "ocean" from @acme/themes could not load its built module',+ );+ expect(result.message).toContain('fonts.css');+ });+it('fails theme-owners for an ambiguous multi-theme record', async () => {const {dir, packageDir} = await fixture([{slug: 'ocean'}, {slug: 'reef'}]);const packageFile = path.join(packageDir, 'package.json');diff --git a/packages/cli/api/integration/pack-check.mjs b/packages/cli/api/integration/pack-check.mjsindex 842e4cc5e3..4098ad45f2 100644--- a/packages/cli/api/integration/pack-check.mjs+++ b/packages/cli/api/integration/pack-check.mjs@@ -40,6 +40,7 @@ import {} from '../../foundation/discovery/docs-discovery.mjs';import {discoverIntegrationThemes} from '../../foundation/discovery/theme-discovery.mjs';import {inspectPackageExport} from '../../foundation/discovery/package-exports.mjs';+import {parse as parseModule} from '@babel/parser';import {moduleExportsName} from '../../foundation/discovery/module-exports.mjs';import {ThemeImportError,@@ -574,6 +575,7 @@ async function validateIncompleteThemeExports(path.join(os.tmpdir(), `astryx-theme-${localTheme.slug}-`),);const expectedCss = path.join(expectedDir, `${localTheme.slug}.css`);+ let expectedModule = path.join(expectedDir, `${localTheme.slug}.js`);try {if (outputs.some(output => output.kind !== 'font stylesheet')) {// The scratch directory is the write root; the package stays the cwd,@@ -583,6 +585,12 @@ async function validateIncompleteThemeExports(if (receipt == null || receipt.type !== 'theme.build') {throw new Error('the theme build produced no complete receipt');}+ expectedModule = builtModuleFile(+ receipt,+ packageDir,+ expectedDir,+ localTheme.slug,+ );}for (const output of outputs) {const localFile = /** @type {string} */ (output.inspected.target);@@ -599,9 +607,7 @@ async function validateIncompleteThemeExports(continue;}const expectedFile =- output.kind === 'module'- ? path.join(expectedDir, `${localTheme.slug}.js`)- : expectedCss;+ output.kind === 'module' ? expectedModule : expectedCss;const expected = normalizeThemeVerifyForCompare(fs.readFileSync(expectedFile, 'utf-8'),);@@ -645,6 +651,250 @@ async function validateIncompleteThemeExports(return issues;}+/**+ * The module a scratch `theme build` wrote. Its file is named by the theme's+ * own name, which can differ from the slug the package exports it under. A+ * receipt that names no file inside the scratch directory falls back to the+ * slug.+ * @param {any} receipt+ * @param {string} cwd the directory the build ran in+ * @param {string} expectedDir+ * @param {string} slug+ * @returns {string}+ */+function builtModuleFile(receipt, cwd, expectedDir, slug) {+ const written = receipt?.data?.outputs?.js;+ if (typeof written === 'string') {+ const file = path.resolve(cwd, written);+ const relative = path.relative(expectedDir, file);+ if (relative && !relative.startsWith('..') && !path.isAbsolute(relative)) {+ return file;+ }+ }+ return path.join(expectedDir, `${slug}.js`);+}++/**+ * The `.js` file a relative module specifier names from `fromFile`, the+ * extension `theme build` gives the built module: the exact path, the path+ * with `.js`, or its `index.js`.+ * @param {string} specifier+ * @param {string} fromFile+ * @returns {string | null}+ */+function resolveRelativeJsModule(specifier, fromFile) {+ if (!specifier.startsWith('./') && !specifier.startsWith('../')) return null;+ const base = path.resolve(path.dirname(fromFile), specifier);+ const candidates = [base, `${base}.js`, path.join(base, 'index.js')];+ return (+ candidates.find(candidate => {+ try {+ return candidate.endsWith('.js') && fs.statSync(candidate).isFile();+ } catch {+ return false;+ }+ }) ?? null+ );+}++/** @param {string} file */+function realFile(file) {+ try {+ return fs.realpathSync(file);+ } catch {+ return null;+ }+}++/**+ * The file a stylesheet import names: a relative path from the module, or a+ * subpath of the package itself, resolved through its own exports.+ * @param {string} specifier+ * @param {string} moduleFile+ * @param {{name?: string}} pkg+ * @param {string} packageDir+ * @returns {string | null}+ */+function resolveStylesheetImport(specifier, moduleFile, pkg, packageDir) {+ if (specifier.startsWith('./') || specifier.startsWith('../')) {+ const file = path.resolve(path.dirname(moduleFile), specifier);+ try {+ return fs.statSync(file).isFile() ? realFile(file) : null;+ } catch {+ return null;+ }+ }+ if (typeof pkg.name !== 'string' || !specifier.startsWith(`${pkg.name}/`)) {+ return null;+ }+ const exported = inspectPackageExport(+ pkg,+ packageDir,+ `.${specifier.slice(pkg.name.length)}`,+ );+ return exported.exported && exported.target+ ? realFile(exported.target)+ : null;+}++/**+ * The theme binding of a built module: the name of its `export const`.+ * @param {string} file+ * @returns {string | null}+ */+function builtThemeBinding(file) {+ try {+ const ast = parseModule(fs.readFileSync(file, 'utf-8'), {+ sourceType: 'module',+ plugins: ['importAttributes'],+ });+ for (const node of ast.program.body) {+ if (+ node.type === 'ExportNamedDeclaration' &&+ node.declaration?.type === 'VariableDeclaration'+ ) {+ const id = node.declaration.declarations[0]?.id;+ return id?.type === 'Identifier' ? id.name : null;+ }+ }+ } catch {+ // An unreadable module has no binding to match.+ }+ return null;+}++/** @param {any} node */+function exportedName(node) {+ return node?.name ?? node?.value;+}++/**+ * Check a `.js` or `.mjs` theme module that is not the built module itself.+ * It is accepted when it only loads the theme's own styles and re-exports the+ * built module: each statement imports the theme's exported stylesheet or font+ * stylesheet for its side effects, except one, which re-exports from a `.js`+ * file that matches the built module either everything or only its theme,+ * under the theme's export name. Returns null for any other file and for a module that+ * re-exports nothing, and otherwise whether it is accepted. A+ * rejection gives the reason, or, when only the re-exported module is stale,+ * that module's specifier with `rebuild` set.+ *+ * @param {string} moduleFile+ * @param {string} expected the built module, normalized for comparison+ * @param {{exportName: string, stylesheetFile: string, fontStylesheetFile?: string, pkg: {name?: string}, packageDir: string}} theme+ * @returns {{ok: true} | {ok: false, reason: string, rebuild: boolean} | null}+ */+function ownStylesEntry(moduleFile, expected, theme) {+ if (!/\.m?js$/u.test(moduleFile)) return null;+ let ast;+ try {+ ast = parseModule(fs.readFileSync(moduleFile, 'utf-8'), {+ sourceType: 'module',+ plugins: ['importAttributes'],+ });+ } catch {+ return null;+ }+ const body = ast.program.body;+ const reexports = body.filter(+ (/** @type {any} */ node) =>+ node.type === 'ExportAllDeclaration' ||+ (node.type === 'ExportNamedDeclaration' && node.source != null),+ );+ if (reexports.length === 0) return null;+ /** @param {string} reason @param {boolean} [rebuild] */+ const reject = (reason, rebuild = false) => ({+ ok: /** @type {const} */ (false),+ reason,+ rebuild,+ });+ if (reexports.length > 1) return reject('it has more than one re-export');+ if ((ast.program.directives ?? []).length > 0) {+ return reject('it has a directive');+ }+ const ownStylesheets = new Set(+ [theme.stylesheetFile, theme.fontStylesheetFile]+ .filter(file => file != null)+ .map(file => realFile(/** @type {string} */ (file))),+ );+ const imported = new Set();+ for (const node of body) {+ if (node === reexports[0]) continue;+ const line = node.loc?.start.line;+ if (node.type !== 'ImportDeclaration') {+ return reject(+ `line ${line} is neither a stylesheet import nor the re-export`,+ );+ }+ const specifier = node.source.value;+ if (+ node.importKind === 'type' ||+ node.specifiers.length > 0 ||+ (node.attributes ?? []).length > 0 ||+ node.phase != null+ ) {+ return reject(`its import of ${specifier} is not a side-effect import`);+ }+ const file = resolveStylesheetImport(+ specifier,+ moduleFile,+ theme.pkg,+ theme.packageDir,+ );+ if (!file || !ownStylesheets.has(file)) {+ return reject(+ `${specifier} is not the theme's own stylesheet or font stylesheet`,+ );+ }+ if (imported.has(file)) return reject(`it imports ${specifier} twice`);+ imported.add(file);+ }+ const reexport = /** @type {any} */ (reexports[0]);+ const from = reexport.source.value;+ /** @type {string | null} */+ let reexported = null;+ if (+ reexport.exportKind === 'type' ||+ (reexport.attributes ?? []).length > 0+ ) {+ return reject(`its re-export from ${from} is not a plain re-export`);+ }+ if (reexport.type === 'ExportAllDeclaration') {+ if (reexport.exported != null) {+ return reject(`it re-exports ${from} as a namespace`);+ }+ } else {+ const specifiers = reexport.specifiers ?? [];+ if (+ specifiers.length !== 1 ||+ specifiers[0].type !== 'ExportSpecifier' ||+ specifiers[0].exportKind === 'type' ||+ exportedName(specifiers[0].exported) !== theme.exportName+ ) {+ return reject(`it re-exports names other than ${theme.exportName}`);+ }+ reexported = exportedName(specifiers[0].local);+ }+ const target = resolveRelativeJsModule(from, moduleFile);+ if (!target) {+ return reject(`its re-export from ${from} does not name a .js module`);+ }+ if (+ normalizeThemeVerifyForCompare(fs.readFileSync(target, 'utf-8')) !==+ expected+ ) {+ return reject(from, true);+ }+ // `theme build` names the theme's export after the theme's own name, which+ // can differ from its slug, so a named re-export may give that export the+ // slug's export name. It must be the theme, not another export of the built+ // module, such as its icon registry.+ if (reexported != null && reexported !== builtThemeBinding(target)) {+ return reject(`it re-exports ${reexported}, which is not the built theme`);+ }+ return {ok: /** @type {const} */ (true)};+}+/*** Prove local theme exports are fresh, prove the same exports resolve from the* tarball, and reject lifecycle changes to source or built output bytes.@@ -777,7 +1027,12 @@ async function validatePackedThemeExports();continue;}- const expectedModule = path.join(expectedDir, `${localTheme.slug}.js`);+ const expectedModule = builtModuleFile(+ receipt,+ localIntegration.__packageDir,+ expectedDir,+ localTheme.slug,+ );/** @type {Array<{kind: string, expected: string, local: string, packed: string, staleCode: string, packedCode: string}>} */const buildOutputs = [{@@ -797,6 +1052,20 @@ async function validatePackedThemeExports(packedCode: 'packed_theme_stylesheet_changed',},];+ const localEntry = {+ exportName: localTheme.exportName,+ stylesheetFile: localImports.stylesheetFile,+ fontStylesheetFile: localImports.fontStylesheetFile,+ pkg: integrationPackageMetadata(localIntegration),+ packageDir: localIntegration.__packageDir,+ };+ const packedEntry = {+ exportName: packedTheme.exportName,+ stylesheetFile: packedImports.stylesheetFile,+ fontStylesheetFile: packedImports.fontStylesheetFile,+ pkg: integrationPackageMetadata(packedIntegration),+ packageDir: packedIntegration.__packageDir,+ };for (const output of buildOutputs) {const expected = normalizeThemeVerifyForCompare(fs.readFileSync(output.expected, 'utf-8'),@@ -807,15 +1076,31 @@ async function validatePackedThemeExports(const packed = normalizeThemeVerifyForCompare(fs.readFileSync(output.packed, 'utf-8'),);- if (expected !== local) {+ // A module that is not the built module may still be an entry that+ // loads the theme's own styles and re-exports the built module.+ const localWrapper =+ output.kind === 'module' && expected !== local+ ? ownStylesEntry(output.local, expected, localEntry)+ : null;+ const packedWrapper =+ output.kind === 'module' && expected !== packed+ ? ownStylesEntry(output.packed, expected, packedEntry)+ : null;+ const localMatches = expected === local || localWrapper?.ok === true;+ const packedMatches = expected === packed || packedWrapper?.ok === true;+ if (!localMatches) {issues.push(error(output.staleCode,- `Theme "${localTheme.slug}" ${output.kind} does not match ${sourceRelative}. Run \`astryx theme build ${sourceRelative}\` before packing.`,+ localWrapper && !localWrapper.ok && !localWrapper.rebuild+ ? `Theme "${localTheme.slug}" module is not the module \`astryx theme build ${sourceRelative}\` writes and does not only wrap it: ${localWrapper.reason}. A module that wraps the built module may only import the theme's own stylesheet and font stylesheet for their side effects and re-export from the built module either everything or only its theme, as ${localTheme.exportName}.`+ : localWrapper && !localWrapper.ok+ ? `Theme "${localTheme.slug}" module re-exports ${localWrapper.reason}, which does not match ${sourceRelative}. Run \`astryx theme build ${sourceRelative}\` before packing.`+ : `Theme "${localTheme.slug}" ${output.kind} does not match ${sourceRelative}. Run \`astryx theme build ${sourceRelative}\` before packing.`,),);}- if (local !== packed) {+ if (local !== packed || (localMatches && !packedMatches)) {issues.push(error(output.packedCode,diff --git a/packages/cli/api/integration/pack-check.test.mjs b/packages/cli/api/integration/pack-check.test.mjsindex 1169c9ed91..9e116e7272 100644--- a/packages/cli/api/integration/pack-check.test.mjs+++ b/packages/cli/api/integration/pack-check.test.mjs@@ -303,6 +303,347 @@ function runCliVerify() {};}+/**+ * Give the built ocean theme a font stylesheet and an entry module that loads+ * the theme's own styles, and export them the way such a package does.+ * @param {string} entry+ * @param {string} [file] the entry's file name in `entries/`+ */+function writeOwnStylesEntry(entry, file = 'ocean.mjs') {+ fs.writeFileSync(+ path.join(tmpDir, 'themes', 'ocean', 'ocean.fonts.css'),+ "@font-face { font-family: 'Ocean Sans'; src: local('Ocean Sans'); }\n",+ );+ fs.mkdirSync(path.join(tmpDir, 'entries'), {recursive: true});+ fs.writeFileSync(path.join(tmpDir, 'entries', file), entry);+ const packageFile = path.join(tmpDir, 'package.json');+ const pkg = JSON.parse(fs.readFileSync(packageFile, 'utf-8'));+ pkg.files = ['astryx.integration.mjs', 'themes', 'entries'];+ pkg.exports = {+ './themes/ocean': `./entries/${file}`,+ './themes/ocean.css': './themes/ocean/ocean.css',+ './themes/ocean.fonts.css': './themes/ocean/ocean.fonts.css',+ };+ fs.writeFileSync(packageFile, `${JSON.stringify(pkg, null, 2)}\n`);+}++/**+ * Rename the ocean theme to deep-sea, keeping its `ocean` slug, and build it,+ * so its outputs are named after the theme: `deep-sea.css` and `deep-sea.js`,+ * which exports `deepSeaTheme`.+ */+function writeRenamedOcean() {+ writePackage({files: ['astryx.integration.mjs', 'themes', 'entries']});+ fs.writeFileSync(+ path.join(tmpDir, 'themes', 'ocean', 'oceanTheme.ts'),+ "import {defineTheme} from '@astryxdesign/core/theme';\n\nexport const oceanTheme = defineTheme({name: 'deep-sea'});\n",+ );+ const built = spawnSync(+ process.execPath,+ [+ path.join(process.cwd(), 'packages/cli/clients/cli/bin/astryx.mjs'),+ 'theme',+ 'build',+ 'themes/ocean/oceanTheme.ts',+ ],+ {cwd: tmpDir, encoding: 'utf-8', timeout: 30_000},+ );+ if (built.status !== 0) {+ throw new Error(`Could not build the theme fixture: ${built.stderr}`);+ }+}++/**+ * Give the ocean theme an icon registry and build it, so its built module+ * also exports `oceanIcons`.+ */+function writeOceanWithIcons() {+ writePackage({files: ['astryx.integration.mjs', 'themes', 'entries']});+ const themeDir = path.join(tmpDir, 'themes', 'ocean');+ fs.writeFileSync(+ path.join(themeDir, 'icons.js'),+ 'export const oceanIcons = {};\n',+ );+ fs.writeFileSync(+ path.join(themeDir, 'oceanTheme.ts'),+ "import {defineTheme} from '@astryxdesign/core/theme';\nimport {oceanIcons} from './icons';\n\nexport const oceanTheme = defineTheme({name: 'ocean', icons: oceanIcons});\n",+ );+ const built = spawnSync(+ process.execPath,+ [+ path.join(process.cwd(), 'packages/cli/clients/cli/bin/astryx.mjs'),+ 'theme',+ 'build',+ 'themes/ocean/oceanTheme.ts',+ ],+ {cwd: tmpDir, encoding: 'utf-8', timeout: 30_000},+ );+ if (built.status !== 0) {+ throw new Error(`Could not build the theme fixture: ${built.stderr}`);+ }+}++// An entry like one whose import is the whole integration: it loads the+// theme's fonts and stylesheet, by relative path and through the package's+// own exports, and re-exports the built theme.+const OWN_STYLES_ENTRY = `// Copyright (c) Acme.++import '../themes/ocean/ocean.fonts.css';+import '@acme/widgets/themes/ocean.css';++export {oceanTheme} from '../themes/ocean/ocean.js';+`;++describe('a theme module that loads its own styles', () => {+ it('passes an entry that imports the theme stylesheet and fonts and re-exports the built module', async () => {+ writePackage({themeExports: true});+ writeOwnStylesEntry(OWN_STYLES_ENTRY);++ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.issues).toEqual([]);+ expect(result.data.packable).toBe(true);+ const cli = runCliVerify();+ expect(cli.status, cli.stderr).toBe(0);+ expect(cli.receipt?.data.issues).toEqual([]);+ });++ it('passes an entry that imports its fonts through the package exports and re-exports everything', async () => {+ writePackage({themeExports: true});+ writeOwnStylesEntry(+ "import '@acme/widgets/themes/ocean.fonts.css';\nimport '../themes/ocean/ocean.css';\nexport * from '../themes/ocean/ocean.js';\n",+ );++ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.issues).toEqual([]);+ expect(result.data.packable).toBe(true);+ });++ it.each([+ [+ 'also imports another stylesheet',+ `${OWN_STYLES_ENTRY}import './other.css';\n`,+ "./other.css is not the theme's own stylesheet or font stylesheet",+ ],+ [+ 'also imports a script',+ `import './setup.mjs';\n${OWN_STYLES_ENTRY}`,+ "./setup.mjs is not the theme's own stylesheet or font stylesheet",+ ],+ [+ 'runs code',+ `${OWN_STYLES_ENTRY}console.log('ocean');\n`,+ 'line 7 is neither a stylesheet import nor the re-export',+ ],+ [+ 'exports another value',+ `${OWN_STYLES_ENTRY}export const extra = 1;\n`,+ 'line 7 is neither a stylesheet import nor the re-export',+ ],+ [+ 'renames the theme it re-exports',+ "import '../themes/ocean/ocean.css';\nexport {oceanTheme, oceanTheme as theme} from '../themes/ocean/ocean.js';\n",+ 'it re-exports names other than oceanTheme',+ ],+ [+ 'binds the stylesheet it imports',+ "import styles from '../themes/ocean/ocean.css';\nexport {oceanTheme} from '../themes/ocean/ocean.js';\n",+ 'its import of ../themes/ocean/ocean.css is not a side-effect import',+ ],+ [+ 'imports the stylesheet as a CSS module script',+ "import '../themes/ocean/ocean.css' with {type: 'css'};\nexport {oceanTheme} from '../themes/ocean/ocean.js';\n",+ 'its import of ../themes/ocean/ocean.css is not a side-effect import',+ ],+ [+ 're-exports another name',+ "import '../themes/ocean/ocean.css';\nexport {oceanTheme, missing} from '../themes/ocean/ocean.js';\n",+ 'it re-exports names other than oceanTheme',+ ],+ [+ 're-exports a copy that is not a .js module',+ "import '../themes/ocean/ocean.css';\nexport {oceanTheme} from './copy.cjs';\n",+ 'its re-export from ./copy.cjs does not name a .js module',+ ],+ [+ 'has a directive',+ `'use client';\n${OWN_STYLES_ENTRY}`,+ 'it has a directive',+ ],+ [+ 're-exports twice',+ `${OWN_STYLES_ENTRY}export * from '../themes/ocean/ocean.js';\n`,+ 'it has more than one re-export',+ ],+ ])('fails an entry that %s', async (_label, entry, reason) => {+ writePackage({themeExports: true});+ writeOwnStylesEntry(entry);+ fs.writeFileSync(path.join(tmpDir, 'entries', 'other.css'), '.x {}\n');+ fs.writeFileSync(path.join(tmpDir, 'entries', 'setup.mjs'), 'export {};\n');+ fs.copyFileSync(+ path.join(tmpDir, 'themes', 'ocean', 'ocean.js'),+ path.join(tmpDir, 'entries', 'copy.cjs'),+ );++ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.packable).toBe(false);+ expect(result.data.issues).toEqual([+ {+ code: 'theme_module_stale',+ severity: 'error',+ message: `Theme "ocean" module is not the module \`astryx theme build themes/ocean/oceanTheme.ts\` writes and does not only wrap it: ${reason}. A module that wraps the built module may only import the theme's own stylesheet and font stylesheet for their side effects and re-export from the built module either everything or only its theme, as oceanTheme.`,+ },+ ]);+ });++ it('fails an entry whose re-exported module drifts from source', async () => {+ writePackage({themeExports: true});+ writeOwnStylesEntry(OWN_STYLES_ENTRY);+ fs.appendFileSync(+ path.join(tmpDir, 'themes', 'ocean', 'ocean.js'),+ '// stale module\n',+ );++ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.packable).toBe(false);+ expect(result.data.issues).toEqual([+ {+ code: 'theme_module_stale',+ severity: 'error',+ message:+ 'Theme "ocean" module re-exports ../themes/ocean/ocean.js, which does not match themes/ocean/oceanTheme.ts. Run `astryx theme build themes/ocean/oceanTheme.ts` before packing.',+ },+ ]);+ });++ it('does not accept a TypeScript entry', async () => {+ writePackage({themeExports: true});+ writeOwnStylesEntry(OWN_STYLES_ENTRY, 'ocean.ts');++ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.packable).toBe(false);+ expect(result.data.issues).toEqual([+ {+ code: 'theme_module_stale',+ severity: 'error',+ message:+ 'Theme "ocean" module does not match themes/ocean/oceanTheme.ts. Run `astryx theme build themes/ocean/oceanTheme.ts` before packing.',+ },+ ]);+ });++ it('does not accept an entry that re-exports itself', async () => {+ writePackage({themeExports: true});+ writeOwnStylesEntry(+ "import '../themes/ocean/ocean.css';\nexport * from './ocean.js';\n",+ 'ocean.js',+ );++ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.packable).toBe(false);+ expect(result.data.issues).toContainEqual(+ expect.objectContaining({+ code: 'theme_import_unresolvable',+ message: expect.stringContaining('does not export "oceanTheme"'),+ }),+ );+ });++ it('passes an entry for a theme whose own name differs from its slug', async () => {+ writeRenamedOcean();+ writeOwnStylesEntry(+ "import '../themes/ocean/deep-sea.css';\nexport {deepSeaTheme as oceanTheme} from '../themes/ocean/deep-sea.js';\n",+ );+ setThemeExports({+ './themes/ocean': './entries/ocean.mjs',+ './themes/ocean.css': './themes/ocean/deep-sea.css',+ });++ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.issues).toEqual([]);+ expect(result.data.packable).toBe(true);+ const cli = runCliVerify();+ expect(cli.status, cli.stderr).toBe(0);+ });++ it('compares a partial export set with the module named after the theme', async () => {+ writeRenamedOcean();+ setThemeExports({'./themes/ocean': './themes/ocean/deep-sea.js'});++ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.packable).toBe(true);+ expect(result.data.issues.map(issue => issue.code)).toEqual([+ 'theme_exports_incomplete',+ ]);+ });++ it('passes an entry that re-exports only the theme from a built module that also exports its icons', async () => {+ writeOceanWithIcons();+ writeOwnStylesEntry(OWN_STYLES_ENTRY);++ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.issues).toEqual([]);+ expect(result.data.packable).toBe(true);+ });++ it('fails an entry that gives the built icons the theme export name', async () => {+ writeOceanWithIcons();+ writeOwnStylesEntry(+ "import '../themes/ocean/ocean.css';\nexport {oceanIcons as oceanTheme} from '../themes/ocean/ocean.js';\n",+ );++ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.packable).toBe(false);+ expect(result.data.issues).toEqual([+ expect.objectContaining({+ code: 'theme_module_stale',+ message: expect.stringContaining(+ 'it re-exports oceanIcons, which is not the built theme',+ ),+ }),+ ]);+ });++ it('fails when packing changes the module an entry re-exports', async () => {+ const prepack = [+ "const fs=require('fs')",+ "fs.copyFileSync('themes/ocean/ocean.js','.ocean.js.orig')",+ "fs.appendFileSync('themes/ocean/ocean.js','// packed\\n')",+ ].join(';');+ const postpack =+ "require('fs').renameSync('.ocean.js.orig','themes/ocean/ocean.js')";+ writePackage({+ themeExports: true,+ scripts: {+ prepack: `node -e "${prepack}"`,+ postpack: `node -e "${postpack}"`,+ },+ });+ writeOwnStylesEntry(OWN_STYLES_ENTRY);++ const result = await integrationPackCheck({cwd: tmpDir});++ expect(result.data.packable).toBe(false);+ expect(result.data.issues).toEqual([+ {+ code: 'packed_theme_module_changed',+ severity: 'error',+ message:+ 'Theme "ocean" module changed during packing. Keep the built output unchanged in the tarball.',+ },+ ]);+ });+});+describe('integrationPackCheck', () => {it('returns packable:true for a valid integration with themes', async () => {writePackage({files: ['astryx.integration.mjs', 'themes']});diff --git a/packages/cli/foundation/fs/module-loader.mjs b/packages/cli/foundation/fs/module-loader.mjsindex afe069d8c4..74ad5f8be2 100644--- a/packages/cli/foundation/fs/module-loader.mjs+++ b/packages/cli/foundation/fs/module-loader.mjs@@ -7,9 +7,11 @@* user-authored module (`.ts` via jiti, `.mjs`/`.js` via native dynamic* import) and (b) find conventional files by basename in a fixed* load-precedence order. Generated theme artifacts also use a dedicated jiti- * path that resolves extensionless JSX/TSX registry imports. These helpers- * centralize that behavior so callers stay in lockstep. A module's stdout writes go to stderr while it loads, so- * project code that prints cannot corrupt a `--json` envelope.+ * path that resolves extensionless JSX/TSX registry imports and loads the+ * stylesheets they import as empty modules. These helpers centralize that+ * behavior so callers stay in lockstep. A module's stdout writes go to stderr+ * while it loads, so project code that prints cannot corrupt a `--json`+ * envelope.** `loadModuleWithParser` builds on these primitives to provide the single* load/validation boundary shared by config, integration, codemod, and@@ -125,6 +127,56 @@ const THEME_ARTIFACT_EXTENSIONS = ['.cts',];+/**+ * @param {string | symbol} specifier+ * @returns {specifier is string}+ */+function isStylesheetSpecifier(specifier) {+ return typeof specifier === 'string' && specifier.endsWith('.css');+}++/**+ * Whether `specifier`, resolved from the module at `from`, names an existing+ * `.css` file.+ * @param {string} specifier+ * @param {string} from+ */+function resolvesToStylesheet(specifier, from) {+ try {+ return createRequire(from).resolve(specifier).endsWith('.css');+ } catch {+ return false;+ }+}++/**+ * A built theme module may import a stylesheet so that the app's bundler emits+ * it. Node cannot load a stylesheet, so an import that ends in `.css` and+ * resolves from the theme module to an existing `.css` file loads as an empty+ * module. Any other import loads as before: a missing stylesheet fails like+ * any missing import, and `./tokens.css` loads `tokens.css.js` when that is+ * the file it names. jiti shows only the import text, so the check resolves it+ * from the theme module's folder, not from the importing module's. A module in+ * another folder fails on a stylesheet it reaches by a different relative+ * path, and passes on a missing stylesheet whose path exists from the theme+ * module's folder.+ * @param {() => string} themeModule returns the theme module's path+ * @returns {Record<string, unknown>}+ */+function themeArtifactStylesheets(themeModule) {+ return new Proxy(+ {},+ {+ has: (_target, specifier) =>+ specifier !== themeModule() &&+ isStylesheetSpecifier(specifier) &&+ resolvesToStylesheet(specifier, themeModule()),+ get: (_target, specifier) =>+ isStylesheetSpecifier(specifier) ? {} : undefined,+ },+ );+}+class ThemeArtifactNotFoundError extends Error {code = 'ERR_THEME_ARTIFACT_NOT_FOUND';@@ -153,17 +205,20 @@ function isMissingPackageExport(error) {/*** Load a generated theme artifact and its extensionless JS/JSX/TS/TSX graph.* Package specifiers resolve from the consumer project, while relative paths- * resolve from that same project root.+ * resolve from that same project root. An import of an existing `.css` file+ * loads as an empty module.* @param {string} specifier* @param {string} cwd* @returns {Promise<Record<string, unknown>>}*/export async function importThemeArtifact(specifier, cwd) {+ let themeModule = path.join(cwd, 'package.json');const loader = createJiti(path.join(cwd, 'package.json'), {moduleCache: false,jsx: true,interopDefault: true,extensions: THEME_ARTIFACT_EXTENSIONS,+ virtualModules: themeArtifactStylesheets(() => themeModule),});let target;if (specifier.startsWith('.') || path.isAbsolute(specifier)) {@@ -179,6 +234,7 @@ export async function importThemeArtifact(specifier, cwd) {if (!fs.existsSync(target)) {throw new ThemeArtifactNotFoundError(specifier);}+ themeModule = target;return await withStdoutOnStderr(() => loader.import(target));}diff --git a/packages/cli/foundation/fs/module-loader.test.mjs b/packages/cli/foundation/fs/module-loader.test.mjsindex c5ee156da2..df4576fca8 100644--- a/packages/cli/foundation/fs/module-loader.test.mjs+++ b/packages/cli/foundation/fs/module-loader.test.mjs@@ -9,6 +9,7 @@ import {pathToFileURL} from 'node:url';import {z} from 'zod';import {findPresentFiles,+ importThemeArtifact,importUserModule,loadModuleWithParser,} from './module-loader.mjs';@@ -155,6 +156,199 @@ process.stdout.write(JSON.stringify({first: first.default?.answer, fresh: fresh.});});+describe('importThemeArtifact', () => {+ const STYLESHEET_RAN = '__astryxThemeArtifactStylesheetRan';++ /** @param {string} file @param {string} content */+ function write(file, content) {+ const target = path.join(tmpDir, file);+ fs.mkdirSync(path.dirname(target), {recursive: true});+ fs.writeFileSync(target, content);+ }++ beforeEach(() => {+ write('package.json', JSON.stringify({type: 'module'}));+ write(+ 'ocean.css',+ '[data-astryx-theme="ocean"] { --color-text: black; }\n',+ );+ });++ afterEach(() => {+ Reflect.deleteProperty(globalThis, STYLESHEET_RAN);+ });++ it('loads a built module that imports its stylesheet, without running the stylesheet', async () => {+ // Valid JavaScript, so running this stylesheet would leave a trace.+ write('ran.css', `globalThis.${STYLESHEET_RAN} = true;\n`);+ write(+ 'ocean.js',+ "import './ocean.css';\nimport './ran.css';\nexport const oceanTheme = {name: 'ocean'};\n",+ );++ const mod = await importThemeArtifact('./ocean.js', tmpDir);++ expect(mod.oceanTheme).toEqual({name: 'ocean'});+ expect(Reflect.get(globalThis, STYLESHEET_RAN)).toBeUndefined();+ });++ it('loads a CommonJS built module that requires its stylesheet', async () => {+ write('commonjs/package.json', JSON.stringify({type: 'commonjs'}));+ write(+ 'commonjs/ocean.css',+ '[data-astryx-theme="ocean"] { --color-text: black; }\n',+ );+ write(+ 'commonjs/ocean.js',+ "require('./ocean.css');\nexports.oceanTheme = {name: 'ocean'};\n",+ );++ const mod = await importThemeArtifact('./commonjs/ocean.js', tmpDir);++ expect(mod.oceanTheme).toEqual({name: 'ocean'});+ });++ it('loads stylesheets imported by a nested module, through a package export, and dynamically', async () => {+ const packageDir = 'node_modules/@acme/themes';+ write(+ `${packageDir}/package.json`,+ JSON.stringify({+ name: '@acme/themes',+ type: 'module',+ exports: {+ './themes/ocean': './dist/ocean.js',+ './themes/ocean.css': './dist/ocean.css',+ },+ }),+ );+ write(+ `${packageDir}/dist/ocean.css`,+ '[data-astryx-theme="ocean"] { --color-text: black; }\n',+ );+ write(+ `${packageDir}/dist/tokens.js`,+ "import '@acme/themes/themes/ocean.css';\nexport const tokens = {};\n",+ );+ write(+ `${packageDir}/dist/ocean.js`,+ "import {tokens} from './tokens.js';\nawait import('./ocean.css');\nexport const oceanTheme = {name: 'ocean', tokens};\n",+ );++ const mod = await importThemeArtifact('@acme/themes/themes/ocean', tmpDir);++ expect(mod.oceanTheme).toEqual({name: 'ocean', tokens: {}});+ });++ it('still resolves an extensionless import to its directory index beside a same-named stylesheet', async () => {+ write('ocean/index.js', "export const oceanTheme = {name: 'ocean'};\n");+ write(+ 'entry.js',+ "import './ocean.css';\nexport {oceanTheme} from './ocean';\n",+ );++ const mod = await importThemeArtifact('./entry.js', tmpDir);++ expect(mod.oceanTheme).toEqual({name: 'ocean'});+ });++ it('loads a module whose import ends in .css but names a JavaScript file', async () => {+ write('tokens.css.js', "export const vars = {accent: 'blue'};\n");+ write(+ 'ocean.js',+ "import './ocean.css';\nimport {vars} from './tokens.css';\nexport const oceanTheme = {name: 'ocean', vars};\n",+ );++ const mod = await importThemeArtifact('./ocean.js', tmpDir);++ expect(mod.oceanTheme).toEqual({name: 'ocean', vars: {accent: 'blue'}});+ });++ it.each([+ ['a missing file', "import './fonts.css';\n", /fonts\.css/],+ [+ 'a package that is not installed',+ "import '@acme/missing-fonts/inter.css';\n",+ /@acme\/missing-fonts\/inter\.css/,+ ],+ ])(+ 'still rejects a stylesheet import of %s',+ async (_label, stylesheetImport, expected) => {+ write(+ 'ocean.js',+ `import './ocean.css';\n${stylesheetImport}export const oceanTheme = {name: 'ocean'};\n`,+ );++ await expect(importThemeArtifact('./ocean.js', tmpDir)).rejects.toThrow(+ expected,+ );+ },+ );++ it('still rejects a theme module path that names a stylesheet', async () => {+ await expect(importThemeArtifact('./ocean.css', tmpDir)).rejects.toThrow(+ /Unknown file extension "\.css"/,+ );+ });++ it('still rejects a stylesheet import that its package does not export', async () => {+ const packageDir = 'node_modules/@acme/themes';+ write(+ `${packageDir}/package.json`,+ JSON.stringify({+ name: '@acme/themes',+ type: 'module',+ exports: {'./themes/ocean': './dist/ocean.js'},+ }),+ );+ write(+ `${packageDir}/dist/ocean.css`,+ '[data-astryx-theme="ocean"] { --color-text: black; }\n',+ );+ write(+ `${packageDir}/dist/ocean.js`,+ "import '@acme/themes/themes/ocean.css';\nexport const oceanTheme = {name: 'ocean'};\n",+ );++ await expect(+ importThemeArtifact('@acme/themes/themes/ocean', tmpDir),+ ).rejects.toThrow(/not defined by "exports"/);+ });++ it.each([+ [+ 'a missing dependency',+ "import './missing.js';\nexport const oceanTheme = {name: 'ocean'};\n",+ /missing\.js/,+ ],+ [+ 'a syntax error in a module it imports',+ "import './broken.js';\nexport const oceanTheme = {name: 'ocean'};\n",+ /ParseError/,+ ],+ [+ 'a throwing module',+ "throw new Error('broken theme module');\n",+ /broken theme module/,+ ],+ [+ 'an asset that is not a stylesheet',+ "import './logo.svg';\nexport const oceanTheme = {name: 'ocean'};\n",+ /Unknown file extension "\.svg"/,+ ],+ ])(+ 'still rejects a built module that imports its stylesheet and has %s',+ async (_label, rest, expected) => {+ write('logo.svg', '<svg xmlns="http://www.w3.org/2000/svg"/>\n');+ write('broken.js', 'export const broken = ;\n');+ write('ocean.js', `import './ocean.css';\n${rest}`);++ await expect(importThemeArtifact('./ocean.js', tmpDir)).rejects.toThrow(+ expected,+ );+ },+ );+});+describe('loadModuleWithParser', () => {// Temp module files live under a repo-local dir (not /tmp): Vite's dynamic// import blocks /tmp, so we mirror the existing repo-local temp pattern.