Skip to content

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

TypeScript

fix(theme): a theme declaration always stays one declaration (#5529)

Baraa Hamodi45a9bf577a7e
diff --git a/.changeset/theme-values-stay-values.md b/.changeset/theme-values-stay-values.md
new file mode 100644
index 0000000000..722e61223c
--- /dev/null
+++ b/.changeset/theme-values-stay-values.md
@@ -0,0 +1,8 @@
+---
+'@astryxdesign/core': patch
+'@astryxdesign/cli': patch
+---
+
+[fix] Keep authored theme declarations inside their CSS boundaries. Drop only an unsafe declaration, preserve valid CSS values and legacy token generation, and continue compiling the rest of the theme. Runtime reports dropped declarations on the console; theme builds include them in the existing receipt warnings. CSS generators accept an optional warning-text array for build collectors, without a callback API or additional exported diagnostic types. (#5529)
+
+@bhamodi
diff --git a/.github/scripts/theme-family-cascade.js b/.github/scripts/theme-family-cascade.js
index 279a980c7b..4f4f9c3270 100644
--- a/.github/scripts/theme-family-cascade.js
+++ b/.github/scripts/theme-family-cascade.js
@@ -172,6 +172,74 @@ async function run() {
'rgb(144, 224, 239)',
);
+ // Exercise the shared compiler in the browser as well as the family
+ // packaging above: an unsafe declaration must not consume valid siblings.
+ const {defineTheme, generateThemeCSS} = await import(
+ require('node:url').pathToFileURL(
+ path.join(root, 'packages/core/dist/theme/index.js'),
+ ).href
+ );
+ const warnings = [];
+ const boundary = generateThemeCSS(
+ defineTheme({
+ name: 'boundary',
+ tokens: {
+ '--font-family-body': 'Gill\\ Sans, "Segoe;UI", serif /* ; */',
+ },
+ components: {
+ button: {
+ base: {
+ color: 'rgb(1, 2, 3)',
+ backgroundColor: 'red; } #escaped { color: rgb(255, 0, 0)',
+ backgroundImage: 'URL(data:image/svg+xml;base64,PHN2Zy8+)',
+ borderRadius: '4px',
+ '::before': {content: '"kept; { }"'},
+ },
+ },
+ },
+ }),
+ warnings,
+ );
+ await page.setContent(
+ '<style>#escaped { color: rgb(4, 5, 6); }</style>' +
+ '<div data-astryx-theme="boundary"><button class="astryx-button">kept</button></div>' +
+ '<div id="escaped">unchanged</div>',
+ );
+ await page.addStyleTag({content: boundary.component + boundary.prose});
+ const boundarySeen = await page.evaluate(() => {
+ const button = document.querySelector('.astryx-button');
+ const style = getComputedStyle(button);
+ return {
+ color: style.color,
+ radius: style.borderRadius,
+ image: style.backgroundImage,
+ content: getComputedStyle(button, '::before').content,
+ outside: getComputedStyle(document.querySelector('#escaped')).color,
+ };
+ });
+ check('boundary drop is reported once', warnings.length, 1);
+ check(
+ 'safe declaration before the drop paints',
+ boundarySeen.color,
+ 'rgb(1, 2, 3)',
+ );
+ check('safe declaration after the drop paints', boundarySeen.radius, '4px');
+ check(
+ 'data URL survives',
+ boundarySeen.image.includes('data:image/svg+xml;base64,PHN2Zy8+'),
+ true,
+ );
+ check(
+ 'quoted semicolon and braces survive',
+ boundarySeen.content,
+ '"kept; { }"',
+ );
+ check(
+ 'an unsafe value cannot style another rule',
+ boundarySeen.outside,
+ 'rgb(4, 5, 6)',
+ );
+
if (failures.length > 0) {
throw new Error(`${failures.length} theme-family assertion(s) failed`);
}
diff --git a/packages/cli/api/theme/build/build.mjs b/packages/cli/api/theme/build/build.mjs
index 2c70c84a57..9aa05a0f0a 100644
--- a/packages/cli/api/theme/build/build.mjs
+++ b/packages/cli/api/theme/build/build.mjs
@@ -12,9 +12,10 @@
* - A .d.ts (plus an optional .variants.d.ts for custom prop values)
*
* It performs the writes and returns a `theme.build` receipt — its `warnings`
- * carry override problems and any fonts the theme names but does not load
- * (font-warning.mjs) — or `null` when the theme produced no CSS (nothing to
- * build). Errors throw AstryxError (with
+ * carry override problems, every declaration core's generator dropped because
+ * its value could not stay one CSS declaration, and any fonts the theme names
+ * but does not load (font-warning.mjs) — or `null` when the theme produced no
+ * CSS (nothing to build). Errors throw AstryxError (with
* a stable code). Human progress is emitted through the shared `logger`
* (silent by default), so the CLI keeps its exact output while a programmatic
* caller stays quiet.
@@ -2303,7 +2304,15 @@ async function themeBuildInternal(
const scopeSelector = themeScopeStart(themeDef.name);
const scopeTo = THEME_SCOPE_TO;
- const {component, prose} = _generateThemeRulesSplit(resolvedTheme);
+ // Older cores ignore this optional collector. Current core writes the same
+ // warning text here that runtime callers receive on the console.
+ /** @type {string[]} */
+ const droppedDeclarations = [];
+
+ const {component, prose} = _generateThemeRulesSplit(
+ resolvedTheme,
+ droppedDeclarations,
+ );
const cssParts = [];
// Prose element defaults always ship — the `<Theme>` runtime
// (generateThemeCSS) always emits them, so the build must too, or the
@@ -2322,7 +2331,7 @@ async function themeBuildInternal(
let adaptationCss;
try {
adaptationCss = _generateAdaptationCSS
- ? _generateAdaptationCSS(resolvedTheme)
+ ? _generateAdaptationCSS(resolvedTheme, droppedDeclarations)
: {component: '', prose: ''};
} catch (error) {
const message =
@@ -2368,11 +2377,16 @@ async function themeBuildInternal(
// adaptations on the same resolved leaf.
let onMediaCss = '';
if (_generateOnMediaCSS) {
- onMediaCss = _generateOnMediaCSS(resolvedTheme);
+ onMediaCss = _generateOnMediaCSS(resolvedTheme, droppedDeclarations);
if (onMediaCss) {
cssParts.push(`@layer astryx-theme {\n${onMediaCss}\n}`);
}
}
+ for (const message of droppedDeclarations) {
+ const w = `Declaration ${message}. The generated CSS omits it; fix the value in the theme source.`;
+ warningMessages.push(w);
+ logger.warn(` ⚠ ${w}`);
+ }
if (cssParts.length === 0) {
logger.log('No overrides found — nothing to build.');
return null;
diff --git a/packages/cli/api/theme/build/build.test.mjs b/packages/cli/api/theme/build/build.test.mjs
index 70e1cea3c1..ee05717cd3 100644
--- a/packages/cli/api/theme/build/build.test.mjs
+++ b/packages/cli/api/theme/build/build.test.mjs
@@ -206,6 +206,133 @@ describe('themeBuild() — receipt', () => {
});
});
+describe('themeBuild() — dropped declarations reach the receipt', () => {
+ // Core's generator refuses a declaration whose value would end it early
+ // (an unquoted `;` or brace, an unclosed string/comment/url). The runtime
+ // says so on the console; a build has a receipt, so every drop must land in
+ // `warnings` — a programmatic caller otherwise sees `warnings: []` while the
+ // CSS silently omits a value the generated JS still carries.
+ it('reports every dropped declaration, from every generator path, in warnings', async () => {
+ const themeFile = path.join(tmpDir, 'dropped.mjs');
+ fs.writeFileSync(
+ themeFile,
+ `export default {
+ name: 'dropped',
+ tokens: {
+ '--color-bg': '#0a0a0a } body { background: url(https://example.com/token) ',
+ },
+ components: {
+ button: {
+ 'variant:secondary': {
+ backgroundColor: 'red; background-image: url(https://example.com/component)',
+ ':hover': {color: '"https://example.com/pseudo'},
+ },
+ },
+ },
+ onDark: {
+ tokens: {'--color-bg': 'url(https://example.com/dark'},
+ },
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {tokens: {'--color-bg': 'red /* https://example.com/adaptation'}},
+ },
+ ],
+ },
+ };\n`,
+ );
+
+ const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ let result;
+ try {
+ result = await themeBuild('dropped.mjs', {}, {cwd: tmpDir});
+ // Drops are collected, not printed: the programmatic API stays silent.
+ expect(warnSpy).not.toHaveBeenCalled();
+ } finally {
+ warnSpy.mockRestore();
+ }
+
+ const css = fs.readFileSync(path.join(tmpDir, 'dropped.css'), 'utf8');
+ expect(css).not.toContain('example.com');
+
+ const warnings = result?.data.warnings ?? [];
+ expect(warnings).toHaveLength(5);
+ expect(warnings).toEqual(
+ expect.arrayContaining([
+ expect.stringMatching(
+ /^Declaration dropped "--color-bg" in tokens: an unquoted "}" would close the rule/,
+ ),
+ expect.stringMatching(
+ /^Declaration dropped "background-color" in components\.button\["variant:secondary"\]: an unquoted ";" would end the declaration/,
+ ),
+ expect.stringMatching(
+ /^Declaration dropped "color" in components\.button\["variant:secondary"\]\[":hover"\]: an unclosed " string/,
+ ),
+ expect.stringMatching(
+ /^Declaration dropped "--color-bg" in onDark\.tokens: an unclosed url\(/,
+ ),
+ expect.stringMatching(
+ /^Declaration dropped "--color-bg" in adaptations\[0\]\.tokens: an unclosed \/\* comment/,
+ ),
+ ]),
+ );
+ for (const w of warnings) {
+ expect(w).toContain('The generated CSS omits it');
+ }
+ });
+
+ it('generates CSS for legacy null tokens without losing neighboring declarations', async () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'legacy.mjs'),
+ `export default {
+ name: 'legacy',
+ tokens: {'--color-background-body': null, '--spacing-4': 12},
+ onDark: {tokens: {'--color-background-body': null}},
+ components: {button: {base: {borderRadius: '4px'}}},
+ };\n`,
+ );
+
+ const result = await themeBuild('legacy.mjs', {}, {cwd: tmpDir});
+ const css = fs.readFileSync(path.join(tmpDir, 'legacy.css'), 'utf8');
+ expect(css).toContain('--color-background-body: null;');
+ expect(css).toContain('--spacing-4: 12;');
+ expect(css).toContain('border-radius: 4px;');
+ expect(result?.data.warnings).toEqual([]);
+ });
+
+ it('keeps valid CSS that carries semicolons, and reports nothing', async () => {
+ const themeFile = path.join(tmpDir, 'kept.mjs');
+ fs.writeFileSync(
+ themeFile,
+ `export default {
+ name: 'kept',
+ tokens: {'--font-family-body': 'Gill\\\\ Sans, "Segoe;UI", serif /* ; */'},
+ components: {
+ button: {
+ 'variant:secondary': {
+ backgroundImage: 'URL(data:image/svg+xml;base64,PHN2Zz4=)',
+ WebkitLineClamp: '2',
+ },
+ },
+ },
+ };\n`,
+ );
+
+ const result = await themeBuild('kept.mjs', {}, {cwd: tmpDir});
+ const css = fs.readFileSync(path.join(tmpDir, 'kept.css'), 'utf8');
+
+ expect(css).toContain(
+ '--font-family-body: Gill\\ Sans, "Segoe;UI", serif /* ; */;',
+ );
+ expect(css).toContain(
+ 'background-image: URL(data:image/svg+xml;base64,PHN2Zz4=);',
+ );
+ expect(css).toContain('-webkit-line-clamp: 2;');
+ expect(result?.data.warnings).toEqual([]);
+ });
+});
+
describe('themeBuild() — nothing to build', () => {
it('returns null and writes nothing when the generator yields no CSS', async () => {
const themeFile = path.join(tmpDir, 'empty.mjs');
diff --git a/packages/core/src/theme/Theme.test.tsx b/packages/core/src/theme/Theme.test.tsx
index 9edad9d38f..41644c0756 100644
--- a/packages/core/src/theme/Theme.test.tsx
+++ b/packages/core/src/theme/Theme.test.tsx
@@ -55,6 +55,38 @@ describe('Theme', () => {
expect(getByText('hello')).toBeTruthy();
});
+ it('mounts the remaining CSS when one authored declaration is dropped', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ try {
+ const theme = defineTheme({
+ name: 'declaration-boundary',
+ tokens: {'--color-accent': 'red; } body { color: red'},
+ components: {button: {base: {borderRadius: '4px'}}},
+ });
+ render(
+ <Theme theme={theme}>
+ <span>child</span>
+ </Theme>,
+ );
+ const css = Array.from(document.querySelectorAll('style'))
+ .map(tag => tag.textContent ?? '')
+ .join('\n');
+ expect(css).not.toContain('body { color: red');
+ expect(css).toContain('border-radius: 4px;');
+ expect(css).toContain(':where(p)');
+ expect(
+ warn.mock.calls.filter(([message]) =>
+ String(message).startsWith('[astryx theme] dropped'),
+ ),
+ ).toHaveLength(1);
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining('dropped "--color-accent" in tokens'),
+ );
+ } finally {
+ warn.mockRestore();
+ }
+ });
+
it('sets data-astryx-theme on wrapper div', () => {
const {container} = render(
<Theme theme={testTheme}>
diff --git a/packages/core/src/theme/declarationBoundary.test.ts b/packages/core/src/theme/declarationBoundary.test.ts
new file mode 100644
index 0000000000..73409c048a
--- /dev/null
+++ b/packages/core/src/theme/declarationBoundary.test.ts
@@ -0,0 +1,126 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Tests for the declaration boundary scanner.
+ *
+ * Every "keeps" case is valid CSS a browser reads as one declaration; every
+ * "rejects" case would end the declaration or rule early, swallow what follows
+ * it, or be discarded by the browser as a bad token.
+ */
+
+import {describe, it, expect} from 'vitest';
+import {
+ checkDeclarationName,
+ checkDeclarationValue,
+} from './declarationBoundary';
+
+describe('checkDeclarationValue keeps valid CSS inside one declaration', () => {
+ it.each([
+ ['plain color', '#FF00FF'],
+ ['color function', 'color-mix(in oklch, #FF00FF 80%, white)'],
+ ['gradient', 'linear-gradient(135deg, #FF00FF 0%, #00FFFF 100%)'],
+ ['calc', 'calc(100% - 24px)'],
+ ['light-dark', 'light-dark(#fff, #111)'],
+ ['font stack', "'Inter Var', ui-sans-serif, system-ui"],
+ ['important flag', 'red !important'],
+ [
+ 'data URI, semicolon inside url()',
+ 'url(data:image/png;base64,iVBORw0KGgo=)',
+ ],
+ ['uppercase URL()', 'URL(data:image/svg+xml;base64,PHN2Zz4=)'],
+ ['uppercase URL with an inert brace', 'URL(data:text/plain,a{b)'],
+ ['mixed-case Url() with spaces', 'Url( data:image/png;base64,iVBORw0= )'],
+ ['quoted url with semicolon', 'url("data:image/svg+xml;utf8,<svg/>")'],
+ ['quoted url with a quoted brace', "url('x.png?a={1;2}')"],
+ ['url nested in image-set', 'image-set(url(a;b.png) 1x, url(c;d.png) 2x)'],
+ ['escaped space in identifier', 'Gill\\ Sans, serif'],
+ ['escaped semicolon in identifier', 'a\\;b'],
+ ['hex escape', '\\31 23'],
+ ['escaped quote inside a string', '"a\\" ; b"'],
+ ['semicolon inside a double-quoted string', '"a;b"'],
+ ['semicolon inside a single-quoted string', "'a;b'"],
+ ['braces inside a string', '"} body { color: red }"'],
+ ['closed comment', '/* brand */ red'],
+ ['closed comment with a semicolon inside', 'red /* ; } */'],
+ ['comment-like text inside a string', '"/* not a comment"'],
+ ['balanced brackets in a grid line name', '[full-start] 1fr [full-end]'],
+ ['semicolon nested in parentheses', 'var(--x, a;b)'],
+ ['brace nested in parentheses', 'var(--x, {a})'],
+ ['backslash before a newline is a delim', 'a\\\nb'],
+ ['whitespace including tab and newline', 'a\t\nb'],
+ ['CRLF string continuation', '"a\\\r\nb"'],
+ ['CRLF after a hex escape in a string', '"\\61\r\nb"'],
+ ['escaped url identifier', 'u\\72l(data:image/png;base64,a)'],
+ ['null is preprocessed by CSS', 'red\u0000'],
+ ['control character inside a string', '"a\u0001b"'],
+ ['control character inside a closed comment', 'red /* \u0001 ; } */'],
+ ['empty value', ''],
+ ])('keeps %s', (_label, value) => {
+ expect(checkDeclarationValue(value)).toBeNull();
+ });
+});
+
+describe('checkDeclarationValue rejects true declaration and rule breaks', () => {
+ it.each([
+ ['top-level semicolon', 'red; background: url(x)', ';'],
+ ['top-level closing brace', 'red } body { color: blue', '}'],
+ ['top-level opening brace', 'red { color: blue }', '{'],
+ ['escaped quote is not a string opener', '\\"; background: red; "', ';'],
+ ['unbalanced closing paren', 'red) ; body { color: blue', ')'],
+ ['unbalanced closing bracket', 'red] ; x', ']'],
+ ['mismatched closer', 'calc(1] ; x)', ']'],
+ ['unclosed paren', 'calc(100% - 24px', '('],
+ ['unclosed bracket', '[full-start', '['],
+ ['unclosed string', '"open', 'string'],
+ ['unclosed comment', 'red /* comment', 'comment'],
+ ['unclosed url', 'url(x.png', 'url('],
+ ['trailing backslash', 'red\\', 'backslash'],
+ ['newline inside a string (bad string)', '"a\nb"', 'bad string'],
+ ['whitespace inside an unquoted url (bad url)', 'url(a b)', 'bad url'],
+ ['uppercase bad url', 'URL(a b)', 'bad url'],
+ ['quote inside an unquoted url (bad url)', 'url(a"b)', 'bad url'],
+ ['paren inside an unquoted url (bad url)', 'url(a(b)', 'bad url'],
+ [
+ 'stray backslash inside an unquoted url (bad url)',
+ 'url(a\\\nb)',
+ 'bad url',
+ ],
+ ['control character inside an unquoted url', 'url(a\u0001b)', 'bad url'],
+ ])('rejects %s', (_label, value, fragment) => {
+ const reason = checkDeclarationValue(value);
+ expect(reason).not.toBeNull();
+ expect(reason).toContain(fragment);
+ });
+});
+
+describe('checkDeclarationName', () => {
+ it.each([
+ 'color',
+ 'background-image',
+ '-webkit-line-clamp',
+ '-moz-osx-font-smoothing',
+ '--brand-accent',
+ '--_internal',
+ '--',
+ '--1',
+ '_private',
+ 'caf\u00e9',
+ 'a\\:b',
+ ])('keeps %s', name => {
+ expect(checkDeclarationName(name)).toBeNull();
+ });
+
+ it.each([
+ '',
+ '1px',
+ '-1',
+ 'color: red',
+ '--x:red} body{color:blue',
+ 'color;',
+ 'a b',
+ 'a\\',
+ 'background{',
+ ])('rejects %j', name => {
+ expect(checkDeclarationName(name)).not.toBeNull();
+ });
+});
diff --git a/packages/core/src/theme/declarationBoundary.ts b/packages/core/src/theme/declarationBoundary.ts
new file mode 100644
index 0000000000..30a1003b6e
--- /dev/null
+++ b/packages/core/src/theme/declarationBoundary.ts
@@ -0,0 +1,347 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Declaration boundary scanner
+ *
+ * Decides whether a consumer-supplied property name and value can be emitted
+ * as exactly one CSS declaration, `name: value;`, without the value ending
+ * the declaration early or swallowing what follows it. Theme definitions are
+ * code, but apps assemble them from stored input (brand colors,
+ * white-labeling), so the generated stylesheet must never extend beyond the
+ * declarations it means to emit.
+ *
+ * The scanner follows the CSS Syntax Module Level 3 tokenizer for everything
+ * that decides where a declaration ends: strings with backslash escapes and
+ * line continuations, comments, `url()` with an unquoted body, escaped code
+ * points outside strings, and `()`, `[]`, `{}` block nesting. Inside any of
+ * those a `;` or a brace is inert, exactly as a browser reads it, so a `data:`
+ * URI, `Gill\ Sans`, or a closed comment passes through byte-identically.
+ * Only what a browser would read as the end of the declaration or rule is
+ * rejected: an unnested `;`, `{` or `}`, an unbalanced closer, and anything
+ * left open at the end of the value (a string, comment, block, or url whose
+ * closer would then be the generator's own `;` or `}`). A `bad-string` or
+ * `bad-url` token is rejected as well: the browser would discard the
+ * declaration anyway, and a diagnostic beats a silent no-op.
+ *
+ * @input A property name or a declaration value as authored in a theme
+ * @output `null` when it can be emitted, otherwise the reason it cannot
+ * @position packages/core/src/theme/declarationBoundary.ts
+ */
+
+/** Newline per CSS Syntax §4.2 (after preprocessing, CR and FF are newlines). */
+function isNewline(ch: string): boolean {
+ return ch === '\n' || ch === '\r' || ch === '\f';
+}
+
+function isWhitespace(ch: string): boolean {
+ return ch === ' ' || ch === '\t' || isNewline(ch);
+}
+
+function isHexDigit(ch: string): boolean {
+ return /^[0-9a-fA-F]$/.test(ch);
+}
+
+/** Name-start code point: letter, underscore, or any non-ASCII code point. */
+function isNameStart(ch: string): boolean {
+ return /^[A-Za-z_]$/.test(ch) || ch.charCodeAt(0) >= 0x80;
+}
+
+function isNameChar(ch: string): boolean {
+ return isNameStart(ch) || /^[0-9-]$/.test(ch);
+}
+
+/** CSS Syntax §3.3 preprocessing, for scanning only; emitted bytes stay intact. */
+function preprocess(input: string): string {
+ return input.replace(/\r\n?|\f/g, '\n').replace(/\0/g, '\uFFFD');
+}
+
+/** Non-printable code points make an unquoted url() a bad-url token. */
+// eslint-disable-next-line no-control-regex -- these code points are the subject
+const NON_PRINTABLE = /[\x01-\x08\x0b\x0e-\x1f\x7f]/;
+
+/** "Check if two code points are a valid escape" (§4.3.8). */
+function isValidEscape(input: string, pos: number): boolean {
+ return (
+ input[pos] === '\\' && pos + 1 < input.length && !isNewline(input[pos + 1])
+ );
+}
+
+/** "Check if three code points would start an ident sequence" (§4.3.9). */
+function startsIdent(input: string, pos: number): boolean {
+ const ch = input[pos];
+ if (ch === '-') {
+ const next = input[pos + 1];
+ return (
+ next !== undefined &&
+ (next === '-' || isNameStart(next) || isValidEscape(input, pos + 1))
+ );
+ }
+ if (ch === '\\') {
+ return isValidEscape(input, pos);
+ }
+ return ch !== undefined && isNameStart(ch);
+}
+
+/**
+ * "Consume an escaped code point" (§4.3.7), positioned after the backslash.
+ * Returns the position after the escape. A hex escape takes up to six hex
+ * digits plus one optional whitespace; anything else takes one code point.
+ */
+function consumeEscape(input: string, pos: number): number {
+ if (isHexDigit(input[pos])) {
+ let end = pos;
+ while (end < input.length && end - pos < 6 && isHexDigit(input[end])) {
+ end++;
+ }
+ if (end < input.length && isWhitespace(input[end])) {
+ end++;
+ }
+ return end;
+ }
+ // A surrogate pair is one code point.
+ const code = input.codePointAt(pos) ?? 0;
+ return pos + (code > 0xffff ? 2 : 1);
+}
+
+/**
+ * "Consume an ident sequence" (§4.3.11) starting at `pos`. Returns the
+ * position after it and the decoded name (escapes resolved, for the
+ * case-insensitive `url` check; hex escapes decode to their code point).
+ */
+function consumeIdent(input: string, pos: number): {end: number; name: string} {
+ let name = '';
+ let i = pos;
+ while (i < input.length) {
+ const ch = input[i];
+ if (isNameChar(ch)) {
+ name += ch;
+ i++;
+ } else if (isValidEscape(input, i)) {
+ const end = consumeEscape(input, i + 1);
+ if (isHexDigit(input[i + 1])) {
+ const hex = input.slice(i + 1, end).trim();
+ const code = parseInt(hex, 16);
+ name +=
+ code === 0 || code > 0x10ffff || (code >= 0xd800 && code <= 0xdfff)
+ ? '\uFFFD'
+ : String.fromCodePoint(code);
+ } else {
+ name += input.slice(i + 1, end);
+ }
+ i = end;
+ } else {
+ break;
+ }
+ }
+ return {end: i, name};
+}
+
+/**
+ * "Consume a string token" (§4.3.5), positioned at the opening quote.
+ * Returns the position after the closing quote, or a rejection reason.
+ */
+function consumeString(
+ input: string,
+ pos: number,
+): {end: number} | {reason: string} {
+ const quote = input[pos];
+ let i = pos + 1;
+ while (i < input.length) {
+ const ch = input[i];
+ if (ch === quote) {
+ return {end: i + 1};
+ }
+ if (isNewline(ch)) {
+ // A raw newline ends the string as a bad-string token; the browser
+ // discards the declaration, so a diagnostic is more useful than
+ // reasoning about where that leaves the next `;`.
+ return {reason: 'a newline inside a quoted string makes a bad string'};
+ }
+ if (ch === '\\') {
+ if (i + 1 >= input.length) {
+ break;
+ }
+ // Escaped newline is a line continuation; any other escape consumes
+ // the escaped code point (so `\"` never closes the string).
+ i = isNewline(input[i + 1]) ? i + 2 : consumeEscape(input, i + 1);
+ continue;
+ }
+ i++;
+ }
+ return {
+ reason: `an unclosed ${quote} string would swallow the rest of the rule`,
+ };
+}
+
+/**
+ * "Consume a url token" (§4.3.6), positioned after `url(` and any leading
+ * whitespace, with a non-quote next code point. Returns the position after
+ * the closing `)`, or a rejection reason (bad-url or unclosed).
+ */
+function consumeUrl(
+ input: string,
+ pos: number,
+): {end: number} | {reason: string} {
+ let i = pos;
+ while (i < input.length) {
+ const ch = input[i];
+ if (ch === ')') {
+ return {end: i + 1};
+ }
+ if (isWhitespace(ch)) {
+ while (i < input.length && isWhitespace(input[i])) {
+ i++;
+ }
+ if (i >= input.length) {
+ break;
+ }
+ if (input[i] === ')') {
+ return {end: i + 1};
+ }
+ return {reason: 'whitespace inside an unquoted url() makes a bad url'};
+ }
+ if (NON_PRINTABLE.test(ch)) {
+ return {reason: 'a non-printable character inside url() makes a bad url'};
+ }
+ if (ch === '"' || ch === "'" || ch === '(') {
+ return {
+ reason: `"${ch}" inside an unquoted url() makes a bad url; quote the URL instead`,
+ };
+ }
+ if (ch === '\\') {
+ if (!isValidEscape(input, i)) {
+ return {reason: 'a stray backslash inside url() makes a bad url'};
+ }
+ i = consumeEscape(input, i + 1);
+ continue;
+ }
+ i++;
+ }
+ return {reason: 'an unclosed url( would swallow the rest of the rule'};
+}
+
+const CLOSER: Record<string, string> = {'(': ')', '[': ']', '{': '}'};
+
+/**
+ * Why `value` cannot be emitted as the value of one declaration, or `null`
+ * when it can. Valid CSS a browser keeps inside one declaration always
+ * returns `null`; see the file header for the exact rules.
+ */
+export function checkDeclarationValue(input: string): string | null {
+ const value = preprocess(input);
+ const open: string[] = [];
+ let i = 0;
+ while (i < value.length) {
+ const ch = value[i];
+
+ if (ch === '/' && value[i + 1] === '*') {
+ const close = value.indexOf('*/', i + 2);
+ if (close === -1) {
+ return 'an unclosed /* comment would swallow the rest of the rule';
+ }
+ i = close + 2;
+ continue;
+ }
+
+ if (ch === '"' || ch === "'") {
+ const result = consumeString(value, i);
+ if ('reason' in result) {
+ return result.reason;
+ }
+ i = result.end;
+ continue;
+ }
+
+ if (startsIdent(value, i)) {
+ const ident = consumeIdent(value, i);
+ i = ident.end;
+ if (value[i] === '(' && ident.name.toLowerCase() === 'url') {
+ let j = i + 1;
+ while (j < value.length && isWhitespace(value[j])) {
+ j++;
+ }
+ if (value[j] === '"' || value[j] === "'") {
+ // `url("...")` is an ordinary function token; the string and the
+ // closing paren are handled by the loop.
+ open.push(')');
+ i = i + 1;
+ continue;
+ }
+ const result = consumeUrl(value, j);
+ if ('reason' in result) {
+ return result.reason;
+ }
+ i = result.end;
+ }
+ continue;
+ }
+
+ if (ch === '\\') {
+ if (i + 1 >= value.length) {
+ // `\` followed by the generator's own `;` would escape it.
+ return 'a trailing backslash would escape the declaration terminator';
+ }
+ // `\` + newline is not an escape: the backslash is a delim and the
+ // newline is whitespace. Anything else escapes the next code point.
+ i = isNewline(value[i + 1]) ? i + 1 : consumeEscape(value, i + 1);
+ continue;
+ }
+
+ if (ch === '(' || ch === '[' || ch === '{') {
+ if (ch === '{' && open.length === 0) {
+ return 'an unquoted "{" would open a nested block';
+ }
+ open.push(CLOSER[ch]);
+ i++;
+ continue;
+ }
+
+ if (ch === ')' || ch === ']' || ch === '}') {
+ if (open.length === 0) {
+ return ch === '}'
+ ? 'an unquoted "}" would close the rule'
+ : `an unbalanced "${ch}" has nothing to close`;
+ }
+ const expected = open.pop();
+ if (expected !== ch) {
+ return `"${ch}" does not close the open "${expected === ')' ? '(' : expected === ']' ? '[' : '{'}"`;
+ }
+ i++;
+ continue;
+ }
+
+ if (ch === ';' && open.length === 0) {
+ return 'an unquoted ";" would end the declaration';
+ }
+
+ i++;
+ }
+
+ if (open.length > 0) {
+ const closer = open[open.length - 1];
+ const opener = closer === ')' ? '(' : closer === ']' ? '[' : '{';
+ return `an unclosed "${opener}" would swallow the rest of the rule`;
+ }
+ return null;
+}
+
+/**
+ * Why `name` cannot be emitted as a declaration's property name, or `null`
+ * when it can. A property name is one CSS ident sequence: a standard
+ * property (`color`), a vendor-prefixed one (`-webkit-line-clamp`), or a
+ * custom property (`--brand-accent`, `--_internal`). Escapes are allowed
+ * because an ident allows them. Whether the name means anything to the
+ * browser is not this check's concern; only that it cannot end the
+ * declaration or leak a second one.
+ */
+export function checkDeclarationName(input: string): string | null {
+ const name = preprocess(input);
+ if (name.length === 0 || !startsIdent(name, 0)) {
+ return 'a property name must be a CSS identifier';
+ }
+ const {end} = consumeIdent(name, 0);
+ if (end !== name.length) {
+ return `a property name must be one CSS identifier; "${name[end]}" cannot appear in one`;
+ }
+ return null;
+}
diff --git a/packages/core/src/theme/generateThemeRules.test.ts b/packages/core/src/theme/generateThemeRules.test.ts
index 14a1dab9e5..389986ece7 100644
--- a/packages/core/src/theme/generateThemeRules.test.ts
+++ b/packages/core/src/theme/generateThemeRules.test.ts
@@ -6,7 +6,7 @@
* correct, consistently ordered CSS for both runtime and build paths.
*/
-import {describe, it, expect} from 'vitest';
+import {describe, it, expect, vi} from 'vitest';
import {
dataTokenDefaults,
defineTheme,
@@ -14,6 +14,7 @@ import {
generateThemeCSS,
generateOnMediaCSS,
generateThemeRules,
+ type DefinedTheme,
} from './index';
import {generateDataTokenDefaultsCSS} from './generateThemeRules';
@@ -293,7 +294,9 @@ describe('generateThemeRules', () => {
r.includes('font-family: var(--font-family-body)'),
);
expect(fontRule).toBeDefined();
- expect(fontRule).toBe(' :scope {\n font-family: var(--font-family-body);\n }');
+ expect(fontRule).toBe(
+ ' :scope {\n font-family: var(--font-family-body);\n }',
+ );
});
it('emits no scope font rule when the theme declares no body font', () => {
@@ -1387,3 +1390,468 @@ describe('data visualization tokens', () => {
).toEqual(['component', 'prose']);
});
});
+
+describe('declaration assembly keeps values as values', () => {
+ /** Run the full runtime generator, collecting every dropped declaration. */
+ function generate(theme: DefinedTheme) {
+ const diagnostics: string[] = [];
+ const {component, prose} = generateThemeCSS(theme, diagnostics);
+ return {css: component + prose, component, prose, diagnostics};
+ }
+
+ /**
+ * Every path a consumer-supplied declaration can take into the stylesheet.
+ * `build` places `value` on that path; `emitted` is the exact declaration
+ * text the path writes for it; `property`/`location` are what a diagnostic
+ * for it must carry.
+ */
+ const paths: {
+ label: string;
+ property: string;
+ location: string;
+ build: (value: string) => DefinedTheme;
+ emitted: (value: string) => string;
+ }[] = [
+ {
+ label: 'root tokens',
+ property: '--color-accent',
+ location: 'tokens',
+ build: value =>
+ defineTheme({name: 'brand', tokens: {'--color-accent': value}}),
+ emitted: value => `--color-accent: ${value};`,
+ },
+ {
+ label: 'theme-local tokens',
+ property: '--brand-accent',
+ location: 'localTokens',
+ build: value =>
+ defineTheme({name: 'brand', localTokens: {'--brand-accent': value}}),
+ emitted: value => `--brand-accent: ${value};`,
+ },
+ {
+ label: 'tokens inherited from a base theme',
+ property: '--color-accent',
+ location: 'tokens',
+ build: value =>
+ defineTheme({
+ name: 'child',
+ extends: defineTheme({
+ name: 'base',
+ tokens: {'--color-accent': value},
+ }),
+ }),
+ emitted: value => `--color-accent: ${value};`,
+ },
+ {
+ label: 'component variant',
+ property: 'background-color',
+ location: 'components.button["variant:secondary"]',
+ build: value =>
+ defineTheme({
+ name: 'brand',
+ components: {
+ button: {'variant:secondary': {backgroundColor: value}},
+ },
+ }),
+ emitted: value => `background-color: ${value};`,
+ },
+ {
+ label: 'component variant inherited from a base theme',
+ property: 'background-color',
+ location: 'components.button["variant:secondary"]',
+ build: value =>
+ defineTheme({
+ name: 'child',
+ extends: defineTheme({
+ name: 'base',
+ components: {
+ button: {'variant:secondary': {backgroundColor: value}},
+ },
+ }),
+ }),
+ emitted: value => `background-color: ${value};`,
+ },
+ {
+ label: 'component pseudo block',
+ property: 'background-color',
+ location: 'components.button["variant:secondary"][":hover"]',
+ build: value =>
+ defineTheme({
+ name: 'brand',
+ components: {
+ button: {'variant:secondary': {':hover': {backgroundColor: value}}},
+ },
+ }),
+ emitted: value => `background-color: ${value};`,
+ },
+ {
+ label: 'onDark tokens',
+ property: '--color-accent',
+ location: 'onDark.tokens',
+ build: value =>
+ defineTheme({
+ name: 'brand',
+ onDark: {tokens: {'--color-accent': value}},
+ }),
+ emitted: value => `--color-accent: ${value};`,
+ },
+ {
+ label: 'onLight component variant',
+ property: 'background-color',
+ location: 'onLight.components.button["variant:secondary"]',
+ build: value =>
+ defineTheme({
+ name: 'brand',
+ onLight: {
+ components: {
+ button: {'variant:secondary': {backgroundColor: value}},
+ },
+ },
+ }),
+ emitted: value => `background-color: ${value};`,
+ },
+ {
+ label: 'onDark component pseudo block',
+ property: 'background-color',
+ location: 'onDark.components.button["variant:secondary"][":hover"]',
+ build: value =>
+ defineTheme({
+ name: 'brand',
+ onDark: {
+ components: {
+ button: {
+ 'variant:secondary': {':hover': {backgroundColor: value}},
+ },
+ },
+ },
+ }),
+ emitted: value => `background-color: ${value};`,
+ },
+ {
+ label: 'adaptation tokens',
+ property: '--color-accent',
+ location: 'adaptations[0].tokens',
+ build: value =>
+ defineTheme({
+ name: 'brand',
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {tokens: {'--color-accent': value}},
+ },
+ ],
+ },
+ }),
+ emitted: value => `--color-accent: ${value};`,
+ },
+ {
+ label: 'adaptation component variant',
+ property: 'background-color',
+ location: 'adaptations[1].components.button["variant:secondary"]',
+ build: value =>
+ defineTheme({
+ name: 'brand',
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'fine'},
+ value: {tokens: {'--spacing-4': '12px'}},
+ },
+ {
+ when: {pointer: 'coarse'},
+ value: {
+ components: {
+ button: {'variant:secondary': {backgroundColor: value}},
+ },
+ },
+ },
+ ],
+ },
+ }),
+ emitted: value => `background-color: ${value};`,
+ },
+ ];
+
+ /** Valid CSS a browser keeps inside one declaration. */
+ const preserved: [string, string][] = [
+ ['a color-mix()', 'color-mix(in oklch, #FF00FF 80%, white)'],
+ ['a gradient', 'linear-gradient(135deg, #FF00FF 0%, #00FFFF 100%)'],
+ ['calc()', 'calc(100% - 24px)'],
+ ['light-dark()', 'light-dark(#fff, #111)'],
+ ['a quoted font stack', "'Inter Var', ui-sans-serif, system-ui"],
+ [
+ 'a data: URI (semicolon inside url())',
+ 'url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUg==)',
+ ],
+ ['an uppercase URL()', 'URL(data:image/svg+xml;base64,PHN2Zz4=)'],
+ [
+ 'a quoted url() carrying a semicolon',
+ 'url("data:image/svg+xml;utf8,<svg/>")',
+ ],
+ ['an escaped identifier', 'Gill\\ Sans, serif'],
+ ['a closed comment with a semicolon inside', 'red /* ; } */'],
+ ['a semicolon inside a string', '"a;b"'],
+ ['an escaped quote inside a string', '"a\\" ; b"'],
+ ['quoted braces', '"} body { color: red }"'],
+ ['important', 'red !important'],
+ ['nested functions', 'var(--fallback, calc(1px + 2px))'],
+ ['CRLF string continuation', '"a\\\r\nb"'],
+ ['closed comment with a control character', 'red /* \u0001 ; } */'],
+ [
+ 'balanced brackets and parentheses',
+ '[full-start] minmax(0, 1fr) [full-end]',
+ ],
+ ];
+
+ /** Values a browser reads as the end of the declaration or rule. */
+ const rejected: [string, string, string][] = [
+ [
+ 'an unquoted semicolon adds a declaration',
+ 'red; background-image: url(https://example.com/leak)',
+ ';',
+ ],
+ [
+ 'an unquoted brace closes the rule',
+ 'red } input[value^="a"] { background: url(https://example.com/leak?a) ',
+ '}',
+ ],
+ [
+ 'an unquoted brace opens a block',
+ 'red { background: url(https://example.com/leak) }',
+ '{',
+ ],
+ [
+ 'an escaped quote is not a string opener',
+ '\\"; background: url(https://example.com/leak); "',
+ ';',
+ ],
+ [
+ 'an unclosed comment swallows the rule',
+ 'red /* https://example.com/leak',
+ 'comment',
+ ],
+ [
+ 'an unclosed string swallows the rule',
+ '"https://example.com/leak',
+ 'string',
+ ],
+ [
+ 'an unclosed url() swallows the rule',
+ 'url(https://example.com/leak',
+ 'url(',
+ ],
+ [
+ 'an unclosed paren swallows the rule',
+ 'calc(1px + var(--example.com/leak)',
+ '(',
+ ],
+ [
+ 'an unbalanced closer',
+ 'red) ; background: url(https://example.com/leak)',
+ ')',
+ ],
+ ['a bad url', 'url(https://example.com/leak a)', 'bad url'],
+ [
+ 'a trailing backslash escapes the terminator',
+ 'https://example.com/leak\\',
+ 'backslash',
+ ],
+ ];
+
+ describe.each(paths)('$label', path => {
+ it.each(preserved)('emits %s byte-identically', (_label, value) => {
+ const {css, diagnostics} = generate(path.build(value));
+ expect(css).toContain(path.emitted(value));
+ expect(diagnostics).toEqual([]);
+ });
+
+ it.each(rejected)('drops a value where %s', (_label, value, reason) => {
+ const {css, diagnostics} = generate(path.build(value));
+ expect(css).not.toContain('example.com');
+ expect(css).not.toContain('leak');
+ expect(diagnostics).toHaveLength(1);
+ expect(diagnostics[0]).toContain(`"${path.property}"`);
+ expect(diagnostics[0]).toContain(path.location);
+ expect(diagnostics[0]).toContain(reason);
+ });
+ });
+
+ it('keeps a vendor-prefixed property name', () => {
+ const {css, diagnostics} = generate(
+ defineTheme({
+ name: 'brand',
+ components: {
+ button: {
+ 'variant:secondary': {
+ WebkitLineClamp: '2',
+ MozOsxFontSmoothing: 'grayscale',
+ },
+ },
+ },
+ }),
+ );
+ expect(css).toContain('-webkit-line-clamp: 2;');
+ expect(css).toContain('-moz-osx-font-smoothing: grayscale;');
+ expect(diagnostics).toEqual([]);
+ });
+
+ it('drops a property name that is not a property name', () => {
+ const {css, diagnostics} = generate(
+ defineTheme({
+ name: 'brand',
+ tokens: {
+ '--x:red} body{color:blue': 'red',
+ } as Record<string, string>,
+ }),
+ );
+ expect(css).not.toContain('body{color:blue');
+ expect(css).not.toContain('body {');
+ expect(diagnostics).toHaveLength(1);
+ expect(diagnostics[0]).toContain('"--x:red} body{color:blue" in tokens');
+ expect(diagnostics[0]).toContain('identifier');
+ });
+
+ it('keeps prose rules intact when a typed token carries a payload', () => {
+ // Prose rules reference the token through var(), so the payload never
+ // reaches them; the token block drops it and the :where(p) rule stays.
+ const {css, prose, diagnostics} = generate(
+ defineTheme({
+ name: 'brand',
+ tokens: {
+ '--text-body-size': '1rem; } body { background: url(x) ',
+ },
+ }),
+ );
+ expect(css).not.toContain('background: url(x)');
+ expect(css).not.toContain('body {');
+ expect(prose).toContain('font-size: var(--text-body-size);');
+ expect(diagnostics).toHaveLength(1);
+ expect(diagnostics[0]).toContain('"--text-body-size" in tokens');
+ });
+
+ it('falls back to the token weight when an authored Heading weight cannot stay a declaration', () => {
+ const payload = '700; } body { background: url(https://example.com/leak) ';
+ const {css, diagnostics} = generate(
+ defineTheme({
+ name: 'brand',
+ components: {heading: {'weight:bold': {fontWeight: payload}}},
+ }),
+ );
+ expect(css).not.toContain('example.com');
+ expect(css).toContain(
+ '.astryx-heading[data-weight="bold"] { font-weight: var(--font-weight-bold); }',
+ );
+ // Reported once, where the authored rule's own declarations are emitted.
+ expect(diagnostics).toHaveLength(1);
+ expect(diagnostics[0]).toContain(
+ '"font-weight" in components.heading["weight:bold"]',
+ );
+ });
+
+ it('falls back to the token weight when an inherited Heading weight cannot stay a declaration', () => {
+ const payload = '700; } body { background: url(https://example.com/leak) ';
+ const {css} = generate(
+ defineTheme({
+ name: 'brand',
+ components: {heading: {'weight:bold': {fontWeight: payload}}},
+ onDark: {components: {heading: {'level:1': {fontSize: '2rem'}}}},
+ }),
+ );
+ expect(css).not.toContain('example.com');
+ expect(css).toContain(
+ ':is([data-astryx-media="dark"]) :is(.astryx-heading[data-weight="bold"]) { font-weight: var(--font-weight-bold); }',
+ );
+ });
+
+ it('a dropped container padding still leaves the rest of the rule intact', () => {
+ const {css, diagnostics} = generate(
+ defineTheme({
+ name: 'brand',
+ components: {
+ card: {
+ base: {
+ padding:
+ '16px; } body { background: url(https://example.com/leak) ',
+ borderRadius: '8px',
+ },
+ },
+ },
+ }),
+ );
+ expect(css).not.toContain('example.com');
+ expect(css).toContain('border-radius: 8px;');
+ expect(diagnostics).toHaveLength(1);
+ expect(diagnostics[0]).toContain('"padding" in components.card["base"]');
+ expect(css).not.toContain('--astryx-card-padding');
+ });
+
+ it('warns on the console only when no warning collector is given', () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const theme = defineTheme({
+ name: 'brand',
+ tokens: {
+ '--color-accent': 'red; background: url(https://example.com/leak)',
+ },
+ });
+
+ const plainCSS = generateThemeCSS(theme);
+ expect(warn).toHaveBeenCalledTimes(1);
+ expect(warn).toHaveBeenCalledWith(
+ expect.stringContaining(
+ '[astryx theme] dropped "--color-accent" in tokens',
+ ),
+ );
+
+ warn.mockClear();
+ const diagnostics: string[] = ['earlier build warning'];
+ const before = JSON.stringify(theme);
+ expect(generateThemeCSS(theme, diagnostics)).toEqual(plainCSS);
+ expect(JSON.stringify(theme)).toBe(before);
+ expect(warn).not.toHaveBeenCalled();
+ expect(diagnostics).toHaveLength(2);
+ expect(diagnostics[0]).toBe('earlier build warning');
+ expect(diagnostics[1]).toContain('dropped "--color-accent" in tokens');
+ warn.mockRestore();
+ });
+
+ it('every shipped generator entry point appends to the warning collector', () => {
+ const theme = defineTheme({
+ name: 'brand',
+ tokens: {
+ '--color-accent': 'red; background: url(https://example.com/leak)',
+ },
+ onDark: {
+ tokens: {
+ '--color-accent': 'red; background: url(https://example.com/dark)',
+ },
+ },
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {
+ tokens: {
+ '--color-accent':
+ 'red; background: url(https://example.com/coarse)',
+ },
+ },
+ },
+ ],
+ },
+ });
+ const seen: string[] = [];
+ expect(generateThemeRules(theme, seen).join('')).not.toContain(
+ 'example.com',
+ );
+ expect(generateOnMediaCSS(theme, seen)).not.toContain('example.com');
+ expect(generateAdaptationCSS(theme, seen).component).not.toContain(
+ 'example.com',
+ );
+ expect(seen).toEqual([
+ expect.stringContaining('in tokens:'),
+ expect.stringContaining('in onDark.tokens:'),
+ expect.stringContaining('in adaptations[0].tokens:'),
+ ]);
+ });
+});
diff --git a/packages/core/src/theme/generateThemeRules.ts b/packages/core/src/theme/generateThemeRules.ts
index 98b63c37ba..7d35640be4 100644
--- a/packages/core/src/theme/generateThemeRules.ts
+++ b/packages/core/src/theme/generateThemeRules.ts
@@ -9,11 +9,17 @@
* Used by both the runtime path (Theme injects <style>) and the build
* path (`astryx theme build` pre-compiles to CSS files).
*
+ * Every consumer-supplied declaration is checked by declarationBoundary.ts
+ * before it is emitted, so a value can never end its declaration or rule
+ * early. A refused declaration is dropped and reported in the supplied
+ * warnings array (build receipts), or through `console.warn` (runtime).
+ *
* Extracted from defineTheme.ts to reduce cyclomatic complexity and provide
* a clear single-responsibility module for CSS generation.
*
- * @input DefinedTheme (resolved theme object from defineTheme)
- * @output CSS rule strings, split by layer (component vs prose)
+ * @input DefinedTheme (resolved theme object from defineTheme), optional warnings array
+ * @output CSS rule strings, split by layer (component vs prose), and warning text
+ * for each dropped declaration
* @position packages/core/src/theme/generateThemeRules.ts
*/
@@ -26,6 +32,10 @@ import {parseStyleKey} from '../utils/parseStyleKey';
import {getDerivedVars} from './derivedVarRegistry';
import {dataTokenDefaults} from './domainTokens/dataTokens';
import {cssVar, classPrefix, dataAttrNamespace} from '../naming';
+import {
+ checkDeclarationName,
+ checkDeclarationValue,
+} from './declarationBoundary';
/**
* Theme @scope selectors.
@@ -366,6 +376,117 @@ function expandContainerPadding(
return tokens;
}
+// =============================================================================
+// Declaration assembly: a declaration always stays one declaration
+// =============================================================================
+
+type DiagnosticSink = (message: string) => void;
+
+const warnToConsole: DiagnosticSink = message => {
+ console.warn(`[astryx theme] ${message}`);
+};
+
+/** Build receipts collect warning text; runtime callers warn by default. */
+function diagnosticSink(warnings: string[] | undefined): DiagnosticSink {
+ return warnings ? message => warnings.push(message) : warnToConsole;
+}
+
+/** Shorten an authored value for a one-line message. */
+function previewValue(value: string): string {
+ const oneLine = JSON.stringify(value);
+ return oneLine.length > 80 ? `${oneLine.slice(0, 77)}..."` : oneLine;
+}
+
+function reportDrop(
+ sink: DiagnosticSink,
+ property: string,
+ value: string,
+ location: string,
+ reason: string,
+): void {
+ sink(
+ `dropped "${property}" in ${location}: ${reason} (value: ${previewValue(value)})`,
+ );
+}
+
+/**
+ * True when `name: value;` stays exactly one declaration; otherwise reports
+ * the drop and returns false. Both checks follow CSS syntax, so valid CSS a
+ * browser keeps inside one declaration (a `data:` URI, `Gill\ Sans`, a closed
+ * comment, a vendor-prefixed property) is never refused; see
+ * declarationBoundary.ts for the rules.
+ */
+function acceptDeclaration(
+ property: string,
+ value: string,
+ location: string,
+ sink: DiagnosticSink,
+): boolean {
+ const reason = checkDeclarationName(property) ?? checkDeclarationValue(value);
+ if (reason === null) {
+ return true;
+ }
+ reportDrop(sink, property, value, location, reason);
+ return false;
+}
+
+/**
+ * Assemble `prop: value;` lines, dropping (and reporting) any entry whose
+ * property or value could not stay a single declaration. Theme definitions
+ * are code, but apps do assemble them from stored input (brand colors,
+ * white-labeling), so the generated stylesheet must never extend beyond the
+ * declarations it means to emit.
+ */
+function joinDeclarations(
+ entries: [string, string][],
+ location: string,
+ sink: DiagnosticSink,
+ mapProp: (prop: string) => string = p => p,
+): string {
+ const lines: string[] = [];
+ for (const [rawProp, rawValue] of entries) {
+ // Legacy unenrolled tokens retain non-string values. Scan the same text
+ // interpolation has always emitted, without changing the normalized theme.
+ const value = `${rawValue}`;
+ const prop = mapProp(rawProp);
+ if (acceptDeclaration(prop, value, location, sink)) {
+ lines.push(` ${prop}: ${value};`);
+ }
+ }
+ return lines.join('\n');
+}
+
+/** The `:scope` token block for portable and theme-local token values. */
+function tokenBlock(
+ source: ThemeRuleSource,
+ location: string,
+ sink: DiagnosticSink,
+): string | null {
+ const declarations = [
+ joinDeclarations(Object.entries(source.tokens), `${location}tokens`, sink),
+ joinDeclarations(
+ Object.entries(source.localTokens ?? {}),
+ `${location}localTokens`,
+ sink,
+ ),
+ ]
+ .filter(block => block.length > 0)
+ .join('\n');
+ const hasEntries =
+ Object.keys(source.tokens).length > 0 ||
+ Object.keys(source.localTokens ?? {}).length > 0;
+ return hasEntries ? ` :scope {\n${declarations}\n }` : null;
+}
+
+/** `components.button["variant:secondary"]`-style location for a rule. */
+function componentLocation(
+ prefix: string,
+ component: string,
+ key: string,
+): string {
+ return `${prefix}components.${component}[${JSON.stringify(key)}]`;
+}
+
// =============================================================================
// Public API
// =============================================================================
@@ -393,9 +514,12 @@ export interface ThemeRuleSource {
components?: ComponentStyleMap;
}
-export function generateThemeRules(theme: ThemeRuleSource): string[] {
+export function generateThemeRules(
+ theme: ThemeRuleSource,
+ warnings?: string[],
+): string[] {
const parts: string[] = [];
- const tokens = theme.tokens;
+ const sink = diagnosticSink(warnings);
// Bare prose rules reference semantic variables instead of baking the root
// value. That lets adaptation token writes take effect through CSS alone
@@ -403,15 +527,9 @@ export function generateThemeRules(theme: ThemeRuleSource): string[] {
const val = (key: string): string => `var(${key})`;
// 1. Token block — CSS custom properties on :scope
- const tokenEntries = [
- ...Object.entries(tokens),
- ...Object.entries(theme.localTokens ?? {}),
- ];
- if (tokenEntries.length > 0) {
- const declarations = tokenEntries
- .map(([prop, value]) => ` ${prop}: ${value};`)
- .join('\n');
- parts.push(` :scope {\n${declarations}\n }`);
+ const tokenRules = tokenBlock(theme, '', sink);
+ if (tokenRules !== null) {
+ parts.push(tokenRules);
}
// 1b. Base font — apply the theme's declared body font to the scope root.
@@ -420,14 +538,14 @@ export function generateThemeRules(theme: ThemeRuleSource): string[] {
// sets a page font. `font-family` inherits, so one rule on :scope covers
// the tree. Only emitted when the theme declares a body font, so a bare
// theme still contributes no scope rules of its own.
- if (tokens['--font-family-body']) {
+ if (theme.tokens['--font-family-body']) {
parts.push(` :scope {\n font-family: var(--font-family-body);\n }`);
}
// 2. Component overrides: stable .astryx-* target classes combined with
// reflected data-* selectors for visual props and runtime states.
if (theme.components) {
- generateComponentRules(theme.components, parts);
+ generateComponentRules(theme.components, parts, {sink});
}
// 3. Prose HTML element rules (h1-h6, p, small, code, hr)
@@ -523,6 +641,13 @@ function generateHeadingWeightOverrides(
}
}
+/**
+ * The `fontWeight` a heading rule authors for `styleKey`, or undefined when
+ * it has none. A value that cannot stay one declaration is treated as not
+ * authored, so the override falls back to the inherited or token weight
+ * instead of interpolating it; the drop itself is reported where that same
+ * rule's declarations are emitted, so it is not reported twice here.
+ */
function getAuthoredHeadingWeight(
headingRuleMap: Record<string, unknown>,
styleKey: string,
@@ -532,13 +657,20 @@ function getAuthoredHeadingWeight(
return undefined;
}
const fontWeight = (rule as Record<string, unknown>).fontWeight;
- return typeof fontWeight === 'string' ? fontWeight : undefined;
+ return typeof fontWeight === 'string' &&
+ checkDeclarationValue(fontWeight) === null
+ ? fontWeight
+ : undefined;
}
/** Options shared by root, adaptation, and media-surface component lowering. */
interface ComponentRuleOptions {
resetInheritedPaddingSpecificity?: boolean;
surface?: MediaSurface;
+ /** Receives dropped declarations; defaults to `console.warn`. */
+ sink?: DiagnosticSink;
+ /** Location prefix for diagnostics, e.g. `onDark.` or `adaptations[0].`. */
+ location?: string;
}
/**
@@ -555,6 +687,8 @@ function generateComponentRules(
{
resetInheritedPaddingSpecificity = false,
surface,
+ sink = warnToConsole,
+ location: locationPrefix = '',
}: ComponentRuleOptions = {},
): void {
for (const [component, rules] of Object.entries(components)) {
@@ -566,6 +700,7 @@ function generateComponentRules(
const suffix = parseStyleKey(key);
const baseSelector = componentSelector(component, suffix, surface);
+ const location = componentLocation(locationPrefix, component, key);
// Separate regular properties from pseudo-class overrides
const props: [string, string][] = [];
@@ -574,7 +709,14 @@ function generateComponentRules(
for (const [prop, value] of entries) {
if (prop.startsWith(':') && typeof value === 'object') {
pseudos.push([prop, value]);
- } else {
+ } else if (
+ acceptDeclaration(
+ toKebabCase(prop),
+ `${value as string}`,
+ location,
+ sink,
+ )
+ ) {
props.push([prop, value as string]);
}
}
@@ -654,9 +796,12 @@ function generateComponentRules(
// Emit base rule
if (finalProps.length > 0) {
- const declarations = finalProps
- .map(([prop, value]) => ` ${toKebabCase(prop)}: ${value};`)
- .join('\n');
+ const declarations = joinDeclarations(
+ finalProps,
+ location,
+ sink,
+ toKebabCase,
+ );
parts.push(` ${baseSelector} {\n${declarations}\n }`);
}
@@ -664,9 +809,12 @@ function generateComponentRules(
for (const [pseudo, pseudoStyles] of pseudos) {
const pseudoEntries = Object.entries(pseudoStyles);
if (pseudoEntries.length > 0) {
- const declarations = pseudoEntries
- .map(([prop, value]) => ` ${toKebabCase(prop)}: ${value};`)
- .join('\n');
+ const declarations = joinDeclarations(
+ pseudoEntries,
+ `${location}[${JSON.stringify(pseudo)}]`,
+ sink,
+ toKebabCase,
+ );
parts.push(
` ${appendPseudoToSelectorList(baseSelector, pseudo)} {\n${declarations}\n }`,
);
@@ -832,8 +980,11 @@ function generateSizeOverrides(
* Component rules (tokens, stable .astryx-* targets plus data-* selectors) are
* that need to beat StyleX — they stay in astryx-theme (above StyleX layers).
*/
-export function generateThemeRulesSplit(theme: DefinedTheme): ThemeRulesSplit {
- const allRules = generateThemeRules(theme);
+export function generateThemeRulesSplit(
+ theme: DefinedTheme,
+ warnings?: string[],
+): ThemeRulesSplit {
+ const allRules = generateThemeRules(theme, warnings);
const prose: string[] = [];
const component: string[] = [];
@@ -857,22 +1008,29 @@ export function generateThemeRulesSplit(theme: DefinedTheme): ThemeRulesSplit {
* to media contexts — only tokens change. Themes can further customize
* via onDark.components / onLight.components.
*/
-export function generateOnMediaCSS(theme: DefinedTheme): string {
+export function generateOnMediaCSS(
+ theme: DefinedTheme,
+ warnings?: string[],
+): string {
const parts: string[] = [];
const scopeSelector = themeScopeStart(theme.name);
+ const sink = diagnosticSink(warnings);
for (const surface of ['dark', 'light'] as const) {
const onMedia = surface === 'dark' ? theme.__onDark : theme.__onLight;
if (!onMedia) {
continue;
}
+ const location = surface === 'dark' ? 'onDark.' : 'onLight.';
// Token overrides
const tokenEntries = Object.entries(onMedia.tokens);
if (tokenEntries.length > 0) {
- const declarations = tokenEntries
- .map(([prop, value]) => ` ${prop}: ${value};`)
- .join('\n');
+ const declarations = joinDeclarations(
+ tokenEntries,
+ `${location}tokens`,
+ sink,
+ );
parts.push(` ${mediaSelector(surface)} {\n${declarations}\n }`);
}
@@ -882,6 +1040,8 @@ export function generateOnMediaCSS(theme: DefinedTheme): string {
generateComponentRules(onMedia.components, parts, {
resetInheritedPaddingSpecificity: true,
surface,
+ sink,
+ location,
});
generateColorOverrides(onMedia.components, parts, surface);
generateSizeOverrides(onMedia.components, parts, surface);
@@ -905,22 +1065,22 @@ export function generateOnMediaCSS(theme: DefinedTheme): string {
}
/** Generate only the declarations one adaptation rule writes. */
-function generateAdaptationRuleRules(rule: ThemeRuleSource): string[] {
+function generateAdaptationRuleRules(
+ rule: ThemeRuleSource,
+ location: string,
+ sink: DiagnosticSink,
+): string[] {
const parts: string[] = [];
- const tokenEntries = [
- ...Object.entries(rule.tokens),
- ...Object.entries(rule.localTokens ?? {}),
- ];
- if (tokenEntries.length > 0) {
- const declarations = tokenEntries
- .map(([prop, value]) => ` ${prop}: ${value};`)
- .join('\n');
- parts.push(` :scope {\n${declarations}\n }`);
+ const tokens = tokenBlock(rule, location, sink);
+ if (tokens !== null) {
+ parts.push(tokens);
}
if (rule.components) {
generateComponentRules(rule.components, parts, {
resetInheritedPaddingSpecificity: true,
+ sink,
+ location,
});
generateColorOverrides(rule.components, parts);
generateSizeOverrides(rule.components, parts);
@@ -958,7 +1118,11 @@ function generateAdaptationMediaBlock(
* rule. Bare prose follows semantic variables, so token writes need no duplicate
* prose selectors here.
*/
-export function generateAdaptationCSS(theme: DefinedTheme): ThemeCSSOutput {
+export function generateAdaptationCSS(
+ theme: DefinedTheme,
+ warnings?: string[],
+): ThemeCSSOutput {
+ const sink = diagnosticSink(warnings);
// Built themes can reach this compiler without passing through defineTheme.
// Validate retained metadata even when it has no rules (and therefore emits
// no CSS): width points remain observable through AppShell and inheritance.
@@ -992,8 +1156,12 @@ export function generateAdaptationCSS(theme: DefinedTheme): ThemeCSSOutput {
// active whenever the later condition matches, even if the earlier condition
// does not. Pairwise merging cannot repair that: multiple mutually exclusive
// earlier rules can each overlap one broad later rule.
- for (const rule of rules) {
- const parts = generateAdaptationRuleRules(rule);
+ for (const [index, rule] of rules.entries()) {
+ const parts = generateAdaptationRuleRules(
+ rule,
+ `adaptations[${index}].`,
+ sink,
+ );
if (parts.length === 0) {
continue;
}
@@ -1039,12 +1207,9 @@ export function generateAdaptationCSS(theme: DefinedTheme): ThemeCSSOutput {
return {prose: '', component: blocks.join('\n\n')};
}
-/** Indent a generated rule one level further, for nesting inside `@media`. */
+/** Indent the rule start without rewriting newlines inside authored values. */
function indentRule(rule: string): string {
- return rule
- .split('\n')
- .map(line => (line.length > 0 ? ` ${line}` : line))
- .join('\n');
+ return ` ${rule}`;
}
/**
@@ -1085,8 +1250,11 @@ export function generateDataTokenDefaultsCSS(): string {
* The theme-independent `--color-data-*` defaults are not part of this output:
* see `generateDataTokenDefaultsCSS`.
*/
-export function generateThemeCSS(theme: DefinedTheme): ThemeCSSOutput {
- const {component, prose} = generateThemeRulesSplit(theme);
+export function generateThemeCSS(
+ theme: DefinedTheme,
+ warnings?: string[],
+): ThemeCSSOutput {
+ const {component, prose} = generateThemeRulesSplit(theme, warnings);
const scopeSelector = themeScopeStart(theme.name);
const scopeTo = THEME_SCOPE_TO;
@@ -1106,14 +1274,14 @@ export function generateThemeCSS(theme: DefinedTheme): ThemeCSSOutput {
// Adaptations follow the root theme in authored order. Media-surface rules
// follow adaptations so onDark/onLight keep their specified precedence.
- const adaptationCss = generateAdaptationCSS(theme);
+ const adaptationCss = generateAdaptationCSS(theme, warnings);
if (adaptationCss.component) {
componentCss = componentCss
? `${componentCss}\n\n${adaptationCss.component}`
: adaptationCss.component;
}
- const onMediaCss = generateOnMediaCSS(theme);
+ const onMediaCss = generateOnMediaCSS(theme, warnings);
if (onMediaCss) {
componentCss = componentCss
? `${componentCss}\n\n${onMediaCss}`
diff --git a/packages/core/src/theme/tokenValueCompat.test.ts b/packages/core/src/theme/tokenValueCompat.test.ts
index 621958e169..d79a42cba1 100644
--- a/packages/core/src/theme/tokenValueCompat.test.ts
+++ b/packages/core/src/theme/tokenValueCompat.test.ts
@@ -22,7 +22,7 @@
*/
import {describe, expect, it} from 'vitest';
-import {defineTheme} from './defineTheme';
+import {defineTheme, generateThemeCSS} from './defineTheme';
import {resolveTokenValue} from './resolveThemeValues';
/** Exactly what the pre-extraction implementation did with each shape. */
@@ -43,6 +43,9 @@ describe('root token values keep their historical acceptance', () => {
});
expect(theme.tokens['--color-background-body']).toBe(expected);
+ expect(generateThemeCSS(theme).component).toContain(
+ `--color-background-body: ${String(expected)};`,
+ );
});
it('still resolves the documented shapes', () => {