An open source design system that's fully customizable and agent ready
TypeScript
feat(cli): build minimal theme family artifacts (#6268)
Cindy Zhangdd9ec6f1ccae
diff --git a/.changeset/theme-family-artifacts.md b/.changeset/theme-family-artifacts.mdnew file mode 100644index 0000000000..9dc385277a--- /dev/null+++ b/.changeset/theme-family-artifacts.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[feat] Build one keyed artifact trio for a selected theme family (#6268)++@cixzhangdiff --git a/.github/scripts/theme-family-cascade.js b/.github/scripts/theme-family-cascade.jsnew file mode 100644index 0000000000..279a980c7b--- /dev/null+++ b/.github/scripts/theme-family-cascade.js@@ -0,0 +1,189 @@+#!/usr/bin/env node+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @description Proves one generated theme-family stylesheet preserves every selected identity in Chromium+ * @input [--port <n>]+ * @output One line per AST-034 browser contract; exit 1 on a cascade mismatch+ */++const {chromium} = require('playwright');+const fs = require('node:fs');+const http = require('node:http');+const os = require('node:os');+const path = require('node:path');++const args = process.argv.slice(2);+const portArg = args.indexOf('--port');+const port = Number(portArg === -1 ? 6013 : args[portArg + 1]);+const root = process.cwd();+const sources = path.join(root, 'apps/sandbox/src/themes/theme-family');+const familyFile = path.join(sources, 'sandbox-ocean-family.css');+const beforeFile = path.join(sources, 'unrelated-before.css');++function serve(dir) {+ return new Promise(resolve => {+ const server = http.createServer((req, res) => {+ const name = req.url === '/' ? 'index.html' : req.url.slice(1);+ const file = path.resolve(dir, name);+ if (!file.startsWith(path.resolve(dir))) {+ res.writeHead(403).end();+ return;+ }+ fs.readFile(file, (error, bytes) => {+ if (error) {+ res.writeHead(404).end();+ return;+ }+ res.writeHead(200, {+ 'Content-Type': file.endsWith('.css') ? 'text/css' : 'text/html',+ });+ res.end(bytes);+ });+ });+ server.listen(port, () => resolve(server));+ });+}++function markup() {+ const specimen = (id, theme, order = '') => `+ <section id="${id}" data-astryx-theme="${theme}" ${order ? `data-family-order="${order}"` : ''}>+ <p class="prose">prose</p>+ <button class="astryx-button" data-variant="primary">button</button>+ <div data-astryx-media="dark"><button class="astryx-button media">media</button></div>+ </section>`;+ return `<!doctype html><html><head>+ <link rel="stylesheet" href="before.css">+ <link rel="stylesheet" href="family.css">+ <style>+ :root { --color-error: rgb(255 0 0); }+ @layer astryx-theme {+ :where([data-family-order='after']) .astryx-button[data-variant='primary'] {+ background-color: var(--color-error);+ }+ }+ </style>+ </head><body>+ ${specimen('switch', 'sandbox-ocean')}+ ${specimen('before', 'sandbox-ocean', 'before')}+ ${specimen('after', 'sandbox-ocean', 'after')}+ <section id="nested" data-astryx-theme="sandbox-ocean">+ <button class="astryx-button" data-variant="primary">base</button>+ <section data-astryx-theme="sandbox-ocean-calm">+ <button class="astryx-button" data-variant="primary">child</button>+ <section data-astryx-theme="sandbox-ocean-calm-deep">+ <button class="astryx-button" data-variant="primary">deep</button>+ </section>+ </section>+ </section>+ ${specimen('sibling', 'sandbox-ocean-midnight')}+ </body></html>`;+}++async function run() {+ if (!fs.existsSync(familyFile)) {+ throw new Error(+ `${familyFile} is missing — run \`pnpm -F @astryxdesign/sandbox generate:theme-family\` first.`,+ );+ }+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-theme-family-'));+ fs.copyFileSync(familyFile, path.join(dir, 'family.css'));+ fs.copyFileSync(beforeFile, path.join(dir, 'before.css'));+ fs.writeFileSync(path.join(dir, 'index.html'), markup());++ let server;+ let browser;+ const failures = [];+ const check = (label, actual, expected) => {+ if (actual === expected) console.log(`✓ ${label} — ${actual}`);+ else {+ failures.push(label);+ console.error(`✗ ${label}: got ${actual}, expected ${expected}`);+ }+ };++ try {+ server = await serve(dir);+ browser = await chromium.launch();+ const page = await browser.newPage({viewport: {width: 1024, height: 800}});+ await page.goto(`http://localhost:${port}/`, {waitUntil: 'networkidle'});++ const read = id =>+ page.locator(`#${id}`).evaluate(node => {+ const prose = getComputedStyle(node.querySelector('.prose'));+ const button = getComputedStyle(+ node.querySelector('.astryx-button[data-variant="primary"]'),+ );+ const media = getComputedStyle(node.querySelector('.media'));+ return {+ background: button.backgroundColor,+ border: button.borderColor,+ minHeight: button.minHeight,+ prose: prose.color,+ surface: getComputedStyle(node).getPropertyValue(+ '--color-background-surface',+ ),+ mediaBorder: media.borderColor,+ };+ });++ const identities = [+ ['sandbox-ocean', 'rgb(0, 119, 182)', 'rgb(2, 62, 138)'],+ ['sandbox-ocean-calm', 'rgb(0, 109, 119)', 'rgb(0, 75, 80)'],+ ['sandbox-ocean-calm-deep', 'rgb(0, 109, 119)', 'rgb(0, 75, 80)'],+ ['sandbox-ocean-midnight', 'rgb(90, 79, 207)', 'rgb(43, 36, 107)'],+ ];+ for (const [identity, background, prose] of identities) {+ await page.locator('#switch').evaluate((node, name) => {+ node.dataset.astryxTheme = name;+ }, identity);+ const seen = await read('switch');+ check(`${identity} component`, seen.background, background);+ check(`${identity} prose`, seen.prose, prose);+ check(`${identity} width adaptation`, seen.minHeight, '42px');+ }++ const nested = await page+ .locator('#nested button')+ .evaluateAll(nodes =>+ nodes.map(node => getComputedStyle(node).backgroundColor),+ );+ check('nested base boundary', nested[0], 'rgb(0, 119, 182)');+ check('nested child boundary', nested[1], 'rgb(0, 109, 119)');+ check('zero-delta descendant identity', nested[2], 'rgb(0, 109, 119)');+ check(+ 'sibling isolation',+ (await read('sibling')).background,+ 'rgb(90, 79, 207)',+ );+ check(+ 'unrelated stylesheet before family loses',+ (await read('before')).background,+ 'rgb(0, 119, 182)',+ );+ check(+ 'unrelated stylesheet after family loses',+ (await read('after')).background,+ 'rgb(0, 119, 182)',+ );+ check(+ 'on-dark surface reaches component',+ (await read('switch')).mediaBorder,+ 'rgb(144, 224, 239)',+ );++ if (failures.length > 0) {+ throw new Error(`${failures.length} theme-family assertion(s) failed`);+ }+ console.log('Theme family cascade guard passed.');+ } finally {+ if (browser) await browser.close();+ if (server) await new Promise(resolve => server.close(resolve));+ fs.rmSync(dir, {recursive: true, force: true});+ }+}++run().catch(error => {+ console.error('Theme family cascade guard failed:', error);+ process.exit(1);+});diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 9641cd2aff..a143410642 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -809,6 +809,18 @@ jobs:- name: Run theme layer cascade guardrun: node .github/scripts/theme-layer-cascade.js+ # AST-034's family contract is also a cascade contract: structural tests+ # cannot prove identity switching, nested boundaries, media surfaces, or+ # equal-specificity unrelated stylesheets in either physical order.+ - name: Build theme-family compiler dependencies+ run: pnpm -F @astryxdesign/core build++ - name: Generate the maintained theme-family fixture+ run: pnpm -F @astryxdesign/sandbox generate:theme-family++ - name: Run theme family cascade guard+ run: node .github/scripts/theme-family-cascade.js+# Guest token boundaries cross portals and the host light/dark cascade. This# requires a production browser render; source and jsdom checks cannot prove# which custom properties paint the portaled surfaces.diff --git a/apps/sandbox/.gitignore b/apps/sandbox/.gitignoreindex 14fe6dc2f6..5ec66e4e2e 100644--- a/apps/sandbox/.gitignore+++ b/apps/sandbox/.gitignore@@ -16,3 +16,8 @@ public/template-assets/# Auto-generated by scripts/generate-xle-tokenizer.mjspublic/xle-tokenizer.mjs++# Auto-generated by `pnpm generate:theme-family`+src/themes/theme-family/sandbox-ocean-family.css+src/themes/theme-family/sandbox-ocean-family.js+src/themes/theme-family/sandbox-ocean-family.d.tsdiff --git a/apps/sandbox/package.json b/apps/sandbox/package.jsonindex dc9b3b4597..f0b40b7af8 100644--- a/apps/sandbox/package.json+++ b/apps/sandbox/package.json@@ -5,12 +5,13 @@"scripts": {"test": "vitest run --root ../.. apps/sandbox --project node","build:deps": "pnpm -F @astryxdesign/theme-neutral build && pnpm -F @astryxdesign/theme-matcha build && pnpm -F @astryxdesign/theme-stone build && pnpm -F @astryxdesign/theme-gothic build && pnpm -F @astryxdesign/theme-chocolate build && pnpm -F @astryxdesign/theme-y2k build && pnpm -F @astryxdesign/theme-butter build",+ "generate:theme-family": "pnpm exec astryx theme build --family src/themes/theme-family/ocean.ts src/themes/theme-family/ocean-calm.ts src/themes/theme-family/ocean-calm-deep.ts src/themes/theme-family/ocean-midnight.ts --family-key sandbox-ocean-family","generate:motion-audit": "node \"src/app/(sandbox)/pages/motion-lab/generate-motion-audit.mjs\"","generate:changelog": "node scripts/generate-changelog.js","generate:cli": "node scripts/generate-cli-registry.mjs","generate:xle": "node scripts/generate-xle-registry.mjs && node scripts/generate-xle-tokenizer.mjs","generate:scores": "node scripts/generate-score-ledger.mjs",- "generate": "node ../../scripts/sync-templates.js && pnpm generate:changelog && pnpm generate:cli && node scripts/generate-foundation-docs.mjs && pnpm generate:xle && pnpm generate:scores && pnpm generate:motion-audit",+ "generate": "node ../../scripts/sync-templates.js && pnpm generate:changelog && pnpm generate:cli && node scripts/generate-foundation-docs.mjs && pnpm generate:xle && pnpm generate:scores && pnpm generate:motion-audit && pnpm generate:theme-family","dev": "pnpm generate && (node ../../scripts/sync-templates.js --watch & next dev)","build": "pnpm generate && next build","start": "next start",diff --git a/apps/sandbox/src/app/(sandbox)/pages/theme-family/page.tsx b/apps/sandbox/src/app/(sandbox)/pages/theme-family/page.tsxnew file mode 100644index 0000000000..0892b8c1a9--- /dev/null+++ b/apps/sandbox/src/app/(sandbox)/pages/theme-family/page.tsx@@ -0,0 +1,163 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @file Sandbox family consumer. @input Generated CSS/ESM. @output Switching and cascade proof. @position Themes page. */++'use client';++import {useState} from 'react';+import * as stylex from '@stylexjs/stylex';+import {Button} from '@astryxdesign/core/Button';+import {Grid} from '@astryxdesign/core/Grid';+import {Layout, LayoutContent} from '@astryxdesign/core/Layout';+import {MediaTheme} from '@astryxdesign/core/theme';+// prettier-ignore+import {SegmentedControl, SegmentedControlItem} from '@astryxdesign/core/SegmentedControl';+import {Stack} from '@astryxdesign/core/Stack';+import {Heading, Text} from '@astryxdesign/core/Text';+import {+ sandboxOceanCalmDeepTheme,+ sandboxOceanCalmTheme,+ sandboxOceanMidnightTheme,+ sandboxOceanTheme,+} from '../../../../themes/theme-family/sandbox-ocean-family.js';++// prettier-ignore+const members = [{label: 'Ocean', theme: sandboxOceanTheme}, {label: 'Calm', theme: sandboxOceanCalmTheme}, {label: 'Deep', theme: sandboxOceanCalmDeepTheme}, {label: 'Midnight', theme: sandboxOceanMidnightTheme}] as const;++function FamilySpecimen({+ order,+ themeName,+}: {+ order: 'before' | 'after';+ themeName: string;+}) {+ return (+ <Stack+ as="section"+ data-astryx-theme={themeName}+ data-family-order={order}+ gap={3}+ padding={4}+ xstyle={styles.specimen}>+ <Heading level={2}>Unrelated theme CSS loaded {order} the family</Heading>+ <Text>+ This prose and the controls below come from the same generated family+ stylesheet in either order.+ </Text>+ <Stack direction="horizontal" gap={2} wrap="wrap">+ <Button label="Family primary" variant="primary" />+ <Button label="Disabled state" isDisabled />+ </Stack>+ <Stack padding={3} xstyle={styles.mediaSurface}>+ <MediaTheme mode="dark">+ <Button label="On dark media" variant="secondary" />+ </MediaTheme>+ </Stack>+ </Stack>+ );+}++function StaticFamilyTree() {+ return (+ <Grid columns={{minWidth: 280, max: 2, repeat: 'fit'}} gap={4}>+ <Stack+ as="section"+ data-astryx-theme={sandboxOceanTheme.name}+ gap={3}+ padding={4}+ xstyle={styles.specimen}>+ <Heading level={2}>Base with nested descendants</Heading>+ <Text>Ocean owns the outer scope and the inherited adaptation.</Text>+ <Button label="Base identity" variant="primary" />+ <Stack+ as="section"+ data-astryx-theme={sandboxOceanCalmTheme.name}+ gap={3}+ padding={3}+ xstyle={styles.nestedSpecimen}>+ <Heading level={3}>Calm child</Heading>+ <Text>+ The child overrides the accent and local border-width token.+ </Text>+ <Button label="Child identity" variant="primary" />+ <Stack+ as="section"+ data-astryx-theme={sandboxOceanCalmDeepTheme.name}+ gap={2}+ padding={3}+ xstyle={styles.nestedSpecimen}>+ <Heading level={4}>Deep zero-delta descendant</Heading>+ <Text>Selectable identity; inherited pixels remain unchanged.</Text>+ <Button label="Zero-delta identity" variant="primary" />+ </Stack>+ </Stack>+ </Stack>++ <Stack+ as="section"+ data-astryx-theme={sandboxOceanMidnightTheme.name}+ gap={3}+ padding={4}+ xstyle={styles.specimen}>+ <Heading level={2}>Midnight sibling</Heading>+ <Text>+ This branch keeps its own accent without leaking into the nested Calm+ branch.+ </Text>+ <Button label="Sibling identity" variant="primary" />+ </Stack>+ </Grid>+ );+}++export default function ThemeFamilyPage() {+ const [activeTheme, setActiveTheme] = useState(sandboxOceanTheme.name);++ return (+ <Layout+ contentWidth={960}+ padding={4}+ content={+ <LayoutContent>+ <Stack as="main" gap={6}>+ <Stack as="header" gap={2}>+ <Heading level={1}>Generated theme family</Heading>+ <Text color="secondary">+ One generated stylesheet and ESM module cover every member.+ Switching changes only the family identity attribute.+ </Text>+ </Stack>++ <SegmentedControl+ label="Active family member"+ layout="fill"+ value={activeTheme}+ onChange={setActiveTheme}>+ {members.map(({label, theme}) => (+ <SegmentedControlItem+ key={theme.name}+ label={label}+ value={theme.name}+ />+ ))}+ </SegmentedControl>++ <Grid columns={{minWidth: 280, max: 2, repeat: 'fit'}} gap={4}>+ <FamilySpecimen order="before" themeName={activeTheme} />+ <FamilySpecimen order="after" themeName={activeTheme} />+ </Grid>++ <StaticFamilyTree />+ </Stack>+ </LayoutContent>+ }+ />+ );+}++// prettier-ignore+const styles = stylex.create({+ specimen: {backgroundColor: 'var(--color-background-surface)', borderRadius: 'var(--radius-container)', color: 'var(--color-text-primary)'},+ nestedSpecimen: {backgroundColor: 'var(--color-background-surface)', borderRadius: 'var(--radius-element)'},+ mediaSurface: {backgroundColor: 'var(--color-background-inverted)', borderRadius: 'var(--radius-element)'},+});diff --git a/apps/sandbox/src/app/globals.css b/apps/sandbox/src/app/globals.cssindex 3d7a72d76e..7c4d6c3f95 100644--- a/apps/sandbox/src/app/globals.css+++ b/apps/sandbox/src/app/globals.css@@ -1,15 +1,25 @@/* Copyright (c) Meta Platforms, Inc. and affiliates. */-@import "./layers.css";-@import "@astryxdesign/core/reset.css";-@import "@astryxdesign/core/astryx.css";-@import "@astryxdesign/lab/lab.css";-@import "@astryxdesign/theme-neutral/theme.css";-@import "@astryxdesign/theme-matcha/theme.css";-@import "@astryxdesign/theme-stone/theme.css";-@import "@astryxdesign/theme-gothic/theme.css";-@import "@astryxdesign/theme-chocolate/theme.css";-@import "@astryxdesign/theme-y2k/theme.css";-@import "@astryxdesign/theme-butter/theme.css";+@import './layers.css';+@import '@astryxdesign/core/reset.css';+@import '@astryxdesign/core/astryx.css';+@import '@astryxdesign/lab/lab.css';+@import '@astryxdesign/theme-neutral/theme.css';+@import '@astryxdesign/theme-matcha/theme.css';+@import '@astryxdesign/theme-stone/theme.css';+@import '@astryxdesign/theme-gothic/theme.css';+@import '@astryxdesign/theme-chocolate/theme.css';+@import '@astryxdesign/theme-y2k/theme.css';+@import '@astryxdesign/theme-butter/theme.css';+@import '../themes/theme-family/unrelated-before.css';+@import '../themes/theme-family/sandbox-ocean-family.css';@stylex;++/* This equal-specificity rule is after the family import. The scoped family+ rule must still win through scope proximity. */+@layer astryx-theme {+ :where([data-family-order='after']) .astryx-button[data-variant='primary'] {+ background-color: var(--color-error);+ }+}diff --git a/apps/sandbox/src/app/sandboxPages.ts b/apps/sandbox/src/app/sandboxPages.tsindex d654c74ae7..4addaf75c6 100644--- a/apps/sandbox/src/app/sandboxPages.ts+++ b/apps/sandbox/src/app/sandboxPages.ts@@ -172,6 +172,12 @@ export const categories: SandboxCategory[] = [slug: 'themes',description: 'Theme palette previews and design token references.',pages: [+ {+ name: 'Theme Family Artifacts',+ href: '/pages/theme-family/',+ description:+ 'One generated CSS/ESM family with attribute switching, nested descendants, sibling isolation, and cascade-order evidence',+ },{name: 'Neutral Palette',href: '/pages/neutral-palette/',diff --git a/apps/sandbox/src/themes/theme-family/ocean-calm-deep.ts b/apps/sandbox/src/themes/theme-family/ocean-calm-deep.tsnew file mode 100644index 0000000000..87d41ea4b7--- /dev/null+++ b/apps/sandbox/src/themes/theme-family/ocean-calm-deep.ts@@ -0,0 +1,11 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @file Sandbox zero-delta theme. @input Calm child. @output Selectable grandchild. @position Maintained consumer source. */++import {defineTheme} from '@astryxdesign/core/theme';+import {oceanCalmTheme} from './ocean-calm';++export const oceanCalmDeepTheme = defineTheme({+ name: 'sandbox-ocean-calm-deep',+ extends: oceanCalmTheme,+});diff --git a/apps/sandbox/src/themes/theme-family/ocean-calm.ts b/apps/sandbox/src/themes/theme-family/ocean-calm.tsnew file mode 100644index 0000000000..de63d3366a--- /dev/null+++ b/apps/sandbox/src/themes/theme-family/ocean-calm.ts@@ -0,0 +1,23 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @file Sandbox family child. @input Ocean root. @output Child deltas. @position Maintained consumer source. */++import {defineTheme} from '@astryxdesign/core/theme';+import {oceanTheme} from './ocean';++export const oceanCalmTheme = defineTheme({+ name: 'sandbox-ocean-calm',+ extends: oceanTheme,+ localTokens: {'--sandbox-family-wave-width': '4px'},+ tokens: {+ '--color-accent': 'rgb(0 109 119)',+ '--color-background-surface': 'rgb(230 255 251)',+ '--color-text-primary': 'rgb(0 75 80)',+ },+ components: {+ button: {+ base: {borderColor: 'rgb(0 75 80)'},+ 'variant:primary': {backgroundColor: 'rgb(0 109 119)'},+ },+ },+});diff --git a/apps/sandbox/src/themes/theme-family/ocean-midnight.ts b/apps/sandbox/src/themes/theme-family/ocean-midnight.tsnew file mode 100644index 0000000000..b86405fa8d--- /dev/null+++ b/apps/sandbox/src/themes/theme-family/ocean-midnight.ts@@ -0,0 +1,21 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @file Sandbox sibling theme. @input Ocean root. @output Isolated sibling branch. @position Maintained consumer source. */++import {defineTheme} from '@astryxdesign/core/theme';+import {oceanTheme} from './ocean';++export const oceanMidnightTheme = defineTheme({+ name: 'sandbox-ocean-midnight',+ extends: oceanTheme,+ tokens: {+ '--color-accent': 'rgb(90 79 207)',+ '--color-background-surface': 'rgb(240 238 255)',+ '--color-text-primary': 'rgb(43 36 107)',+ },+ components: {+ button: {+ 'variant:primary': {backgroundColor: 'rgb(90 79 207)'},+ },+ },+});diff --git a/apps/sandbox/src/themes/theme-family/ocean.ts b/apps/sandbox/src/themes/theme-family/ocean.tsnew file mode 100644index 0000000000..05a0bbaf6f--- /dev/null+++ b/apps/sandbox/src/themes/theme-family/ocean.ts@@ -0,0 +1,43 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/** @file Sandbox family root. @input Authored theme config. @output Root family member. @position Maintained consumer source. */++import {defineTheme} from '@astryxdesign/core/theme';++export const oceanTheme = defineTheme({+ name: 'sandbox-ocean',+ typography: {+ body: {family: 'Arial', fallbacks: 'sans-serif'},+ heading: {family: 'Georgia', fallbacks: 'serif'},+ },+ tokens: {+ '--color-accent': 'rgb(0 119 182)',+ '--color-background-surface': 'rgb(240 248 255)',+ '--color-text-primary': 'rgb(2 62 138)',+ },+ localTokens: {'--sandbox-family-wave-width': '2px'},+ components: {+ button: {+ base: {+ borderColor: 'rgb(0 53 84)',+ borderStyle: 'solid',+ borderWidth: 'var(--sandbox-family-wave-width)',+ },+ 'variant:primary': {+ backgroundColor: 'rgb(0 119 182)',+ color: 'rgb(255 255 255)',+ },+ },+ },+ adaptations: {+ rules: [+ {+ when: {width: {from: 'md'}},+ value: {components: {button: {base: {minHeight: '42px'}}}},+ },+ ],+ },+ onDark: {+ components: {button: {base: {borderColor: 'rgb(144 224 239)'}}},+ },+});diff --git a/apps/sandbox/src/themes/theme-family/unrelated-before.css b/apps/sandbox/src/themes/theme-family/unrelated-before.cssnew file mode 100644index 0000000000..08f9a05b07--- /dev/null+++ b/apps/sandbox/src/themes/theme-family/unrelated-before.css@@ -0,0 +1,9 @@+/* Copyright (c) Meta Platforms, Inc. and affiliates. */++/* Loaded before the generated family stylesheet. Scope proximity must keep the+ active family rule in control despite equal specificity and layer. */+@layer astryx-theme {+ :where([data-family-order='before']) .astryx-button[data-variant='primary'] {+ background-color: var(--color-error);+ }+}diff --git a/packages/cli/api/theme/build/build.family.test.mjs b/packages/cli/api/theme/build/build.family.test.mjsnew file mode 100644index 0000000000..d746c1011a--- /dev/null+++ b/packages/cli/api/theme/build/build.family.test.mjs@@ -0,0 +1,435 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/** @file Focused contract tests for keyed theme-family builds. */+import {parse} from '@babel/parser';+import {execFileSync} from 'node:child_process';+// prettier-ignore+import {afterEach, beforeAll, beforeEach, describe, expect, it, vi} from 'vitest';+import * as fs from 'node:fs';+import * as os from 'node:os';+import * as path from 'node:path';+import {pathToFileURL} from 'node:url';+import {defineTheme as defineCoreTheme} from '@astryxdesign/core/theme';+import {themeBuild, themeBuildFamily} from './build.mjs';+import {interceptCore} from './core-interception.mjs';+import {ensureCoreBuilt} from '../../../clients/cli/commands/ensure-core-built.mjs';+import {runCli} from '../../../test-utils/run-cli.mjs';+vi.setConfig({testTimeout: 120_000});+const CLI_ROOT = path.resolve(import.meta.dirname, '../../..');+const FAMILY_KEY = 'ocean-family';+const OUTPUTS = [`${FAMILY_KEY}.css`, `${FAMILY_KEY}.js`, `${FAMILY_KEY}.d.ts`];+/** @type {string[]} */ let dirs;+beforeAll(() => ensureCoreBuilt(), 200_000);+beforeEach(() => (dirs = []));+// prettier-ignore+afterEach(() => { for (const dir of dirs) fs.rmSync(dir, {recursive: true, force: true}); });+// prettier-ignore+function makeDir() { const dir = fs.mkdtempSync(path.join(CLI_ROOT, '.tmp-theme-family-')); dirs.push(dir); fs.mkdirSync(path.join(dir, 'themes'), {recursive: true}); fs.writeFileSync(path.join(dir, 'package.json'), '{"type":"module"}\n'); return dir; }+function writeFamily(dir) {+ const themes = path.join(dir, 'themes');+ const hidden = path.join(themes, '.hidden');+ fs.mkdirSync(hidden, {recursive: true});+ const write = (root, name, source) =>+ fs.writeFileSync(path.join(root, name), source);+ const helper = path.join(dir, 'node_modules/@fixture/static-helper');+ fs.mkdirSync(helper, {recursive: true});+ fs.writeFileSync(+ path.join(helper, 'package.json'),+ JSON.stringify({+ name: '@fixture/static-helper',+ type: 'module',+ exports: {import: './index.mjs'},+ }),+ );+ fs.writeFileSync(+ path.join(helper, 'index.mjs'),+ `export const marker=true;\n`,+ );+ // prettier-ignore+ for (const [root, name, source] of [[themes, 'base-icons.mjs', `import '@fixture/static-helper';export {icons} from './base-icons-leaf.mjs';\n`], [themes, 'base-icons-leaf.mjs', `export const icons={close:'base-close',menu:'base-menu'};\n`], [hidden, 'child-icons.mjs', `export const icons={close:'child-close'};\n`], [themes, 'base-indicators.mjs', `export const indicators={check:'base-check',radio:'base-radio'};\n`], [hidden, 'child-indicators.mjs', `export const indicators={check:'child-check'};\n`]]) write(root, name, source);+ // prettier-ignore+ write(themes, 'ocean.mjs', `import {defineTheme} from '@astryxdesign/core/theme';+import {icons} from './base-icons.mjs';+import {indicators} from './base-indicators.mjs';+await Promise.resolve();+export const oceanTheme=defineTheme({+ name:'ocean',icons,indicators,+ tokens:{'--color-accent':'rgb(0 119 182)','--color-background-body':'rgb(240 248 255)'},+ localTokens:{'--tide':'8px','--wash':'linear-gradient(\\nred,\\nblue\\n)','--commented':'red /* ) */','--payload':'[one; two]'},+ components:{button:{base:{borderRadius:'6px',backgroundImage:'url(/icons/*/mark.svg)',':hover':{backgroundColor:'rgb(220 40 40)'}},'variant:a{b':{color:'rgb(1 2 3)'}},card:{base:{padding:'8px 16px'}},text:{'type:body':{letterSpacing:'0.01em'}}},+ adaptations:{rules:[{when:{width:{below:'md'}},value:{tokens:{'--spacing-4':'12px'},components:{button:{base:{minHeight:'40px'}}}}}]},+ onDark:{tokens:{'--color-border':'rgb(80 120 140)'},components:{button:{base:{borderColor:'rgb(80 120 140)','::before':{content:\`'@scope ([data-astryx-theme="ocean"])'\`}}}}},+});export default oceanTheme;\n`,+ );+ write(+ themes,+ 'ocean-barrel.mjs',+ `export {oceanTheme} from './ocean.mjs';\n`,+ );+ // prettier-ignore+ write(hidden, 'ocean-calm.mjs', `import {defineTheme} from '@astryxdesign/core/theme';+import {oceanTheme} from '../ocean-barrel.mjs';+import {icons as brandIcons} from './child-icons.mjs';+import {indicators as brandIndicators} from './child-indicators.mjs';+export const resolvedOceanCalmTheme=defineTheme({+ name:'ocean-calm',extends:oceanTheme,icons:brandIcons,indicators:brandIndicators,+ tokens:{'--color-accent':['rgb(0 150 170)','rgb(0 170 190)']},+ localTokens:{'--tide':'10px','--wash':'linear-gradient(\\nred,\\ngreen\\n)','--payload':'[one; three]'},+ components:{button:{base:{backgroundColor:'rgb(220 250 250)',borderColor:'rgb(0 0 0)',minHeight:'28px'},'variant:lagoon':{backgroundColor:'rgb(0 90 110)'}},card:{base:{padding:'24px'}}},+ adaptations:{widthBreakpoints:{md:900}},+});export const oceanCalmTheme={...resolvedOceanCalmTheme};export default oceanCalmTheme;\n`,+ );+ // prettier-ignore+ write(hidden, 'ocean-calm-deep.mjs', `import {defineTheme} from '@astryxdesign/core/theme';\nimport {oceanCalmTheme} from './ocean-calm.mjs';\nexport const oceanCalmDeepTheme=defineTheme({name:'ocean-calm-deep',extends:oceanCalmTheme});\n`);+ // prettier-ignore+ write(themes, 'ocean-midnight.mjs', `import {oceanTheme} from './ocean.mjs';\nexport const oceanMidnightTheme={name:'ocean-midnight',extends:oceanTheme,tokens:{'--color-background-body':'rgb(4 20 32)'},components:{button:{base:{color:'rgb(235 250 255)'}}}};export default oceanMidnightTheme;\n`);+ // prettier-ignore+ return ['themes/ocean.mjs', 'themes/.hidden/ocean-calm.mjs', 'themes/.hidden/ocean-calm-deep.mjs', 'themes/ocean-midnight.mjs'];+}+const count = (text, needle) => text.split(needle).length - 1;+/** @param {string} source */+// prettier-ignore+function executableDependencies(source) {+ const ast = parse(source, {sourceType: 'module'}); /** @type {string[]} */ const dependencies = [];+ /** @param {any} node */ const visit = node => {+ if (!node || typeof node !== 'object') return;+ if (['ImportDeclaration', 'ExportNamedDeclaration', 'ExportAllDeclaration'].includes(node.type) && typeof node.source?.value === 'string') dependencies.push(node.source.value);+ const dynamic = node.type === 'ImportExpression' ? node.source : node.type === 'CallExpression' && (node.callee?.type === 'Import' || node.callee?.name === 'require') ? node.arguments?.[0] : null;+ if (dynamic) dependencies.push(typeof dynamic.value === 'string' ? dynamic.value : '<non-static>');+ for (const value of Object.values(node)) if (Array.isArray(value)) value.forEach(child => child?.type && visit(child)); else if (value?.type) visit(value);+ };+ visit(ast); return dependencies;+}+// prettier-ignore+const build = (dir, files, options = {}) => themeBuildFamily(files, {familyKey: FAMILY_KEY, ...options}, {cwd: dir});+describe('themeBuildFamily()', () => {+ // prettier-ignore+ it('does not add lineage metadata to ordinary Core themes', () => {+ const base = defineCoreTheme({name: 'runtime-base'}), child = defineCoreTheme({name: 'runtime-child', extends: base}), spread = {...child};+ expect(Object.getOwnPropertySymbols(base)).toEqual([]); expect(Object.getOwnPropertySymbols(child)).toEqual([]);+ expect(Reflect.ownKeys(spread)).toEqual(Reflect.ownKeys(child)); expect(JSON.stringify(spread)).toBe(JSON.stringify(child));+ });++ it('emits one deterministic complete trio with shared rules and member deltas', async () => {+ const first = makeDir();+ const second = makeDir();+ const firstFiles = writeFamily(first);+ const secondFiles = writeFamily(second);+ // prettier-ignore+ const result = await build(first, [firstFiles[2], firstFiles[3], firstFiles[0], firstFiles[1]]);+ // prettier-ignore+ await build(second, [secondFiles[1], secondFiles[0], secondFiles[3], secondFiles[2]]);+ expect(result?.type).toBe('theme.build');+ expect(result?.data.name).toBe('ocean');+ // prettier-ignore+ expect(result?.data.outputs).toEqual({css: `themes/${FAMILY_KEY}.css`, js: `themes/${FAMILY_KEY}.js`, dts: `themes/${FAMILY_KEY}.d.ts`});+ // prettier-ignore+ for (const output of OUTPUTS) { const a = fs.readFileSync(path.join(first, 'themes', output), 'utf8'), b = fs.readFileSync(path.join(second, 'themes', output), 'utf8'); expect({output, content: a}).toEqual({output, content: b}); }+ const css = fs.readFileSync(+ path.join(first, 'themes', `${FAMILY_KEY}.css`),+ 'utf8',+ );+ expect(css).toContain(+ ':where([data-astryx-theme="ocean"], [data-astryx-theme="ocean-calm"], [data-astryx-theme="ocean-calm-deep"], [data-astryx-theme="ocean-midnight"])',+ );+ expect(css).toContain(+ ':where([data-astryx-theme="ocean-calm"], [data-astryx-theme="ocean-calm-deep"])',+ );+ expect(css).not.toContain(':where(.astryx-button)');+ expect(css).toContain('--tide: 8px;');+ expect(css).toMatch(/--wash: linear-gradient\(\s*red,\s*green\s*\);/);+ expect(css).toContain('--commented: red /* ) */;');+ expect(css).toContain('[data-variant="a{b"]');+ expect(css).toContain('background-image: url(/icons/*/mark.svg);');+ expect(css).toContain('--payload: [one; two];');+ expect(css).toContain('--payload: [one; three];');+ expect(css).toContain(`content: '@scope ([data-astryx-theme="ocean"])';`);+ expect(css).toContain('--tide: 10px;');+ expect(count(css, '--tide: 8px;')).toBe(1);+ expect(count(css, '--tide: 10px;')).toBe(1);+ expect(css).toContain('--astryx-card-padding: 24px;');+ expect(css).toContain('--astryx-card-padding-inline: 16px;');+ expect(css).toContain('@media (width < 768px)');+ expect(css).toContain('@media (width < 900px)');+ expect(css).toContain('[data-astryx-media="dark"]');+ // prettier-ignore+ for (const text of [':root:where([data-astryx-theme="ocean-calm"], [data-astryx-theme="ocean-calm-deep"])', ':where(:scope:not([data-theme]):not(html[data-theme] *))', ':where(:scope:not([data-theme]):is(html[data-theme="dark"] *))', 'html[data-theme="dark"]:where([data-astryx-theme="ocean-calm"], [data-astryx-theme="ocean-calm-deep"])']) expect(css).toContain(text);+ expect(css).not.toContain('\n :root { color-scheme: light dark; }');+ // prettier-ignore+ expect(css).not.toContain('@scope (:where([data-astryx-theme="ocean-calm-deep"]))');+ // prettier-ignore+ const js = fs.readFileSync(path.join(first, 'themes', `${FAMILY_KEY}.js`), 'utf8'), dts = fs.readFileSync(path.join(first, 'themes', `${FAMILY_KEY}.d.ts`), 'utf8');+ const dependencies = executableDependencies(js);+ expect(dependencies).not.toContain('<non-static>');+ expect(+ dependencies.some(specifier => /\.css(?:$|[?#])/i.test(specifier)),+ ).toBe(false);+ expect(js).toContain('from "./.hidden/child-icons.mjs"');+ // prettier-ignore+ for (const name of ['oceanTheme', 'oceanCalmTheme', 'oceanCalmDeepTheme', 'oceanMidnightTheme']) {+ expect(js).toContain(`export const ${name}`);+ expect(dts).toContain(`export declare const ${name}`);+ }+ // prettier-ignore+ const imported = await import(`${pathToFileURL(path.join(first, 'themes', `${FAMILY_KEY}.js`)).href}?${Date.now()}`);+ expect(imported.oceanTheme.icons.close).toBe('base-close');+ expect(imported.oceanCalmTheme.icons.close).toBe('child-close');+ expect(imported.oceanCalmTheme.icons.menu).toBe('base-menu');+ expect(imported.oceanCalmDeepTheme.icons.menu).toBe('base-menu');+ expect(imported.oceanCalmTheme.indicators.check).toBe('child-check');+ expect(imported.oceanCalmTheme.indicators.radio).toBe('base-radio');+ expect(imported.oceanCalmDeepTheme.indicators.radio).toBe('base-radio');+ expect(imported.oceanCalmDeepTheme.name).toBe('ocean-calm-deep');+ expect(Object.hasOwn(imported.oceanCalmTheme, '__extends')).toBe(false);+ fs.writeFileSync(+ path.join(first, 'themes', 'consumer.tsx'),+ `import type {DefinedTheme} from '@astryxdesign/core/theme';\n` ++ `import {Button} from '@astryxdesign/core/Button';\n` ++ `import {oceanTheme, oceanCalmTheme, oceanCalmDeepTheme, oceanMidnightTheme} from './ocean-family.js';\n` ++ `const family: DefinedTheme[] = [oceanTheme, oceanCalmTheme, oceanCalmDeepTheme, oceanMidnightTheme];\n` ++ `// @ts-expect-error family lineage is build-private, not DefinedTheme API\n` ++ `oceanCalmTheme.__extends;\n` ++ `export const Probe = () => <Button label={String(family.length)} variant="lagoon" />;\n`,+ );+ fs.writeFileSync(+ path.join(first, 'themes', 'tsconfig.json'),+ JSON.stringify({+ compilerOptions: {+ module: 'esnext',+ target: 'es2022',+ jsx: 'react-jsx',+ moduleResolution: 'bundler',+ strict: true,+ skipLibCheck: true,+ },+ include: ['consumer.tsx', 'ocean-family.d.ts'],+ }),+ );+ execFileSync(+ 'pnpm',+ ['exec', 'tsc', '--project', 'tsconfig.json', '--noEmit'],+ {cwd: path.join(first, 'themes'), stdio: 'pipe'},+ );+ // prettier-ignore+ for (const member of ['ocean', 'ocean-calm', 'ocean-calm-deep', 'ocean-midnight']) expect(fs.existsSync(path.join(first, 'themes', `${member}.css`))).toBe(false);+ });+ // prettier-ignore+ it('retains private capture across cached frozen exports', () => {+ const core = {defineTheme: input => Object.freeze({name: input.name, tokens: {}})}, first = interceptCore(core), wrapped = /** @type {any} */ (first.modules['@astryxdesign/core/theme']);+ const parent = wrapped.defineTheme({name: 'parent'}), child = wrapped.defineTheme({name: 'child', extends: parent, adaptations: {rules: []}});+ first.retain(child); first.strip(child); const retry = interceptCore(core);+ expect(retry.parentOf(child)).toBe(parent); expect(retry.lineageOf(child).some(value => value?.adaptations)).toBe(true); expect(retry.unobservedIn(child)).toEqual([]);+ });++ it('checks the exact keyed trio without writing stale or missing output', async () => {+ const dir = makeDir();+ const files = writeFamily(dir);+ await build(dir, files);+ const cssPath = path.join(dir, 'themes', `${FAMILY_KEY}.css`);+ const jsPath = path.join(dir, 'themes', `${FAMILY_KEY}.js`);+ const dtsPath = path.join(dir, 'themes', `${FAMILY_KEY}.d.ts`);+ const cssBefore = fs.readFileSync(cssPath, 'utf8');+ expect((await build(dir, files, {check: true}))?.data).toMatchObject({+ upToDate: true,+ stale: [],+ checked: OUTPUTS.map(file => `themes/${file}`),+ });+ fs.writeFileSync(jsPath, '/* stale */\n');+ fs.rmSync(dtsPath);+ const checked = await build(dir, files, {check: true});+ expect(checked?.type).toBe('theme.build.check');+ expect(checked?.data.upToDate).toBe(false);+ expect(checked?.data.stale).toEqual([+ {path: `themes/${FAMILY_KEY}.js`, reason: 'outdated'},+ {path: `themes/${FAMILY_KEY}.d.ts`, reason: 'missing'},+ ]);+ expect(fs.readFileSync(cssPath, 'utf8')).toBe(cssBefore);+ expect(fs.readFileSync(jsPath, 'utf8')).toBe('/* stale */\n');+ expect(fs.existsSync(dtsPath)).toBe(false);+ });++ it('fails without publishing a mixed trio when staging a write fails', async () => {+ const dir = makeDir();+ const files = writeFamily(dir);+ const outputDir = path.join(dir, 'themes');+ const blockedTmp = path.join(+ outputDir,+ `${FAMILY_KEY}.js.${process.pid}.tmp`,+ );+ fs.mkdirSync(blockedTmp);++ await expect(build(dir, files)).rejects.toThrow(+ /Failed to write theme outputs/,+ );+ for (const output of OUTPUTS) {+ expect(fs.existsSync(path.join(outputDir, output))).toBe(false);+ }+ expect(+ fs.existsSync(+ path.join(outputDir, `${FAMILY_KEY}.css.${process.pid}.tmp`),+ ),+ ).toBe(false);+ });++ it('rejects invalid graphs and keys before touching an existing trio', async () => {+ const dir = makeDir();+ const files = writeFamily(dir);+ const outputDir = path.join(dir, 'themes');+ for (const output of [...OUTPUTS, 'ocean.css', 'ocean.js', 'ocean.d.ts']) {+ fs.writeFileSync(path.join(outputDir, output), `sentinel:${output}`);+ }+ const unrelated = 'themes/unrelated.mjs';+ // prettier-ignore+ fs.writeFileSync(path.join(dir, unrelated), `import {defineTheme} from '@astryxdesign/core/theme';export default defineTheme({name:'unrelated'});\n`);+ const duplicate = 'themes/duplicate.mjs';+ // prettier-ignore+ fs.writeFileSync(path.join(dir, duplicate), `import {defineTheme} from '@astryxdesign/core/theme';export default defineTheme({name:'ocean'});\n`);+ const impostor = 'themes/impostor.mjs';+ const impostorChild = 'themes/impostor-child.mjs';+ // prettier-ignore+ fs.writeFileSync(path.join(dir, impostor), `import {oceanTheme} from './ocean.mjs';export const impostor={...oceanTheme};\n`);+ // prettier-ignore+ fs.writeFileSync(path.join(dir, impostorChild), `import {defineTheme} from '@astryxdesign/core/theme';import {impostor} from './impostor.mjs';export default defineTheme({name:'impostor-child',extends:impostor});\n`);+ const emptyParent = 'themes/empty-parent.mjs';+ // prettier-ignore+ fs.writeFileSync(path.join(dir, emptyParent), `import {defineTheme} from '@astryxdesign/core/theme';const invalid={name:'',tokens:{}};export default defineTheme({name:'empty-parent',extends:invalid});\n`);+ const sourceCollision = 'themes/Theme-family.js';+ const sourceBytes = `export const baseTheme={name:'base',tokens:{},extends:undefined};\n`;+ fs.writeFileSync(path.join(dir, sourceCollision), sourceBytes);+ const sourceChild = 'themes/source-child.mjs';+ // prettier-ignore+ fs.writeFileSync(path.join(dir, sourceChild), `import {defineTheme} from '@astryxdesign/core/theme';import {baseTheme} from './Theme-family.js';export default defineTheme({name:'source-child',extends:baseTheme});\n`);+ const bypass = 'themes/bypass.mjs';+ fs.writeFileSync(+ path.join(dir, bypass),+ `export default {name:'bypass',tokens:{}};\n`,+ );+ const graphIcons = 'themes/graph-icons.mjs';+ const graphRoot = 'themes/graph-root.mjs';+ const graphChild = 'themes/graph-child.mjs';+ // prettier-ignore+ fs.writeFileSync(path.join(dir, graphIcons), `export const icons={close:'x'};if(false)import(\`./hidden.css\`);\n`);+ fs.writeFileSync(path.join(dir, 'themes/hidden.css'), '.hidden{}\n');+ // prettier-ignore+ fs.writeFileSync(path.join(dir, graphRoot), `import {defineTheme} from '@astryxdesign/core/theme';import {icons} from './graph-icons.mjs';export const root=defineTheme({name:'graph-root',icons,tokens:{'--color-accent':'red'}});\n`);+ // prettier-ignore+ fs.writeFileSync(path.join(dir, graphChild), `import {defineTheme} from '@astryxdesign/core/theme';import {root} from './graph-root.mjs';export default defineTheme({name:'graph-child',extends:root});\n`);+ // prettier-ignore+ for (const [name, type, entry, source] of [['external-registry', 'module', 'index.mjs', `export const icons={close:'external'};if(false)import('./missing.mjs');\n`], ['computed-registry', 'module', 'index.mjs', `export const icons={close:'computed'};const extension='css';if(false)import(\`./hidden.\${extension}\`);\n`], ['cjs-registry', 'commonjs', 'index.cjs', `exports.icons={close:'cjs'};\n`]]) { const root = path.join(dir, 'node_modules/@fixture', name); fs.mkdirSync(root, {recursive: true}); fs.writeFileSync(path.join(root, 'package.json'), JSON.stringify({name: `@fixture/${name}`, type, exports: `./${entry}`})); fs.writeFileSync(path.join(root, entry), source); }+ fs.writeFileSync(+ path.join(dir, 'node_modules/@fixture/computed-registry/hidden.css'),+ '.hidden{}\n',+ );+ const cycleShared = 'themes/cycle-shared.mjs';+ const cycleA = 'themes/cycle-a.mjs';+ const cycleB = 'themes/cycle-b.mjs';+ // prettier-ignore+ fs.writeFileSync(path.join(dir, cycleShared), `import {defineTheme} from '@astryxdesign/core/theme';const input={name:'cycle-a'};export const a=defineTheme(input);export const b=defineTheme({name:'cycle-b',extends:a});input.extends=b;\n`);+ fs.writeFileSync(+ path.join(dir, cycleA),+ `export {a as default} from './cycle-shared.mjs';\n`,+ );+ fs.writeFileSync(+ path.join(dir, cycleB),+ `export {b as default} from './cycle-shared.mjs';\n`,+ );+ // prettier-ignore+ const cases = [+ {files: [files[0]], key: FAMILY_KEY, message: /at least two/i}, {files: [files[0], files[0]], key: FAMILY_KEY, message: /duplicate/i},+ {files: [files[0], duplicate], key: FAMILY_KEY, message: /duplicate.*ocean/i}, {files: [files[1], unrelated], key: FAMILY_KEY, message: /ancestor|parent/i},+ {files: [files[0], unrelated], key: FAMILY_KEY, message: /one selected root/i}, {files: [files[0], impostorChild], key: FAMILY_KEY, message: /does not extend the selected/i},+ {files: [files[0], bypass], key: FAMILY_KEY, message: /exact family ancestry could not be observed/i},+ {files: [cycleA, cycleB], key: FAMILY_KEY, message: /cycle/i},+ {files: [graphRoot, graphChild], key: 'graph-family', message: /registry graph imports CSS/i},+ {files: [emptyParent, unrelated], key: FAMILY_KEY, message: /invalid normalized parent/i},+ {files: [sourceCollision, sourceChild], key: 'theme-family', message: /collides with a selected source/i},+ {files, key: 'ocean', message: /collides.*standalone/i},+ {files, key: '../escaped', message: /family key/i},+ {files, key: 'Ocean_Family', message: /lower-kebab/i},+ ];+ // prettier-ignore+ for (const testCase of cases) await expect(themeBuildFamily(testCase.files, {familyKey: testCase.key}, {cwd: dir})).rejects.toThrow(testCase.message);+ // prettier-ignore+ fs.writeFileSync(path.join(dir, graphIcons), `export const icons={close:'x'};if(false)import('./missing.mjs');\n`);+ // prettier-ignore+ await expect(themeBuildFamily([graphRoot, graphChild], {familyKey: 'graph-family'}, {cwd: dir})).rejects.toThrow(/cannot resolve registry import/i);+ // prettier-ignore+ fs.writeFileSync(path.join(dir, graphIcons), `export {icons} from './nested-icons';\n`);+ // prettier-ignore+ fs.writeFileSync(path.join(dir, 'themes/nested-icons.mjs'), `export const icons={close:'x'};\n`);+ // prettier-ignore+ await expect(themeBuildFamily([graphRoot, graphChild], {familyKey: 'graph-family'}, {cwd: dir})).rejects.toThrow(/cannot resolve registry import/i);+ // prettier-ignore+ for (const [name, source] of [['graph-icons.mjs', `export const icons={close:'x'};\n`], ['graph-leaf.mjs', `export const other={};\n`], ['broken-icons.mjs', `import {missing} from './graph-leaf.mjs';export {missing as icons};\n`], ['compiled-icons.mjs', `export const icons={close:'x'};\n`]]) fs.writeFileSync(path.join(dir, 'themes', name), source);+ // prettier-ignore+ await expect(themeBuildFamily([graphRoot, graphChild], {familyKey: 'graph-family', iconsSpecifier: './broken-icons.mjs'}, {cwd: dir})).rejects.toThrow(/cannot import family registry|does not export/i);+ // prettier-ignore+ await expect(themeBuildFamily([graphRoot, graphChild], {familyKey: 'graph-family', iconsSpecifier: './compiled-icons'}, {cwd: dir})).rejects.toThrow(/cannot resolve registry import/i);+ // prettier-ignore+ await expect(themeBuildFamily([graphRoot, graphChild], {familyKey: 'graph-family', iconsSpecifier: '@fixture/external-registry'}, {cwd: dir})).rejects.toThrow(/cannot resolve registry import/i);+ // prettier-ignore+ await expect(themeBuildFamily([graphRoot, graphChild], {familyKey: 'computed-family', iconsSpecifier: '@fixture/computed-registry'}, {cwd: dir})).rejects.toThrow(/non-static dependency.*resolvable and CSS-free/i);+ // prettier-ignore+ for (const extension of ['css', 'js', 'd.ts']) expect(fs.existsSync(path.join(outputDir, `computed-family.${extension}`))).toBe(false);+ // prettier-ignore+ fs.writeFileSync(path.join(dir, 'themes/cjs-icons.mjs'), `export {icons} from '@fixture/cjs-registry';\n`);+ // prettier-ignore+ await expect(themeBuildFamily([graphRoot, graphChild], {familyKey: 'cjs-family', iconsSpecifier: './cjs-icons.mjs', check: true}, {cwd: dir})).resolves.toMatchObject({data: {upToDate: false}});+ // prettier-ignore+ expect(fs.readFileSync(path.join(dir, sourceCollision), 'utf8')).toBe(sourceBytes);+ // prettier-ignore+ for (const output of [...OUTPUTS, 'ocean.css', 'ocean.js', 'ocean.d.ts']) expect(fs.readFileSync(path.join(outputDir, output), 'utf8')).toBe(`sentinel:${output}`);+ });+ it('leaves standalone build bytes and outputs independent of family mode', async () => {+ const dir = makeDir();+ const files = writeFamily(dir);+ const standalone = await themeBuild(files[0], {}, {cwd: dir});+ // prettier-ignore+ const before = Object.fromEntries(['ocean.css', 'ocean.js', 'ocean.d.ts'].map(file => [file, fs.readFileSync(path.join(dir, 'themes', file), 'utf8')]));+ await build(dir, files);+ const checked = await themeBuild(files[0], {check: true}, {cwd: dir});+ expect(standalone?.type).toBe('theme.build');+ expect(checked?.data.upToDate).toBe(true);+ // prettier-ignore+ for (const [file, content] of Object.entries(before)) expect(fs.readFileSync(path.join(dir, 'themes', file), 'utf8')).toBe(content);+ });+});+describe('theme build --family CLI', () => {+ it('requires the key exactly with family mode and closes incompatible flags', async () => {+ const dir = makeDir();+ const files = writeFamily(dir);+ // prettier-ignore+ const cases = [+ {args: ['theme', 'build', '--family', ...files], message: /family-key/i},+ {args: ['theme', 'build', ...files, '--family-key', FAMILY_KEY], message: /family/i},+ {args: ['theme', 'build', '--family', ...files, '--family-key', FAMILY_KEY, '--out', 'other.css'], message: /--out/i},+ {args: ['theme', 'build', '--family', ...files, '--family-key', FAMILY_KEY, '--watch'], message: /--watch/i},+ ];+ // prettier-ignore+ for (const testCase of cases) { const result = await runCli(testCase.args, dir); expect(result.status).toBe(1); expect(result.stdout + result.stderr).toMatch(testCase.message); }+ });+ it('builds and checks one family through the existing response contract', async () => {+ const dir = makeDir();+ const files = writeFamily(dir);+ const args = [+ '--json',+ 'theme',+ 'build',+ '--family',+ ...files,+ '--family-key',+ FAMILY_KEY,+ ];+ const built = await runCli(args, dir);+ expect(built.status).toBe(0);+ expect(JSON.parse(built.stdout)).toMatchObject({+ type: 'theme.build',+ data: {name: 'ocean'},+ });+ const checked = await runCli([...args, '--check'], dir);+ expect(checked.status).toBe(0);+ expect(JSON.parse(checked.stdout)).toMatchObject({+ type: 'theme.build.check',+ data: {name: 'ocean', upToDate: true},+ });+ });+});diff --git a/packages/cli/api/theme/build/build.mjs b/packages/cli/api/theme/build/build.mjsindex 117cb09df9..2c70c84a57 100644--- a/packages/cli/api/theme/build/build.mjs+++ b/packages/cli/api/theme/build/build.mjs@@ -1,10 +1,10 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file theme build API — compile a defineTheme file to CSS + JS + .d.ts.+ * @file theme build API — compile standalone themes or one selected family.*- * `themeBuild(file, options, ctx)` is the programmatic surface behind- * `astryx theme build`. It reads a theme file that uses defineTheme() and, via+ * `themeBuild` and `themeBuildFamily` share the same loader, compiler,+ * serializers, check, and writer. They read defineTheme() sources and, via* @astryxdesign/core's shared generator (the SINGLE source of truth so the* build emits the exact CSS the `<Theme>` runtime does), writes:* - A CSS file with token overrides and component styles@@ -39,7 +39,9 @@import * as fs from 'node:fs';import * as path from 'node:path';-import {fileURLToPath} from 'node:url';+import {isBuiltin} from 'node:module';+import {fileURLToPath, pathToFileURL} from 'node:url';+import {parse} from '@babel/parser';import {createJiti} from 'jiti';import {getCliInvocation} from '../../../foundation/env/package-manager.mjs';import {CLI_ROOT, findCoreDir} from '../../../foundation/fs/paths.mjs';@@ -58,6 +60,7 @@ import {} from '../../../foundation/discovery/theming-targets.mjs';import {collectUnloadedFonts, formatFontLoadingHelp} from './font-warning.mjs';import {interceptCore} from './core-interception.mjs';+import {generateFamilyCSS, resolveThemeFamily} from './family.mjs';// Import shared theme processing from core. `astryx theme build` MUST produce the// exact same CSS as the `<Theme>` runtime, so it has exactly one generation@@ -199,6 +202,52 @@ function normalizeForCompare(content) {.join('\n');}+/** @param {Array<{dest: string, content: string}>} writes @param {string} cwd @returns {Array<{path: string, reason: 'missing' | 'outdated'}>} */+function staleBuildOutputs(writes, cwd) {+ /** @type {Array<{path: string, reason: 'missing' | 'outdated'}>} */+ const stale = [];+ for (const write of writes) {+ const rel = path.relative(cwd, write.dest);+ if (!fs.existsSync(write.dest)) {+ stale.push({path: rel, reason: 'missing'});+ continue;+ }+ const onDisk = fs.readFileSync(write.dest, 'utf8');+ if (normalizeForCompare(onDisk) !== normalizeForCompare(write.content)) {+ stale.push({path: rel, reason: 'outdated'});+ }+ }+ return stale;+}++/** @param {Array<{dest: string, content: string}>} writes */+function writeBuildOutputs(writes) {+ if (writes.length === 0) return;+ fs.mkdirSync(path.dirname(writes[0].dest), {recursive: true});+ /** @type {Array<{tmp: string, dest: string}>} */+ const staged = [];+ try {+ for (const write of writes) {+ const tmp = `${write.dest}.${process.pid}.tmp`;+ fs.writeFileSync(tmp, write.content);+ staged.push({tmp, dest: write.dest});+ }+ for (const stagedWrite of staged) {+ fs.renameSync(stagedWrite.tmp, stagedWrite.dest);+ }+ } catch (error) {+ for (const stagedWrite of staged) {+ try {+ fs.rmSync(stagedWrite.tmp, {force: true});+ } catch {+ // Best effort: the command still fails and never reports success.+ }+ }+ const message = `Failed to write theme outputs: ${/** @type {Error} */ (error).message}`;+ throw new AstryxError(message, undefined, ERROR_CODES.ERR_WRITE_FAILED);+ }+}+/*** Convert a theme name to a valid JS identifier.*@@ -1157,7 +1206,85 @@ const THEME_MODULE_EXTENSIONS = ['.js','.json',];-+// prettier-ignore+const registryGraphError = (/** @type {string} */ message) => new AstryxError(message, undefined, ERROR_CODES.ERR_THEME_INVALID);+// prettier-ignore+function parseRegistryModule(/** @type {string} */ source, /** @type {string} */ filePath) {+ try { return parse(source, {sourceType: 'unambiguous', plugins: ['typescript', 'jsx', 'decorators-legacy', 'importAttributes']}); }+ catch (error) { throw registryGraphError(`Cannot inspect registry module ${filePath}: ${error instanceof Error ? error.message : String(error)}`); }+}+// prettier-ignore+function moduleDependencies(/** @type {string} */ source, /** @type {string} */ filePath) {+ const ast = parseRegistryModule(source, filePath);+ /** @type {Array<{specifier: string, commonJs: boolean, imports: string[]}>} */ const found = [];+ /** @param {any} node */ const literal = node => typeof node?.value === 'string' ? node.value : node?.type === 'TemplateLiteral' && node.expressions.length === 0 ? node.quasis[0]?.value?.cooked : null;+ /** @param {any} node */ const visit = node => {+ if (!node || typeof node !== 'object') return;+ if (['ImportDeclaration', 'ExportNamedDeclaration', 'ExportAllDeclaration'].includes(node.type) && node.importKind !== 'type' && typeof node.source?.value === 'string') {+ const specifiers = /** @type {any[]} */ (node.specifiers);+ const imports = node.type === 'ImportDeclaration' ? specifiers.filter(item => item.importKind !== 'type' && item.type !== 'ImportNamespaceSpecifier').map(item => item.type === 'ImportDefaultSpecifier' ? 'default' : item.imported?.name ?? item.imported?.value) : node.type === 'ExportNamedDeclaration' ? specifiers.filter(item => item.exportKind !== 'type' && item.type === 'ExportSpecifier').map(item => item.local?.name ?? item.local?.value) : [];+ found.push({specifier: node.source.value, commonJs: false, imports});+ }+ const dependency = node.type === 'ImportExpression' ? node.source : node.type === 'CallExpression' && (node.callee?.type === 'Import' || node.callee?.name === 'require') ? node.arguments?.[0] : null;+ if (dependency) { const specifier = literal(dependency); if (specifier == null) throw registryGraphError(`Registry module ${filePath} has a non-static dependency; family output cannot prove that graph is resolvable and CSS-free.`); found.push({specifier, commonJs: node.callee?.name === 'require', imports: []}); }+ for (const value of Object.values(node)) if (Array.isArray(value)) value.forEach(child => child?.type && visit(child)); else if (value?.type) visit(value);+ };+ visit(ast); return found;+}+// prettier-ignore+function resolveRegistryModule(/** @type {string} */ specifier, /** @type {string} */ parentPath, commonJs = false) {+ if (isBuiltin(specifier) || specifier.startsWith('node:')) return null;+ let resolved;+ try {+ const resolver = createJiti(parentPath, {extensions: THEME_MODULE_EXTENSIONS});+ if (commonJs) resolved = resolver.resolve(specifier);+ else if (specifier.startsWith('.')) resolved = fileURLToPath(new URL(specifier, pathToFileURL(parentPath)));+ else if (path.isAbsolute(specifier)) resolved = specifier;+ else { const url = resolver.esmResolve(specifier); resolved = url.startsWith('file:') ? fileURLToPath(url) : url; }+ } catch (error) { throw registryGraphError(`Cannot resolve registry import "${specifier}" from ${parentPath}: ${error instanceof Error ? error.message : String(error)}`); }+ if (!fs.existsSync(resolved) || !fs.statSync(resolved).isFile()) throw registryGraphError(`Cannot resolve registry import "${specifier}" from ${parentPath}.`);+ return fs.realpathSync(resolved);+}+/** @returns {boolean | null} */+// prettier-ignore+function hasNamedExport(/** @type {string} */ file, /** @type {string} */ name, seen = new Set()) {+ const key = `${file}\0${name}`; if (seen.has(key)) return false; seen.add(key);+ const ast = parseRegistryModule(fs.readFileSync(file, 'utf8'), file); let esm = false; let unknown = false;+ for (const node of /** @type {any[]} */ (ast.program.body)) {+ if (node.type === 'ExportDefaultDeclaration') { esm = true; if (name === 'default') return true; }+ if (node.type === 'ExportNamedDeclaration') {+ esm = true; const declaration = /** @type {any} */ (node.declaration);+ if ((declaration?.id?.name === name) || (declaration?.type === 'VariableDeclaration' && declaration.declarations.some((/** @type {any} */ item) => item.id?.name === name))) return true;+ for (const specifier of /** @type {any[]} */ (node.specifiers)) if ((specifier.exported?.name ?? specifier.exported?.value) === name) {+ if (!node.source || specifier.type === 'ExportNamespaceSpecifier') return true;+ const target = resolveRegistryModule(node.source.value, file); return target ? hasNamedExport(target, specifier.local?.name ?? specifier.local?.value, seen) : false;+ }+ }+ if (node.type === 'ExportAllDeclaration') { esm = true; const target = resolveRegistryModule(node.source.value, file); const status = target ? hasNamedExport(target, name, seen) : false; if (status === true) return true; if (status === null) unknown = true; }+ }+ return esm ? unknown ? null : false : null;+}+// prettier-ignore+async function validateRegistryGraphs(/** @type {Array<{specifier: string, exportName: string}>} */ registries, /** @type {string} */ aggregatePath) {+ /** @type {Array<{specifier: string, parent: string, commonJs: boolean, imports: string[], root?: {exportName: string}}>} */ const pending = registries.map(root => ({specifier: root.specifier, parent: aggregatePath, commonJs: false, imports: [root.exportName], root}));+ /** @type {Array<{file: string, exportName: string}>} */ const runtimeChecks = []; const seen = new Set();+ while (pending.length > 0) {+ const current = pending.pop(); if (!current) break; const {specifier, parent, commonJs, imports, root} = current;+ if (/\.css(?:$|[?#])/i.test(specifier)) throw registryGraphError(`Theme family registry graph imports CSS: ${specifier}`);+ const file = resolveRegistryModule(specifier, parent, commonJs); if (!file) continue;+ if (/\.css$/i.test(file)) throw registryGraphError(`Theme family registry graph imports CSS: ${file}`);+ const external = file.split(path.sep).includes('node_modules');+ for (const name of imports) if (external) runtimeChecks.push({file, exportName: name}); else { const named = hasNamedExport(file, name); if (named === false) throw registryGraphError(`Family registry ${file} does not export "${name}".`); if (named === null) runtimeChecks.push({file, exportName: name}); }+ if (root) runtimeChecks.push({file, exportName: root.exportName});+ if (seen.has(file)) continue; seen.add(file);+ if (/\.[cm]?[jt]sx?$/i.test(file)) for (const edge of moduleDependencies(fs.readFileSync(file, 'utf8'), file)) pending.push({...edge, parent: file});+ }+ for (const [index, root] of runtimeChecks.entries()) {+ let exports; try { exports = await import(`${pathToFileURL(root.file).href}?astryx-family-check=${Date.now()}-${index}`); }+ catch (error) { throw registryGraphError(`Cannot import family registry ${root.file}: ${error instanceof Error ? error.message : String(error)}`); }+ if (!(root.exportName in exports)) throw registryGraphError(`Family registry ${root.file} does not export "${root.exportName}".`);+ }+}/*** Errors that mean "the synchronous loader cannot evaluate this module", as* opposed to "this module is broken". Only the former may fall back to the@@ -1196,23 +1323,27 @@ function isSyncLoaderLimitation(error) {* author's adaptations unobserved. The sync path transpiles it, so the wrapped* core reaches inside installed packages too.*- * A module the sync path cannot evaluate at all (top-level await) still has to- * load, so it falls back to the async import — but that fallback is DEGRADED:- * package sources on that path resolve their own core again. The caller is- * told, and treats anything it could not observe as unproven rather than- * assuming it is clean.+ * A module the sync path cannot evaluate (top-level await) is force-transpiled+ * through jiti's asynchronous evaluator. That keeps interception active for+ * the entry and captures its exact `extends` value; relative dependencies may+ * use native ESM, so family mode binds those objects back to the exact selected+ * source export and old-Core adaptation checks keep treating that path as+ * degraded/fail-closed.** @param {string} filePath* @param {import('./core-interception.mjs').CoreInterception} [interception]* @returns {Promise<{theme: any, degraded: {topLevelAwait: boolean, commonJs: boolean}}>}*/-async function importThemeModule(filePath, interception) {- const jiti = createJiti(import.meta.url, {- moduleCache: false,- jsx: true,- extensions: THEME_MODULE_EXTENSIONS,- ...(interception ? {virtualModules: interception.modules} : {}),- });+// prettier-ignore+async function importThemeModule(filePath, interception, /** @type {any} */ loader = undefined) {+ const jiti =+ loader ??+ createJiti(import.meta.url, {+ moduleCache: false,+ jsx: true,+ extensions: THEME_MODULE_EXTENSIONS,+ ...(interception ? {virtualModules: interception.modules} : {}),+ });/** @type {any} */let mod;@@ -1232,7 +1363,17 @@ async function importThemeModule(filePath, interception) {// theme's own failure and belongs to the caller unchanged.if (!isSyncLoaderLimitation(error)) throw error;degraded.topLevelAwait = true;- mod = await jiti.import(filePath, {default: true});+ // Force asynchronous transformation instead of native import: this+ // keeps virtual Core interception active even when the module uses+ // top-level await.+ mod = await jiti.evalModule(fs.readFileSync(filePath, 'utf8'), {+ id: filePath,+ filename: filePath,+ ext: path.extname(filePath),+ cache: jiti.cache,+ async: true,+ forceTranspile: true,+ });}} finally {commonJsPatch.undo();@@ -1282,9 +1423,10 @@ function isThemeObject(value) {* @param {import('./core-interception.mjs').CoreInterception} [interception]* @returns {Promise<{theme: any, degraded: {topLevelAwait: boolean, commonJs: boolean}}>}*/-async function extractThemeDefinition(filePath, interception) {+// prettier-ignore+async function extractThemeDefinition(filePath, interception, /** @type {any} */ loader = undefined) {try {- return await importThemeModule(filePath, interception);+ return await importThemeModule(filePath, interception, loader);} catch (jitiError) {try {return {@@ -1352,26 +1494,45 @@ function extractThemeDefinitionLegacy(filePath) {* @param {string} filePath* @returns {{exportName: string, importPath: string} | null}*/-function extractIconInfo(filePath) {+function extractRegistryInfo(filePath, field = 'icons', familyMode = false) {const content = fs.readFileSync(filePath, 'utf8');-- // Find the icons field in defineTheme- const iconsMatch = content.match(/icons:\s*([a-zA-Z_][a-zA-Z0-9_]*)/);- if (!iconsMatch) return null;-- const varName = /** @type {string} */ (iconsMatch[1]);-- // Find the import for that variable- const importRegex = new RegExp(- `import\\s*{[^}]*\\b${varName}\\b[^}]*}\\s*from\\s*['"]([^'"]+)['"]`,+ if (!familyMode) {+ const fieldMatch = content.match(+ new RegExp(`${field}:\\s*([a-zA-Z_][a-zA-Z0-9_]*)`),+ );+ if (!fieldMatch) return null;+ const varName = fieldMatch[1];+ const match = content.match(+ new RegExp(+ `import\\s*{[^}]*\\b${varName}\\b[^}]*}\\s*from\\s*['"]([^'"]+)['"]`,+ ),+ );+ return match ? {exportName: varName, importPath: match[1]} : null;+ }+ const defineIndex = content.indexOf('defineTheme(');+ if (defineIndex < 0) return null;+ const themeSource = content.slice(defineIndex);+ const explicit = themeSource.match(+ new RegExp(`${field}:\\s*([a-zA-Z_][a-zA-Z0-9_]*)\\s*(?=[,}])`),);- const importMatch = content.match(importRegex);- if (!importMatch) return null;-- return {- exportName: varName,- importPath: /** @type {string} */ (importMatch[1]),- };+ const shorthand = themeSource.match(+ new RegExp(`[,{]\\s*(${field})\\s*(?=[,}])`),+ );+ const varName = explicit?.[1] ?? shorthand?.[1];+ if (!varName) return null;+ for (const match of content.matchAll(+ /import\s*{([^}]*)}\s*from\s*['"]([^'"]+)['"]/g,+ )) {+ for (const specifier of match[1].split(',')) {+ const [exportName, localName = exportName] = specifier+ .trim()+ .split(/\s+as\s+/);+ if (localName === varName) {+ return {exportName, importPath: match[2]};+ }+ }+ }+ return null;}/**@@ -1397,9 +1558,20 @@ function extractIconInfo(filePath) {* @param {any} themeDef* @param {{exportName: string, importPath: string} | null} iconInfo* @param {string} [iconsSpecifier] - Overrides the scraped icon import specifier.+ * @param {{themeBinding?: string, iconBinding?: string, iconsExpression?: string, indicatorsExpression?: string, artifactBaseName?: string, exportIcons?: boolean}} [moduleOptions]* @returns {string}*/-function generateBuiltModule(themeDef, iconInfo, iconsSpecifier) {+function generateBuiltModule(+ themeDef,+ iconInfo,+ iconsSpecifier,+ moduleOptions = {},+) {+ const themeBinding =+ moduleOptions.themeBinding ?? `${toIdentifier(themeDef.name)}Theme`;+ const iconBinding = moduleOptions.iconBinding ?? iconInfo?.exportName;+ const artifactBaseName = moduleOptions.artifactBaseName ?? themeDef.name;+ const exportIcons = moduleOptions.exportIcons ?? true;// Preserve the historical generated bytes when no override is supplied.// User-provided specifiers need string-literal encoding so quotes and// backslashes cannot produce invalid JavaScript.@@ -1408,10 +1580,18 @@ function generateBuiltModule(themeDef, iconInfo, iconsSpecifier) {? `'${iconInfo?.importPath}'`: JSON.stringify(iconsSpecifier);const iconImport = iconInfo- ? `import { ${iconInfo.exportName} } from ${renderedSpecifier};\n`+ ? `import { ${iconInfo.exportName}${iconBinding === iconInfo.exportName ? '' : ` as ${iconBinding}`} } from ${renderedSpecifier};\n`+ : '';+ const iconsExpression =+ moduleOptions.iconsExpression ?? (iconInfo ? iconBinding : undefined);+ const iconsField = iconsExpression ? ` icons: ${iconsExpression},` : '';+ const indicatorsField = moduleOptions.indicatorsExpression+ ? `\n indicators: ${moduleOptions.indicatorsExpression},`: '';- const iconsField = iconInfo ? ` icons: ${iconInfo.exportName},` : '';- const iconReExport = iconInfo ? `\nexport { ${iconInfo.exportName} };\n` : '';+ const iconReExport =+ iconInfo && exportIcons+ ? `\nexport { ${iconBinding}${iconBinding === iconInfo.exportName ? '' : ` as ${iconInfo.exportName}`} };\n`+ : '';// Resolve token values — tuples become light-dark() strings/** @type {Record<string, unknown>} */@@ -1474,14 +1654,14 @@ function generateBuiltModule(themeDef, iconInfo, iconsSpecifier) {* ${themeDef.name} theme — built by \`${getCliInvocation()} theme build\`* Import the CSS file alongside this module:*- * import { ${toIdentifier(themeDef.name)}Theme } from './${themeDef.name}';- * import './${themeDef.name}.css';+ * import { ${themeBinding} } from './${artifactBaseName}';+ * import './${artifactBaseName}.css';*/-export const ${toIdentifier(themeDef.name)}Theme = {+export const ${themeBinding} = {name: '${themeDef.name}',__built: true,tokens: ${tokensStr},-${inheritableFields}${iconsField}+${inheritableFields}${iconsField}${indicatorsField}};${iconReExport}`;}@@ -1491,14 +1671,23 @@ ${iconReExport}`;* @param {any} themeDef* @param {{exportName: string, importPath: string} | null} iconInfo* @param {string | null} variantsFileName+ * @param {{themeBinding?: string, includeIconExport?: boolean, includeThemeImport?: boolean}} [typeOptions]* @returns {string}*/-function generateBuiltTypes(themeDef, iconInfo, variantsFileName) {- const iconType = iconInfo- ? `import type { IconRegistry } from '@astryxdesign/core/Icon';+function generateBuiltTypes(+ themeDef,+ iconInfo,+ variantsFileName,+ typeOptions = {},+) {+ const themeBinding =+ typeOptions.themeBinding ?? `${toIdentifier(themeDef.name)}Theme`;+ const iconType =+ iconInfo && (typeOptions.includeIconExport ?? true)+ ? `import type { IconRegistry } from '@astryxdesign/core/Icon';export declare const ${iconInfo.exportName}: IconRegistry;`- : '';+ : '';// Pull in the generated custom-variant augmentations so that importing the// theme's types also loads the module augmentations (otherwise the// `.variants.d.ts` is emitted but never referenced, and the custom variants@@ -1507,9 +1696,11 @@ export declare const ${iconInfo.exportName}: IconRegistry;? `/// <reference path="./${variantsFileName}" />`: '';- return `${variantsRef}import type { DefinedTheme } from '@astryxdesign/core/theme';-${iconType}export declare const ${toIdentifier(themeDef.name)}Theme: DefinedTheme;-`;+ const themeImport =+ (typeOptions.includeThemeImport ?? true)+ ? `import type { DefinedTheme } from '@astryxdesign/core/theme';\n`+ : '';+ return `${variantsRef}${themeImport}${iconType}export declare const ${themeBinding}: DefinedTheme;\n`;}// =============================================================================@@ -1853,15 +2044,15 @@ function validateHeadingTypeAugmentationSupport(themeDef) {* `logger` (silent by default).** @param {string} file - Theme file path, resolved against `cwd`.- * @param {{out?: string, check?: boolean, iconsSpecifier?: string}} [options] -+ * @param {{out?: string, check?: boolean, iconsSpecifier?: string, __prepareFamily?: boolean, __familyLoader?: any, __familyInterception?: any}} [options] -* `out` overrides the output CSS path; `check` compares against on-disk outputs* instead of writing. `iconsSpecifier` overrides the icon registry import* specifier in the generated module (e.g. `./icons.mjs`); when omitted, the* specifier scraped from the theme source is emitted unchanged.* @param {{cwd?: string}} [ctx]- * @returns {Promise<import('../theme.type.mjs').ThemeBuildResponse | import('../theme.type.mjs').ThemeBuildCheckResponse | null>}+ * @returns {Promise<any>}*/-export async function themeBuild(+async function themeBuildInternal(file,options = {},{cwd = process.cwd()} = {},@@ -1878,21 +2069,26 @@ export async function themeBuild(logger.log(`\nBuilding theme from ${path.relative(cwd, filePath)}...`);- // When the installed core cannot compile adaptations, watch its- // `defineTheme` as the theme loads: that core erases `adaptations` while- // resolving, so the raw input captured here is the only remaining witness- // to what the author wrote. Costs no extra execution — the theme is loaded- // once either way — and a core that CAN compile them needs none of it.- const interception = _generateAdaptationCSS- ? undefined- : interceptCore(_coreThemeModule, _coreRootModule);+ // Standalone builds only need interception when an older Core could erase+ // adaptations. 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+ ? undefined+ : interceptCore(_coreThemeModule, _coreRootModule));// Extract theme definitionlet themeDef;/** Paths through the load that interception could not fully observe. */let loadDegradation;try {- const loaded = await extractThemeDefinition(filePath, interception);+ const loaded = await extractThemeDefinition(+ filePath,+ interception,+ options.__familyLoader,+ );themeDef = loaded.theme;loadDegradation = loaded.degraded;} catch (e) {@@ -1904,6 +2100,16 @@ export async function themeBuild(// reaches anything that reads or writes it. (Symbol keys are invisible to// JSON.stringify and Object.keys, so it could not reach output regardless.)// Both reads happen BEFORE the strip, which is what removes the evidence.+ const ancestryObserved =+ !options.__prepareFamily ||+ !interception ||+ interception.observed(themeDef) ||+ Object.hasOwn(themeDef, 'extends');+ if (options.__prepareFamily && interception) interception.retain(themeDef);+ const sourceParent =+ options.__prepareFamily && interception+ ? interception.parentOf(themeDef)+ : undefined;const adaptationLineage = interception? interception.lineageOf(themeDef): undefined;@@ -1916,6 +2122,13 @@ export async function themeBuild(const unobservedLineage =interception && hasCoverageGap ? interception.unobservedIn(themeDef) : [];if (interception) interception.strip(themeDef);+ if (!ancestryObserved) {+ throw new AstryxError(+ `Theme "${themeDef.name ?? path.basename(filePath)}" exact family ancestry could not be observed during CLI loading.`,+ undefined,+ ERROR_CODES.ERR_THEME_INVALID,+ );+ }if (!themeDef.name) {throw new AstryxError(@@ -2009,6 +2222,7 @@ export async function themeBuild(let css;let resolvedTheme;+ let cssPlan;{// jiti returns an already-resolved theme; a plain object literal (or the// legacy eval path) returns raw defineTheme input, which still has to go@@ -2152,8 +2366,9 @@ export async function themeBuild(}// Media-surface rules come last so onDark/onLight win over matching// adaptations on the same resolved leaf.+ let onMediaCss = '';if (_generateOnMediaCSS) {- const onMediaCss = _generateOnMediaCSS(resolvedTheme);+ onMediaCss = _generateOnMediaCSS(resolvedTheme);if (onMediaCss) {cssParts.push(`@layer astryx-theme {\n${onMediaCss}\n}`);}@@ -2182,6 +2397,15 @@ export async function themeBuild(`@layer astryx-base {\n${baseCss}\n}`,);}+ cssPlan = {+ base: baseCss,+ prose,+ component,+ adaptation: adaptationCss.component,+ adaptationProse: adaptationCss.prose,+ onMedia: onMediaCss,+ colorScheme: colorSchemeDecl.trimEnd(),+ };css = cssParts.join('\n\n') + '\n';}@@ -2225,7 +2449,14 @@ export async function themeBuild(const jsPath = path.join(outDir, `${baseName}.js`);const dtsPath = path.join(outDir, `${baseName}.d.ts`);- const iconInfo = extractIconInfo(filePath);+ const iconInfo = extractRegistryInfo(+ filePath,+ 'icons',+ options.__prepareFamily,+ );+ const indicatorInfo = options.__prepareFamily+ ? extractRegistryInfo(filePath, 'indicators', true)+ : null;// Type augmentation .d.ts if theme has custom prop values. Computed// before the main .d.ts so the latter can reference it (see below).@@ -2258,10 +2489,34 @@ export async function themeBuild(generatedHeader(sourceRelative, 'ts', buildCommand, versions) +generateBuiltTypes(themeDef, iconInfo, variantsFileName);- // Atomic-ish write: stage every file as `<dest>.tmp`, then rename- // each into place. If any stage step fails we clean up partials and- // exit; if a rename fails mid-way we still have the originals (or- // nothing) — never a half-built output set.+ const unloadedFonts = [+ ...new Set([+ ...collectUnloadedFonts(resolvedTheme),+ ...adaptationRuleValues(resolvedTheme).flatMap(+ (/** @type {any} */ value) => collectUnloadedFonts(value),+ ),+ ]),+ ];++ if (options.__prepareFamily) {+ return {+ filePath,+ sourceRelative: sourceRelative.split(path.sep).join('/'),+ theme: displayTheme,+ sourceTheme: themeDef,+ sourceParent,+ iconInfo,+ indicatorInfo,+ variantDecl,+ css: cssPlan,+ versions,+ tokenCount,+ componentCount,+ warnings: warningMessages,+ unloadedFonts,+ };+ }+const writes = [{dest: outPath, content: cssContent},{dest: jsPath, content: jsContent},@@ -2276,19 +2531,7 @@ export async function themeBuild(// volatile @generated `Command:` line is ignored. Returns a// receipt listing stale/missing outputs so callers (CI) can fail on drift.if (options.check) {- /** @type {Array<{path: string, reason: 'missing' | 'outdated'}>} */- const stale = [];- for (const w of writes) {- const rel = path.relative(cwd, w.dest);- if (!fs.existsSync(w.dest)) {- stale.push({path: rel, reason: 'missing'});- continue;- }- const onDisk = fs.readFileSync(w.dest, 'utf8');- if (normalizeForCompare(onDisk) !== normalizeForCompare(w.content)) {- stale.push({path: rel, reason: 'outdated'});- }- }+ const stale = staleBuildOutputs(writes, cwd);const upToDate = stale.length === 0;if (upToDate) {logger.log(`\n✓ Theme outputs are up to date with ${sourceRelative}.`);@@ -2314,30 +2557,7 @@ export async function themeBuild(};}- fs.mkdirSync(outDir, {recursive: true});- /** @type {Array<{tmp: string, dest: string}>} */- const staged = [];- try {- for (const w of writes) {- const tmp = `${w.dest}.${process.pid}.tmp`;- fs.writeFileSync(tmp, w.content);- staged.push({tmp, dest: w.dest});- }- for (const s of staged) {- fs.renameSync(s.tmp, s.dest);- }- } catch (err) {- // Roll back any temp files we managed to create.- for (const s of staged) {- try {- fs.rmSync(s.tmp, {force: true});- } catch {- /* best-effort */- }- }- const msg = `Failed to write theme outputs: ${/** @type {Error} */ (err).message}`;- throw new AstryxError(msg, undefined, ERROR_CODES.ERR_WRITE_FAILED);- }+ writeBuildOutputs(writes);logger.log(`\n✓ ${path.relative(cwd, outPath)}`);logger.log(@@ -2390,14 +2610,6 @@ Or with a <link> tag:// permanently in violation of its own "compiles with no warnings" guard).// Adaptation rules are resolved theme writes in their own right, so a family// named only inside one needs the same notice as one named at the root.- const unloadedFonts = [- ...new Set([- ...collectUnloadedFonts(resolvedTheme),- ...adaptationRuleValues(resolvedTheme).flatMap(- (/** @type {any} */ value) => collectUnloadedFonts(value),- ),- ]),- ];for (const family of unloadedFonts) {const msg = `Font "${family}" is named by this theme but not loaded — add a <link> or @font-face in your app (recipe: astryx docs typography)`;noticeMessages.push(msg);@@ -2427,3 +2639,330 @@ Or with a <link> tag:},};}++/** @param {string} file @param {{out?: string, check?: boolean, iconsSpecifier?: string}} [options] @param {{cwd?: string}} [ctx] @returns {Promise<import('../theme.type.mjs').ThemeBuildResponse | import('../theme.type.mjs').ThemeBuildCheckResponse | null>} */+export async function themeBuild(file, options = {}, ctx = {}) {+ return /** @type {any} */ (themeBuildInternal(file, options, ctx));+}+/** @param {string} name */+// prettier-ignore+function familyThemeBinding(name) {+ const words = name.split(/[^A-Za-z0-9_$]+/).filter(Boolean);+ let identifier = words.map((word, index) => index === 0 ? word : word.charAt(0).toUpperCase() + word.slice(1)).join('');+ if (!/^[A-Za-z_$]/.test(identifier)) identifier = `_${identifier}`;+ return `${identifier || '_'}Theme`;+}+/** @param {any[]} members */+// prettier-ignore+function allocateFamilyBindings(members) {+ const used = new Map();+ return new Map(members.map(member => { const base = familyThemeBinding(member.theme.name), count = used.get(base) ?? 0; used.set(base, count + 1); return [member.theme.name, count === 0 ? base : `${base}${count + 1}`]; }));+}+/** Rebase a scraped relative registry import to the aggregate module. @param {any} info @param {string} filePath @param {string} outDir @param {string | undefined} override */+// prettier-ignore+function familyRegistryInput(info, filePath, outDir, override) {+ if (!info || override !== undefined) return {info, specifier: override};+ const source = info.importPath;+ if (!source.startsWith('./') && !source.startsWith('../')) return {info, specifier: undefined};+ const absolute = path.resolve(path.dirname(filePath), source);+ let specifier = path.relative(outDir, absolute).split(path.sep).join('/');+ if (!specifier.startsWith('./') && !specifier.startsWith('../')) specifier = `./${specifier}`;+ return {info, specifier};+}+/** Dependency-first load plan including local barrels between selected files. @param {string[]} files @param {string} cwd */+// prettier-ignore+function planFamilySources(files, cwd) {+ /** @type {Array<{file: string, filePath: string}>} */ const entries = files.map(file => ({file, filePath: path.resolve(cwd, file)}));+ /** @param {string} value */ const canonical = value => fs.existsSync(value) ? fs.realpathSync(value) : path.resolve(value);+ /** @type {Map<string, {file: string, filePath: string}>} */ const selected = new Map(entries.map(entry => [canonical(entry.filePath), entry]));+ if (selected.size !== entries.length) return entries.map(entry => ({...entry, selected: true}));+ /** @type {Map<string, Set<string>>} */ const reachableMemo = new Map(), dependencies = new Map();+ /** @param {string} filePath @param {Set<string>} [visiting] @returns {Set<string>} */+ const reachableSelected = (filePath, visiting = new Set()) => {+ const key = canonical(filePath), cached = reachableMemo.get(key); if (cached) return cached;+ if (visiting.has(key) || !fs.existsSync(key)) return new Set();+ visiting.add(key); /** @type {Set<string>} */ const found = new Set(), direct = new Set(); let ast;+ try { ast = parse(fs.readFileSync(key, 'utf8'), {sourceType: 'unambiguous', plugins: ['typescript', 'jsx', 'decorators-legacy', 'importAttributes']}); }+ catch { visiting.delete(key); reachableMemo.set(key, found); return found; }+ for (const node of /** @type {any[]} */ (ast.program.body)) {+ const specifier = node.importKind !== 'type' ? node.source?.value : null; if (typeof specifier !== 'string' || (!specifier.startsWith('.') && !path.isAbsolute(specifier))) continue;+ let dependency; try { dependency = canonical(createJiti(key, {extensions: THEME_MODULE_EXTENSIONS}).resolve(specifier)); } catch { continue; }+ if (!dependency.split(path.sep).includes('node_modules') && /\.[cm]?[jt]sx?$/.test(dependency)) direct.add(dependency);+ if (selected.has(dependency)) found.add(dependency); else for (const nested of reachableSelected(dependency, visiting)) found.add(nested);+ }+ visiting.delete(key); dependencies.set(key, direct); reachableMemo.set(key, found); return found;+ };+ for (const entry of entries) reachableSelected(entry.filePath);+ /** @type {Array<{file: string, filePath: string, selected: boolean}>} */ const plan = []; /** @type {Set<string>} */ const marks = new Set();+ /** @param {string} key */ const visit = key => { if (marks.has(key)) return; marks.add(key); for (const dependency of dependencies.get(key) ?? []) if (selected.has(dependency) || reachableSelected(dependency).size > 0) visit(dependency); const entry = selected.get(key); plan.push(entry ? {...entry, selected: true} : {file: key, filePath: key, selected: false}); };+ for (const entry of entries) visit(canonical(entry.filePath)); return plan;+}++/** Preload an intermediary module into the shared family cache. @param {string} filePath @param {any} loader @param {import('./core-interception.mjs').CoreInterception} interception */+// prettier-ignore+async function preloadFamilySource(filePath, loader, interception) {+ const patch = interception.patchCommonJs(filePath);+ try { try { loader(filePath); } catch (error) { if (!isSyncLoaderLimitation(error)) throw error; await loader.evalModule(fs.readFileSync(filePath, 'utf8'), {id: filePath, filename: filePath, ext: path.extname(filePath), cache: loader.cache, async: true, forceTranspile: true}); } }+ finally { patch.undo(); }+}++/** @param {string[]} files @param {{familyKey: string, check?: boolean, iconsSpecifier?: string}} options @param {{cwd?: string}} [ctx] */+export async function themeBuildFamily(+ files,+ options,+ {cwd = process.cwd()} = {},+) {+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(options?.familyKey ?? '')) {+ throw new AstryxError(+ 'Family key must be an exact lower-kebab filename stem (for example, ocean-family).',+ undefined,+ ERROR_CODES.ERR_THEME_INVALID,+ );+ }+ try {+ sanitizeName(options.familyKey, {label: 'family key'});+ } catch (error) {+ const message =+ error instanceof Error ? error.message : 'Invalid family key.';+ throw new AstryxError(message, undefined, ERROR_CODES.ERR_THEME_INVALID);+ }+ const familyInterception = interceptCore(_coreThemeModule, _coreRootModule);+ // prettier-ignore+ const familyLoader = createJiti(import.meta.url, {moduleCache: true, interopDefault: false, jsx: true, extensions: THEME_MODULE_EXTENSIONS, virtualModules: familyInterception.modules});+ /** @type {any[]} */+ const prepared = [];+ for (const source of planFamilySources(files, cwd)) {+ if (!source.selected) {+ await preloadFamilySource(+ source.filePath,+ familyLoader,+ familyInterception,+ );+ continue;+ }+ const file = source.file;+ // prettier-ignore+ const member = await themeBuildInternal(file, {iconsSpecifier: options.iconsSpecifier, __prepareFamily: true, __familyLoader: familyLoader, __familyInterception: familyInterception}, {cwd});+ if (!member || member.type) {+ throw new AstryxError(+ `Theme family member "${file}" did not produce a complete build plan.`,+ undefined,+ ERROR_CODES.ERR_THEME_INVALID,+ );+ }+ prepared.push(member);+ }+ let members;+ try {+ members = resolveThemeFamily(prepared);+ } catch (error) {+ const message =+ error instanceof Error ? error.message : 'Invalid selected theme family.';+ throw new AstryxError(message, undefined, ERROR_CODES.ERR_THEME_INVALID);+ }+ for (const member of members) {+ for (const [field, info] of [+ ['icons', member.iconInfo],+ ['indicators', member.indicatorInfo],+ ]) {+ const value = member.theme[field];+ const inherited = member.sourceParent?.[field];+ if (+ value &&+ Object.keys(value).length > 0 &&+ value !== inherited &&+ !info+ ) {+ throw new AstryxError(+ `Theme "${member.theme.name}" must supply ${field} through a named import for family output.`,+ undefined,+ ERROR_CODES.ERR_THEME_INVALID,+ );+ }+ }+ }+ const baseName = options.familyKey;+ if (members.some(member => member.theme.name === baseName)) {+ throw new AstryxError(+ `Family key "${baseName}" collides with a selected theme's standalone outputs. Choose a distinct filename stem.`,+ undefined,+ ERROR_CODES.ERR_THEME_INVALID,+ );+ }+ const root = members[0];+ const outDir = path.dirname(root.filePath);+ const outPath = path.join(outDir, `${baseName}.css`);+ const jsPath = path.join(outDir, `${baseName}.js`);+ const dtsPath = path.join(outDir, `${baseName}.d.ts`);+ const sources = new Set(+ members.flatMap(member =>+ [path.resolve(member.filePath), fs.realpathSync(member.filePath)].map(+ value => value.toLowerCase(),+ ),+ ),+ );+ const collision = [outPath, jsPath, dtsPath].find(output => {+ const candidates = [path.resolve(output)];+ if (fs.existsSync(output)) candidates.push(fs.realpathSync(output));+ return candidates.some(value => sources.has(value.toLowerCase()));+ });+ if (collision) {+ throw new AstryxError(+ `Family output ${path.relative(cwd, collision)} collides with a selected source file.`,+ undefined,+ ERROR_CODES.ERR_THEME_INVALID,+ );+ }+ const sourceRelative = members+ .map(member => member.sourceRelative)+ .join(', ');+ const buildCommand = `${getCliInvocation()} theme build --family ${members+ .map(member => member.sourceRelative)+ .join(' ')} --family-key ${baseName}`;+ const bindings = allocateFamilyBindings(members);+ const css = generateFamilyCSS(members);+ /** @type {Array<{specifier: string, exportName: string}>} */+ const registryImports = [];+ const js = members+ .map(member => {+ const themeBinding = bindings.get(member.theme.name);+ const parentBinding = member.parentName+ ? bindings.get(member.parentName)+ : null;+ // prettier-ignore+ const icon = familyRegistryInput(member.iconInfo, member.filePath, outDir, options.iconsSpecifier);+ // prettier-ignore+ const indicator = familyRegistryInput(member.indicatorInfo, member.filePath, outDir, undefined);+ // prettier-ignore+ for (const registry of [icon, indicator]) if (registry.info) registryImports.push({specifier: registry.specifier ?? registry.info.importPath, exportName: registry.info.exportName});+ const ownIcons = icon.info ? `${themeBinding}Icons` : null;+ const inheritedIcons = parentBinding ? `${parentBinding}.icons` : null;+ const ownIndicators = indicator.info ? `${themeBinding}Indicators` : null;+ const inheritedIndicators = parentBinding+ ? `${parentBinding}.indicators`+ : null;+ /** @param {string | null} own @param {string | null} inherited */+ const expression = (own, inherited) =>+ own && inherited+ ? `{...${inherited}, ...${own}}`+ : (own ?? inherited ?? undefined);+ const indicatorImport = indicator.info+ ? `import { ${indicator.info.exportName} as ${ownIndicators} } from ${JSON.stringify(indicator.specifier ?? indicator.info.importPath)};\n`+ : '';+ return (+ indicatorImport ++ generateBuiltModule(member.theme, icon.info, icon.specifier, {+ themeBinding,+ iconBinding: ownIcons ?? undefined,+ iconsExpression: expression(ownIcons, inheritedIcons),+ indicatorsExpression: expression(ownIndicators, inheritedIndicators),+ artifactBaseName: baseName,+ exportIcons: false,+ })+ );+ })+ .join('\n');+ await validateRegistryGraphs(registryImports, jsPath);+ const declarations = members+ .map((member, index) =>+ generateBuiltTypes(member.theme, member.iconInfo, null, {+ themeBinding: bindings.get(member.theme.name),+ includeIconExport: false,+ includeThemeImport: index === 0,+ }),+ )+ .join('');+ const augmentations = [+ ...new Set(members.map(member => member.variantDecl).filter(Boolean)),+ ].join('\n');+ const writes = [+ {+ dest: outPath,+ content:+ generatedHeader(sourceRelative, 'css', buildCommand, root.versions) ++ css,+ },+ {+ dest: jsPath,+ content:+ generatedHeader(sourceRelative, 'js', buildCommand, root.versions) + js,+ },+ {+ dest: dtsPath,+ content:+ generatedHeader(sourceRelative, 'ts', buildCommand, root.versions) ++ declarations ++ (augmentations ? `\n${augmentations}` : ''),+ },+ ];+ const outputs = {+ css: path.relative(cwd, outPath),+ js: path.relative(cwd, jsPath),+ dts: path.relative(cwd, dtsPath),+ };+ if (options.check) {+ const stale = staleBuildOutputs(writes, cwd);+ const upToDate = stale.length === 0;+ if (upToDate) {+ logger.log(+ `\n✓ Theme family outputs are up to date with ${sourceRelative}.`,+ );+ } else {+ logger.error(+ `\n✗ ${stale.length} theme family output(s) are out of date:`,+ );+ for (const entry of stale) {+ logger.error(+ ` ${entry.reason === 'missing' ? 'missing' : 'stale'}: ${entry.path}`,+ );+ }+ logger.error(`\n Rebuild with: ${buildCommand}`);+ }+ return {+ type: 'theme.build.check',+ data: {+ name: root.theme.name,+ upToDate,+ stale,+ checked: writes.map(write => path.relative(cwd, write.dest)),+ },+ };+ }+ writeBuildOutputs(writes);+ for (const output of Object.values(outputs)) logger.log(`✓ ${output}`);+ const themeBindings = members.map(member => bindings.get(member.theme.name));+ const relOutDir = path.relative(cwd, outDir) || '.';+ const jsImport = importSpecifier(relOutDir, baseName);+ const cssImport = `${jsImport}.css`;+ logger.log(`+Load the family CSS once, then select any member by theme identity:+ import { ${themeBindings.join(', ')} } from '${jsImport}';+ import '${cssImport}';+Or load the same stylesheet natively:+ <link rel="stylesheet" href="${cssImport}" />+`);+ const warnings = [...new Set(members.flatMap(member => member.warnings))];+ const unloadedFonts = [+ ...new Set(members.flatMap(member => member.unloadedFonts)),+ ];+ const notices = unloadedFonts.map(+ family =>+ `Font "${family}" is named by this theme family but not loaded — add a <link> or @font-face in your app (recipe: astryx docs typography)`,+ );+ for (const notice of notices) logger.log(` note: ${notice}`);+ return {+ type: 'theme.build',+ data: {+ name: root.theme.name,+ tokenCount: members.reduce((sum, member) => sum + member.tokenCount, 0),+ componentCount: members.reduce(+ (sum, member) => sum + member.componentCount,+ 0,+ ),+ sizeKB: parseFloat((Buffer.byteLength(css) / 1024).toFixed(1)),+ outputs,+ warnings,+ notices,+ },+ };+}diff --git a/packages/cli/api/theme/build/build.packed-old-core.test.mjs b/packages/cli/api/theme/build/build.packed-old-core.test.mjsindex eab1dcee07..c2b52d3fcc 100644--- a/packages/cli/api/theme/build/build.packed-old-core.test.mjs+++ b/packages/cli/api/theme/build/build.packed-old-core.test.mjs@@ -47,7 +47,13 @@ const CORE_THEME_ENTRY = path.join(CORE_DIST, 'theme/index.js');/** The CLI's published file set (packages/cli package.json `files`). */const PACKED_DIRS = ['clients', 'api', 'assets', 'authoring', 'foundation'];/** Runtime dependencies the packed CLI resolves from its install root. */-const RUNTIME_DEPS = ['commander', 'jiti', 'jscodeshift', 'zod'];+const RUNTIME_DEPS = [+ '@babel/parser',+ 'commander',+ 'jiti',+ 'jscodeshift',+ 'zod',+];const OLD_CORE_VERSION = '0.5.4';const CURRENT_CORE_VERSION = '0.6.0';@@ -262,7 +268,7 @@ ${options.tla ? `const surface = await Promise.resolve('#eee');\n` : ''}export c}/**- * @param {string} themeFile+ * @param {string | string[]} themeFile* @param {string[]} [extraArgs]* @returns {{status: number, envelope: any}}*/@@ -272,11 +278,8 @@ function buildTheme(themeFile, extraArgs = []) {'node_modules/@astryxdesign/cli/clients/cli/bin/astryx.mjs',);try {- const stdout = execFileSync(- process.execPath,- [bin, 'theme', 'build', themeFile, ...extraArgs, '--json'],- {cwd: consumer, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe']},- );+ // prettier-ignore+ const stdout = execFileSync(process.execPath, [bin, 'theme', 'build', ...(Array.isArray(themeFile) ? themeFile : [themeFile]), ...extraArgs, '--json'], {cwd: consumer, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe']});return {status: 0, envelope: JSON.parse(stdout)};} catch (error) {const e = /** @type {any} */ (error);@@ -432,7 +435,9 @@ beforeAll(() => {for (const dep of RUNTIME_DEPS) {const installed = findInstalledPackage(CLI_PKG, dep);if (!installed) throw new Error(`${dep} is not installed under ${CLI_PKG}`);- fs.symlinkSync(fs.realpathSync(installed), path.join(modules, dep));+ const target = path.join(modules, dep);+ fs.mkdirSync(path.dirname(target), {recursive: true});+ fs.symlinkSync(fs.realpathSync(installed), target);}// The installed core. Real built implementations behind a swappable@@ -1088,6 +1093,12 @@ afterAll(() => {describe('packed CLI against a core that predates adaptations', () => {beforeAll(() => useCore('old'));+ it('rejects a family before an old core can erase adaptations', () => {+ // prettier-ignore+ const result = buildTheme(['adaptive-base.ts', 'extending.ts'], ['--family', '--family-key', 'adaptive-family']);+ expect(result.envelope.code).toBe('ERR_CORE_INCOMPATIBLE');+ });+it('builds a non-adaptation theme', () => {const {status, envelope} = buildTheme('plain.ts');diff --git a/packages/cli/api/theme/build/core-interception.mjs b/packages/cli/api/theme/build/core-interception.mjsindex 29513ee416..2649e4d27f 100644--- a/packages/cli/api/theme/build/core-interception.mjs+++ b/packages/cli/api/theme/build/core-interception.mjs@@ -79,6 +79,8 @@ import {findInstalledPackage} from '../../../foundation/fs/paths.mjs';*/export const THEME_LINEAGE = Symbol.for('astryx.theme.lineage');+/** Complete private capture retained for cached exports and repeated checks. */+const retainedLineageByReference = new WeakMap();/*** @typedef {object} ThemeLineage* @property {any} input - The raw `defineTheme()` argument.@@ -90,6 +92,9 @@ export const THEME_LINEAGE = Symbol.for('astryx.theme.lineage');** @typedef {object} CoreInterception* @property {Record<string, unknown>} modules - `virtualModules` for jiti.+ * @property {(theme: any) => boolean} observed - Whether authored input was captured.+ * @property {(theme: any) => void} retain - Retain capture before stripping.+ * @property {(theme: any) => any} parentOf - Exact authored `extends` value.* @property {(theme: any) => any[]} lineageOf - Every raw input that fed a* theme, following its own `extends` chain and spread provenance.* @property {(theme: any) => any[]} unobservedIn - Lineage members this@@ -105,17 +110,16 @@ export const THEME_LINEAGE = Symbol.for('astryx.theme.lineage');*//**- * Was this theme produced by a `defineTheme()` call the recorder saw?- * Must be asked BEFORE `strip` — that is what removes the evidence.+ * Was this theme produced by a `defineTheme()` call the recorder saw? The+ * temporary symbol must be read before `strip`; retained WeakMap capture remains+ * available for cached retries.** @param {any} value* @param {WeakMap<object, ThemeLineage>} byReference* @returns {boolean}*/-function wasObserved(value, byReference) {- if (!value || typeof value !== 'object') return false;- return byReference.has(value) || value[THEME_LINEAGE] !== undefined;-}+// prettier-ignore+function wasObserved(value, byReference) { return Boolean(value && typeof value === 'object' && (byReference.has(value) || retainedLineageByReference.has(value) || value[THEME_LINEAGE] !== undefined)); }const GENERATIVE_AXIS_KEYS = ['typography', 'color', 'radius', 'motion'];@@ -228,8 +232,8 @@ function mergeGenerativeAxes(inherited, own) {* silently delete every one of those exports from a theme file that imports a* component. Every real export is preserved on each; one function is wrapped.*- * A core that already compiles adaptations should never be wrapped — it- * reports its own — but wrapping is harmless if it is.+ * Current-Core family builds also use this private recorder for exact parents;+ * standalone builds with current Core do not.** @param {any} coreThemeModule - The installed `@astryxdesign/core/theme` namespace.* @param {any} [coreRootModule] - The installed `@astryxdesign/core` namespace.@@ -243,6 +247,7 @@ export function interceptCore(coreThemeModule, coreRootModule) {const mark = (value, lineage) => {if (!value || typeof value !== 'object') return;byReference.set(value, lineage);+ retainedLineageByReference.set(value, lineage);try {// Enumerable so a spread of this theme carries it; configurable so it// can be removed again before the theme is used for output.@@ -258,10 +263,8 @@ export function interceptCore(coreThemeModule, coreRootModule) {};/** @param {any} value @returns {ThemeLineage | undefined} */- const lineageFor = value => {- if (!value || typeof value !== 'object') return undefined;- return byReference.get(value) ?? value[THEME_LINEAGE];- };+ // prettier-ignore+ const lineageFor = value => value && typeof value === 'object' ? byReference.get(value) ?? retainedLineageByReference.get(value) ?? value[THEME_LINEAGE] : undefined;/*** One namespace, spread so exports this file does not know about still@@ -293,6 +296,12 @@ export function interceptCore(coreThemeModule, coreRootModule) {'@astryxdesign/core': wrapNamespace(coreRootModule ?? coreThemeModule),},+ // prettier-ignore+ observed(theme) { return wasObserved(theme, byReference); },+ // prettier-ignore+ retain(theme) { const lineage = lineageFor(theme); if (lineage && theme && typeof theme === 'object') retainedLineageByReference.set(theme, lineage); },+ // prettier-ignore+ parentOf(theme) { const input = lineageFor(theme)?.input; return input && typeof input === 'object' && 'extends' in input ? input.extends : theme && typeof theme === 'object' ? theme.extends : undefined; },lineageOf(theme) {/** @type {any[]} */const inputs = [];@@ -327,8 +336,8 @@ export function interceptCore(coreThemeModule, coreRootModule) {unobservedIn(theme) {// Lineage members this recorder never saw AND that carry no adaptation// metadata of their own. On a degraded load these are exactly the- // themes whose adaptations, if any, were erased unobserved. Must be- // called before `strip`.+ // themes whose adaptations, if any, were erased unobserved. Retained+ // WeakMap capture keeps this answer stable after a cached retry.//// A RAW INPUT reached through an observed result is itself evidence —// it is the very object the recorder captured, and only the result@@ -404,6 +413,7 @@ export function interceptCore(coreThemeModule, coreRootModule) {if (!value || typeof value !== 'object' || seen.has(value)) continue;seen.add(value);const lineage = lineageFor(value);+ if (lineage) retainedLineageByReference.set(value, lineage);if (Object.hasOwn(value, THEME_LINEAGE)) {try {delete value[THEME_LINEAGE];diff --git a/packages/cli/api/theme/build/family.mjs b/packages/cli/api/theme/build/family.mjsnew file mode 100644index 0000000000..dadf0f1c6e--- /dev/null+++ b/packages/cli/api/theme/build/family.mjs@@ -0,0 +1,442 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+/**+ * @file Thin family packaging over existing compiler output.+ */+const THEME_SCOPE_TO = '[data-astryx-theme]';+/** @param {string} a @param {string} b */+const compareText = (a, b) => (a < b ? -1 : a > b ? 1 : 0);+/**+ * @param {Array<{theme: any, sourceTheme: any, sourceParent: any, filePath: string}>} members+ * @returns {any[]}+ */+export function resolveThemeFamily(members) {+ if (members.length < 2)+ throw new Error(+ 'A theme family requires at least two selected theme files.',+ );+ const byName = new Map();+ const sources = new Set();+ for (const member of members) {+ if (sources.has(member.filePath)) {+ throw new Error(+ `Duplicate family source: ${member.filePath}. Select each theme file once.`,+ );+ }+ if (byName.has(member.theme.name)) {+ throw new Error(+ `Duplicate theme identity "${member.theme.name}" in the selected family.`,+ );+ }+ sources.add(member.filePath);+ byName.set(member.theme.name, member);+ }+ const withParents = members.map(member => {+ const parent = member.sourceParent;+ if (+ parent !== undefined &&+ (!parent ||+ typeof parent !== 'object' ||+ typeof parent.name !== 'string' ||+ parent.name.length === 0)+ ) {+ throw new Error(+ `Theme "${member.theme.name}" has an invalid normalized parent.`,+ );+ }+ const parentName = parent?.name ?? null;+ if (parentName && !byName.has(parentName)) {+ throw new Error(+ `Theme "${member.theme.name}" is missing selected ancestor "${parentName}".`,+ );+ }+ if (parentName && parent !== byName.get(parentName).sourceTheme) {+ throw new Error(+ `Theme "${member.theme.name}" does not extend the selected "${parentName}" source.`,+ );+ }+ return {...member, parentName};+ });+ const resolved = new Map(+ withParents.map(member => [member.theme.name, member]),+ );+ const marks = new Map();+ /** @param {any} member */+ const visit = member => {+ const mark = marks.get(member.theme.name) ?? 0;+ if (mark === 1)+ throw new Error(+ `Cycle detected in selected theme family at "${member.theme.name}".`,+ );+ if (mark === 2) return;+ marks.set(member.theme.name, 1);+ if (member.parentName) visit(resolved.get(member.parentName));+ marks.set(member.theme.name, 2);+ };+ for (const member of withParents) visit(member);+ const roots = withParents.filter(member => member.parentName === null);+ if (roots.length !== 1) {+ throw new Error(+ `A theme family must have exactly one selected root; found ${roots.length}.`,+ );+ }+ const emitted = new Set();+ /** @type {any[]} */+ const ordered = [];+ while (ordered.length < withParents.length) {+ const eligible = withParents+ .filter(+ member =>+ !emitted.has(member.theme.name) &&+ (!member.parentName || emitted.has(member.parentName)),+ )+ .sort((a, b) =>+ compareText(+ `${a.theme.name}\0${a.filePath}`,+ `${b.theme.name}\0${b.filePath}`,+ ),+ );+ if (eligible.length === 0)+ throw new Error('Cycle detected in selected theme family.');+ emitted.add(eligible[0].theme.name);+ ordered.push(eligible[0]);+ }+ return ordered;+}+/** @param {string} name */+const themeSelector = name => `[data-astryx-theme=${JSON.stringify(name)}]`;+/** @param {string[]} names */+const familyScopeSelector = names =>+ `:where(${names.map(themeSelector).join(', ')})`;+/** @param {string} rule @returns {{open: number, close: number}} */+function ruleBounds(rule) {+ let open = -1;+ let depth = 0;+ let paren = 0;+ let urlDepth = 0;+ let quote = '';+ let escaped = false;+ let comment = false;+ for (let index = 0; index < rule.length; index++) {+ const char = rule[index];+ if (comment) {+ if (char === '*' && rule[index + 1] === '/') {+ comment = false;+ index++;+ }+ } else if (escaped) {+ escaped = false;+ } else if (char === '\\') {+ escaped = true;+ } else if (quote) {+ if (char === quote) quote = '';+ } else if (char === '"' || char === "'") {+ quote = char;+ } else if (urlDepth === 0 && char === '/' && rule[index + 1] === '*') {+ comment = true;+ index++;+ } else if (char === '(') {+ paren++;+ if (rule.slice(Math.max(0, index - 3), index).toLowerCase() === 'url') {+ urlDepth = paren;+ }+ } else if (char === ')' && paren > 0) {+ if (urlDepth === paren) urlDepth = 0;+ paren--;+ } else if (char === '{' && paren === 0) {+ if (open === -1) open = index;+ depth++;+ } else if (char === '}' && paren === 0 && open !== -1 && --depth === 0) {+ return {open, close: index};+ }+ }+ throw new Error('Theme compiler emitted a malformed rule.');+}+/** @param {string} rule */+function declarationEntries(rule) {+ const {open, close} = ruleBounds(rule);+ const selector = rule.slice(0, open).trim();+ const body = rule.slice(open + 1, close);+ /** @type {string[]} */+ const declarations = [];+ let start = 0;+ let quote = '';+ let escaped = false;+ let comment = false;+ let paren = 0;+ let urlDepth = 0;+ let braces = 0;+ let brackets = 0;+ for (let index = 0; index < body.length; index++) {+ const char = body[index];+ if (comment) {+ if (char === '*' && body[index + 1] === '/') {+ comment = false;+ index++;+ }+ } else if (escaped) {+ escaped = false;+ } else if (char === '\\') {+ escaped = true;+ } else if (quote) {+ if (char === quote) quote = '';+ } else if (char === '"' || char === "'") {+ quote = char;+ } else if (urlDepth === 0 && char === '/' && body[index + 1] === '*') {+ comment = true;+ index++;+ } else if (char === '(') {+ paren++;+ if (body.slice(Math.max(0, index - 3), index).toLowerCase() === 'url') {+ urlDepth = paren;+ }+ } else if (char === ')' && paren > 0) {+ if (urlDepth === paren) urlDepth = 0;+ paren--;+ } else if (char === '[' && urlDepth === 0) {+ brackets++;+ } else if (char === ']' && urlDepth === 0 && brackets > 0) {+ brackets--;+ } else if (char === '{' && paren === 0) {+ braces++;+ } else if (char === '}' && paren === 0 && braces > 0) {+ braces--;+ } else if (char === ';' && paren === 0 && braces === 0 && brackets === 0) {+ const declaration = body.slice(start, index + 1).trim();+ if (declaration) declarations.push(declaration);+ start = index + 1;+ }+ }+ if (body.slice(start).trim())+ throw new Error('Theme compiler emitted an unterminated declaration.');+ const counts = new Map();+ return declarations+ .map(declaration => {+ const property = declaration.slice(0, declaration.indexOf(':')).trim();+ const occurrence = counts.get(property) ?? 0;+ counts.set(property, occurrence + 1);+ return {key: `${property}\0${occurrence}`, declaration};+ })+ .map(entry => ({...entry, selector}));+}+/** @param {string[]} rules */+function ruleEntries(rules) {+ const counts = new Map();+ return rules.map(rule => {+ const {open} = ruleBounds(rule);+ const selector = rule.slice(0, open).trim();+ const occurrence = counts.get(selector) ?? 0;+ counts.set(selector, occurrence + 1);+ return {key: `${selector}\0${occurrence}`, rule, selector};+ });+}+/** @param {Array<Array<{key: string}>>} sequences @param {string} _description @returns {string[] | null} */+function orderedKeys(sequences, _description) {+ const rank = new Map();+ const edges = new Map();+ const indegree = new Map();+ let nextRank = 0;+ for (const sequence of sequences) {+ for (const entry of sequence) {+ if (!rank.has(entry.key)) rank.set(entry.key, nextRank++);+ edges.set(entry.key, edges.get(entry.key) ?? new Set());+ indegree.set(entry.key, indegree.get(entry.key) ?? 0);+ }+ for (let index = 1; index < sequence.length; index++) {+ const before = sequence[index - 1].key;+ const after = sequence[index].key;+ if (!edges.get(before).has(after)) {+ edges.get(before).add(after);+ indegree.set(after, indegree.get(after) + 1);+ }+ }+ }+ const ready = [...rank.keys()].filter(key => indegree.get(key) === 0);+ /** @type {string[]} */+ const ordered = [];+ while (ready.length > 0) {+ ready.sort((a, b) => rank.get(a) - rank.get(b) || compareText(a, b));+ const key = ready.shift();+ ordered.push(key);+ for (const after of edges.get(key)) {+ indegree.set(after, indegree.get(after) - 1);+ if (indegree.get(after) === 0) ready.push(after);+ }+ }+ if (ordered.length !== rank.size) return null;+ return ordered;+}+/** @param {Array<{names: string[], selector: string, declaration: string}>} items */+function renderDeclarations(items) {+ /** @type {Array<{scope: string, names: string[], selector: string, declarations: string[]}>} */+ const blocks = [];+ /** @type {{scope: string, names: string[], selector: string, declarations: string[]} | undefined} */+ let current;+ for (const item of items) {+ const scope = `${item.names.join('\0')}\0${item.selector}`;+ if (!current || current.scope !== scope) {+ current = {+ scope,+ names: item.names,+ selector: item.selector,+ declarations: [],+ };+ blocks.push(current);+ }+ current.declarations.push(item.declaration);+ }+ return blocks.map(block => {+ const declarations = block.declarations+ .map(value => ` ${value}`)+ .join('\n');+ return `@scope (${familyScopeSelector(block.names)}) to (${THEME_SCOPE_TO}) {\n ${block.selector} {\n${declarations}\n }\n}`;+ });+}+/** @param {any[]} members @param {string} field */+function completeMemberRules(members, field) {+ return members+ .filter(member => member.css[field].length > 0)+ .map(+ member =>+ `@scope (${familyScopeSelector([member.theme.name])}) to (${THEME_SCOPE_TO}) {\n${member.css[field].join('\n\n')}\n}`,+ );+}+/** @param {any[]} members @param {string} field */+function factorRules(members, field) {+ const ruleSequences = members.map(member => ruleEntries(member.css[field]));+ const ruleMaps = ruleSequences.map(+ sequence => new Map(sequence.map(entry => [entry.key, entry])),+ );+ /** @type {Array<{names: string[], selector: string, declaration: string}>} */+ const items = [];+ const ruleOrder = orderedKeys(ruleSequences, 'rule');+ if (!ruleOrder) return completeMemberRules(members, field);+ for (const ruleKey of ruleOrder) {+ const declarations = ruleMaps.map(map => {+ const rule = map.get(ruleKey);+ return rule ? declarationEntries(rule.rule) : [];+ });+ const declarationMaps = declarations.map(+ sequence => new Map(sequence.map(entry => [entry.key, entry])),+ );+ const declarationOrder = orderedKeys(declarations, 'declaration');+ if (!declarationOrder) return completeMemberRules(members, field);+ for (const declarationKey of declarationOrder) {+ /** @type {Map<string, {selector: string, declaration: string, names: string[]}>} */+ const groups = new Map();+ for (let index = 0; index < members.length; index++) {+ const entry = declarationMaps[index].get(declarationKey);+ if (!entry) continue;+ const group = groups.get(entry.declaration) ?? {+ selector: entry.selector,+ declaration: entry.declaration,+ names: [],+ };+ group.names.push(members[index].theme.name);+ groups.set(entry.declaration, group);+ }+ items.push(...groups.values());+ }+ }+ return renderDeclarations(items);+}+/** Replace only a generated @scope prelude, never authored CSS payloads. @param {string} css @param {string} search @param {string} replacement */+// prettier-ignore+function replaceScopeSyntax(css, search, replacement) {+ let output = '', quote = '', escaped = false, comment = false, lastCode = '';+ for (let index = 0; index < css.length; index++) {+ const char = css[index];+ if (comment) {+ output += char;+ if (char === '*' && css[index + 1] === '/') { output += '/'; comment = false; index++; }+ continue;+ }+ if (quote) {+ output += char;+ if (escaped) escaped = false;+ else if (char === '\\') escaped = true;+ else if (char === quote) quote = '';+ continue;+ }+ if (char === '/' && css[index + 1] === '*') { output += '/*'; comment = true; index++; continue; }+ if (char === '"' || char === "'") { output += char; quote = char; continue; }+ if ((lastCode === '' || lastCode === '{' || lastCode === '}') && css.startsWith(search, index)) {+ output += replacement; lastCode = ')'; index += search.length - 1; continue;+ }+ output += char;+ if (!/\s/.test(char)) lastCode = char;+ }+ return output;+}+/** @param {string} css @param {string} name */+const normalizeScope = (css, name) =>+ replaceScopeSyntax(+ css,+ `@scope (${themeSelector(name)})`,+ '@scope (__ASTRYX_FAMILY_SCOPE__)',+ );+/** @param {string} css @param {string[]} names */+const applyScope = (css, names) =>+ replaceScopeSyntax(+ css,+ '@scope (__ASTRYX_FAMILY_SCOPE__)',+ `@scope (${familyScopeSelector(names)})`,+ );+/** @param {any[]} members @param {string} field */+function factorSections(members, field) {+ /** @type {Map<string, {css: string, names: string[]}>} */+ const groups = new Map();+ for (const member of members) {+ const css = normalizeScope(member.css[field] ?? '', member.theme.name);+ if (!css) continue;+ const group = groups.get(css) ?? {css, names: []};+ group.names.push(member.theme.name);+ groups.set(css, group);+ }+ return [...groups.values()].map(group => applyScope(group.css, group.names));+}+/** Keep document rules top-level-active; initialize nested tuple members locally. @param {any[]} members */+// prettier-ignore+function colorSchemeSections(members) {+ const groups = new Map();+ for (const member of members) {+ const css = member.css.colorScheme;+ if (!css) continue;+ const names = groups.get(css) ?? []; names.push(member.theme.name); groups.set(css, names);+ }+ return [...groups].reduce((result, [css, names]) => {+ const identities = familyScopeSelector(names), top = `${identities}:not(:where([data-astryx-theme] [data-astryx-theme]))`;+ const active = (/** @type {string} */ selector) => `${selector}${identities},\n${selector}:where(:not([data-astryx-theme])):has(${top})`;+ result.base.push(`@scope (${identities}) to (${THEME_SCOPE_TO}) {\n :where(:scope:not([data-theme]):not(html[data-theme] *)) { color-scheme: light dark; }\n :where(:scope:not([data-theme]):is(html[data-theme="light"] *)) { color-scheme: light; }\n :where(:scope:not([data-theme]):is(html[data-theme="dark"] *)) { color-scheme: dark; }\n}`);+ result.themed.push(css.replace(':root', active(':root')).replace('html[data-theme="light"]', active('html[data-theme="light"]')).replace('html[data-theme="dark"]', active('html[data-theme="dark"]')));+ return result;+ }, /** @type {{base: string[], themed: string[]}} */ ({base: [], themed: []}));+}+/** @param {any[]} members */+export function generateFamilyCSS(members) {+ const root = members[0];+ for (const member of members) {+ if (member.css.base !== root.css.base)+ throw new Error(+ 'Theme-independent base CSS changed between family members.',+ );+ }+ const prose = [+ ...factorRules(members, 'prose'),+ ...factorSections(members, 'adaptationProse'),+ ];+ const schemes = colorSchemeSections(members);+ const themed = [+ ...schemes.themed,+ ...factorRules(members, 'component'),+ ...factorSections(members, 'adaptation'),+ ...factorSections(members, 'onMedia'),+ ].filter(Boolean);+ const parts = [];+ if (prose.length > 0) parts.push(`@layer reset {\n${prose.join('\n\n')}\n}`);+ const base = [root.css.base, ...schemes.base].filter(Boolean);+ if (base.length > 0)+ parts.push(`@layer astryx-base {\n${base.join('\n\n')}\n}`);+ if (themed.length > 0)+ parts.push(`@layer astryx-theme {\n${themed.join('\n\n')}\n}`);+ return `${parts.join('\n\n')}\n`;+}diff --git a/packages/cli/assets/docs/theme.doc.dense.mjs b/packages/cli/assets/docs/theme.doc.dense.mjsindex 4c4942bd76..89cd78ce9c 100644--- a/packages/cli/assets/docs/theme.doc.dense.mjs+++ b/packages/cli/assets/docs/theme.doc.dense.mjs@@ -128,6 +128,18 @@ export const docsDense = {null,],},+ {+ section: 'Building a Theme Family',+ title: 'Family Build',+ content: [+ {+ type: 'prose',+ text: 'theme build --family <base> <descendants...> --family-key <key> emits one keyed .css + .js + .d.ts beside the root; key must differ from every member name. load CSS once; import ESM separately; switch by theme identity only. all members download eagerly. --check compares the trio. use standalone build for one theme.',+ },+ null,+ null,+ ],+ },{section: 'Runtime vs Built Themes',title: 'Runtime vs Built',diff --git a/packages/cli/assets/docs/theme.doc.mjs b/packages/cli/assets/docs/theme.doc.mjsindex fcc00bc6f4..c6bc8fc403 100644--- a/packages/cli/assets/docs/theme.doc.mjs+++ b/packages/cli/assets/docs/theme.doc.mjs@@ -576,6 +576,43 @@ import './themes/ocean.css';},],},+ {+ title: 'Building a Theme Family',+ category: 'guide',+ content: [+ {+ type: 'prose',+ text: 'Use family mode when an app switches among one base theme and its selected descendants. The build writes one keyed CSS file containing every member, plus one keyed JavaScript module and one declaration file beside the root source.',+ },+ {+ type: 'code',+ lang: 'bash',+ label: 'Build one family',+ code: `astryx theme build --family \\+ ./src/themes/ocean.mjs \\+ ./src/themes/ocean-calm.mjs \\+ ./src/themes/ocean-calm-deep.mjs \\+ --family-key ocean-family`,+ },+ {+ type: 'code',+ lang: 'html',+ label: 'Load native CSS and ESM independently',+ code: `<link rel="stylesheet" href="./src/themes/ocean-family.css" />+<script type="module">+ import {oceanCalmTheme} from './src/themes/ocean-family.js';+</script>`,+ },+ {+ type: 'prose',+ text: 'The family stylesheet eagerly downloads every selected member so first paint is complete. Switching members changes only the theme identity; it does not add, remove, or reorder stylesheets. A bundler such as Vite consumes the same CSS and ESM files.',+ },+ {+ type: 'prose',+ text: 'The family key is only the filename stem (`ocean-family.css`, `.js`, and `.d.ts`) and must differ from every selected member name. Use the ordinary standalone build when an app needs only one complete theme. Add `--check` to compare the exact keyed trio without writing.',+ },+ ],+ },{title: 'Runtime vs Built Themes',category: 'guide',diff --git a/packages/cli/clients/cli/commands/build-theme.mjs b/packages/cli/clients/cli/commands/build-theme.mjsindex a909add0e0..3e31e8e41b 100644--- a/packages/cli/clients/cli/commands/build-theme.mjs+++ b/packages/cli/clients/cli/commands/build-theme.mjs@@ -18,11 +18,13 @@* astryx theme build ./src/themes/ocean.ts* astryx theme build ./src/themes/ocean.ts --out ./dist/ocean.css* astryx theme build ./src/themes/*.ts+ * astryx theme build --family ./src/themes/ocean.ts ./src/themes/ocean-calm.ts --family-key ocean-family*- * `build` takes one or more theme files. Each is compiled by the same+ * Ordinary builds take one or more theme files. Each is compiled by the same* single-file API call, in argument order, in one process — so the outputs are* byte-identical to running the CLI once per theme, and the first failure stops- * the run exactly as a shell loop under `set -e` would.+ * the run exactly as a shell loop under `set -e` would. Family mode delegates+ * the selected files once to the API's in-memory family orchestration.*/import * as fs from 'node:fs';@@ -45,7 +47,11 @@ import {serializePaletteCandidate,themePaletteGenerate,} from '../../../api/theme/palette/generate/generate.mjs';-import {themeBuild, importSpecifier} from '../../../api/theme/build/build.mjs';+import {+ themeBuild,+ themeBuildFamily,+ importSpecifier,+} from '../../../api/theme/build/build.mjs';import {defineCommand} from '../lib/define-command.mjs';import {NO_RESULT_SET, resultSet} from '../../../foundation/debug/index.mjs';import {doc as themeGroup} from './theme.doc.mjs';@@ -400,7 +406,7 @@ export function registerTheme(program) {fn: themeBuildFn,action: async (/** @type {string[]} */ files,- /** @type {{out?: string, watch?: boolean, check?: boolean, iconsSpecifier?: string}} */ options,+ /** @type {{out?: string, watch?: boolean, check?: boolean, iconsSpecifier?: string, family?: boolean, familyKey?: string}} */ options,) => {const json = program.opts().json || false;const entries = files.map(file => ({@@ -427,6 +433,28 @@ export function registerTheme(program) {});}+ // Family mode is a thin orchestration branch over the existing build API.+ // Its key is required exactly with --family, and options that describe one+ // standalone output or a long-running loop remain intentionally separate.+ if (Boolean(options.family) !== Boolean(options.familyKey)) {+ return cliError(+ options.family+ ? '--family requires --family-key <key>'+ : '--family-key requires --family',+ {code: ERROR_CODES.ERR_THEME_INVALID},+ );+ }+ if (options.family && options.out) {+ return cliError('--family cannot be combined with --out', {+ code: ERROR_CODES.ERR_THEME_INVALID,+ });+ }+ if (options.family && options.watch) {+ return cliError('--family cannot be combined with --watch', {+ code: ERROR_CODES.ERR_THEME_INVALID,+ });+ }+// --check and --watch are mutually exclusive: check is a one-shot,// exit-coded verification; watch is a long-running rebuild loop.if (options.check && options.watch) {@@ -466,6 +494,33 @@ export function registerTheme(program) {// ✓/warning lines, and the install instructions are all emitted from// inside themeBuild via the shared logger.logger.setSilent(json);++ if (options.family) {+ try {+ const result = await themeBuildFamily(+ files,+ {+ familyKey: /** @type {string} */ (options.familyKey),+ check: options.check,+ iconsSpecifier: options.iconsSpecifier,+ },+ {cwd: process.cwd()},+ );+ if (json) jsonOut(result);+ if (result.type === 'theme.build.check' && !result.data.upToDate) {+ process.exitCode = 1;+ }+ return NO_RESULT_SET;+ } catch (e) {+ const err =+ /** @type {import('../../../api/error.mjs').AstryxError} */ (e);+ return cliError(err.message, {+ suggestions: err.suggestions,+ code: err.code,+ });+ }+ }+/** @type {Array<{file: string, receipt: import('../../../api/theme/theme.type.mjs').ThemeBuildResponse | import('../../../api/theme/theme.type.mjs').ThemeBuildCheckResponse | null}>} */const results = [];let stale = false;@@ -591,7 +646,10 @@ export function registerTheme(program) {try {result =options.list || !slug- ? await themeListAvailable({cwd: process.cwd(), package: options.package})+ ? await themeListAvailable({+ cwd: process.cwd(),+ package: options.package,+ }): await themeAdd(slug, {targetPath,overwrite: options.overwrite,diff --git a/packages/cli/clients/cli/commands/theme-build.doc.mjs b/packages/cli/clients/cli/commands/theme-build.doc.mjsindex f3b88b0110..d195524983 100644--- a/packages/cli/clients/cli/commands/theme-build.doc.mjs+++ b/packages/cli/clients/cli/commands/theme-build.doc.mjs@@ -14,19 +14,32 @@ export const doc = {name: 'theme build',displayName: 'astryx theme build',namespace: 'cli',- summary: 'Compile one or more defineTheme files to CSS + JS',+ summary: 'Compile standalone themes or one keyed theme family',description:- 'Compiles a file that calls defineTheme() into a scoped CSS file, a JS module, and ' +- 'type declarations: the exact CSS the <Theme> runtime emits. Takes any number of theme ' +- 'files and compiles them in one process, in argument order, stopping at the first ' +- 'failure; an app with several themes does not need a shell loop. With --check it writes ' +- 'nothing and instead reports whether the committed outputs have drifted from source. ' +- 'When a separate build step emits the icon registry, --icons-specifier declares the ' +- 'fully specified module path that the generated JS should import.',+ 'Compiles defineTheme() sources through the same theme pipeline into scoped CSS, ' ++ 'standard ESM, and type declarations. Ordinary mode writes one complete set per ' ++ 'theme. --family combines one selected extension tree into the three files named by ' ++ 'the required --family-key, ready for one CSS load and identity-only switching. ' ++ 'With --check it writes nothing and reports source drift. --icons-specifier keeps ' ++ 'its existing generated-module behavior.',fn: 'themeBuild',args: [{name: 'files', param: 'file', required: true, variadic: true}],options: [- {flag: '-o, --out <path>', param: 'options.out', description: 'Output CSS file path (single theme only)'},+ {+ flag: '--family',+ description:+ 'Build the selected extension family into one keyed CSS, JS, and declaration set',+ },+ {+ flag: '--family-key <key>',+ description:+ 'Lower-kebab filename stem required with --family; must differ from every member name',+ },+ {+ flag: '-o, --out <path>',+ param: 'options.out',+ description: 'Output CSS file path (single theme only)',+ },{flag: '--icons-specifier <specifier>',param: 'options.iconsSpecifier',@@ -35,7 +48,8 @@ export const doc = {},{flag: '-w, --watch',- description: 'Rebuild automatically when a theme file changes (Ctrl-C to stop)',+ description:+ 'Rebuild automatically when a theme file changes (Ctrl-C to stop)',},{flag: '-c, --check',@@ -49,6 +63,10 @@ export const doc = {label: 'Build to a CSS file',cli: 'astryx theme build ./src/themes/ocean.ts --out ./dist/ocean.css',},+ {+ label: 'Build one related family for attribute-only switching',+ cli: 'astryx theme build --family ./themes/ocean.mjs ./themes/ocean-calm.mjs --family-key ocean-family',+ },{label: 'Build every theme in a directory',cli: 'astryx theme build ./src/themes/*.ts',